1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the ASTContext interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "CXXABI.h" 15 #include "Interp/Context.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTConcept.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTTypeTraits.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/AttrIterator.h" 22 #include "clang/AST/CharUnits.h" 23 #include "clang/AST/Comment.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclBase.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclContextInternals.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/DeclarationName.h" 32 #include "clang/AST/DependenceFlags.h" 33 #include "clang/AST/Expr.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprConcepts.h" 36 #include "clang/AST/ExternalASTSource.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/MangleNumberingContext.h" 39 #include "clang/AST/NestedNameSpecifier.h" 40 #include "clang/AST/ParentMapContext.h" 41 #include "clang/AST/RawCommentList.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/Stmt.h" 44 #include "clang/AST/TemplateBase.h" 45 #include "clang/AST/TemplateName.h" 46 #include "clang/AST/Type.h" 47 #include "clang/AST/TypeLoc.h" 48 #include "clang/AST/UnresolvedSet.h" 49 #include "clang/AST/VTableBuilder.h" 50 #include "clang/Basic/AddressSpaces.h" 51 #include "clang/Basic/Builtins.h" 52 #include "clang/Basic/CommentOptions.h" 53 #include "clang/Basic/ExceptionSpecificationType.h" 54 #include "clang/Basic/FixedPoint.h" 55 #include "clang/Basic/IdentifierTable.h" 56 #include "clang/Basic/LLVM.h" 57 #include "clang/Basic/LangOptions.h" 58 #include "clang/Basic/Linkage.h" 59 #include "clang/Basic/Module.h" 60 #include "clang/Basic/ObjCRuntime.h" 61 #include "clang/Basic/SanitizerBlacklist.h" 62 #include "clang/Basic/SourceLocation.h" 63 #include "clang/Basic/SourceManager.h" 64 #include "clang/Basic/Specifiers.h" 65 #include "clang/Basic/TargetCXXABI.h" 66 #include "clang/Basic/TargetInfo.h" 67 #include "clang/Basic/XRayLists.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/ArrayRef.h" 71 #include "llvm/ADT/DenseMap.h" 72 #include "llvm/ADT/DenseSet.h" 73 #include "llvm/ADT/FoldingSet.h" 74 #include "llvm/ADT/None.h" 75 #include "llvm/ADT/Optional.h" 76 #include "llvm/ADT/PointerUnion.h" 77 #include "llvm/ADT/STLExtras.h" 78 #include "llvm/ADT/SmallPtrSet.h" 79 #include "llvm/ADT/SmallVector.h" 80 #include "llvm/ADT/StringExtras.h" 81 #include "llvm/ADT/StringRef.h" 82 #include "llvm/ADT/Triple.h" 83 #include "llvm/Support/Capacity.h" 84 #include "llvm/Support/Casting.h" 85 #include "llvm/Support/Compiler.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <cstdlib> 94 #include <map> 95 #include <memory> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 102 enum FloatingRank { 103 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 104 }; 105 106 /// \returns location that is relevant when searching for Doc comments related 107 /// to \p D. 108 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 109 SourceManager &SourceMgr) { 110 assert(D); 111 112 // User can not attach documentation to implicit declarations. 113 if (D->isImplicit()) 114 return {}; 115 116 // User can not attach documentation to implicit instantiations. 117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 119 return {}; 120 } 121 122 if (const auto *VD = dyn_cast<VarDecl>(D)) { 123 if (VD->isStaticDataMember() && 124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 125 return {}; 126 } 127 128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 130 return {}; 131 } 132 133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 135 if (TSK == TSK_ImplicitInstantiation || 136 TSK == TSK_Undeclared) 137 return {}; 138 } 139 140 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 142 return {}; 143 } 144 if (const auto *TD = dyn_cast<TagDecl>(D)) { 145 // When tag declaration (but not definition!) is part of the 146 // decl-specifier-seq of some other declaration, it doesn't get comment 147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 148 return {}; 149 } 150 // TODO: handle comments for function parameters properly. 151 if (isa<ParmVarDecl>(D)) 152 return {}; 153 154 // TODO: we could look up template parameter documentation in the template 155 // documentation. 156 if (isa<TemplateTypeParmDecl>(D) || 157 isa<NonTypeTemplateParmDecl>(D) || 158 isa<TemplateTemplateParmDecl>(D)) 159 return {}; 160 161 // Find declaration location. 162 // For Objective-C declarations we generally don't expect to have multiple 163 // declarators, thus use declaration starting location as the "declaration 164 // location". 165 // For all other declarations multiple declarators are used quite frequently, 166 // so we use the location of the identifier as the "declaration location". 167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 168 isa<ObjCPropertyDecl>(D) || 169 isa<RedeclarableTemplateDecl>(D) || 170 isa<ClassTemplateSpecializationDecl>(D) || 171 // Allow association with Y across {} in `typedef struct X {} Y`. 172 isa<TypedefDecl>(D)) 173 return D->getBeginLoc(); 174 else { 175 const SourceLocation DeclLoc = D->getLocation(); 176 if (DeclLoc.isMacroID()) { 177 if (isa<TypedefDecl>(D)) { 178 // If location of the typedef name is in a macro, it is because being 179 // declared via a macro. Try using declaration's starting location as 180 // the "declaration location". 181 return D->getBeginLoc(); 182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) { 183 // If location of the tag decl is inside a macro, but the spelling of 184 // the tag name comes from a macro argument, it looks like a special 185 // macro like NS_ENUM is being used to define the tag decl. In that 186 // case, adjust the source location to the expansion loc so that we can 187 // attach the comment to the tag decl. 188 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 189 TD->isCompleteDefinition()) 190 return SourceMgr.getExpansionLoc(DeclLoc); 191 } 192 } 193 return DeclLoc; 194 } 195 196 return {}; 197 } 198 199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 200 const Decl *D, const SourceLocation RepresentativeLocForDecl, 201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 202 // If the declaration doesn't map directly to a location in a file, we 203 // can't find the comment. 204 if (RepresentativeLocForDecl.isInvalid() || 205 !RepresentativeLocForDecl.isFileID()) 206 return nullptr; 207 208 // If there are no comments anywhere, we won't find anything. 209 if (CommentsInTheFile.empty()) 210 return nullptr; 211 212 // Decompose the location for the declaration and find the beginning of the 213 // file buffer. 214 const std::pair<FileID, unsigned> DeclLocDecomp = 215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 216 217 // Slow path. 218 auto OffsetCommentBehindDecl = 219 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 220 221 // First check whether we have a trailing comment. 222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 224 if ((CommentBehindDecl->isDocumentation() || 225 LangOpts.CommentOpts.ParseAllComments) && 226 CommentBehindDecl->isTrailingComment() && 227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 229 230 // Check that Doxygen trailing comment comes after the declaration, starts 231 // on the same line and in the same file as the declaration. 232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 234 OffsetCommentBehindDecl->first)) { 235 return CommentBehindDecl; 236 } 237 } 238 } 239 240 // The comment just after the declaration was not a trailing comment. 241 // Let's look at the previous comment. 242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 243 return nullptr; 244 245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 247 248 // Check that we actually have a non-member Doxygen comment. 249 if (!(CommentBeforeDecl->isDocumentation() || 250 LangOpts.CommentOpts.ParseAllComments) || 251 CommentBeforeDecl->isTrailingComment()) 252 return nullptr; 253 254 // Decompose the end of the comment. 255 const unsigned CommentEndOffset = 256 Comments.getCommentEndOffset(CommentBeforeDecl); 257 258 // Get the corresponding buffer. 259 bool Invalid = false; 260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 261 &Invalid).data(); 262 if (Invalid) 263 return nullptr; 264 265 // Extract text between the comment and declaration. 266 StringRef Text(Buffer + CommentEndOffset, 267 DeclLocDecomp.second - CommentEndOffset); 268 269 // There should be no other declarations or preprocessor directives between 270 // comment and declaration. 271 if (Text.find_first_of(";{}#@") != StringRef::npos) 272 return nullptr; 273 274 return CommentBeforeDecl; 275 } 276 277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 279 280 // If the declaration doesn't map directly to a location in a file, we 281 // can't find the comment. 282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 283 return nullptr; 284 285 if (ExternalSource && !CommentsLoaded) { 286 ExternalSource->ReadComments(); 287 CommentsLoaded = true; 288 } 289 290 if (Comments.empty()) 291 return nullptr; 292 293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 294 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 295 if (!CommentsInThisFile || CommentsInThisFile->empty()) 296 return nullptr; 297 298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 299 } 300 301 void ASTContext::addComment(const RawComment &RC) { 302 assert(LangOpts.RetainCommentsFromSystemHeaders || 303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 305 } 306 307 /// If we have a 'templated' declaration for a template, adjust 'D' to 308 /// refer to the actual template. 309 /// If we have an implicit instantiation, adjust 'D' to refer to template. 310 static const Decl &adjustDeclToTemplate(const Decl &D) { 311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 312 // Is this function declaration part of a function template? 313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 314 return *FTD; 315 316 // Nothing to do if function is not an implicit instantiation. 317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 318 return D; 319 320 // Function is an implicit instantiation of a function template? 321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 322 return *FTD; 323 324 // Function is instantiated from a member definition of a class template? 325 if (const FunctionDecl *MemberDecl = 326 FD->getInstantiatedFromMemberFunction()) 327 return *MemberDecl; 328 329 return D; 330 } 331 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 332 // Static data member is instantiated from a member definition of a class 333 // template? 334 if (VD->isStaticDataMember()) 335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 336 return *MemberDecl; 337 338 return D; 339 } 340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 341 // Is this class declaration part of a class template? 342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 343 return *CTD; 344 345 // Class is an implicit instantiation of a class template or partial 346 // specialization? 347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 349 return D; 350 llvm::PointerUnion<ClassTemplateDecl *, 351 ClassTemplatePartialSpecializationDecl *> 352 PU = CTSD->getSpecializedTemplateOrPartial(); 353 return PU.is<ClassTemplateDecl *>() 354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 355 : *static_cast<const Decl *>( 356 PU.get<ClassTemplatePartialSpecializationDecl *>()); 357 } 358 359 // Class is instantiated from a member definition of a class template? 360 if (const MemberSpecializationInfo *Info = 361 CRD->getMemberSpecializationInfo()) 362 return *Info->getInstantiatedFrom(); 363 364 return D; 365 } 366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 367 // Enum is instantiated from a member definition of a class template? 368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 369 return *MemberDecl; 370 371 return D; 372 } 373 // FIXME: Adjust alias templates? 374 return D; 375 } 376 377 const RawComment *ASTContext::getRawCommentForAnyRedecl( 378 const Decl *D, 379 const Decl **OriginalDecl) const { 380 if (!D) { 381 if (OriginalDecl) 382 OriginalDecl = nullptr; 383 return nullptr; 384 } 385 386 D = &adjustDeclToTemplate(*D); 387 388 // Any comment directly attached to D? 389 { 390 auto DeclComment = DeclRawComments.find(D); 391 if (DeclComment != DeclRawComments.end()) { 392 if (OriginalDecl) 393 *OriginalDecl = D; 394 return DeclComment->second; 395 } 396 } 397 398 // Any comment attached to any redeclaration of D? 399 const Decl *CanonicalD = D->getCanonicalDecl(); 400 if (!CanonicalD) 401 return nullptr; 402 403 { 404 auto RedeclComment = RedeclChainComments.find(CanonicalD); 405 if (RedeclComment != RedeclChainComments.end()) { 406 if (OriginalDecl) 407 *OriginalDecl = RedeclComment->second; 408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 409 assert(CommentAtRedecl != DeclRawComments.end() && 410 "This decl is supposed to have comment attached."); 411 return CommentAtRedecl->second; 412 } 413 } 414 415 // Any redeclarations of D that we haven't checked for comments yet? 416 // We can't use DenseMap::iterator directly since it'd get invalid. 417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 419 if (LookupRes != CommentlessRedeclChains.end()) 420 return LookupRes->second; 421 return nullptr; 422 }(); 423 424 for (const auto Redecl : D->redecls()) { 425 assert(Redecl); 426 // Skip all redeclarations that have been checked previously. 427 if (LastCheckedRedecl) { 428 if (LastCheckedRedecl == Redecl) { 429 LastCheckedRedecl = nullptr; 430 } 431 continue; 432 } 433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 434 if (RedeclComment) { 435 cacheRawCommentForDecl(*Redecl, *RedeclComment); 436 if (OriginalDecl) 437 *OriginalDecl = Redecl; 438 return RedeclComment; 439 } 440 CommentlessRedeclChains[CanonicalD] = Redecl; 441 } 442 443 if (OriginalDecl) 444 *OriginalDecl = nullptr; 445 return nullptr; 446 } 447 448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 449 const RawComment &Comment) const { 450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 451 DeclRawComments.try_emplace(&OriginalD, &Comment); 452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 454 CommentlessRedeclChains.erase(CanonicalDecl); 455 } 456 457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 458 SmallVectorImpl<const NamedDecl *> &Redeclared) { 459 const DeclContext *DC = ObjCMethod->getDeclContext(); 460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 461 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 462 if (!ID) 463 return; 464 // Add redeclared method here. 465 for (const auto *Ext : ID->known_extensions()) { 466 if (ObjCMethodDecl *RedeclaredMethod = 467 Ext->getMethod(ObjCMethod->getSelector(), 468 ObjCMethod->isInstanceMethod())) 469 Redeclared.push_back(RedeclaredMethod); 470 } 471 } 472 } 473 474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 475 const Preprocessor *PP) { 476 if (Comments.empty() || Decls.empty()) 477 return; 478 479 FileID File; 480 for (Decl *D : Decls) { 481 SourceLocation Loc = D->getLocation(); 482 if (Loc.isValid()) { 483 // See if there are any new comments that are not attached to a decl. 484 // The location doesn't have to be precise - we care only about the file. 485 File = SourceMgr.getDecomposedLoc(Loc).first; 486 break; 487 } 488 } 489 490 if (File.isInvalid()) 491 return; 492 493 auto CommentsInThisFile = Comments.getCommentsInFile(File); 494 if (!CommentsInThisFile || CommentsInThisFile->empty() || 495 CommentsInThisFile->rbegin()->second->isAttached()) 496 return; 497 498 // There is at least one comment not attached to a decl. 499 // Maybe it should be attached to one of Decls? 500 // 501 // Note that this way we pick up not only comments that precede the 502 // declaration, but also comments that *follow* the declaration -- thanks to 503 // the lookahead in the lexer: we've consumed the semicolon and looked 504 // ahead through comments. 505 506 for (const Decl *D : Decls) { 507 assert(D); 508 if (D->isInvalidDecl()) 509 continue; 510 511 D = &adjustDeclToTemplate(*D); 512 513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 514 515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 516 continue; 517 518 if (DeclRawComments.count(D) > 0) 519 continue; 520 521 if (RawComment *const DocComment = 522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 523 cacheRawCommentForDecl(*D, *DocComment); 524 comments::FullComment *FC = DocComment->parse(*this, PP, D); 525 ParsedComments[D->getCanonicalDecl()] = FC; 526 } 527 } 528 } 529 530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 531 const Decl *D) const { 532 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 533 ThisDeclInfo->CommentDecl = D; 534 ThisDeclInfo->IsFilled = false; 535 ThisDeclInfo->fill(); 536 ThisDeclInfo->CommentDecl = FC->getDecl(); 537 if (!ThisDeclInfo->TemplateParameters) 538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 539 comments::FullComment *CFC = 540 new (*this) comments::FullComment(FC->getBlocks(), 541 ThisDeclInfo); 542 return CFC; 543 } 544 545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 546 const RawComment *RC = getRawCommentForDeclNoCache(D); 547 return RC ? RC->parse(*this, nullptr, D) : nullptr; 548 } 549 550 comments::FullComment *ASTContext::getCommentForDecl( 551 const Decl *D, 552 const Preprocessor *PP) const { 553 if (!D || D->isInvalidDecl()) 554 return nullptr; 555 D = &adjustDeclToTemplate(*D); 556 557 const Decl *Canonical = D->getCanonicalDecl(); 558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 559 ParsedComments.find(Canonical); 560 561 if (Pos != ParsedComments.end()) { 562 if (Canonical != D) { 563 comments::FullComment *FC = Pos->second; 564 comments::FullComment *CFC = cloneFullComment(FC, D); 565 return CFC; 566 } 567 return Pos->second; 568 } 569 570 const Decl *OriginalDecl = nullptr; 571 572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 573 if (!RC) { 574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 575 SmallVector<const NamedDecl*, 8> Overridden; 576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 577 if (OMD && OMD->isPropertyAccessor()) 578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 580 return cloneFullComment(FC, D); 581 if (OMD) 582 addRedeclaredMethods(OMD, Overridden); 583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 584 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 586 return cloneFullComment(FC, D); 587 } 588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 589 // Attach any tag type's documentation to its typedef if latter 590 // does not have one of its own. 591 QualType QT = TD->getUnderlyingType(); 592 if (const auto *TT = QT->getAs<TagType>()) 593 if (const Decl *TD = TT->getDecl()) 594 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 595 return cloneFullComment(FC, D); 596 } 597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 598 while (IC->getSuperClass()) { 599 IC = IC->getSuperClass(); 600 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 601 return cloneFullComment(FC, D); 602 } 603 } 604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 606 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 607 return cloneFullComment(FC, D); 608 } 609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 610 if (!(RD = RD->getDefinition())) 611 return nullptr; 612 // Check non-virtual bases. 613 for (const auto &I : RD->bases()) { 614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 615 continue; 616 QualType Ty = I.getType(); 617 if (Ty.isNull()) 618 continue; 619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 620 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 621 continue; 622 623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 624 return cloneFullComment(FC, D); 625 } 626 } 627 // Check virtual bases. 628 for (const auto &I : RD->vbases()) { 629 if (I.getAccessSpecifier() != AS_public) 630 continue; 631 QualType Ty = I.getType(); 632 if (Ty.isNull()) 633 continue; 634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 635 if (!(VirtualBase= VirtualBase->getDefinition())) 636 continue; 637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 638 return cloneFullComment(FC, D); 639 } 640 } 641 } 642 return nullptr; 643 } 644 645 // If the RawComment was attached to other redeclaration of this Decl, we 646 // should parse the comment in context of that other Decl. This is important 647 // because comments can contain references to parameter names which can be 648 // different across redeclarations. 649 if (D != OriginalDecl && OriginalDecl) 650 return getCommentForDecl(OriginalDecl, PP); 651 652 comments::FullComment *FC = RC->parse(*this, PP, D); 653 ParsedComments[Canonical] = FC; 654 return FC; 655 } 656 657 void 658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 659 const ASTContext &C, 660 TemplateTemplateParmDecl *Parm) { 661 ID.AddInteger(Parm->getDepth()); 662 ID.AddInteger(Parm->getPosition()); 663 ID.AddBoolean(Parm->isParameterPack()); 664 665 TemplateParameterList *Params = Parm->getTemplateParameters(); 666 ID.AddInteger(Params->size()); 667 for (TemplateParameterList::const_iterator P = Params->begin(), 668 PEnd = Params->end(); 669 P != PEnd; ++P) { 670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 671 ID.AddInteger(0); 672 ID.AddBoolean(TTP->isParameterPack()); 673 const TypeConstraint *TC = TTP->getTypeConstraint(); 674 ID.AddBoolean(TC != nullptr); 675 if (TC) 676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 677 /*Canonical=*/true); 678 if (TTP->isExpandedParameterPack()) { 679 ID.AddBoolean(true); 680 ID.AddInteger(TTP->getNumExpansionParameters()); 681 } else 682 ID.AddBoolean(false); 683 continue; 684 } 685 686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 687 ID.AddInteger(1); 688 ID.AddBoolean(NTTP->isParameterPack()); 689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 690 if (NTTP->isExpandedParameterPack()) { 691 ID.AddBoolean(true); 692 ID.AddInteger(NTTP->getNumExpansionTypes()); 693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 694 QualType T = NTTP->getExpansionType(I); 695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 696 } 697 } else 698 ID.AddBoolean(false); 699 continue; 700 } 701 702 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 703 ID.AddInteger(2); 704 Profile(ID, C, TTP); 705 } 706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 707 ID.AddBoolean(RequiresClause != nullptr); 708 if (RequiresClause) 709 RequiresClause->Profile(ID, C, /*Canonical=*/true); 710 } 711 712 static Expr * 713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 714 QualType ConstrainedType) { 715 // This is a bit ugly - we need to form a new immediately-declared 716 // constraint that references the new parameter; this would ideally 717 // require semantic analysis (e.g. template<C T> struct S {}; - the 718 // converted arguments of C<T> could be an argument pack if C is 719 // declared as template<typename... T> concept C = ...). 720 // We don't have semantic analysis here so we dig deep into the 721 // ready-made constraint expr and change the thing manually. 722 ConceptSpecializationExpr *CSE; 723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 725 else 726 CSE = cast<ConceptSpecializationExpr>(IDC); 727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 728 SmallVector<TemplateArgument, 3> NewConverted; 729 NewConverted.reserve(OldConverted.size()); 730 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 731 // The case: 732 // template<typename... T> concept C = true; 733 // template<C<int> T> struct S; -> constraint is C<{T, int}> 734 NewConverted.push_back(ConstrainedType); 735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 736 NewConverted.push_back(Arg); 737 TemplateArgument NewPack(NewConverted); 738 739 NewConverted.clear(); 740 NewConverted.push_back(NewPack); 741 assert(OldConverted.size() == 1 && 742 "Template parameter pack should be the last parameter"); 743 } else { 744 assert(OldConverted.front().getKind() == TemplateArgument::Type && 745 "Unexpected first argument kind for immediately-declared " 746 "constraint"); 747 NewConverted.push_back(ConstrainedType); 748 for (auto &Arg : OldConverted.drop_front(1)) 749 NewConverted.push_back(Arg); 750 } 751 Expr *NewIDC = ConceptSpecializationExpr::Create( 752 C, CSE->getNamedConcept(), NewConverted, nullptr, 753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 754 755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 756 NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC, 757 BinaryOperatorKind::BO_LAnd, 758 SourceLocation(), /*RHS=*/nullptr, 759 SourceLocation(), /*NumExpansions=*/None); 760 return NewIDC; 761 } 762 763 TemplateTemplateParmDecl * 764 ASTContext::getCanonicalTemplateTemplateParmDecl( 765 TemplateTemplateParmDecl *TTP) const { 766 // Check if we already have a canonical template template parameter. 767 llvm::FoldingSetNodeID ID; 768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 769 void *InsertPos = nullptr; 770 CanonicalTemplateTemplateParm *Canonical 771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 772 if (Canonical) 773 return Canonical->getParam(); 774 775 // Build a canonical template parameter list. 776 TemplateParameterList *Params = TTP->getTemplateParameters(); 777 SmallVector<NamedDecl *, 4> CanonParams; 778 CanonParams.reserve(Params->size()); 779 for (TemplateParameterList::const_iterator P = Params->begin(), 780 PEnd = Params->end(); 781 P != PEnd; ++P) { 782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 785 TTP->getDepth(), TTP->getIndex(), nullptr, false, 786 TTP->isParameterPack(), TTP->hasTypeConstraint(), 787 TTP->isExpandedParameterPack() ? 788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 789 if (const auto *TC = TTP->getTypeConstraint()) { 790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 792 *this, TC->getImmediatelyDeclaredConstraint(), 793 ParamAsArgument); 794 TemplateArgumentListInfo CanonArgsAsWritten; 795 if (auto *Args = TC->getTemplateArgsAsWritten()) 796 for (const auto &ArgLoc : Args->arguments()) 797 CanonArgsAsWritten.addArgument( 798 TemplateArgumentLoc(ArgLoc.getArgument(), 799 TemplateArgumentLocInfo())); 800 NewTTP->setTypeConstraint( 801 NestedNameSpecifierLoc(), 802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 803 SourceLocation()), /*FoundDecl=*/nullptr, 804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 805 // simply omit the ArgsAsWritten 806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 807 } 808 CanonParams.push_back(NewTTP); 809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 810 QualType T = getCanonicalType(NTTP->getType()); 811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 812 NonTypeTemplateParmDecl *Param; 813 if (NTTP->isExpandedParameterPack()) { 814 SmallVector<QualType, 2> ExpandedTypes; 815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 818 ExpandedTInfos.push_back( 819 getTrivialTypeSourceInfo(ExpandedTypes.back())); 820 } 821 822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 823 SourceLocation(), 824 SourceLocation(), 825 NTTP->getDepth(), 826 NTTP->getPosition(), nullptr, 827 T, 828 TInfo, 829 ExpandedTypes, 830 ExpandedTInfos); 831 } else { 832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 833 SourceLocation(), 834 SourceLocation(), 835 NTTP->getDepth(), 836 NTTP->getPosition(), nullptr, 837 T, 838 NTTP->isParameterPack(), 839 TInfo); 840 } 841 if (AutoType *AT = T->getContainedAutoType()) { 842 if (AT->isConstrained()) { 843 Param->setPlaceholderTypeConstraint( 844 canonicalizeImmediatelyDeclaredConstraint( 845 *this, NTTP->getPlaceholderTypeConstraint(), T)); 846 } 847 } 848 CanonParams.push_back(Param); 849 850 } else 851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 852 cast<TemplateTemplateParmDecl>(*P))); 853 } 854 855 Expr *CanonRequiresClause = nullptr; 856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 857 CanonRequiresClause = RequiresClause; 858 859 TemplateTemplateParmDecl *CanonTTP 860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 861 SourceLocation(), TTP->getDepth(), 862 TTP->getPosition(), 863 TTP->isParameterPack(), 864 nullptr, 865 TemplateParameterList::Create(*this, SourceLocation(), 866 SourceLocation(), 867 CanonParams, 868 SourceLocation(), 869 CanonRequiresClause)); 870 871 // Get the new insert position for the node we care about. 872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 873 assert(!Canonical && "Shouldn't be in the map!"); 874 (void)Canonical; 875 876 // Create the canonical template template parameter entry. 877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 879 return CanonTTP; 880 } 881 882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 883 if (!LangOpts.CPlusPlus) return nullptr; 884 885 switch (T.getCXXABI().getKind()) { 886 case TargetCXXABI::Fuchsia: 887 case TargetCXXABI::GenericARM: // Same as Itanium at this level 888 case TargetCXXABI::iOS: 889 case TargetCXXABI::iOS64: 890 case TargetCXXABI::WatchOS: 891 case TargetCXXABI::GenericAArch64: 892 case TargetCXXABI::GenericMIPS: 893 case TargetCXXABI::GenericItanium: 894 case TargetCXXABI::WebAssembly: 895 case TargetCXXABI::XL: 896 return CreateItaniumCXXABI(*this); 897 case TargetCXXABI::Microsoft: 898 return CreateMicrosoftCXXABI(*this); 899 } 900 llvm_unreachable("Invalid CXXABI type!"); 901 } 902 903 interp::Context &ASTContext::getInterpContext() { 904 if (!InterpContext) { 905 InterpContext.reset(new interp::Context(*this)); 906 } 907 return *InterpContext.get(); 908 } 909 910 ParentMapContext &ASTContext::getParentMapContext() { 911 if (!ParentMapCtx) 912 ParentMapCtx.reset(new ParentMapContext(*this)); 913 return *ParentMapCtx.get(); 914 } 915 916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 917 const LangOptions &LOpts) { 918 if (LOpts.FakeAddressSpaceMap) { 919 // The fake address space map must have a distinct entry for each 920 // language-specific address space. 921 static const unsigned FakeAddrSpaceMap[] = { 922 0, // Default 923 1, // opencl_global 924 3, // opencl_local 925 2, // opencl_constant 926 0, // opencl_private 927 4, // opencl_generic 928 5, // cuda_device 929 6, // cuda_constant 930 7, // cuda_shared 931 8, // ptr32_sptr 932 9, // ptr32_uptr 933 10 // ptr64 934 }; 935 return &FakeAddrSpaceMap; 936 } else { 937 return &T.getAddressSpaceMap(); 938 } 939 } 940 941 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 942 const LangOptions &LangOpts) { 943 switch (LangOpts.getAddressSpaceMapMangling()) { 944 case LangOptions::ASMM_Target: 945 return TI.useAddressSpaceMapMangling(); 946 case LangOptions::ASMM_On: 947 return true; 948 case LangOptions::ASMM_Off: 949 return false; 950 } 951 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 952 } 953 954 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 955 IdentifierTable &idents, SelectorTable &sels, 956 Builtin::Context &builtins) 957 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), 958 TemplateSpecializationTypes(this_()), 959 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 960 SubstTemplateTemplateParmPacks(this_()), 961 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 962 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 963 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 964 LangOpts.XRayNeverInstrumentFiles, 965 LangOpts.XRayAttrListFiles, SM)), 966 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 967 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM), 968 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 969 CompCategories(this_()), LastSDM(nullptr, 0) { 970 TUDecl = TranslationUnitDecl::Create(*this); 971 TraversalScope = {TUDecl}; 972 } 973 974 ASTContext::~ASTContext() { 975 // Release the DenseMaps associated with DeclContext objects. 976 // FIXME: Is this the ideal solution? 977 ReleaseDeclContextMaps(); 978 979 // Call all of the deallocation functions on all of their targets. 980 for (auto &Pair : Deallocations) 981 (Pair.first)(Pair.second); 982 983 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 984 // because they can contain DenseMaps. 985 for (llvm::DenseMap<const ObjCContainerDecl*, 986 const ASTRecordLayout*>::iterator 987 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 988 // Increment in loop to prevent using deallocated memory. 989 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 990 R->Destroy(*this); 991 992 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 993 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 994 // Increment in loop to prevent using deallocated memory. 995 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 996 R->Destroy(*this); 997 } 998 999 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1000 AEnd = DeclAttrs.end(); 1001 A != AEnd; ++A) 1002 A->second->~AttrVec(); 1003 1004 for (const auto &Value : ModuleInitializers) 1005 Value.second->~PerModuleInitializers(); 1006 1007 for (APValue *Value : APValueCleanups) 1008 Value->~APValue(); 1009 } 1010 1011 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1012 TraversalScope = TopLevelDecls; 1013 getParentMapContext().clear(); 1014 } 1015 1016 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1017 Deallocations.push_back({Callback, Data}); 1018 } 1019 1020 void 1021 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1022 ExternalSource = std::move(Source); 1023 } 1024 1025 void ASTContext::PrintStats() const { 1026 llvm::errs() << "\n*** AST Context Stats:\n"; 1027 llvm::errs() << " " << Types.size() << " types total.\n"; 1028 1029 unsigned counts[] = { 1030 #define TYPE(Name, Parent) 0, 1031 #define ABSTRACT_TYPE(Name, Parent) 1032 #include "clang/AST/TypeNodes.inc" 1033 0 // Extra 1034 }; 1035 1036 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1037 Type *T = Types[i]; 1038 counts[(unsigned)T->getTypeClass()]++; 1039 } 1040 1041 unsigned Idx = 0; 1042 unsigned TotalBytes = 0; 1043 #define TYPE(Name, Parent) \ 1044 if (counts[Idx]) \ 1045 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1046 << " types, " << sizeof(Name##Type) << " each " \ 1047 << "(" << counts[Idx] * sizeof(Name##Type) \ 1048 << " bytes)\n"; \ 1049 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1050 ++Idx; 1051 #define ABSTRACT_TYPE(Name, Parent) 1052 #include "clang/AST/TypeNodes.inc" 1053 1054 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1055 1056 // Implicit special member functions. 1057 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1058 << NumImplicitDefaultConstructors 1059 << " implicit default constructors created\n"; 1060 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1061 << NumImplicitCopyConstructors 1062 << " implicit copy constructors created\n"; 1063 if (getLangOpts().CPlusPlus) 1064 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1065 << NumImplicitMoveConstructors 1066 << " implicit move constructors created\n"; 1067 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1068 << NumImplicitCopyAssignmentOperators 1069 << " implicit copy assignment operators created\n"; 1070 if (getLangOpts().CPlusPlus) 1071 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1072 << NumImplicitMoveAssignmentOperators 1073 << " implicit move assignment operators created\n"; 1074 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1075 << NumImplicitDestructors 1076 << " implicit destructors created\n"; 1077 1078 if (ExternalSource) { 1079 llvm::errs() << "\n"; 1080 ExternalSource->PrintStats(); 1081 } 1082 1083 BumpAlloc.PrintStats(); 1084 } 1085 1086 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1087 bool NotifyListeners) { 1088 if (NotifyListeners) 1089 if (auto *Listener = getASTMutationListener()) 1090 Listener->RedefinedHiddenDefinition(ND, M); 1091 1092 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1093 } 1094 1095 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1096 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1097 if (It == MergedDefModules.end()) 1098 return; 1099 1100 auto &Merged = It->second; 1101 llvm::DenseSet<Module*> Found; 1102 for (Module *&M : Merged) 1103 if (!Found.insert(M).second) 1104 M = nullptr; 1105 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 1106 } 1107 1108 ArrayRef<Module *> 1109 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1110 auto MergedIt = 1111 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1112 if (MergedIt == MergedDefModules.end()) 1113 return None; 1114 return MergedIt->second; 1115 } 1116 1117 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1118 if (LazyInitializers.empty()) 1119 return; 1120 1121 auto *Source = Ctx.getExternalSource(); 1122 assert(Source && "lazy initializers but no external source"); 1123 1124 auto LazyInits = std::move(LazyInitializers); 1125 LazyInitializers.clear(); 1126 1127 for (auto ID : LazyInits) 1128 Initializers.push_back(Source->GetExternalDecl(ID)); 1129 1130 assert(LazyInitializers.empty() && 1131 "GetExternalDecl for lazy module initializer added more inits"); 1132 } 1133 1134 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1135 // One special case: if we add a module initializer that imports another 1136 // module, and that module's only initializer is an ImportDecl, simplify. 1137 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1138 auto It = ModuleInitializers.find(ID->getImportedModule()); 1139 1140 // Maybe the ImportDecl does nothing at all. (Common case.) 1141 if (It == ModuleInitializers.end()) 1142 return; 1143 1144 // Maybe the ImportDecl only imports another ImportDecl. 1145 auto &Imported = *It->second; 1146 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1147 Imported.resolve(*this); 1148 auto *OnlyDecl = Imported.Initializers.front(); 1149 if (isa<ImportDecl>(OnlyDecl)) 1150 D = OnlyDecl; 1151 } 1152 } 1153 1154 auto *&Inits = ModuleInitializers[M]; 1155 if (!Inits) 1156 Inits = new (*this) PerModuleInitializers; 1157 Inits->Initializers.push_back(D); 1158 } 1159 1160 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1161 auto *&Inits = ModuleInitializers[M]; 1162 if (!Inits) 1163 Inits = new (*this) PerModuleInitializers; 1164 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1165 IDs.begin(), IDs.end()); 1166 } 1167 1168 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1169 auto It = ModuleInitializers.find(M); 1170 if (It == ModuleInitializers.end()) 1171 return None; 1172 1173 auto *Inits = It->second; 1174 Inits->resolve(*this); 1175 return Inits->Initializers; 1176 } 1177 1178 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1179 if (!ExternCContext) 1180 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1181 1182 return ExternCContext; 1183 } 1184 1185 BuiltinTemplateDecl * 1186 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1187 const IdentifierInfo *II) const { 1188 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 1189 BuiltinTemplate->setImplicit(); 1190 TUDecl->addDecl(BuiltinTemplate); 1191 1192 return BuiltinTemplate; 1193 } 1194 1195 BuiltinTemplateDecl * 1196 ASTContext::getMakeIntegerSeqDecl() const { 1197 if (!MakeIntegerSeqDecl) 1198 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1199 getMakeIntegerSeqName()); 1200 return MakeIntegerSeqDecl; 1201 } 1202 1203 BuiltinTemplateDecl * 1204 ASTContext::getTypePackElementDecl() const { 1205 if (!TypePackElementDecl) 1206 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1207 getTypePackElementName()); 1208 return TypePackElementDecl; 1209 } 1210 1211 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1212 RecordDecl::TagKind TK) const { 1213 SourceLocation Loc; 1214 RecordDecl *NewDecl; 1215 if (getLangOpts().CPlusPlus) 1216 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1217 Loc, &Idents.get(Name)); 1218 else 1219 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1220 &Idents.get(Name)); 1221 NewDecl->setImplicit(); 1222 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1223 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1224 return NewDecl; 1225 } 1226 1227 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1228 StringRef Name) const { 1229 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1230 TypedefDecl *NewDecl = TypedefDecl::Create( 1231 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1232 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1233 NewDecl->setImplicit(); 1234 return NewDecl; 1235 } 1236 1237 TypedefDecl *ASTContext::getInt128Decl() const { 1238 if (!Int128Decl) 1239 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1240 return Int128Decl; 1241 } 1242 1243 TypedefDecl *ASTContext::getUInt128Decl() const { 1244 if (!UInt128Decl) 1245 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1246 return UInt128Decl; 1247 } 1248 1249 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1250 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1251 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1252 Types.push_back(Ty); 1253 } 1254 1255 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1256 const TargetInfo *AuxTarget) { 1257 assert((!this->Target || this->Target == &Target) && 1258 "Incorrect target reinitialization"); 1259 assert(VoidTy.isNull() && "Context reinitialized?"); 1260 1261 this->Target = &Target; 1262 this->AuxTarget = AuxTarget; 1263 1264 ABI.reset(createCXXABI(Target)); 1265 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1266 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1267 1268 // C99 6.2.5p19. 1269 InitBuiltinType(VoidTy, BuiltinType::Void); 1270 1271 // C99 6.2.5p2. 1272 InitBuiltinType(BoolTy, BuiltinType::Bool); 1273 // C99 6.2.5p3. 1274 if (LangOpts.CharIsSigned) 1275 InitBuiltinType(CharTy, BuiltinType::Char_S); 1276 else 1277 InitBuiltinType(CharTy, BuiltinType::Char_U); 1278 // C99 6.2.5p4. 1279 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1280 InitBuiltinType(ShortTy, BuiltinType::Short); 1281 InitBuiltinType(IntTy, BuiltinType::Int); 1282 InitBuiltinType(LongTy, BuiltinType::Long); 1283 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1284 1285 // C99 6.2.5p6. 1286 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1287 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1288 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1289 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1290 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1291 1292 // C99 6.2.5p10. 1293 InitBuiltinType(FloatTy, BuiltinType::Float); 1294 InitBuiltinType(DoubleTy, BuiltinType::Double); 1295 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1296 1297 // GNU extension, __float128 for IEEE quadruple precision 1298 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1299 1300 // C11 extension ISO/IEC TS 18661-3 1301 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1302 1303 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1304 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1305 InitBuiltinType(AccumTy, BuiltinType::Accum); 1306 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1307 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1308 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1309 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1310 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1311 InitBuiltinType(FractTy, BuiltinType::Fract); 1312 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1313 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1314 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1315 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1316 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1317 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1318 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1319 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1320 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1321 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1322 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1323 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1324 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1325 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1326 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1327 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1328 1329 // GNU extension, 128-bit integers. 1330 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1331 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1332 1333 // C++ 3.9.1p5 1334 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1335 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1336 else // -fshort-wchar makes wchar_t be unsigned. 1337 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1338 if (LangOpts.CPlusPlus && LangOpts.WChar) 1339 WideCharTy = WCharTy; 1340 else { 1341 // C99 (or C++ using -fno-wchar). 1342 WideCharTy = getFromTargetType(Target.getWCharType()); 1343 } 1344 1345 WIntTy = getFromTargetType(Target.getWIntType()); 1346 1347 // C++20 (proposed) 1348 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1349 1350 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1351 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1352 else // C99 1353 Char16Ty = getFromTargetType(Target.getChar16Type()); 1354 1355 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1356 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1357 else // C99 1358 Char32Ty = getFromTargetType(Target.getChar32Type()); 1359 1360 // Placeholder type for type-dependent expressions whose type is 1361 // completely unknown. No code should ever check a type against 1362 // DependentTy and users should never see it; however, it is here to 1363 // help diagnose failures to properly check for type-dependent 1364 // expressions. 1365 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1366 1367 // Placeholder type for functions. 1368 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1369 1370 // Placeholder type for bound members. 1371 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1372 1373 // Placeholder type for pseudo-objects. 1374 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1375 1376 // "any" type; useful for debugger-like clients. 1377 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1378 1379 // Placeholder type for unbridged ARC casts. 1380 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1381 1382 // Placeholder type for builtin functions. 1383 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1384 1385 // Placeholder type for OMP array sections. 1386 if (LangOpts.OpenMP) { 1387 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1388 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1389 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1390 } 1391 if (LangOpts.MatrixTypes) 1392 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1393 1394 // C99 6.2.5p11. 1395 FloatComplexTy = getComplexType(FloatTy); 1396 DoubleComplexTy = getComplexType(DoubleTy); 1397 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1398 Float128ComplexTy = getComplexType(Float128Ty); 1399 1400 // Builtin types for 'id', 'Class', and 'SEL'. 1401 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1402 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1403 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1404 1405 if (LangOpts.OpenCL) { 1406 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1407 InitBuiltinType(SingletonId, BuiltinType::Id); 1408 #include "clang/Basic/OpenCLImageTypes.def" 1409 1410 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1411 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1412 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1413 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1414 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1415 1416 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1417 InitBuiltinType(Id##Ty, BuiltinType::Id); 1418 #include "clang/Basic/OpenCLExtensionTypes.def" 1419 } 1420 1421 if (Target.hasAArch64SVETypes()) { 1422 #define SVE_TYPE(Name, Id, SingletonId) \ 1423 InitBuiltinType(SingletonId, BuiltinType::Id); 1424 #include "clang/Basic/AArch64SVEACLETypes.def" 1425 } 1426 1427 // Builtin type for __objc_yes and __objc_no 1428 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1429 SignedCharTy : BoolTy); 1430 1431 ObjCConstantStringType = QualType(); 1432 1433 ObjCSuperType = QualType(); 1434 1435 // void * type 1436 if (LangOpts.OpenCLVersion >= 200) { 1437 auto Q = VoidTy.getQualifiers(); 1438 Q.setAddressSpace(LangAS::opencl_generic); 1439 VoidPtrTy = getPointerType(getCanonicalType( 1440 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1441 } else { 1442 VoidPtrTy = getPointerType(VoidTy); 1443 } 1444 1445 // nullptr type (C++0x 2.14.7) 1446 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1447 1448 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1449 InitBuiltinType(HalfTy, BuiltinType::Half); 1450 1451 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1452 1453 // Builtin type used to help define __builtin_va_list. 1454 VaListTagDecl = nullptr; 1455 1456 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1457 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1458 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1459 TUDecl->addDecl(MSGuidTagDecl); 1460 } 1461 } 1462 1463 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1464 return SourceMgr.getDiagnostics(); 1465 } 1466 1467 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1468 AttrVec *&Result = DeclAttrs[D]; 1469 if (!Result) { 1470 void *Mem = Allocate(sizeof(AttrVec)); 1471 Result = new (Mem) AttrVec; 1472 } 1473 1474 return *Result; 1475 } 1476 1477 /// Erase the attributes corresponding to the given declaration. 1478 void ASTContext::eraseDeclAttrs(const Decl *D) { 1479 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1480 if (Pos != DeclAttrs.end()) { 1481 Pos->second->~AttrVec(); 1482 DeclAttrs.erase(Pos); 1483 } 1484 } 1485 1486 // FIXME: Remove ? 1487 MemberSpecializationInfo * 1488 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1489 assert(Var->isStaticDataMember() && "Not a static data member"); 1490 return getTemplateOrSpecializationInfo(Var) 1491 .dyn_cast<MemberSpecializationInfo *>(); 1492 } 1493 1494 ASTContext::TemplateOrSpecializationInfo 1495 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1496 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1497 TemplateOrInstantiation.find(Var); 1498 if (Pos == TemplateOrInstantiation.end()) 1499 return {}; 1500 1501 return Pos->second; 1502 } 1503 1504 void 1505 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1506 TemplateSpecializationKind TSK, 1507 SourceLocation PointOfInstantiation) { 1508 assert(Inst->isStaticDataMember() && "Not a static data member"); 1509 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1510 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1511 Tmpl, TSK, PointOfInstantiation)); 1512 } 1513 1514 void 1515 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1516 TemplateOrSpecializationInfo TSI) { 1517 assert(!TemplateOrInstantiation[Inst] && 1518 "Already noted what the variable was instantiated from"); 1519 TemplateOrInstantiation[Inst] = TSI; 1520 } 1521 1522 NamedDecl * 1523 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1524 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1525 if (Pos == InstantiatedFromUsingDecl.end()) 1526 return nullptr; 1527 1528 return Pos->second; 1529 } 1530 1531 void 1532 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1533 assert((isa<UsingDecl>(Pattern) || 1534 isa<UnresolvedUsingValueDecl>(Pattern) || 1535 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1536 "pattern decl is not a using decl"); 1537 assert((isa<UsingDecl>(Inst) || 1538 isa<UnresolvedUsingValueDecl>(Inst) || 1539 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1540 "instantiation did not produce a using decl"); 1541 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1542 InstantiatedFromUsingDecl[Inst] = Pattern; 1543 } 1544 1545 UsingShadowDecl * 1546 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1547 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1548 = InstantiatedFromUsingShadowDecl.find(Inst); 1549 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1550 return nullptr; 1551 1552 return Pos->second; 1553 } 1554 1555 void 1556 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1557 UsingShadowDecl *Pattern) { 1558 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1559 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1560 } 1561 1562 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1563 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1564 = InstantiatedFromUnnamedFieldDecl.find(Field); 1565 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1566 return nullptr; 1567 1568 return Pos->second; 1569 } 1570 1571 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1572 FieldDecl *Tmpl) { 1573 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1574 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1575 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1576 "Already noted what unnamed field was instantiated from"); 1577 1578 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1579 } 1580 1581 ASTContext::overridden_cxx_method_iterator 1582 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1583 return overridden_methods(Method).begin(); 1584 } 1585 1586 ASTContext::overridden_cxx_method_iterator 1587 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1588 return overridden_methods(Method).end(); 1589 } 1590 1591 unsigned 1592 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1593 auto Range = overridden_methods(Method); 1594 return Range.end() - Range.begin(); 1595 } 1596 1597 ASTContext::overridden_method_range 1598 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1599 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1600 OverriddenMethods.find(Method->getCanonicalDecl()); 1601 if (Pos == OverriddenMethods.end()) 1602 return overridden_method_range(nullptr, nullptr); 1603 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1604 } 1605 1606 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1607 const CXXMethodDecl *Overridden) { 1608 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1609 OverriddenMethods[Method].push_back(Overridden); 1610 } 1611 1612 void ASTContext::getOverriddenMethods( 1613 const NamedDecl *D, 1614 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1615 assert(D); 1616 1617 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1618 Overridden.append(overridden_methods_begin(CXXMethod), 1619 overridden_methods_end(CXXMethod)); 1620 return; 1621 } 1622 1623 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1624 if (!Method) 1625 return; 1626 1627 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1628 Method->getOverriddenMethods(OverDecls); 1629 Overridden.append(OverDecls.begin(), OverDecls.end()); 1630 } 1631 1632 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1633 assert(!Import->getNextLocalImport() && 1634 "Import declaration already in the chain"); 1635 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1636 if (!FirstLocalImport) { 1637 FirstLocalImport = Import; 1638 LastLocalImport = Import; 1639 return; 1640 } 1641 1642 LastLocalImport->setNextLocalImport(Import); 1643 LastLocalImport = Import; 1644 } 1645 1646 //===----------------------------------------------------------------------===// 1647 // Type Sizing and Analysis 1648 //===----------------------------------------------------------------------===// 1649 1650 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1651 /// scalar floating point type. 1652 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1653 switch (T->castAs<BuiltinType>()->getKind()) { 1654 default: 1655 llvm_unreachable("Not a floating point type!"); 1656 case BuiltinType::BFloat16: 1657 return Target->getBFloat16Format(); 1658 case BuiltinType::Float16: 1659 case BuiltinType::Half: 1660 return Target->getHalfFormat(); 1661 case BuiltinType::Float: return Target->getFloatFormat(); 1662 case BuiltinType::Double: return Target->getDoubleFormat(); 1663 case BuiltinType::LongDouble: 1664 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1665 return AuxTarget->getLongDoubleFormat(); 1666 return Target->getLongDoubleFormat(); 1667 case BuiltinType::Float128: 1668 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1669 return AuxTarget->getFloat128Format(); 1670 return Target->getFloat128Format(); 1671 } 1672 } 1673 1674 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1675 unsigned Align = Target->getCharWidth(); 1676 1677 bool UseAlignAttrOnly = false; 1678 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1679 Align = AlignFromAttr; 1680 1681 // __attribute__((aligned)) can increase or decrease alignment 1682 // *except* on a struct or struct member, where it only increases 1683 // alignment unless 'packed' is also specified. 1684 // 1685 // It is an error for alignas to decrease alignment, so we can 1686 // ignore that possibility; Sema should diagnose it. 1687 if (isa<FieldDecl>(D)) { 1688 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1689 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1690 } else { 1691 UseAlignAttrOnly = true; 1692 } 1693 } 1694 else if (isa<FieldDecl>(D)) 1695 UseAlignAttrOnly = 1696 D->hasAttr<PackedAttr>() || 1697 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1698 1699 // If we're using the align attribute only, just ignore everything 1700 // else about the declaration and its type. 1701 if (UseAlignAttrOnly) { 1702 // do nothing 1703 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1704 QualType T = VD->getType(); 1705 if (const auto *RT = T->getAs<ReferenceType>()) { 1706 if (ForAlignof) 1707 T = RT->getPointeeType(); 1708 else 1709 T = getPointerType(RT->getPointeeType()); 1710 } 1711 QualType BaseT = getBaseElementType(T); 1712 if (T->isFunctionType()) 1713 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1714 else if (!BaseT->isIncompleteType()) { 1715 // Adjust alignments of declarations with array type by the 1716 // large-array alignment on the target. 1717 if (const ArrayType *arrayType = getAsArrayType(T)) { 1718 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1719 if (!ForAlignof && MinWidth) { 1720 if (isa<VariableArrayType>(arrayType)) 1721 Align = std::max(Align, Target->getLargeArrayAlign()); 1722 else if (isa<ConstantArrayType>(arrayType) && 1723 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1724 Align = std::max(Align, Target->getLargeArrayAlign()); 1725 } 1726 } 1727 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1728 if (BaseT.getQualifiers().hasUnaligned()) 1729 Align = Target->getCharWidth(); 1730 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1731 if (VD->hasGlobalStorage() && !ForAlignof) { 1732 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1733 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1734 } 1735 } 1736 } 1737 1738 // Fields can be subject to extra alignment constraints, like if 1739 // the field is packed, the struct is packed, or the struct has a 1740 // a max-field-alignment constraint (#pragma pack). So calculate 1741 // the actual alignment of the field within the struct, and then 1742 // (as we're expected to) constrain that by the alignment of the type. 1743 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1744 const RecordDecl *Parent = Field->getParent(); 1745 // We can only produce a sensible answer if the record is valid. 1746 if (!Parent->isInvalidDecl()) { 1747 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1748 1749 // Start with the record's overall alignment. 1750 unsigned FieldAlign = toBits(Layout.getAlignment()); 1751 1752 // Use the GCD of that and the offset within the record. 1753 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1754 if (Offset > 0) { 1755 // Alignment is always a power of 2, so the GCD will be a power of 2, 1756 // which means we get to do this crazy thing instead of Euclid's. 1757 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1758 if (LowBitOfOffset < FieldAlign) 1759 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1760 } 1761 1762 Align = std::min(Align, FieldAlign); 1763 } 1764 } 1765 } 1766 1767 return toCharUnitsFromBits(Align); 1768 } 1769 1770 CharUnits ASTContext::getExnObjectAlignment() const { 1771 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1772 } 1773 1774 // getTypeInfoDataSizeInChars - Return the size of a type, in 1775 // chars. If the type is a record, its data size is returned. This is 1776 // the size of the memcpy that's performed when assigning this type 1777 // using a trivial copy/move assignment operator. 1778 std::pair<CharUnits, CharUnits> 1779 ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1780 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1781 1782 // In C++, objects can sometimes be allocated into the tail padding 1783 // of a base-class subobject. We decide whether that's possible 1784 // during class layout, so here we can just trust the layout results. 1785 if (getLangOpts().CPlusPlus) { 1786 if (const auto *RT = T->getAs<RecordType>()) { 1787 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1788 sizeAndAlign.first = layout.getDataSize(); 1789 } 1790 } 1791 1792 return sizeAndAlign; 1793 } 1794 1795 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1796 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1797 std::pair<CharUnits, CharUnits> 1798 static getConstantArrayInfoInChars(const ASTContext &Context, 1799 const ConstantArrayType *CAT) { 1800 std::pair<CharUnits, CharUnits> EltInfo = 1801 Context.getTypeInfoInChars(CAT->getElementType()); 1802 uint64_t Size = CAT->getSize().getZExtValue(); 1803 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1804 (uint64_t)(-1)/Size) && 1805 "Overflow in array type char size evaluation"); 1806 uint64_t Width = EltInfo.first.getQuantity() * Size; 1807 unsigned Align = EltInfo.second.getQuantity(); 1808 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1809 Context.getTargetInfo().getPointerWidth(0) == 64) 1810 Width = llvm::alignTo(Width, Align); 1811 return std::make_pair(CharUnits::fromQuantity(Width), 1812 CharUnits::fromQuantity(Align)); 1813 } 1814 1815 std::pair<CharUnits, CharUnits> 1816 ASTContext::getTypeInfoInChars(const Type *T) const { 1817 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1818 return getConstantArrayInfoInChars(*this, CAT); 1819 TypeInfo Info = getTypeInfo(T); 1820 return std::make_pair(toCharUnitsFromBits(Info.Width), 1821 toCharUnitsFromBits(Info.Align)); 1822 } 1823 1824 std::pair<CharUnits, CharUnits> 1825 ASTContext::getTypeInfoInChars(QualType T) const { 1826 return getTypeInfoInChars(T.getTypePtr()); 1827 } 1828 1829 bool ASTContext::isAlignmentRequired(const Type *T) const { 1830 return getTypeInfo(T).AlignIsRequired; 1831 } 1832 1833 bool ASTContext::isAlignmentRequired(QualType T) const { 1834 return isAlignmentRequired(T.getTypePtr()); 1835 } 1836 1837 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const { 1838 // An alignment on a typedef overrides anything else. 1839 if (const auto *TT = T->getAs<TypedefType>()) 1840 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1841 return Align; 1842 1843 // If we have an (array of) complete type, we're done. 1844 T = getBaseElementType(T); 1845 if (!T->isIncompleteType()) 1846 return getTypeAlign(T); 1847 1848 // If we had an array type, its element type might be a typedef 1849 // type with an alignment attribute. 1850 if (const auto *TT = T->getAs<TypedefType>()) 1851 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1852 return Align; 1853 1854 // Otherwise, see if the declaration of the type had an attribute. 1855 if (const auto *TT = T->getAs<TagType>()) 1856 return TT->getDecl()->getMaxAlignment(); 1857 1858 return 0; 1859 } 1860 1861 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1862 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1863 if (I != MemoizedTypeInfo.end()) 1864 return I->second; 1865 1866 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1867 TypeInfo TI = getTypeInfoImpl(T); 1868 MemoizedTypeInfo[T] = TI; 1869 return TI; 1870 } 1871 1872 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1873 /// method does not work on incomplete types. 1874 /// 1875 /// FIXME: Pointers into different addr spaces could have different sizes and 1876 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1877 /// should take a QualType, &c. 1878 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1879 uint64_t Width = 0; 1880 unsigned Align = 8; 1881 bool AlignIsRequired = false; 1882 unsigned AS = 0; 1883 switch (T->getTypeClass()) { 1884 #define TYPE(Class, Base) 1885 #define ABSTRACT_TYPE(Class, Base) 1886 #define NON_CANONICAL_TYPE(Class, Base) 1887 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1888 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1889 case Type::Class: \ 1890 assert(!T->isDependentType() && "should not see dependent types here"); \ 1891 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1892 #include "clang/AST/TypeNodes.inc" 1893 llvm_unreachable("Should not see dependent types"); 1894 1895 case Type::FunctionNoProto: 1896 case Type::FunctionProto: 1897 // GCC extension: alignof(function) = 32 bits 1898 Width = 0; 1899 Align = 32; 1900 break; 1901 1902 case Type::IncompleteArray: 1903 case Type::VariableArray: 1904 case Type::ConstantArray: { 1905 // Model non-constant sized arrays as size zero, but track the alignment. 1906 uint64_t Size = 0; 1907 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1908 Size = CAT->getSize().getZExtValue(); 1909 1910 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1911 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1912 "Overflow in array type bit size evaluation"); 1913 Width = EltInfo.Width * Size; 1914 Align = EltInfo.Align; 1915 AlignIsRequired = EltInfo.AlignIsRequired; 1916 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1917 getTargetInfo().getPointerWidth(0) == 64) 1918 Width = llvm::alignTo(Width, Align); 1919 break; 1920 } 1921 1922 case Type::ExtVector: 1923 case Type::Vector: { 1924 const auto *VT = cast<VectorType>(T); 1925 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1926 Width = EltInfo.Width * VT->getNumElements(); 1927 Align = Width; 1928 // If the alignment is not a power of 2, round up to the next power of 2. 1929 // This happens for non-power-of-2 length vectors. 1930 if (Align & (Align-1)) { 1931 Align = llvm::NextPowerOf2(Align); 1932 Width = llvm::alignTo(Width, Align); 1933 } 1934 // Adjust the alignment based on the target max. 1935 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1936 if (TargetVectorAlign && TargetVectorAlign < Align) 1937 Align = TargetVectorAlign; 1938 break; 1939 } 1940 1941 case Type::ConstantMatrix: { 1942 const auto *MT = cast<ConstantMatrixType>(T); 1943 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 1944 // The internal layout of a matrix value is implementation defined. 1945 // Initially be ABI compatible with arrays with respect to alignment and 1946 // size. 1947 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 1948 Align = ElementInfo.Align; 1949 break; 1950 } 1951 1952 case Type::Builtin: 1953 switch (cast<BuiltinType>(T)->getKind()) { 1954 default: llvm_unreachable("Unknown builtin type!"); 1955 case BuiltinType::Void: 1956 // GCC extension: alignof(void) = 8 bits. 1957 Width = 0; 1958 Align = 8; 1959 break; 1960 case BuiltinType::Bool: 1961 Width = Target->getBoolWidth(); 1962 Align = Target->getBoolAlign(); 1963 break; 1964 case BuiltinType::Char_S: 1965 case BuiltinType::Char_U: 1966 case BuiltinType::UChar: 1967 case BuiltinType::SChar: 1968 case BuiltinType::Char8: 1969 Width = Target->getCharWidth(); 1970 Align = Target->getCharAlign(); 1971 break; 1972 case BuiltinType::WChar_S: 1973 case BuiltinType::WChar_U: 1974 Width = Target->getWCharWidth(); 1975 Align = Target->getWCharAlign(); 1976 break; 1977 case BuiltinType::Char16: 1978 Width = Target->getChar16Width(); 1979 Align = Target->getChar16Align(); 1980 break; 1981 case BuiltinType::Char32: 1982 Width = Target->getChar32Width(); 1983 Align = Target->getChar32Align(); 1984 break; 1985 case BuiltinType::UShort: 1986 case BuiltinType::Short: 1987 Width = Target->getShortWidth(); 1988 Align = Target->getShortAlign(); 1989 break; 1990 case BuiltinType::UInt: 1991 case BuiltinType::Int: 1992 Width = Target->getIntWidth(); 1993 Align = Target->getIntAlign(); 1994 break; 1995 case BuiltinType::ULong: 1996 case BuiltinType::Long: 1997 Width = Target->getLongWidth(); 1998 Align = Target->getLongAlign(); 1999 break; 2000 case BuiltinType::ULongLong: 2001 case BuiltinType::LongLong: 2002 Width = Target->getLongLongWidth(); 2003 Align = Target->getLongLongAlign(); 2004 break; 2005 case BuiltinType::Int128: 2006 case BuiltinType::UInt128: 2007 Width = 128; 2008 Align = 128; // int128_t is 128-bit aligned on all targets. 2009 break; 2010 case BuiltinType::ShortAccum: 2011 case BuiltinType::UShortAccum: 2012 case BuiltinType::SatShortAccum: 2013 case BuiltinType::SatUShortAccum: 2014 Width = Target->getShortAccumWidth(); 2015 Align = Target->getShortAccumAlign(); 2016 break; 2017 case BuiltinType::Accum: 2018 case BuiltinType::UAccum: 2019 case BuiltinType::SatAccum: 2020 case BuiltinType::SatUAccum: 2021 Width = Target->getAccumWidth(); 2022 Align = Target->getAccumAlign(); 2023 break; 2024 case BuiltinType::LongAccum: 2025 case BuiltinType::ULongAccum: 2026 case BuiltinType::SatLongAccum: 2027 case BuiltinType::SatULongAccum: 2028 Width = Target->getLongAccumWidth(); 2029 Align = Target->getLongAccumAlign(); 2030 break; 2031 case BuiltinType::ShortFract: 2032 case BuiltinType::UShortFract: 2033 case BuiltinType::SatShortFract: 2034 case BuiltinType::SatUShortFract: 2035 Width = Target->getShortFractWidth(); 2036 Align = Target->getShortFractAlign(); 2037 break; 2038 case BuiltinType::Fract: 2039 case BuiltinType::UFract: 2040 case BuiltinType::SatFract: 2041 case BuiltinType::SatUFract: 2042 Width = Target->getFractWidth(); 2043 Align = Target->getFractAlign(); 2044 break; 2045 case BuiltinType::LongFract: 2046 case BuiltinType::ULongFract: 2047 case BuiltinType::SatLongFract: 2048 case BuiltinType::SatULongFract: 2049 Width = Target->getLongFractWidth(); 2050 Align = Target->getLongFractAlign(); 2051 break; 2052 case BuiltinType::BFloat16: 2053 Width = Target->getBFloat16Width(); 2054 Align = Target->getBFloat16Align(); 2055 break; 2056 case BuiltinType::Float16: 2057 case BuiltinType::Half: 2058 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2059 !getLangOpts().OpenMPIsDevice) { 2060 Width = Target->getHalfWidth(); 2061 Align = Target->getHalfAlign(); 2062 } else { 2063 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2064 "Expected OpenMP device compilation."); 2065 Width = AuxTarget->getHalfWidth(); 2066 Align = AuxTarget->getHalfAlign(); 2067 } 2068 break; 2069 case BuiltinType::Float: 2070 Width = Target->getFloatWidth(); 2071 Align = Target->getFloatAlign(); 2072 break; 2073 case BuiltinType::Double: 2074 Width = Target->getDoubleWidth(); 2075 Align = Target->getDoubleAlign(); 2076 break; 2077 case BuiltinType::LongDouble: 2078 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2079 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2080 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2081 Width = AuxTarget->getLongDoubleWidth(); 2082 Align = AuxTarget->getLongDoubleAlign(); 2083 } else { 2084 Width = Target->getLongDoubleWidth(); 2085 Align = Target->getLongDoubleAlign(); 2086 } 2087 break; 2088 case BuiltinType::Float128: 2089 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2090 !getLangOpts().OpenMPIsDevice) { 2091 Width = Target->getFloat128Width(); 2092 Align = Target->getFloat128Align(); 2093 } else { 2094 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2095 "Expected OpenMP device compilation."); 2096 Width = AuxTarget->getFloat128Width(); 2097 Align = AuxTarget->getFloat128Align(); 2098 } 2099 break; 2100 case BuiltinType::NullPtr: 2101 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2102 Align = Target->getPointerAlign(0); // == sizeof(void*) 2103 break; 2104 case BuiltinType::ObjCId: 2105 case BuiltinType::ObjCClass: 2106 case BuiltinType::ObjCSel: 2107 Width = Target->getPointerWidth(0); 2108 Align = Target->getPointerAlign(0); 2109 break; 2110 case BuiltinType::OCLSampler: 2111 case BuiltinType::OCLEvent: 2112 case BuiltinType::OCLClkEvent: 2113 case BuiltinType::OCLQueue: 2114 case BuiltinType::OCLReserveID: 2115 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2116 case BuiltinType::Id: 2117 #include "clang/Basic/OpenCLImageTypes.def" 2118 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2119 case BuiltinType::Id: 2120 #include "clang/Basic/OpenCLExtensionTypes.def" 2121 AS = getTargetAddressSpace( 2122 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2123 Width = Target->getPointerWidth(AS); 2124 Align = Target->getPointerAlign(AS); 2125 break; 2126 // The SVE types are effectively target-specific. The length of an 2127 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2128 // of 128 bits. There is one predicate bit for each vector byte, so the 2129 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2130 // 2131 // Because the length is only known at runtime, we use a dummy value 2132 // of 0 for the static length. The alignment values are those defined 2133 // by the Procedure Call Standard for the Arm Architecture. 2134 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2135 IsSigned, IsFP, IsBF) \ 2136 case BuiltinType::Id: \ 2137 Width = 0; \ 2138 Align = 128; \ 2139 break; 2140 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2141 case BuiltinType::Id: \ 2142 Width = 0; \ 2143 Align = 16; \ 2144 break; 2145 #include "clang/Basic/AArch64SVEACLETypes.def" 2146 } 2147 break; 2148 case Type::ObjCObjectPointer: 2149 Width = Target->getPointerWidth(0); 2150 Align = Target->getPointerAlign(0); 2151 break; 2152 case Type::BlockPointer: 2153 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2154 Width = Target->getPointerWidth(AS); 2155 Align = Target->getPointerAlign(AS); 2156 break; 2157 case Type::LValueReference: 2158 case Type::RValueReference: 2159 // alignof and sizeof should never enter this code path here, so we go 2160 // the pointer route. 2161 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2162 Width = Target->getPointerWidth(AS); 2163 Align = Target->getPointerAlign(AS); 2164 break; 2165 case Type::Pointer: 2166 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2167 Width = Target->getPointerWidth(AS); 2168 Align = Target->getPointerAlign(AS); 2169 break; 2170 case Type::MemberPointer: { 2171 const auto *MPT = cast<MemberPointerType>(T); 2172 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2173 Width = MPI.Width; 2174 Align = MPI.Align; 2175 break; 2176 } 2177 case Type::Complex: { 2178 // Complex types have the same alignment as their elements, but twice the 2179 // size. 2180 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2181 Width = EltInfo.Width * 2; 2182 Align = EltInfo.Align; 2183 break; 2184 } 2185 case Type::ObjCObject: 2186 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2187 case Type::Adjusted: 2188 case Type::Decayed: 2189 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2190 case Type::ObjCInterface: { 2191 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2192 if (ObjCI->getDecl()->isInvalidDecl()) { 2193 Width = 8; 2194 Align = 8; 2195 break; 2196 } 2197 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2198 Width = toBits(Layout.getSize()); 2199 Align = toBits(Layout.getAlignment()); 2200 break; 2201 } 2202 case Type::ExtInt: { 2203 const auto *EIT = cast<ExtIntType>(T); 2204 Align = 2205 std::min(static_cast<unsigned>(std::max( 2206 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2207 Target->getLongLongAlign()); 2208 Width = llvm::alignTo(EIT->getNumBits(), Align); 2209 break; 2210 } 2211 case Type::Record: 2212 case Type::Enum: { 2213 const auto *TT = cast<TagType>(T); 2214 2215 if (TT->getDecl()->isInvalidDecl()) { 2216 Width = 8; 2217 Align = 8; 2218 break; 2219 } 2220 2221 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2222 const EnumDecl *ED = ET->getDecl(); 2223 TypeInfo Info = 2224 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2225 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2226 Info.Align = AttrAlign; 2227 Info.AlignIsRequired = true; 2228 } 2229 return Info; 2230 } 2231 2232 const auto *RT = cast<RecordType>(TT); 2233 const RecordDecl *RD = RT->getDecl(); 2234 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2235 Width = toBits(Layout.getSize()); 2236 Align = toBits(Layout.getAlignment()); 2237 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 2238 break; 2239 } 2240 2241 case Type::SubstTemplateTypeParm: 2242 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2243 getReplacementType().getTypePtr()); 2244 2245 case Type::Auto: 2246 case Type::DeducedTemplateSpecialization: { 2247 const auto *A = cast<DeducedType>(T); 2248 assert(!A->getDeducedType().isNull() && 2249 "cannot request the size of an undeduced or dependent auto type"); 2250 return getTypeInfo(A->getDeducedType().getTypePtr()); 2251 } 2252 2253 case Type::Paren: 2254 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2255 2256 case Type::MacroQualified: 2257 return getTypeInfo( 2258 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2259 2260 case Type::ObjCTypeParam: 2261 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2262 2263 case Type::Typedef: { 2264 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2265 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2266 // If the typedef has an aligned attribute on it, it overrides any computed 2267 // alignment we have. This violates the GCC documentation (which says that 2268 // attribute(aligned) can only round up) but matches its implementation. 2269 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2270 Align = AttrAlign; 2271 AlignIsRequired = true; 2272 } else { 2273 Align = Info.Align; 2274 AlignIsRequired = Info.AlignIsRequired; 2275 } 2276 Width = Info.Width; 2277 break; 2278 } 2279 2280 case Type::Elaborated: 2281 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2282 2283 case Type::Attributed: 2284 return getTypeInfo( 2285 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2286 2287 case Type::Atomic: { 2288 // Start with the base type information. 2289 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2290 Width = Info.Width; 2291 Align = Info.Align; 2292 2293 if (!Width) { 2294 // An otherwise zero-sized type should still generate an 2295 // atomic operation. 2296 Width = Target->getCharWidth(); 2297 assert(Align); 2298 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2299 // If the size of the type doesn't exceed the platform's max 2300 // atomic promotion width, make the size and alignment more 2301 // favorable to atomic operations: 2302 2303 // Round the size up to a power of 2. 2304 if (!llvm::isPowerOf2_64(Width)) 2305 Width = llvm::NextPowerOf2(Width); 2306 2307 // Set the alignment equal to the size. 2308 Align = static_cast<unsigned>(Width); 2309 } 2310 } 2311 break; 2312 2313 case Type::Pipe: 2314 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2315 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2316 break; 2317 } 2318 2319 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2320 return TypeInfo(Width, Align, AlignIsRequired); 2321 } 2322 2323 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2324 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2325 if (I != MemoizedUnadjustedAlign.end()) 2326 return I->second; 2327 2328 unsigned UnadjustedAlign; 2329 if (const auto *RT = T->getAs<RecordType>()) { 2330 const RecordDecl *RD = RT->getDecl(); 2331 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2332 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2333 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2334 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2335 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2336 } else { 2337 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2338 } 2339 2340 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2341 return UnadjustedAlign; 2342 } 2343 2344 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2345 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2346 // Target ppc64 with QPX: simd default alignment for pointer to double is 32. 2347 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 || 2348 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) && 2349 getTargetInfo().getABI() == "elfv1-qpx" && 2350 T->isSpecificBuiltinType(BuiltinType::Double)) 2351 SimdAlign = 256; 2352 return SimdAlign; 2353 } 2354 2355 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2356 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2357 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2358 } 2359 2360 /// toBits - Convert a size in characters to a size in characters. 2361 int64_t ASTContext::toBits(CharUnits CharSize) const { 2362 return CharSize.getQuantity() * getCharWidth(); 2363 } 2364 2365 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2366 /// This method does not work on incomplete types. 2367 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2368 return getTypeInfoInChars(T).first; 2369 } 2370 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2371 return getTypeInfoInChars(T).first; 2372 } 2373 2374 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2375 /// characters. This method does not work on incomplete types. 2376 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2377 return toCharUnitsFromBits(getTypeAlign(T)); 2378 } 2379 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2380 return toCharUnitsFromBits(getTypeAlign(T)); 2381 } 2382 2383 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2384 /// type, in characters, before alignment adustments. This method does 2385 /// not work on incomplete types. 2386 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2387 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2388 } 2389 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2390 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2391 } 2392 2393 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2394 /// type for the current target in bits. This can be different than the ABI 2395 /// alignment in cases where it is beneficial for performance to overalign 2396 /// a data type. 2397 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2398 TypeInfo TI = getTypeInfo(T); 2399 unsigned ABIAlign = TI.Align; 2400 2401 T = T->getBaseElementTypeUnsafe(); 2402 2403 // The preferred alignment of member pointers is that of a pointer. 2404 if (T->isMemberPointerType()) 2405 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2406 2407 if (!Target->allowsLargerPreferedTypeAlignment()) 2408 return ABIAlign; 2409 2410 // Double and long long should be naturally aligned if possible. 2411 if (const auto *CT = T->getAs<ComplexType>()) 2412 T = CT->getElementType().getTypePtr(); 2413 if (const auto *ET = T->getAs<EnumType>()) 2414 T = ET->getDecl()->getIntegerType().getTypePtr(); 2415 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2416 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2417 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 2418 // Don't increase the alignment if an alignment attribute was specified on a 2419 // typedef declaration. 2420 if (!TI.AlignIsRequired) 2421 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2422 2423 return ABIAlign; 2424 } 2425 2426 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2427 /// for __attribute__((aligned)) on this target, to be used if no alignment 2428 /// value is specified. 2429 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2430 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2431 } 2432 2433 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2434 /// to a global variable of the specified type. 2435 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2436 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2437 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize)); 2438 } 2439 2440 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2441 /// should be given to a global variable of the specified type. 2442 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2443 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2444 } 2445 2446 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2447 CharUnits Offset = CharUnits::Zero(); 2448 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2449 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2450 Offset += Layout->getBaseClassOffset(Base); 2451 Layout = &getASTRecordLayout(Base); 2452 } 2453 return Offset; 2454 } 2455 2456 /// DeepCollectObjCIvars - 2457 /// This routine first collects all declared, but not synthesized, ivars in 2458 /// super class and then collects all ivars, including those synthesized for 2459 /// current class. This routine is used for implementation of current class 2460 /// when all ivars, declared and synthesized are known. 2461 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2462 bool leafClass, 2463 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2464 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2465 DeepCollectObjCIvars(SuperClass, false, Ivars); 2466 if (!leafClass) { 2467 for (const auto *I : OI->ivars()) 2468 Ivars.push_back(I); 2469 } else { 2470 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2471 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2472 Iv= Iv->getNextIvar()) 2473 Ivars.push_back(Iv); 2474 } 2475 } 2476 2477 /// CollectInheritedProtocols - Collect all protocols in current class and 2478 /// those inherited by it. 2479 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2480 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2481 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2482 // We can use protocol_iterator here instead of 2483 // all_referenced_protocol_iterator since we are walking all categories. 2484 for (auto *Proto : OI->all_referenced_protocols()) { 2485 CollectInheritedProtocols(Proto, Protocols); 2486 } 2487 2488 // Categories of this Interface. 2489 for (const auto *Cat : OI->visible_categories()) 2490 CollectInheritedProtocols(Cat, Protocols); 2491 2492 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2493 while (SD) { 2494 CollectInheritedProtocols(SD, Protocols); 2495 SD = SD->getSuperClass(); 2496 } 2497 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2498 for (auto *Proto : OC->protocols()) { 2499 CollectInheritedProtocols(Proto, Protocols); 2500 } 2501 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2502 // Insert the protocol. 2503 if (!Protocols.insert( 2504 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2505 return; 2506 2507 for (auto *Proto : OP->protocols()) 2508 CollectInheritedProtocols(Proto, Protocols); 2509 } 2510 } 2511 2512 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2513 const RecordDecl *RD) { 2514 assert(RD->isUnion() && "Must be union type"); 2515 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2516 2517 for (const auto *Field : RD->fields()) { 2518 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2519 return false; 2520 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2521 if (FieldSize != UnionSize) 2522 return false; 2523 } 2524 return !RD->field_empty(); 2525 } 2526 2527 static bool isStructEmpty(QualType Ty) { 2528 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2529 2530 if (!RD->field_empty()) 2531 return false; 2532 2533 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2534 return ClassDecl->isEmpty(); 2535 2536 return true; 2537 } 2538 2539 static llvm::Optional<int64_t> 2540 structHasUniqueObjectRepresentations(const ASTContext &Context, 2541 const RecordDecl *RD) { 2542 assert(!RD->isUnion() && "Must be struct/class type"); 2543 const auto &Layout = Context.getASTRecordLayout(RD); 2544 2545 int64_t CurOffsetInBits = 0; 2546 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2547 if (ClassDecl->isDynamicClass()) 2548 return llvm::None; 2549 2550 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2551 for (const auto &Base : ClassDecl->bases()) { 2552 // Empty types can be inherited from, and non-empty types can potentially 2553 // have tail padding, so just make sure there isn't an error. 2554 if (!isStructEmpty(Base.getType())) { 2555 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2556 Context, Base.getType()->castAs<RecordType>()->getDecl()); 2557 if (!Size) 2558 return llvm::None; 2559 Bases.emplace_back(Base.getType(), Size.getValue()); 2560 } 2561 } 2562 2563 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, 2564 const std::pair<QualType, int64_t> &R) { 2565 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2566 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2567 }); 2568 2569 for (const auto &Base : Bases) { 2570 int64_t BaseOffset = Context.toBits( 2571 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2572 int64_t BaseSize = Base.second; 2573 if (BaseOffset != CurOffsetInBits) 2574 return llvm::None; 2575 CurOffsetInBits = BaseOffset + BaseSize; 2576 } 2577 } 2578 2579 for (const auto *Field : RD->fields()) { 2580 if (!Field->getType()->isReferenceType() && 2581 !Context.hasUniqueObjectRepresentations(Field->getType())) 2582 return llvm::None; 2583 2584 int64_t FieldSizeInBits = 2585 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2586 if (Field->isBitField()) { 2587 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2588 2589 if (BitfieldSize > FieldSizeInBits) 2590 return llvm::None; 2591 FieldSizeInBits = BitfieldSize; 2592 } 2593 2594 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2595 2596 if (FieldOffsetInBits != CurOffsetInBits) 2597 return llvm::None; 2598 2599 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2600 } 2601 2602 return CurOffsetInBits; 2603 } 2604 2605 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2606 // C++17 [meta.unary.prop]: 2607 // The predicate condition for a template specialization 2608 // has_unique_object_representations<T> shall be 2609 // satisfied if and only if: 2610 // (9.1) - T is trivially copyable, and 2611 // (9.2) - any two objects of type T with the same value have the same 2612 // object representation, where two objects 2613 // of array or non-union class type are considered to have the same value 2614 // if their respective sequences of 2615 // direct subobjects have the same values, and two objects of union type 2616 // are considered to have the same 2617 // value if they have the same active member and the corresponding members 2618 // have the same value. 2619 // The set of scalar types for which this condition holds is 2620 // implementation-defined. [ Note: If a type has padding 2621 // bits, the condition does not hold; otherwise, the condition holds true 2622 // for unsigned integral types. -- end note ] 2623 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2624 2625 // Arrays are unique only if their element type is unique. 2626 if (Ty->isArrayType()) 2627 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2628 2629 // (9.1) - T is trivially copyable... 2630 if (!Ty.isTriviallyCopyableType(*this)) 2631 return false; 2632 2633 // All integrals and enums are unique. 2634 if (Ty->isIntegralOrEnumerationType()) 2635 return true; 2636 2637 // All other pointers are unique. 2638 if (Ty->isPointerType()) 2639 return true; 2640 2641 if (Ty->isMemberPointerType()) { 2642 const auto *MPT = Ty->getAs<MemberPointerType>(); 2643 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2644 } 2645 2646 if (Ty->isRecordType()) { 2647 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2648 2649 if (Record->isInvalidDecl()) 2650 return false; 2651 2652 if (Record->isUnion()) 2653 return unionHasUniqueObjectRepresentations(*this, Record); 2654 2655 Optional<int64_t> StructSize = 2656 structHasUniqueObjectRepresentations(*this, Record); 2657 2658 return StructSize && 2659 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2660 } 2661 2662 // FIXME: More cases to handle here (list by rsmith): 2663 // vectors (careful about, eg, vector of 3 foo) 2664 // _Complex int and friends 2665 // _Atomic T 2666 // Obj-C block pointers 2667 // Obj-C object pointers 2668 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2669 // clk_event_t, queue_t, reserve_id_t) 2670 // There're also Obj-C class types and the Obj-C selector type, but I think it 2671 // makes sense for those to return false here. 2672 2673 return false; 2674 } 2675 2676 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2677 unsigned count = 0; 2678 // Count ivars declared in class extension. 2679 for (const auto *Ext : OI->known_extensions()) 2680 count += Ext->ivar_size(); 2681 2682 // Count ivar defined in this class's implementation. This 2683 // includes synthesized ivars. 2684 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2685 count += ImplDecl->ivar_size(); 2686 2687 return count; 2688 } 2689 2690 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2691 if (!E) 2692 return false; 2693 2694 // nullptr_t is always treated as null. 2695 if (E->getType()->isNullPtrType()) return true; 2696 2697 if (E->getType()->isAnyPointerType() && 2698 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2699 Expr::NPC_ValueDependentIsNull)) 2700 return true; 2701 2702 // Unfortunately, __null has type 'int'. 2703 if (isa<GNUNullExpr>(E)) return true; 2704 2705 return false; 2706 } 2707 2708 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2709 /// exists. 2710 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2711 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2712 I = ObjCImpls.find(D); 2713 if (I != ObjCImpls.end()) 2714 return cast<ObjCImplementationDecl>(I->second); 2715 return nullptr; 2716 } 2717 2718 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2719 /// exists. 2720 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2721 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2722 I = ObjCImpls.find(D); 2723 if (I != ObjCImpls.end()) 2724 return cast<ObjCCategoryImplDecl>(I->second); 2725 return nullptr; 2726 } 2727 2728 /// Set the implementation of ObjCInterfaceDecl. 2729 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2730 ObjCImplementationDecl *ImplD) { 2731 assert(IFaceD && ImplD && "Passed null params"); 2732 ObjCImpls[IFaceD] = ImplD; 2733 } 2734 2735 /// Set the implementation of ObjCCategoryDecl. 2736 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2737 ObjCCategoryImplDecl *ImplD) { 2738 assert(CatD && ImplD && "Passed null params"); 2739 ObjCImpls[CatD] = ImplD; 2740 } 2741 2742 const ObjCMethodDecl * 2743 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2744 return ObjCMethodRedecls.lookup(MD); 2745 } 2746 2747 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2748 const ObjCMethodDecl *Redecl) { 2749 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2750 ObjCMethodRedecls[MD] = Redecl; 2751 } 2752 2753 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2754 const NamedDecl *ND) const { 2755 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2756 return ID; 2757 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2758 return CD->getClassInterface(); 2759 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2760 return IMD->getClassInterface(); 2761 2762 return nullptr; 2763 } 2764 2765 /// Get the copy initialization expression of VarDecl, or nullptr if 2766 /// none exists. 2767 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2768 assert(VD && "Passed null params"); 2769 assert(VD->hasAttr<BlocksAttr>() && 2770 "getBlockVarCopyInits - not __block var"); 2771 auto I = BlockVarCopyInits.find(VD); 2772 if (I != BlockVarCopyInits.end()) 2773 return I->second; 2774 return {nullptr, false}; 2775 } 2776 2777 /// Set the copy initialization expression of a block var decl. 2778 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2779 bool CanThrow) { 2780 assert(VD && CopyExpr && "Passed null params"); 2781 assert(VD->hasAttr<BlocksAttr>() && 2782 "setBlockVarCopyInits - not __block var"); 2783 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2784 } 2785 2786 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2787 unsigned DataSize) const { 2788 if (!DataSize) 2789 DataSize = TypeLoc::getFullDataSizeForType(T); 2790 else 2791 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2792 "incorrect data size provided to CreateTypeSourceInfo!"); 2793 2794 auto *TInfo = 2795 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2796 new (TInfo) TypeSourceInfo(T); 2797 return TInfo; 2798 } 2799 2800 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2801 SourceLocation L) const { 2802 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2803 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2804 return DI; 2805 } 2806 2807 const ASTRecordLayout & 2808 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2809 return getObjCLayout(D, nullptr); 2810 } 2811 2812 const ASTRecordLayout & 2813 ASTContext::getASTObjCImplementationLayout( 2814 const ObjCImplementationDecl *D) const { 2815 return getObjCLayout(D->getClassInterface(), D); 2816 } 2817 2818 //===----------------------------------------------------------------------===// 2819 // Type creation/memoization methods 2820 //===----------------------------------------------------------------------===// 2821 2822 QualType 2823 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2824 unsigned fastQuals = quals.getFastQualifiers(); 2825 quals.removeFastQualifiers(); 2826 2827 // Check if we've already instantiated this type. 2828 llvm::FoldingSetNodeID ID; 2829 ExtQuals::Profile(ID, baseType, quals); 2830 void *insertPos = nullptr; 2831 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2832 assert(eq->getQualifiers() == quals); 2833 return QualType(eq, fastQuals); 2834 } 2835 2836 // If the base type is not canonical, make the appropriate canonical type. 2837 QualType canon; 2838 if (!baseType->isCanonicalUnqualified()) { 2839 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2840 canonSplit.Quals.addConsistentQualifiers(quals); 2841 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2842 2843 // Re-find the insert position. 2844 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2845 } 2846 2847 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2848 ExtQualNodes.InsertNode(eq, insertPos); 2849 return QualType(eq, fastQuals); 2850 } 2851 2852 QualType ASTContext::getAddrSpaceQualType(QualType T, 2853 LangAS AddressSpace) const { 2854 QualType CanT = getCanonicalType(T); 2855 if (CanT.getAddressSpace() == AddressSpace) 2856 return T; 2857 2858 // If we are composing extended qualifiers together, merge together 2859 // into one ExtQuals node. 2860 QualifierCollector Quals; 2861 const Type *TypeNode = Quals.strip(T); 2862 2863 // If this type already has an address space specified, it cannot get 2864 // another one. 2865 assert(!Quals.hasAddressSpace() && 2866 "Type cannot be in multiple addr spaces!"); 2867 Quals.addAddressSpace(AddressSpace); 2868 2869 return getExtQualType(TypeNode, Quals); 2870 } 2871 2872 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2873 // If we are composing extended qualifiers together, merge together 2874 // into one ExtQuals node. 2875 QualifierCollector Quals; 2876 const Type *TypeNode = Quals.strip(T); 2877 2878 // If the qualifier doesn't have an address space just return it. 2879 if (!Quals.hasAddressSpace()) 2880 return T; 2881 2882 Quals.removeAddressSpace(); 2883 2884 // Removal of the address space can mean there are no longer any 2885 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 2886 // or required. 2887 if (Quals.hasNonFastQualifiers()) 2888 return getExtQualType(TypeNode, Quals); 2889 else 2890 return QualType(TypeNode, Quals.getFastQualifiers()); 2891 } 2892 2893 QualType ASTContext::getObjCGCQualType(QualType T, 2894 Qualifiers::GC GCAttr) const { 2895 QualType CanT = getCanonicalType(T); 2896 if (CanT.getObjCGCAttr() == GCAttr) 2897 return T; 2898 2899 if (const auto *ptr = T->getAs<PointerType>()) { 2900 QualType Pointee = ptr->getPointeeType(); 2901 if (Pointee->isAnyPointerType()) { 2902 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2903 return getPointerType(ResultType); 2904 } 2905 } 2906 2907 // If we are composing extended qualifiers together, merge together 2908 // into one ExtQuals node. 2909 QualifierCollector Quals; 2910 const Type *TypeNode = Quals.strip(T); 2911 2912 // If this type already has an ObjCGC specified, it cannot get 2913 // another one. 2914 assert(!Quals.hasObjCGCAttr() && 2915 "Type cannot have multiple ObjCGCs!"); 2916 Quals.addObjCGCAttr(GCAttr); 2917 2918 return getExtQualType(TypeNode, Quals); 2919 } 2920 2921 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 2922 if (const PointerType *Ptr = T->getAs<PointerType>()) { 2923 QualType Pointee = Ptr->getPointeeType(); 2924 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 2925 return getPointerType(removeAddrSpaceQualType(Pointee)); 2926 } 2927 } 2928 return T; 2929 } 2930 2931 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2932 FunctionType::ExtInfo Info) { 2933 if (T->getExtInfo() == Info) 2934 return T; 2935 2936 QualType Result; 2937 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2938 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2939 } else { 2940 const auto *FPT = cast<FunctionProtoType>(T); 2941 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2942 EPI.ExtInfo = Info; 2943 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2944 } 2945 2946 return cast<FunctionType>(Result.getTypePtr()); 2947 } 2948 2949 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2950 QualType ResultType) { 2951 FD = FD->getMostRecentDecl(); 2952 while (true) { 2953 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 2954 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2955 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2956 if (FunctionDecl *Next = FD->getPreviousDecl()) 2957 FD = Next; 2958 else 2959 break; 2960 } 2961 if (ASTMutationListener *L = getASTMutationListener()) 2962 L->DeducedReturnType(FD, ResultType); 2963 } 2964 2965 /// Get a function type and produce the equivalent function type with the 2966 /// specified exception specification. Type sugar that can be present on a 2967 /// declaration of a function with an exception specification is permitted 2968 /// and preserved. Other type sugar (for instance, typedefs) is not. 2969 QualType ASTContext::getFunctionTypeWithExceptionSpec( 2970 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 2971 // Might have some parens. 2972 if (const auto *PT = dyn_cast<ParenType>(Orig)) 2973 return getParenType( 2974 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 2975 2976 // Might be wrapped in a macro qualified type. 2977 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 2978 return getMacroQualifiedType( 2979 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 2980 MQT->getMacroIdentifier()); 2981 2982 // Might have a calling-convention attribute. 2983 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 2984 return getAttributedType( 2985 AT->getAttrKind(), 2986 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 2987 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 2988 2989 // Anything else must be a function type. Rebuild it with the new exception 2990 // specification. 2991 const auto *Proto = Orig->castAs<FunctionProtoType>(); 2992 return getFunctionType( 2993 Proto->getReturnType(), Proto->getParamTypes(), 2994 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2995 } 2996 2997 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 2998 QualType U) { 2999 return hasSameType(T, U) || 3000 (getLangOpts().CPlusPlus17 && 3001 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3002 getFunctionTypeWithExceptionSpec(U, EST_None))); 3003 } 3004 3005 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3006 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3007 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3008 SmallVector<QualType, 16> Args(Proto->param_types()); 3009 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3010 Args[i] = removePtrSizeAddrSpace(Args[i]); 3011 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3012 } 3013 3014 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3015 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3016 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3017 } 3018 3019 return T; 3020 } 3021 3022 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3023 return hasSameType(T, U) || 3024 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3025 getFunctionTypeWithoutPtrSizes(U)); 3026 } 3027 3028 void ASTContext::adjustExceptionSpec( 3029 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3030 bool AsWritten) { 3031 // Update the type. 3032 QualType Updated = 3033 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3034 FD->setType(Updated); 3035 3036 if (!AsWritten) 3037 return; 3038 3039 // Update the type in the type source information too. 3040 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3041 // If the type and the type-as-written differ, we may need to update 3042 // the type-as-written too. 3043 if (TSInfo->getType() != FD->getType()) 3044 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3045 3046 // FIXME: When we get proper type location information for exceptions, 3047 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3048 // up the TypeSourceInfo; 3049 assert(TypeLoc::getFullDataSizeForType(Updated) == 3050 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3051 "TypeLoc size mismatch from updating exception specification"); 3052 TSInfo->overrideType(Updated); 3053 } 3054 } 3055 3056 /// getComplexType - Return the uniqued reference to the type for a complex 3057 /// number with the specified element type. 3058 QualType ASTContext::getComplexType(QualType T) const { 3059 // Unique pointers, to guarantee there is only one pointer of a particular 3060 // structure. 3061 llvm::FoldingSetNodeID ID; 3062 ComplexType::Profile(ID, T); 3063 3064 void *InsertPos = nullptr; 3065 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3066 return QualType(CT, 0); 3067 3068 // If the pointee type isn't canonical, this won't be a canonical type either, 3069 // so fill in the canonical type field. 3070 QualType Canonical; 3071 if (!T.isCanonical()) { 3072 Canonical = getComplexType(getCanonicalType(T)); 3073 3074 // Get the new insert position for the node we care about. 3075 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3076 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3077 } 3078 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3079 Types.push_back(New); 3080 ComplexTypes.InsertNode(New, InsertPos); 3081 return QualType(New, 0); 3082 } 3083 3084 /// getPointerType - Return the uniqued reference to the type for a pointer to 3085 /// the specified type. 3086 QualType ASTContext::getPointerType(QualType T) const { 3087 // Unique pointers, to guarantee there is only one pointer of a particular 3088 // structure. 3089 llvm::FoldingSetNodeID ID; 3090 PointerType::Profile(ID, T); 3091 3092 void *InsertPos = nullptr; 3093 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3094 return QualType(PT, 0); 3095 3096 // If the pointee type isn't canonical, this won't be a canonical type either, 3097 // so fill in the canonical type field. 3098 QualType Canonical; 3099 if (!T.isCanonical()) { 3100 Canonical = getPointerType(getCanonicalType(T)); 3101 3102 // Get the new insert position for the node we care about. 3103 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3105 } 3106 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3107 Types.push_back(New); 3108 PointerTypes.InsertNode(New, InsertPos); 3109 return QualType(New, 0); 3110 } 3111 3112 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3113 llvm::FoldingSetNodeID ID; 3114 AdjustedType::Profile(ID, Orig, New); 3115 void *InsertPos = nullptr; 3116 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3117 if (AT) 3118 return QualType(AT, 0); 3119 3120 QualType Canonical = getCanonicalType(New); 3121 3122 // Get the new insert position for the node we care about. 3123 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3124 assert(!AT && "Shouldn't be in the map!"); 3125 3126 AT = new (*this, TypeAlignment) 3127 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3128 Types.push_back(AT); 3129 AdjustedTypes.InsertNode(AT, InsertPos); 3130 return QualType(AT, 0); 3131 } 3132 3133 QualType ASTContext::getDecayedType(QualType T) const { 3134 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3135 3136 QualType Decayed; 3137 3138 // C99 6.7.5.3p7: 3139 // A declaration of a parameter as "array of type" shall be 3140 // adjusted to "qualified pointer to type", where the type 3141 // qualifiers (if any) are those specified within the [ and ] of 3142 // the array type derivation. 3143 if (T->isArrayType()) 3144 Decayed = getArrayDecayedType(T); 3145 3146 // C99 6.7.5.3p8: 3147 // A declaration of a parameter as "function returning type" 3148 // shall be adjusted to "pointer to function returning type", as 3149 // in 6.3.2.1. 3150 if (T->isFunctionType()) 3151 Decayed = getPointerType(T); 3152 3153 llvm::FoldingSetNodeID ID; 3154 AdjustedType::Profile(ID, T, Decayed); 3155 void *InsertPos = nullptr; 3156 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3157 if (AT) 3158 return QualType(AT, 0); 3159 3160 QualType Canonical = getCanonicalType(Decayed); 3161 3162 // Get the new insert position for the node we care about. 3163 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3164 assert(!AT && "Shouldn't be in the map!"); 3165 3166 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3167 Types.push_back(AT); 3168 AdjustedTypes.InsertNode(AT, InsertPos); 3169 return QualType(AT, 0); 3170 } 3171 3172 /// getBlockPointerType - Return the uniqued reference to the type for 3173 /// a pointer to the specified block. 3174 QualType ASTContext::getBlockPointerType(QualType T) const { 3175 assert(T->isFunctionType() && "block of function types only"); 3176 // Unique pointers, to guarantee there is only one block of a particular 3177 // structure. 3178 llvm::FoldingSetNodeID ID; 3179 BlockPointerType::Profile(ID, T); 3180 3181 void *InsertPos = nullptr; 3182 if (BlockPointerType *PT = 3183 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3184 return QualType(PT, 0); 3185 3186 // If the block pointee type isn't canonical, this won't be a canonical 3187 // type either so fill in the canonical type field. 3188 QualType Canonical; 3189 if (!T.isCanonical()) { 3190 Canonical = getBlockPointerType(getCanonicalType(T)); 3191 3192 // Get the new insert position for the node we care about. 3193 BlockPointerType *NewIP = 3194 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3195 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3196 } 3197 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3198 Types.push_back(New); 3199 BlockPointerTypes.InsertNode(New, InsertPos); 3200 return QualType(New, 0); 3201 } 3202 3203 /// getLValueReferenceType - Return the uniqued reference to the type for an 3204 /// lvalue reference to the specified type. 3205 QualType 3206 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3207 assert(getCanonicalType(T) != OverloadTy && 3208 "Unresolved overloaded function type"); 3209 3210 // Unique pointers, to guarantee there is only one pointer of a particular 3211 // structure. 3212 llvm::FoldingSetNodeID ID; 3213 ReferenceType::Profile(ID, T, SpelledAsLValue); 3214 3215 void *InsertPos = nullptr; 3216 if (LValueReferenceType *RT = 3217 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3218 return QualType(RT, 0); 3219 3220 const auto *InnerRef = T->getAs<ReferenceType>(); 3221 3222 // If the referencee type isn't canonical, this won't be a canonical type 3223 // either, so fill in the canonical type field. 3224 QualType Canonical; 3225 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3226 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3227 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3228 3229 // Get the new insert position for the node we care about. 3230 LValueReferenceType *NewIP = 3231 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3232 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3233 } 3234 3235 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3236 SpelledAsLValue); 3237 Types.push_back(New); 3238 LValueReferenceTypes.InsertNode(New, InsertPos); 3239 3240 return QualType(New, 0); 3241 } 3242 3243 /// getRValueReferenceType - Return the uniqued reference to the type for an 3244 /// rvalue reference to the specified type. 3245 QualType ASTContext::getRValueReferenceType(QualType T) const { 3246 // Unique pointers, to guarantee there is only one pointer of a particular 3247 // structure. 3248 llvm::FoldingSetNodeID ID; 3249 ReferenceType::Profile(ID, T, false); 3250 3251 void *InsertPos = nullptr; 3252 if (RValueReferenceType *RT = 3253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3254 return QualType(RT, 0); 3255 3256 const auto *InnerRef = T->getAs<ReferenceType>(); 3257 3258 // If the referencee type isn't canonical, this won't be a canonical type 3259 // either, so fill in the canonical type field. 3260 QualType Canonical; 3261 if (InnerRef || !T.isCanonical()) { 3262 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3263 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3264 3265 // Get the new insert position for the node we care about. 3266 RValueReferenceType *NewIP = 3267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3268 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3269 } 3270 3271 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3272 Types.push_back(New); 3273 RValueReferenceTypes.InsertNode(New, InsertPos); 3274 return QualType(New, 0); 3275 } 3276 3277 /// getMemberPointerType - Return the uniqued reference to the type for a 3278 /// member pointer to the specified type, in the specified class. 3279 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3280 // Unique pointers, to guarantee there is only one pointer of a particular 3281 // structure. 3282 llvm::FoldingSetNodeID ID; 3283 MemberPointerType::Profile(ID, T, Cls); 3284 3285 void *InsertPos = nullptr; 3286 if (MemberPointerType *PT = 3287 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3288 return QualType(PT, 0); 3289 3290 // If the pointee or class type isn't canonical, this won't be a canonical 3291 // type either, so fill in the canonical type field. 3292 QualType Canonical; 3293 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3294 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3295 3296 // Get the new insert position for the node we care about. 3297 MemberPointerType *NewIP = 3298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3299 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3300 } 3301 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3302 Types.push_back(New); 3303 MemberPointerTypes.InsertNode(New, InsertPos); 3304 return QualType(New, 0); 3305 } 3306 3307 /// getConstantArrayType - Return the unique reference to the type for an 3308 /// array of the specified element type. 3309 QualType ASTContext::getConstantArrayType(QualType EltTy, 3310 const llvm::APInt &ArySizeIn, 3311 const Expr *SizeExpr, 3312 ArrayType::ArraySizeModifier ASM, 3313 unsigned IndexTypeQuals) const { 3314 assert((EltTy->isDependentType() || 3315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3316 "Constant array of VLAs is illegal!"); 3317 3318 // We only need the size as part of the type if it's instantiation-dependent. 3319 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3320 SizeExpr = nullptr; 3321 3322 // Convert the array size into a canonical width matching the pointer size for 3323 // the target. 3324 llvm::APInt ArySize(ArySizeIn); 3325 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3326 3327 llvm::FoldingSetNodeID ID; 3328 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3329 IndexTypeQuals); 3330 3331 void *InsertPos = nullptr; 3332 if (ConstantArrayType *ATP = 3333 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3334 return QualType(ATP, 0); 3335 3336 // If the element type isn't canonical or has qualifiers, or the array bound 3337 // is instantiation-dependent, this won't be a canonical type either, so fill 3338 // in the canonical type field. 3339 QualType Canon; 3340 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3341 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3342 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3343 ASM, IndexTypeQuals); 3344 Canon = getQualifiedType(Canon, canonSplit.Quals); 3345 3346 // Get the new insert position for the node we care about. 3347 ConstantArrayType *NewIP = 3348 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3349 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3350 } 3351 3352 void *Mem = Allocate( 3353 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3354 TypeAlignment); 3355 auto *New = new (Mem) 3356 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3357 ConstantArrayTypes.InsertNode(New, InsertPos); 3358 Types.push_back(New); 3359 return QualType(New, 0); 3360 } 3361 3362 /// getVariableArrayDecayedType - Turns the given type, which may be 3363 /// variably-modified, into the corresponding type with all the known 3364 /// sizes replaced with [*]. 3365 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3366 // Vastly most common case. 3367 if (!type->isVariablyModifiedType()) return type; 3368 3369 QualType result; 3370 3371 SplitQualType split = type.getSplitDesugaredType(); 3372 const Type *ty = split.Ty; 3373 switch (ty->getTypeClass()) { 3374 #define TYPE(Class, Base) 3375 #define ABSTRACT_TYPE(Class, Base) 3376 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3377 #include "clang/AST/TypeNodes.inc" 3378 llvm_unreachable("didn't desugar past all non-canonical types?"); 3379 3380 // These types should never be variably-modified. 3381 case Type::Builtin: 3382 case Type::Complex: 3383 case Type::Vector: 3384 case Type::DependentVector: 3385 case Type::ExtVector: 3386 case Type::DependentSizedExtVector: 3387 case Type::ConstantMatrix: 3388 case Type::DependentSizedMatrix: 3389 case Type::DependentAddressSpace: 3390 case Type::ObjCObject: 3391 case Type::ObjCInterface: 3392 case Type::ObjCObjectPointer: 3393 case Type::Record: 3394 case Type::Enum: 3395 case Type::UnresolvedUsing: 3396 case Type::TypeOfExpr: 3397 case Type::TypeOf: 3398 case Type::Decltype: 3399 case Type::UnaryTransform: 3400 case Type::DependentName: 3401 case Type::InjectedClassName: 3402 case Type::TemplateSpecialization: 3403 case Type::DependentTemplateSpecialization: 3404 case Type::TemplateTypeParm: 3405 case Type::SubstTemplateTypeParmPack: 3406 case Type::Auto: 3407 case Type::DeducedTemplateSpecialization: 3408 case Type::PackExpansion: 3409 case Type::ExtInt: 3410 case Type::DependentExtInt: 3411 llvm_unreachable("type should never be variably-modified"); 3412 3413 // These types can be variably-modified but should never need to 3414 // further decay. 3415 case Type::FunctionNoProto: 3416 case Type::FunctionProto: 3417 case Type::BlockPointer: 3418 case Type::MemberPointer: 3419 case Type::Pipe: 3420 return type; 3421 3422 // These types can be variably-modified. All these modifications 3423 // preserve structure except as noted by comments. 3424 // TODO: if we ever care about optimizing VLAs, there are no-op 3425 // optimizations available here. 3426 case Type::Pointer: 3427 result = getPointerType(getVariableArrayDecayedType( 3428 cast<PointerType>(ty)->getPointeeType())); 3429 break; 3430 3431 case Type::LValueReference: { 3432 const auto *lv = cast<LValueReferenceType>(ty); 3433 result = getLValueReferenceType( 3434 getVariableArrayDecayedType(lv->getPointeeType()), 3435 lv->isSpelledAsLValue()); 3436 break; 3437 } 3438 3439 case Type::RValueReference: { 3440 const auto *lv = cast<RValueReferenceType>(ty); 3441 result = getRValueReferenceType( 3442 getVariableArrayDecayedType(lv->getPointeeType())); 3443 break; 3444 } 3445 3446 case Type::Atomic: { 3447 const auto *at = cast<AtomicType>(ty); 3448 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3449 break; 3450 } 3451 3452 case Type::ConstantArray: { 3453 const auto *cat = cast<ConstantArrayType>(ty); 3454 result = getConstantArrayType( 3455 getVariableArrayDecayedType(cat->getElementType()), 3456 cat->getSize(), 3457 cat->getSizeExpr(), 3458 cat->getSizeModifier(), 3459 cat->getIndexTypeCVRQualifiers()); 3460 break; 3461 } 3462 3463 case Type::DependentSizedArray: { 3464 const auto *dat = cast<DependentSizedArrayType>(ty); 3465 result = getDependentSizedArrayType( 3466 getVariableArrayDecayedType(dat->getElementType()), 3467 dat->getSizeExpr(), 3468 dat->getSizeModifier(), 3469 dat->getIndexTypeCVRQualifiers(), 3470 dat->getBracketsRange()); 3471 break; 3472 } 3473 3474 // Turn incomplete types into [*] types. 3475 case Type::IncompleteArray: { 3476 const auto *iat = cast<IncompleteArrayType>(ty); 3477 result = getVariableArrayType( 3478 getVariableArrayDecayedType(iat->getElementType()), 3479 /*size*/ nullptr, 3480 ArrayType::Normal, 3481 iat->getIndexTypeCVRQualifiers(), 3482 SourceRange()); 3483 break; 3484 } 3485 3486 // Turn VLA types into [*] types. 3487 case Type::VariableArray: { 3488 const auto *vat = cast<VariableArrayType>(ty); 3489 result = getVariableArrayType( 3490 getVariableArrayDecayedType(vat->getElementType()), 3491 /*size*/ nullptr, 3492 ArrayType::Star, 3493 vat->getIndexTypeCVRQualifiers(), 3494 vat->getBracketsRange()); 3495 break; 3496 } 3497 } 3498 3499 // Apply the top-level qualifiers from the original. 3500 return getQualifiedType(result, split.Quals); 3501 } 3502 3503 /// getVariableArrayType - Returns a non-unique reference to the type for a 3504 /// variable array of the specified element type. 3505 QualType ASTContext::getVariableArrayType(QualType EltTy, 3506 Expr *NumElts, 3507 ArrayType::ArraySizeModifier ASM, 3508 unsigned IndexTypeQuals, 3509 SourceRange Brackets) const { 3510 // Since we don't unique expressions, it isn't possible to unique VLA's 3511 // that have an expression provided for their size. 3512 QualType Canon; 3513 3514 // Be sure to pull qualifiers off the element type. 3515 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3516 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3517 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3518 IndexTypeQuals, Brackets); 3519 Canon = getQualifiedType(Canon, canonSplit.Quals); 3520 } 3521 3522 auto *New = new (*this, TypeAlignment) 3523 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3524 3525 VariableArrayTypes.push_back(New); 3526 Types.push_back(New); 3527 return QualType(New, 0); 3528 } 3529 3530 /// getDependentSizedArrayType - Returns a non-unique reference to 3531 /// the type for a dependently-sized array of the specified element 3532 /// type. 3533 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3534 Expr *numElements, 3535 ArrayType::ArraySizeModifier ASM, 3536 unsigned elementTypeQuals, 3537 SourceRange brackets) const { 3538 assert((!numElements || numElements->isTypeDependent() || 3539 numElements->isValueDependent()) && 3540 "Size must be type- or value-dependent!"); 3541 3542 // Dependently-sized array types that do not have a specified number 3543 // of elements will have their sizes deduced from a dependent 3544 // initializer. We do no canonicalization here at all, which is okay 3545 // because they can't be used in most locations. 3546 if (!numElements) { 3547 auto *newType 3548 = new (*this, TypeAlignment) 3549 DependentSizedArrayType(*this, elementType, QualType(), 3550 numElements, ASM, elementTypeQuals, 3551 brackets); 3552 Types.push_back(newType); 3553 return QualType(newType, 0); 3554 } 3555 3556 // Otherwise, we actually build a new type every time, but we 3557 // also build a canonical type. 3558 3559 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3560 3561 void *insertPos = nullptr; 3562 llvm::FoldingSetNodeID ID; 3563 DependentSizedArrayType::Profile(ID, *this, 3564 QualType(canonElementType.Ty, 0), 3565 ASM, elementTypeQuals, numElements); 3566 3567 // Look for an existing type with these properties. 3568 DependentSizedArrayType *canonTy = 3569 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3570 3571 // If we don't have one, build one. 3572 if (!canonTy) { 3573 canonTy = new (*this, TypeAlignment) 3574 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3575 QualType(), numElements, ASM, elementTypeQuals, 3576 brackets); 3577 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3578 Types.push_back(canonTy); 3579 } 3580 3581 // Apply qualifiers from the element type to the array. 3582 QualType canon = getQualifiedType(QualType(canonTy,0), 3583 canonElementType.Quals); 3584 3585 // If we didn't need extra canonicalization for the element type or the size 3586 // expression, then just use that as our result. 3587 if (QualType(canonElementType.Ty, 0) == elementType && 3588 canonTy->getSizeExpr() == numElements) 3589 return canon; 3590 3591 // Otherwise, we need to build a type which follows the spelling 3592 // of the element type. 3593 auto *sugaredType 3594 = new (*this, TypeAlignment) 3595 DependentSizedArrayType(*this, elementType, canon, numElements, 3596 ASM, elementTypeQuals, brackets); 3597 Types.push_back(sugaredType); 3598 return QualType(sugaredType, 0); 3599 } 3600 3601 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3602 ArrayType::ArraySizeModifier ASM, 3603 unsigned elementTypeQuals) const { 3604 llvm::FoldingSetNodeID ID; 3605 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3606 3607 void *insertPos = nullptr; 3608 if (IncompleteArrayType *iat = 3609 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3610 return QualType(iat, 0); 3611 3612 // If the element type isn't canonical, this won't be a canonical type 3613 // either, so fill in the canonical type field. We also have to pull 3614 // qualifiers off the element type. 3615 QualType canon; 3616 3617 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3618 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3619 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3620 ASM, elementTypeQuals); 3621 canon = getQualifiedType(canon, canonSplit.Quals); 3622 3623 // Get the new insert position for the node we care about. 3624 IncompleteArrayType *existing = 3625 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3626 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3627 } 3628 3629 auto *newType = new (*this, TypeAlignment) 3630 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3631 3632 IncompleteArrayTypes.InsertNode(newType, insertPos); 3633 Types.push_back(newType); 3634 return QualType(newType, 0); 3635 } 3636 3637 ASTContext::BuiltinVectorTypeInfo 3638 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3639 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3640 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount(ELTS, true), \ 3641 NUMVECTORS}; 3642 3643 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3644 {ELTTY, llvm::ElementCount(ELTS, true), NUMVECTORS}; 3645 3646 switch (Ty->getKind()) { 3647 default: 3648 llvm_unreachable("Unsupported builtin vector type"); 3649 case BuiltinType::SveInt8: 3650 return SVE_INT_ELTTY(8, 16, true, 1); 3651 case BuiltinType::SveUint8: 3652 return SVE_INT_ELTTY(8, 16, false, 1); 3653 case BuiltinType::SveInt8x2: 3654 return SVE_INT_ELTTY(8, 16, true, 2); 3655 case BuiltinType::SveUint8x2: 3656 return SVE_INT_ELTTY(8, 16, false, 2); 3657 case BuiltinType::SveInt8x3: 3658 return SVE_INT_ELTTY(8, 16, true, 3); 3659 case BuiltinType::SveUint8x3: 3660 return SVE_INT_ELTTY(8, 16, false, 3); 3661 case BuiltinType::SveInt8x4: 3662 return SVE_INT_ELTTY(8, 16, true, 4); 3663 case BuiltinType::SveUint8x4: 3664 return SVE_INT_ELTTY(8, 16, false, 4); 3665 case BuiltinType::SveInt16: 3666 return SVE_INT_ELTTY(16, 8, true, 1); 3667 case BuiltinType::SveUint16: 3668 return SVE_INT_ELTTY(16, 8, false, 1); 3669 case BuiltinType::SveInt16x2: 3670 return SVE_INT_ELTTY(16, 8, true, 2); 3671 case BuiltinType::SveUint16x2: 3672 return SVE_INT_ELTTY(16, 8, false, 2); 3673 case BuiltinType::SveInt16x3: 3674 return SVE_INT_ELTTY(16, 8, true, 3); 3675 case BuiltinType::SveUint16x3: 3676 return SVE_INT_ELTTY(16, 8, false, 3); 3677 case BuiltinType::SveInt16x4: 3678 return SVE_INT_ELTTY(16, 8, true, 4); 3679 case BuiltinType::SveUint16x4: 3680 return SVE_INT_ELTTY(16, 8, false, 4); 3681 case BuiltinType::SveInt32: 3682 return SVE_INT_ELTTY(32, 4, true, 1); 3683 case BuiltinType::SveUint32: 3684 return SVE_INT_ELTTY(32, 4, false, 1); 3685 case BuiltinType::SveInt32x2: 3686 return SVE_INT_ELTTY(32, 4, true, 2); 3687 case BuiltinType::SveUint32x2: 3688 return SVE_INT_ELTTY(32, 4, false, 2); 3689 case BuiltinType::SveInt32x3: 3690 return SVE_INT_ELTTY(32, 4, true, 3); 3691 case BuiltinType::SveUint32x3: 3692 return SVE_INT_ELTTY(32, 4, false, 3); 3693 case BuiltinType::SveInt32x4: 3694 return SVE_INT_ELTTY(32, 4, true, 4); 3695 case BuiltinType::SveUint32x4: 3696 return SVE_INT_ELTTY(32, 4, false, 4); 3697 case BuiltinType::SveInt64: 3698 return SVE_INT_ELTTY(64, 2, true, 1); 3699 case BuiltinType::SveUint64: 3700 return SVE_INT_ELTTY(64, 2, false, 1); 3701 case BuiltinType::SveInt64x2: 3702 return SVE_INT_ELTTY(64, 2, true, 2); 3703 case BuiltinType::SveUint64x2: 3704 return SVE_INT_ELTTY(64, 2, false, 2); 3705 case BuiltinType::SveInt64x3: 3706 return SVE_INT_ELTTY(64, 2, true, 3); 3707 case BuiltinType::SveUint64x3: 3708 return SVE_INT_ELTTY(64, 2, false, 3); 3709 case BuiltinType::SveInt64x4: 3710 return SVE_INT_ELTTY(64, 2, true, 4); 3711 case BuiltinType::SveUint64x4: 3712 return SVE_INT_ELTTY(64, 2, false, 4); 3713 case BuiltinType::SveBool: 3714 return SVE_ELTTY(BoolTy, 16, 1); 3715 case BuiltinType::SveFloat16: 3716 return SVE_ELTTY(HalfTy, 8, 1); 3717 case BuiltinType::SveFloat16x2: 3718 return SVE_ELTTY(HalfTy, 8, 2); 3719 case BuiltinType::SveFloat16x3: 3720 return SVE_ELTTY(HalfTy, 8, 3); 3721 case BuiltinType::SveFloat16x4: 3722 return SVE_ELTTY(HalfTy, 8, 4); 3723 case BuiltinType::SveFloat32: 3724 return SVE_ELTTY(FloatTy, 4, 1); 3725 case BuiltinType::SveFloat32x2: 3726 return SVE_ELTTY(FloatTy, 4, 2); 3727 case BuiltinType::SveFloat32x3: 3728 return SVE_ELTTY(FloatTy, 4, 3); 3729 case BuiltinType::SveFloat32x4: 3730 return SVE_ELTTY(FloatTy, 4, 4); 3731 case BuiltinType::SveFloat64: 3732 return SVE_ELTTY(DoubleTy, 2, 1); 3733 case BuiltinType::SveFloat64x2: 3734 return SVE_ELTTY(DoubleTy, 2, 2); 3735 case BuiltinType::SveFloat64x3: 3736 return SVE_ELTTY(DoubleTy, 2, 3); 3737 case BuiltinType::SveFloat64x4: 3738 return SVE_ELTTY(DoubleTy, 2, 4); 3739 case BuiltinType::SveBFloat16: 3740 return SVE_ELTTY(BFloat16Ty, 8, 1); 3741 case BuiltinType::SveBFloat16x2: 3742 return SVE_ELTTY(BFloat16Ty, 8, 2); 3743 case BuiltinType::SveBFloat16x3: 3744 return SVE_ELTTY(BFloat16Ty, 8, 3); 3745 case BuiltinType::SveBFloat16x4: 3746 return SVE_ELTTY(BFloat16Ty, 8, 4); 3747 } 3748 } 3749 3750 /// getScalableVectorType - Return the unique reference to a scalable vector 3751 /// type of the specified element type and size. VectorType must be a built-in 3752 /// type. 3753 QualType ASTContext::getScalableVectorType(QualType EltTy, 3754 unsigned NumElts) const { 3755 if (Target->hasAArch64SVETypes()) { 3756 uint64_t EltTySize = getTypeSize(EltTy); 3757 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3758 IsSigned, IsFP, IsBF) \ 3759 if (!EltTy->isBooleanType() && \ 3760 ((EltTy->hasIntegerRepresentation() && \ 3761 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3762 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3763 IsFP && !IsBF) || \ 3764 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3765 IsBF && !IsFP)) && \ 3766 EltTySize == ElBits && NumElts == NumEls) { \ 3767 return SingletonId; \ 3768 } 3769 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3770 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3771 return SingletonId; 3772 #include "clang/Basic/AArch64SVEACLETypes.def" 3773 } 3774 return QualType(); 3775 } 3776 3777 /// getVectorType - Return the unique reference to a vector type of 3778 /// the specified element type and size. VectorType must be a built-in type. 3779 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3780 VectorType::VectorKind VecKind) const { 3781 assert(vecType->isBuiltinType()); 3782 3783 // Check if we've already instantiated a vector of this type. 3784 llvm::FoldingSetNodeID ID; 3785 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3786 3787 void *InsertPos = nullptr; 3788 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3789 return QualType(VTP, 0); 3790 3791 // If the element type isn't canonical, this won't be a canonical type either, 3792 // so fill in the canonical type field. 3793 QualType Canonical; 3794 if (!vecType.isCanonical()) { 3795 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3796 3797 // Get the new insert position for the node we care about. 3798 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3799 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3800 } 3801 auto *New = new (*this, TypeAlignment) 3802 VectorType(vecType, NumElts, Canonical, VecKind); 3803 VectorTypes.InsertNode(New, InsertPos); 3804 Types.push_back(New); 3805 return QualType(New, 0); 3806 } 3807 3808 QualType 3809 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3810 SourceLocation AttrLoc, 3811 VectorType::VectorKind VecKind) const { 3812 llvm::FoldingSetNodeID ID; 3813 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3814 VecKind); 3815 void *InsertPos = nullptr; 3816 DependentVectorType *Canon = 3817 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3818 DependentVectorType *New; 3819 3820 if (Canon) { 3821 New = new (*this, TypeAlignment) DependentVectorType( 3822 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3823 } else { 3824 QualType CanonVecTy = getCanonicalType(VecType); 3825 if (CanonVecTy == VecType) { 3826 New = new (*this, TypeAlignment) DependentVectorType( 3827 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3828 3829 DependentVectorType *CanonCheck = 3830 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3831 assert(!CanonCheck && 3832 "Dependent-sized vector_size canonical type broken"); 3833 (void)CanonCheck; 3834 DependentVectorTypes.InsertNode(New, InsertPos); 3835 } else { 3836 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 3837 SourceLocation(), VecKind); 3838 New = new (*this, TypeAlignment) DependentVectorType( 3839 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 3840 } 3841 } 3842 3843 Types.push_back(New); 3844 return QualType(New, 0); 3845 } 3846 3847 /// getExtVectorType - Return the unique reference to an extended vector type of 3848 /// the specified element type and size. VectorType must be a built-in type. 3849 QualType 3850 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3851 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3852 3853 // Check if we've already instantiated a vector of this type. 3854 llvm::FoldingSetNodeID ID; 3855 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3856 VectorType::GenericVector); 3857 void *InsertPos = nullptr; 3858 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3859 return QualType(VTP, 0); 3860 3861 // If the element type isn't canonical, this won't be a canonical type either, 3862 // so fill in the canonical type field. 3863 QualType Canonical; 3864 if (!vecType.isCanonical()) { 3865 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3866 3867 // Get the new insert position for the node we care about. 3868 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3869 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3870 } 3871 auto *New = new (*this, TypeAlignment) 3872 ExtVectorType(vecType, NumElts, Canonical); 3873 VectorTypes.InsertNode(New, InsertPos); 3874 Types.push_back(New); 3875 return QualType(New, 0); 3876 } 3877 3878 QualType 3879 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3880 Expr *SizeExpr, 3881 SourceLocation AttrLoc) const { 3882 llvm::FoldingSetNodeID ID; 3883 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3884 SizeExpr); 3885 3886 void *InsertPos = nullptr; 3887 DependentSizedExtVectorType *Canon 3888 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3889 DependentSizedExtVectorType *New; 3890 if (Canon) { 3891 // We already have a canonical version of this array type; use it as 3892 // the canonical type for a newly-built type. 3893 New = new (*this, TypeAlignment) 3894 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3895 SizeExpr, AttrLoc); 3896 } else { 3897 QualType CanonVecTy = getCanonicalType(vecType); 3898 if (CanonVecTy == vecType) { 3899 New = new (*this, TypeAlignment) 3900 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3901 AttrLoc); 3902 3903 DependentSizedExtVectorType *CanonCheck 3904 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3905 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3906 (void)CanonCheck; 3907 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3908 } else { 3909 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3910 SourceLocation()); 3911 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 3912 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 3913 } 3914 } 3915 3916 Types.push_back(New); 3917 return QualType(New, 0); 3918 } 3919 3920 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 3921 unsigned NumColumns) const { 3922 llvm::FoldingSetNodeID ID; 3923 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 3924 Type::ConstantMatrix); 3925 3926 assert(MatrixType::isValidElementType(ElementTy) && 3927 "need a valid element type"); 3928 assert(ConstantMatrixType::isDimensionValid(NumRows) && 3929 ConstantMatrixType::isDimensionValid(NumColumns) && 3930 "need valid matrix dimensions"); 3931 void *InsertPos = nullptr; 3932 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 3933 return QualType(MTP, 0); 3934 3935 QualType Canonical; 3936 if (!ElementTy.isCanonical()) { 3937 Canonical = 3938 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 3939 3940 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 3941 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 3942 (void)NewIP; 3943 } 3944 3945 auto *New = new (*this, TypeAlignment) 3946 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 3947 MatrixTypes.InsertNode(New, InsertPos); 3948 Types.push_back(New); 3949 return QualType(New, 0); 3950 } 3951 3952 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 3953 Expr *RowExpr, 3954 Expr *ColumnExpr, 3955 SourceLocation AttrLoc) const { 3956 QualType CanonElementTy = getCanonicalType(ElementTy); 3957 llvm::FoldingSetNodeID ID; 3958 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 3959 ColumnExpr); 3960 3961 void *InsertPos = nullptr; 3962 DependentSizedMatrixType *Canon = 3963 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 3964 3965 if (!Canon) { 3966 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 3967 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 3968 #ifndef NDEBUG 3969 DependentSizedMatrixType *CanonCheck = 3970 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 3971 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 3972 #endif 3973 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 3974 Types.push_back(Canon); 3975 } 3976 3977 // Already have a canonical version of the matrix type 3978 // 3979 // If it exactly matches the requested type, use it directly. 3980 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 3981 Canon->getRowExpr() == ColumnExpr) 3982 return QualType(Canon, 0); 3983 3984 // Use Canon as the canonical type for newly-built type. 3985 DependentSizedMatrixType *New = new (*this, TypeAlignment) 3986 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 3987 ColumnExpr, AttrLoc); 3988 Types.push_back(New); 3989 return QualType(New, 0); 3990 } 3991 3992 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 3993 Expr *AddrSpaceExpr, 3994 SourceLocation AttrLoc) const { 3995 assert(AddrSpaceExpr->isInstantiationDependent()); 3996 3997 QualType canonPointeeType = getCanonicalType(PointeeType); 3998 3999 void *insertPos = nullptr; 4000 llvm::FoldingSetNodeID ID; 4001 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4002 AddrSpaceExpr); 4003 4004 DependentAddressSpaceType *canonTy = 4005 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4006 4007 if (!canonTy) { 4008 canonTy = new (*this, TypeAlignment) 4009 DependentAddressSpaceType(*this, canonPointeeType, 4010 QualType(), AddrSpaceExpr, AttrLoc); 4011 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4012 Types.push_back(canonTy); 4013 } 4014 4015 if (canonPointeeType == PointeeType && 4016 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4017 return QualType(canonTy, 0); 4018 4019 auto *sugaredType 4020 = new (*this, TypeAlignment) 4021 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4022 AddrSpaceExpr, AttrLoc); 4023 Types.push_back(sugaredType); 4024 return QualType(sugaredType, 0); 4025 } 4026 4027 /// Determine whether \p T is canonical as the result type of a function. 4028 static bool isCanonicalResultType(QualType T) { 4029 return T.isCanonical() && 4030 (T.getObjCLifetime() == Qualifiers::OCL_None || 4031 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4032 } 4033 4034 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4035 QualType 4036 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4037 const FunctionType::ExtInfo &Info) const { 4038 // Unique functions, to guarantee there is only one function of a particular 4039 // structure. 4040 llvm::FoldingSetNodeID ID; 4041 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4042 4043 void *InsertPos = nullptr; 4044 if (FunctionNoProtoType *FT = 4045 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4046 return QualType(FT, 0); 4047 4048 QualType Canonical; 4049 if (!isCanonicalResultType(ResultTy)) { 4050 Canonical = 4051 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4052 4053 // Get the new insert position for the node we care about. 4054 FunctionNoProtoType *NewIP = 4055 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4056 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4057 } 4058 4059 auto *New = new (*this, TypeAlignment) 4060 FunctionNoProtoType(ResultTy, Canonical, Info); 4061 Types.push_back(New); 4062 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4063 return QualType(New, 0); 4064 } 4065 4066 CanQualType 4067 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4068 CanQualType CanResultType = getCanonicalType(ResultType); 4069 4070 // Canonical result types do not have ARC lifetime qualifiers. 4071 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4072 Qualifiers Qs = CanResultType.getQualifiers(); 4073 Qs.removeObjCLifetime(); 4074 return CanQualType::CreateUnsafe( 4075 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4076 } 4077 4078 return CanResultType; 4079 } 4080 4081 static bool isCanonicalExceptionSpecification( 4082 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4083 if (ESI.Type == EST_None) 4084 return true; 4085 if (!NoexceptInType) 4086 return false; 4087 4088 // C++17 onwards: exception specification is part of the type, as a simple 4089 // boolean "can this function type throw". 4090 if (ESI.Type == EST_BasicNoexcept) 4091 return true; 4092 4093 // A noexcept(expr) specification is (possibly) canonical if expr is 4094 // value-dependent. 4095 if (ESI.Type == EST_DependentNoexcept) 4096 return true; 4097 4098 // A dynamic exception specification is canonical if it only contains pack 4099 // expansions (so we can't tell whether it's non-throwing) and all its 4100 // contained types are canonical. 4101 if (ESI.Type == EST_Dynamic) { 4102 bool AnyPackExpansions = false; 4103 for (QualType ET : ESI.Exceptions) { 4104 if (!ET.isCanonical()) 4105 return false; 4106 if (ET->getAs<PackExpansionType>()) 4107 AnyPackExpansions = true; 4108 } 4109 return AnyPackExpansions; 4110 } 4111 4112 return false; 4113 } 4114 4115 QualType ASTContext::getFunctionTypeInternal( 4116 QualType ResultTy, ArrayRef<QualType> ArgArray, 4117 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4118 size_t NumArgs = ArgArray.size(); 4119 4120 // Unique functions, to guarantee there is only one function of a particular 4121 // structure. 4122 llvm::FoldingSetNodeID ID; 4123 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4124 *this, true); 4125 4126 QualType Canonical; 4127 bool Unique = false; 4128 4129 void *InsertPos = nullptr; 4130 if (FunctionProtoType *FPT = 4131 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4132 QualType Existing = QualType(FPT, 0); 4133 4134 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4135 // it so long as our exception specification doesn't contain a dependent 4136 // noexcept expression, or we're just looking for a canonical type. 4137 // Otherwise, we're going to need to create a type 4138 // sugar node to hold the concrete expression. 4139 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4140 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4141 return Existing; 4142 4143 // We need a new type sugar node for this one, to hold the new noexcept 4144 // expression. We do no canonicalization here, but that's OK since we don't 4145 // expect to see the same noexcept expression much more than once. 4146 Canonical = getCanonicalType(Existing); 4147 Unique = true; 4148 } 4149 4150 bool NoexceptInType = getLangOpts().CPlusPlus17; 4151 bool IsCanonicalExceptionSpec = 4152 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4153 4154 // Determine whether the type being created is already canonical or not. 4155 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4156 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4157 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4158 if (!ArgArray[i].isCanonicalAsParam()) 4159 isCanonical = false; 4160 4161 if (OnlyWantCanonical) 4162 assert(isCanonical && 4163 "given non-canonical parameters constructing canonical type"); 4164 4165 // If this type isn't canonical, get the canonical version of it if we don't 4166 // already have it. The exception spec is only partially part of the 4167 // canonical type, and only in C++17 onwards. 4168 if (!isCanonical && Canonical.isNull()) { 4169 SmallVector<QualType, 16> CanonicalArgs; 4170 CanonicalArgs.reserve(NumArgs); 4171 for (unsigned i = 0; i != NumArgs; ++i) 4172 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4173 4174 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4175 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4176 CanonicalEPI.HasTrailingReturn = false; 4177 4178 if (IsCanonicalExceptionSpec) { 4179 // Exception spec is already OK. 4180 } else if (NoexceptInType) { 4181 switch (EPI.ExceptionSpec.Type) { 4182 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4183 // We don't know yet. It shouldn't matter what we pick here; no-one 4184 // should ever look at this. 4185 LLVM_FALLTHROUGH; 4186 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4187 CanonicalEPI.ExceptionSpec.Type = EST_None; 4188 break; 4189 4190 // A dynamic exception specification is almost always "not noexcept", 4191 // with the exception that a pack expansion might expand to no types. 4192 case EST_Dynamic: { 4193 bool AnyPacks = false; 4194 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4195 if (ET->getAs<PackExpansionType>()) 4196 AnyPacks = true; 4197 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4198 } 4199 if (!AnyPacks) 4200 CanonicalEPI.ExceptionSpec.Type = EST_None; 4201 else { 4202 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4203 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4204 } 4205 break; 4206 } 4207 4208 case EST_DynamicNone: 4209 case EST_BasicNoexcept: 4210 case EST_NoexceptTrue: 4211 case EST_NoThrow: 4212 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4213 break; 4214 4215 case EST_DependentNoexcept: 4216 llvm_unreachable("dependent noexcept is already canonical"); 4217 } 4218 } else { 4219 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4220 } 4221 4222 // Adjust the canonical function result type. 4223 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4224 Canonical = 4225 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4226 4227 // Get the new insert position for the node we care about. 4228 FunctionProtoType *NewIP = 4229 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4230 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4231 } 4232 4233 // Compute the needed size to hold this FunctionProtoType and the 4234 // various trailing objects. 4235 auto ESH = FunctionProtoType::getExceptionSpecSize( 4236 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4237 size_t Size = FunctionProtoType::totalSizeToAlloc< 4238 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4239 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4240 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4241 NumArgs, EPI.Variadic, 4242 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4243 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4244 EPI.ExtParameterInfos ? NumArgs : 0, 4245 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4246 4247 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4248 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4249 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4250 Types.push_back(FTP); 4251 if (!Unique) 4252 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4253 return QualType(FTP, 0); 4254 } 4255 4256 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4257 llvm::FoldingSetNodeID ID; 4258 PipeType::Profile(ID, T, ReadOnly); 4259 4260 void *InsertPos = nullptr; 4261 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4262 return QualType(PT, 0); 4263 4264 // If the pipe element type isn't canonical, this won't be a canonical type 4265 // either, so fill in the canonical type field. 4266 QualType Canonical; 4267 if (!T.isCanonical()) { 4268 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4269 4270 // Get the new insert position for the node we care about. 4271 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4272 assert(!NewIP && "Shouldn't be in the map!"); 4273 (void)NewIP; 4274 } 4275 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4276 Types.push_back(New); 4277 PipeTypes.InsertNode(New, InsertPos); 4278 return QualType(New, 0); 4279 } 4280 4281 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4282 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4283 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4284 : Ty; 4285 } 4286 4287 QualType ASTContext::getReadPipeType(QualType T) const { 4288 return getPipeType(T, true); 4289 } 4290 4291 QualType ASTContext::getWritePipeType(QualType T) const { 4292 return getPipeType(T, false); 4293 } 4294 4295 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const { 4296 llvm::FoldingSetNodeID ID; 4297 ExtIntType::Profile(ID, IsUnsigned, NumBits); 4298 4299 void *InsertPos = nullptr; 4300 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4301 return QualType(EIT, 0); 4302 4303 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits); 4304 ExtIntTypes.InsertNode(New, InsertPos); 4305 Types.push_back(New); 4306 return QualType(New, 0); 4307 } 4308 4309 QualType ASTContext::getDependentExtIntType(bool IsUnsigned, 4310 Expr *NumBitsExpr) const { 4311 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4312 llvm::FoldingSetNodeID ID; 4313 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4314 4315 void *InsertPos = nullptr; 4316 if (DependentExtIntType *Existing = 4317 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4318 return QualType(Existing, 0); 4319 4320 auto *New = new (*this, TypeAlignment) 4321 DependentExtIntType(*this, IsUnsigned, NumBitsExpr); 4322 DependentExtIntTypes.InsertNode(New, InsertPos); 4323 4324 Types.push_back(New); 4325 return QualType(New, 0); 4326 } 4327 4328 #ifndef NDEBUG 4329 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4330 if (!isa<CXXRecordDecl>(D)) return false; 4331 const auto *RD = cast<CXXRecordDecl>(D); 4332 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4333 return true; 4334 if (RD->getDescribedClassTemplate() && 4335 !isa<ClassTemplateSpecializationDecl>(RD)) 4336 return true; 4337 return false; 4338 } 4339 #endif 4340 4341 /// getInjectedClassNameType - Return the unique reference to the 4342 /// injected class name type for the specified templated declaration. 4343 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4344 QualType TST) const { 4345 assert(NeedsInjectedClassNameType(Decl)); 4346 if (Decl->TypeForDecl) { 4347 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4348 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4349 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4350 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4351 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4352 } else { 4353 Type *newType = 4354 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4355 Decl->TypeForDecl = newType; 4356 Types.push_back(newType); 4357 } 4358 return QualType(Decl->TypeForDecl, 0); 4359 } 4360 4361 /// getTypeDeclType - Return the unique reference to the type for the 4362 /// specified type declaration. 4363 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4364 assert(Decl && "Passed null for Decl param"); 4365 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4366 4367 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4368 return getTypedefType(Typedef); 4369 4370 assert(!isa<TemplateTypeParmDecl>(Decl) && 4371 "Template type parameter types are always available."); 4372 4373 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4374 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4375 assert(!NeedsInjectedClassNameType(Record)); 4376 return getRecordType(Record); 4377 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4378 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4379 return getEnumType(Enum); 4380 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4381 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 4382 Decl->TypeForDecl = newType; 4383 Types.push_back(newType); 4384 } else 4385 llvm_unreachable("TypeDecl without a type?"); 4386 4387 return QualType(Decl->TypeForDecl, 0); 4388 } 4389 4390 /// getTypedefType - Return the unique reference to the type for the 4391 /// specified typedef name decl. 4392 QualType 4393 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4394 QualType Canonical) const { 4395 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4396 4397 if (Canonical.isNull()) 4398 Canonical = getCanonicalType(Decl->getUnderlyingType()); 4399 auto *newType = new (*this, TypeAlignment) 4400 TypedefType(Type::Typedef, Decl, Canonical); 4401 Decl->TypeForDecl = newType; 4402 Types.push_back(newType); 4403 return QualType(newType, 0); 4404 } 4405 4406 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4407 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4408 4409 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4410 if (PrevDecl->TypeForDecl) 4411 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4412 4413 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4414 Decl->TypeForDecl = newType; 4415 Types.push_back(newType); 4416 return QualType(newType, 0); 4417 } 4418 4419 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4420 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4421 4422 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4423 if (PrevDecl->TypeForDecl) 4424 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4425 4426 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4427 Decl->TypeForDecl = newType; 4428 Types.push_back(newType); 4429 return QualType(newType, 0); 4430 } 4431 4432 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4433 QualType modifiedType, 4434 QualType equivalentType) { 4435 llvm::FoldingSetNodeID id; 4436 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4437 4438 void *insertPos = nullptr; 4439 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4440 if (type) return QualType(type, 0); 4441 4442 QualType canon = getCanonicalType(equivalentType); 4443 type = new (*this, TypeAlignment) 4444 AttributedType(canon, attrKind, modifiedType, equivalentType); 4445 4446 Types.push_back(type); 4447 AttributedTypes.InsertNode(type, insertPos); 4448 4449 return QualType(type, 0); 4450 } 4451 4452 /// Retrieve a substitution-result type. 4453 QualType 4454 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4455 QualType Replacement) const { 4456 assert(Replacement.isCanonical() 4457 && "replacement types must always be canonical"); 4458 4459 llvm::FoldingSetNodeID ID; 4460 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4461 void *InsertPos = nullptr; 4462 SubstTemplateTypeParmType *SubstParm 4463 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4464 4465 if (!SubstParm) { 4466 SubstParm = new (*this, TypeAlignment) 4467 SubstTemplateTypeParmType(Parm, Replacement); 4468 Types.push_back(SubstParm); 4469 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4470 } 4471 4472 return QualType(SubstParm, 0); 4473 } 4474 4475 /// Retrieve a 4476 QualType ASTContext::getSubstTemplateTypeParmPackType( 4477 const TemplateTypeParmType *Parm, 4478 const TemplateArgument &ArgPack) { 4479 #ifndef NDEBUG 4480 for (const auto &P : ArgPack.pack_elements()) { 4481 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4482 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4483 } 4484 #endif 4485 4486 llvm::FoldingSetNodeID ID; 4487 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4488 void *InsertPos = nullptr; 4489 if (SubstTemplateTypeParmPackType *SubstParm 4490 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4491 return QualType(SubstParm, 0); 4492 4493 QualType Canon; 4494 if (!Parm->isCanonicalUnqualified()) { 4495 Canon = getCanonicalType(QualType(Parm, 0)); 4496 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4497 ArgPack); 4498 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4499 } 4500 4501 auto *SubstParm 4502 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4503 ArgPack); 4504 Types.push_back(SubstParm); 4505 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4506 return QualType(SubstParm, 0); 4507 } 4508 4509 /// Retrieve the template type parameter type for a template 4510 /// parameter or parameter pack with the given depth, index, and (optionally) 4511 /// name. 4512 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4513 bool ParameterPack, 4514 TemplateTypeParmDecl *TTPDecl) const { 4515 llvm::FoldingSetNodeID ID; 4516 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4517 void *InsertPos = nullptr; 4518 TemplateTypeParmType *TypeParm 4519 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4520 4521 if (TypeParm) 4522 return QualType(TypeParm, 0); 4523 4524 if (TTPDecl) { 4525 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4526 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4527 4528 TemplateTypeParmType *TypeCheck 4529 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4530 assert(!TypeCheck && "Template type parameter canonical type broken"); 4531 (void)TypeCheck; 4532 } else 4533 TypeParm = new (*this, TypeAlignment) 4534 TemplateTypeParmType(Depth, Index, ParameterPack); 4535 4536 Types.push_back(TypeParm); 4537 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4538 4539 return QualType(TypeParm, 0); 4540 } 4541 4542 TypeSourceInfo * 4543 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4544 SourceLocation NameLoc, 4545 const TemplateArgumentListInfo &Args, 4546 QualType Underlying) const { 4547 assert(!Name.getAsDependentTemplateName() && 4548 "No dependent template names here!"); 4549 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4550 4551 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4552 TemplateSpecializationTypeLoc TL = 4553 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4554 TL.setTemplateKeywordLoc(SourceLocation()); 4555 TL.setTemplateNameLoc(NameLoc); 4556 TL.setLAngleLoc(Args.getLAngleLoc()); 4557 TL.setRAngleLoc(Args.getRAngleLoc()); 4558 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4559 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4560 return DI; 4561 } 4562 4563 QualType 4564 ASTContext::getTemplateSpecializationType(TemplateName Template, 4565 const TemplateArgumentListInfo &Args, 4566 QualType Underlying) const { 4567 assert(!Template.getAsDependentTemplateName() && 4568 "No dependent template names here!"); 4569 4570 SmallVector<TemplateArgument, 4> ArgVec; 4571 ArgVec.reserve(Args.size()); 4572 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4573 ArgVec.push_back(Arg.getArgument()); 4574 4575 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4576 } 4577 4578 #ifndef NDEBUG 4579 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4580 for (const TemplateArgument &Arg : Args) 4581 if (Arg.isPackExpansion()) 4582 return true; 4583 4584 return true; 4585 } 4586 #endif 4587 4588 QualType 4589 ASTContext::getTemplateSpecializationType(TemplateName Template, 4590 ArrayRef<TemplateArgument> Args, 4591 QualType Underlying) const { 4592 assert(!Template.getAsDependentTemplateName() && 4593 "No dependent template names here!"); 4594 // Look through qualified template names. 4595 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4596 Template = TemplateName(QTN->getTemplateDecl()); 4597 4598 bool IsTypeAlias = 4599 Template.getAsTemplateDecl() && 4600 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4601 QualType CanonType; 4602 if (!Underlying.isNull()) 4603 CanonType = getCanonicalType(Underlying); 4604 else { 4605 // We can get here with an alias template when the specialization contains 4606 // a pack expansion that does not match up with a parameter pack. 4607 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4608 "Caller must compute aliased type"); 4609 IsTypeAlias = false; 4610 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4611 } 4612 4613 // Allocate the (non-canonical) template specialization type, but don't 4614 // try to unique it: these types typically have location information that 4615 // we don't unique and don't want to lose. 4616 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4617 sizeof(TemplateArgument) * Args.size() + 4618 (IsTypeAlias? sizeof(QualType) : 0), 4619 TypeAlignment); 4620 auto *Spec 4621 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4622 IsTypeAlias ? Underlying : QualType()); 4623 4624 Types.push_back(Spec); 4625 return QualType(Spec, 0); 4626 } 4627 4628 QualType ASTContext::getCanonicalTemplateSpecializationType( 4629 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4630 assert(!Template.getAsDependentTemplateName() && 4631 "No dependent template names here!"); 4632 4633 // Look through qualified template names. 4634 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4635 Template = TemplateName(QTN->getTemplateDecl()); 4636 4637 // Build the canonical template specialization type. 4638 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4639 SmallVector<TemplateArgument, 4> CanonArgs; 4640 unsigned NumArgs = Args.size(); 4641 CanonArgs.reserve(NumArgs); 4642 for (const TemplateArgument &Arg : Args) 4643 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4644 4645 // Determine whether this canonical template specialization type already 4646 // exists. 4647 llvm::FoldingSetNodeID ID; 4648 TemplateSpecializationType::Profile(ID, CanonTemplate, 4649 CanonArgs, *this); 4650 4651 void *InsertPos = nullptr; 4652 TemplateSpecializationType *Spec 4653 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4654 4655 if (!Spec) { 4656 // Allocate a new canonical template specialization type. 4657 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4658 sizeof(TemplateArgument) * NumArgs), 4659 TypeAlignment); 4660 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4661 CanonArgs, 4662 QualType(), QualType()); 4663 Types.push_back(Spec); 4664 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4665 } 4666 4667 assert(Spec->isDependentType() && 4668 "Non-dependent template-id type must have a canonical type"); 4669 return QualType(Spec, 0); 4670 } 4671 4672 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4673 NestedNameSpecifier *NNS, 4674 QualType NamedType, 4675 TagDecl *OwnedTagDecl) const { 4676 llvm::FoldingSetNodeID ID; 4677 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4678 4679 void *InsertPos = nullptr; 4680 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4681 if (T) 4682 return QualType(T, 0); 4683 4684 QualType Canon = NamedType; 4685 if (!Canon.isCanonical()) { 4686 Canon = getCanonicalType(NamedType); 4687 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4688 assert(!CheckT && "Elaborated canonical type broken"); 4689 (void)CheckT; 4690 } 4691 4692 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4693 TypeAlignment); 4694 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4695 4696 Types.push_back(T); 4697 ElaboratedTypes.InsertNode(T, InsertPos); 4698 return QualType(T, 0); 4699 } 4700 4701 QualType 4702 ASTContext::getParenType(QualType InnerType) const { 4703 llvm::FoldingSetNodeID ID; 4704 ParenType::Profile(ID, InnerType); 4705 4706 void *InsertPos = nullptr; 4707 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4708 if (T) 4709 return QualType(T, 0); 4710 4711 QualType Canon = InnerType; 4712 if (!Canon.isCanonical()) { 4713 Canon = getCanonicalType(InnerType); 4714 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4715 assert(!CheckT && "Paren canonical type broken"); 4716 (void)CheckT; 4717 } 4718 4719 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4720 Types.push_back(T); 4721 ParenTypes.InsertNode(T, InsertPos); 4722 return QualType(T, 0); 4723 } 4724 4725 QualType 4726 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4727 const IdentifierInfo *MacroII) const { 4728 QualType Canon = UnderlyingTy; 4729 if (!Canon.isCanonical()) 4730 Canon = getCanonicalType(UnderlyingTy); 4731 4732 auto *newType = new (*this, TypeAlignment) 4733 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4734 Types.push_back(newType); 4735 return QualType(newType, 0); 4736 } 4737 4738 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4739 NestedNameSpecifier *NNS, 4740 const IdentifierInfo *Name, 4741 QualType Canon) const { 4742 if (Canon.isNull()) { 4743 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4744 if (CanonNNS != NNS) 4745 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4746 } 4747 4748 llvm::FoldingSetNodeID ID; 4749 DependentNameType::Profile(ID, Keyword, NNS, Name); 4750 4751 void *InsertPos = nullptr; 4752 DependentNameType *T 4753 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4754 if (T) 4755 return QualType(T, 0); 4756 4757 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4758 Types.push_back(T); 4759 DependentNameTypes.InsertNode(T, InsertPos); 4760 return QualType(T, 0); 4761 } 4762 4763 QualType 4764 ASTContext::getDependentTemplateSpecializationType( 4765 ElaboratedTypeKeyword Keyword, 4766 NestedNameSpecifier *NNS, 4767 const IdentifierInfo *Name, 4768 const TemplateArgumentListInfo &Args) const { 4769 // TODO: avoid this copy 4770 SmallVector<TemplateArgument, 16> ArgCopy; 4771 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4772 ArgCopy.push_back(Args[I].getArgument()); 4773 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4774 } 4775 4776 QualType 4777 ASTContext::getDependentTemplateSpecializationType( 4778 ElaboratedTypeKeyword Keyword, 4779 NestedNameSpecifier *NNS, 4780 const IdentifierInfo *Name, 4781 ArrayRef<TemplateArgument> Args) const { 4782 assert((!NNS || NNS->isDependent()) && 4783 "nested-name-specifier must be dependent"); 4784 4785 llvm::FoldingSetNodeID ID; 4786 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4787 Name, Args); 4788 4789 void *InsertPos = nullptr; 4790 DependentTemplateSpecializationType *T 4791 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4792 if (T) 4793 return QualType(T, 0); 4794 4795 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4796 4797 ElaboratedTypeKeyword CanonKeyword = Keyword; 4798 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4799 4800 bool AnyNonCanonArgs = false; 4801 unsigned NumArgs = Args.size(); 4802 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4803 for (unsigned I = 0; I != NumArgs; ++I) { 4804 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4805 if (!CanonArgs[I].structurallyEquals(Args[I])) 4806 AnyNonCanonArgs = true; 4807 } 4808 4809 QualType Canon; 4810 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4811 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4812 Name, 4813 CanonArgs); 4814 4815 // Find the insert position again. 4816 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4817 } 4818 4819 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4820 sizeof(TemplateArgument) * NumArgs), 4821 TypeAlignment); 4822 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4823 Name, Args, Canon); 4824 Types.push_back(T); 4825 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4826 return QualType(T, 0); 4827 } 4828 4829 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4830 TemplateArgument Arg; 4831 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4832 QualType ArgType = getTypeDeclType(TTP); 4833 if (TTP->isParameterPack()) 4834 ArgType = getPackExpansionType(ArgType, None); 4835 4836 Arg = TemplateArgument(ArgType); 4837 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4838 Expr *E = new (*this) DeclRefExpr( 4839 *this, NTTP, /*enclosing*/ false, 4840 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this), 4841 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4842 4843 if (NTTP->isParameterPack()) 4844 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 4845 None); 4846 Arg = TemplateArgument(E); 4847 } else { 4848 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 4849 if (TTP->isParameterPack()) 4850 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 4851 else 4852 Arg = TemplateArgument(TemplateName(TTP)); 4853 } 4854 4855 if (Param->isTemplateParameterPack()) 4856 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 4857 4858 return Arg; 4859 } 4860 4861 void 4862 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 4863 SmallVectorImpl<TemplateArgument> &Args) { 4864 Args.reserve(Args.size() + Params->size()); 4865 4866 for (NamedDecl *Param : *Params) 4867 Args.push_back(getInjectedTemplateArg(Param)); 4868 } 4869 4870 QualType ASTContext::getPackExpansionType(QualType Pattern, 4871 Optional<unsigned> NumExpansions) { 4872 llvm::FoldingSetNodeID ID; 4873 PackExpansionType::Profile(ID, Pattern, NumExpansions); 4874 4875 // A deduced type can deduce to a pack, eg 4876 // auto ...x = some_pack; 4877 // That declaration isn't (yet) valid, but is created as part of building an 4878 // init-capture pack: 4879 // [...x = some_pack] {} 4880 assert((Pattern->containsUnexpandedParameterPack() || 4881 Pattern->getContainedDeducedType()) && 4882 "Pack expansions must expand one or more parameter packs"); 4883 void *InsertPos = nullptr; 4884 PackExpansionType *T 4885 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4886 if (T) 4887 return QualType(T, 0); 4888 4889 QualType Canon; 4890 if (!Pattern.isCanonical()) { 4891 Canon = getCanonicalType(Pattern); 4892 // The canonical type might not contain an unexpanded parameter pack, if it 4893 // contains an alias template specialization which ignores one of its 4894 // parameters. 4895 if (Canon->containsUnexpandedParameterPack()) { 4896 Canon = getPackExpansionType(Canon, NumExpansions); 4897 4898 // Find the insert position again, in case we inserted an element into 4899 // PackExpansionTypes and invalidated our insert position. 4900 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4901 } 4902 } 4903 4904 T = new (*this, TypeAlignment) 4905 PackExpansionType(Pattern, Canon, NumExpansions); 4906 Types.push_back(T); 4907 PackExpansionTypes.InsertNode(T, InsertPos); 4908 return QualType(T, 0); 4909 } 4910 4911 /// CmpProtocolNames - Comparison predicate for sorting protocols 4912 /// alphabetically. 4913 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 4914 ObjCProtocolDecl *const *RHS) { 4915 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 4916 } 4917 4918 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 4919 if (Protocols.empty()) return true; 4920 4921 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 4922 return false; 4923 4924 for (unsigned i = 1; i != Protocols.size(); ++i) 4925 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 4926 Protocols[i]->getCanonicalDecl() != Protocols[i]) 4927 return false; 4928 return true; 4929 } 4930 4931 static void 4932 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 4933 // Sort protocols, keyed by name. 4934 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 4935 4936 // Canonicalize. 4937 for (ObjCProtocolDecl *&P : Protocols) 4938 P = P->getCanonicalDecl(); 4939 4940 // Remove duplicates. 4941 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 4942 Protocols.erase(ProtocolsEnd, Protocols.end()); 4943 } 4944 4945 QualType ASTContext::getObjCObjectType(QualType BaseType, 4946 ObjCProtocolDecl * const *Protocols, 4947 unsigned NumProtocols) const { 4948 return getObjCObjectType(BaseType, {}, 4949 llvm::makeArrayRef(Protocols, NumProtocols), 4950 /*isKindOf=*/false); 4951 } 4952 4953 QualType ASTContext::getObjCObjectType( 4954 QualType baseType, 4955 ArrayRef<QualType> typeArgs, 4956 ArrayRef<ObjCProtocolDecl *> protocols, 4957 bool isKindOf) const { 4958 // If the base type is an interface and there aren't any protocols or 4959 // type arguments to add, then the interface type will do just fine. 4960 if (typeArgs.empty() && protocols.empty() && !isKindOf && 4961 isa<ObjCInterfaceType>(baseType)) 4962 return baseType; 4963 4964 // Look in the folding set for an existing type. 4965 llvm::FoldingSetNodeID ID; 4966 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 4967 void *InsertPos = nullptr; 4968 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 4969 return QualType(QT, 0); 4970 4971 // Determine the type arguments to be used for canonicalization, 4972 // which may be explicitly specified here or written on the base 4973 // type. 4974 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 4975 if (effectiveTypeArgs.empty()) { 4976 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 4977 effectiveTypeArgs = baseObject->getTypeArgs(); 4978 } 4979 4980 // Build the canonical type, which has the canonical base type and a 4981 // sorted-and-uniqued list of protocols and the type arguments 4982 // canonicalized. 4983 QualType canonical; 4984 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 4985 effectiveTypeArgs.end(), 4986 [&](QualType type) { 4987 return type.isCanonical(); 4988 }); 4989 bool protocolsSorted = areSortedAndUniqued(protocols); 4990 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 4991 // Determine the canonical type arguments. 4992 ArrayRef<QualType> canonTypeArgs; 4993 SmallVector<QualType, 4> canonTypeArgsVec; 4994 if (!typeArgsAreCanonical) { 4995 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 4996 for (auto typeArg : effectiveTypeArgs) 4997 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 4998 canonTypeArgs = canonTypeArgsVec; 4999 } else { 5000 canonTypeArgs = effectiveTypeArgs; 5001 } 5002 5003 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5004 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5005 if (!protocolsSorted) { 5006 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5007 SortAndUniqueProtocols(canonProtocolsVec); 5008 canonProtocols = canonProtocolsVec; 5009 } else { 5010 canonProtocols = protocols; 5011 } 5012 5013 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5014 canonProtocols, isKindOf); 5015 5016 // Regenerate InsertPos. 5017 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5018 } 5019 5020 unsigned size = sizeof(ObjCObjectTypeImpl); 5021 size += typeArgs.size() * sizeof(QualType); 5022 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5023 void *mem = Allocate(size, TypeAlignment); 5024 auto *T = 5025 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5026 isKindOf); 5027 5028 Types.push_back(T); 5029 ObjCObjectTypes.InsertNode(T, InsertPos); 5030 return QualType(T, 0); 5031 } 5032 5033 /// Apply Objective-C protocol qualifiers to the given type. 5034 /// If this is for the canonical type of a type parameter, we can apply 5035 /// protocol qualifiers on the ObjCObjectPointerType. 5036 QualType 5037 ASTContext::applyObjCProtocolQualifiers(QualType type, 5038 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5039 bool allowOnPointerType) const { 5040 hasError = false; 5041 5042 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5043 return getObjCTypeParamType(objT->getDecl(), protocols); 5044 } 5045 5046 // Apply protocol qualifiers to ObjCObjectPointerType. 5047 if (allowOnPointerType) { 5048 if (const auto *objPtr = 5049 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5050 const ObjCObjectType *objT = objPtr->getObjectType(); 5051 // Merge protocol lists and construct ObjCObjectType. 5052 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5053 protocolsVec.append(objT->qual_begin(), 5054 objT->qual_end()); 5055 protocolsVec.append(protocols.begin(), protocols.end()); 5056 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5057 type = getObjCObjectType( 5058 objT->getBaseType(), 5059 objT->getTypeArgsAsWritten(), 5060 protocols, 5061 objT->isKindOfTypeAsWritten()); 5062 return getObjCObjectPointerType(type); 5063 } 5064 } 5065 5066 // Apply protocol qualifiers to ObjCObjectType. 5067 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5068 // FIXME: Check for protocols to which the class type is already 5069 // known to conform. 5070 5071 return getObjCObjectType(objT->getBaseType(), 5072 objT->getTypeArgsAsWritten(), 5073 protocols, 5074 objT->isKindOfTypeAsWritten()); 5075 } 5076 5077 // If the canonical type is ObjCObjectType, ... 5078 if (type->isObjCObjectType()) { 5079 // Silently overwrite any existing protocol qualifiers. 5080 // TODO: determine whether that's the right thing to do. 5081 5082 // FIXME: Check for protocols to which the class type is already 5083 // known to conform. 5084 return getObjCObjectType(type, {}, protocols, false); 5085 } 5086 5087 // id<protocol-list> 5088 if (type->isObjCIdType()) { 5089 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5090 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5091 objPtr->isKindOfType()); 5092 return getObjCObjectPointerType(type); 5093 } 5094 5095 // Class<protocol-list> 5096 if (type->isObjCClassType()) { 5097 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5098 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5099 objPtr->isKindOfType()); 5100 return getObjCObjectPointerType(type); 5101 } 5102 5103 hasError = true; 5104 return type; 5105 } 5106 5107 QualType 5108 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5109 ArrayRef<ObjCProtocolDecl *> protocols) const { 5110 // Look in the folding set for an existing type. 5111 llvm::FoldingSetNodeID ID; 5112 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5113 void *InsertPos = nullptr; 5114 if (ObjCTypeParamType *TypeParam = 5115 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5116 return QualType(TypeParam, 0); 5117 5118 // We canonicalize to the underlying type. 5119 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5120 if (!protocols.empty()) { 5121 // Apply the protocol qualifers. 5122 bool hasError; 5123 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5124 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5125 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5126 } 5127 5128 unsigned size = sizeof(ObjCTypeParamType); 5129 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5130 void *mem = Allocate(size, TypeAlignment); 5131 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5132 5133 Types.push_back(newType); 5134 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5135 return QualType(newType, 0); 5136 } 5137 5138 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5139 ObjCTypeParamDecl *New) const { 5140 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5141 // Update TypeForDecl after updating TypeSourceInfo. 5142 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5143 SmallVector<ObjCProtocolDecl *, 8> protocols; 5144 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5145 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5146 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5147 } 5148 5149 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5150 /// protocol list adopt all protocols in QT's qualified-id protocol 5151 /// list. 5152 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5153 ObjCInterfaceDecl *IC) { 5154 if (!QT->isObjCQualifiedIdType()) 5155 return false; 5156 5157 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5158 // If both the right and left sides have qualifiers. 5159 for (auto *Proto : OPT->quals()) { 5160 if (!IC->ClassImplementsProtocol(Proto, false)) 5161 return false; 5162 } 5163 return true; 5164 } 5165 return false; 5166 } 5167 5168 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5169 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5170 /// of protocols. 5171 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5172 ObjCInterfaceDecl *IDecl) { 5173 if (!QT->isObjCQualifiedIdType()) 5174 return false; 5175 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5176 if (!OPT) 5177 return false; 5178 if (!IDecl->hasDefinition()) 5179 return false; 5180 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5181 CollectInheritedProtocols(IDecl, InheritedProtocols); 5182 if (InheritedProtocols.empty()) 5183 return false; 5184 // Check that if every protocol in list of id<plist> conforms to a protocol 5185 // of IDecl's, then bridge casting is ok. 5186 bool Conforms = false; 5187 for (auto *Proto : OPT->quals()) { 5188 Conforms = false; 5189 for (auto *PI : InheritedProtocols) { 5190 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5191 Conforms = true; 5192 break; 5193 } 5194 } 5195 if (!Conforms) 5196 break; 5197 } 5198 if (Conforms) 5199 return true; 5200 5201 for (auto *PI : InheritedProtocols) { 5202 // If both the right and left sides have qualifiers. 5203 bool Adopts = false; 5204 for (auto *Proto : OPT->quals()) { 5205 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5206 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5207 break; 5208 } 5209 if (!Adopts) 5210 return false; 5211 } 5212 return true; 5213 } 5214 5215 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5216 /// the given object type. 5217 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5218 llvm::FoldingSetNodeID ID; 5219 ObjCObjectPointerType::Profile(ID, ObjectT); 5220 5221 void *InsertPos = nullptr; 5222 if (ObjCObjectPointerType *QT = 5223 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5224 return QualType(QT, 0); 5225 5226 // Find the canonical object type. 5227 QualType Canonical; 5228 if (!ObjectT.isCanonical()) { 5229 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5230 5231 // Regenerate InsertPos. 5232 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5233 } 5234 5235 // No match. 5236 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5237 auto *QType = 5238 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5239 5240 Types.push_back(QType); 5241 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5242 return QualType(QType, 0); 5243 } 5244 5245 /// getObjCInterfaceType - Return the unique reference to the type for the 5246 /// specified ObjC interface decl. The list of protocols is optional. 5247 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5248 ObjCInterfaceDecl *PrevDecl) const { 5249 if (Decl->TypeForDecl) 5250 return QualType(Decl->TypeForDecl, 0); 5251 5252 if (PrevDecl) { 5253 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5254 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5255 return QualType(PrevDecl->TypeForDecl, 0); 5256 } 5257 5258 // Prefer the definition, if there is one. 5259 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5260 Decl = Def; 5261 5262 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5263 auto *T = new (Mem) ObjCInterfaceType(Decl); 5264 Decl->TypeForDecl = T; 5265 Types.push_back(T); 5266 return QualType(T, 0); 5267 } 5268 5269 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5270 /// TypeOfExprType AST's (since expression's are never shared). For example, 5271 /// multiple declarations that refer to "typeof(x)" all contain different 5272 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5273 /// on canonical type's (which are always unique). 5274 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5275 TypeOfExprType *toe; 5276 if (tofExpr->isTypeDependent()) { 5277 llvm::FoldingSetNodeID ID; 5278 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5279 5280 void *InsertPos = nullptr; 5281 DependentTypeOfExprType *Canon 5282 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5283 if (Canon) { 5284 // We already have a "canonical" version of an identical, dependent 5285 // typeof(expr) type. Use that as our canonical type. 5286 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5287 QualType((TypeOfExprType*)Canon, 0)); 5288 } else { 5289 // Build a new, canonical typeof(expr) type. 5290 Canon 5291 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5292 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5293 toe = Canon; 5294 } 5295 } else { 5296 QualType Canonical = getCanonicalType(tofExpr->getType()); 5297 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5298 } 5299 Types.push_back(toe); 5300 return QualType(toe, 0); 5301 } 5302 5303 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5304 /// TypeOfType nodes. The only motivation to unique these nodes would be 5305 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5306 /// an issue. This doesn't affect the type checker, since it operates 5307 /// on canonical types (which are always unique). 5308 QualType ASTContext::getTypeOfType(QualType tofType) const { 5309 QualType Canonical = getCanonicalType(tofType); 5310 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5311 Types.push_back(tot); 5312 return QualType(tot, 0); 5313 } 5314 5315 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5316 /// nodes. This would never be helpful, since each such type has its own 5317 /// expression, and would not give a significant memory saving, since there 5318 /// is an Expr tree under each such type. 5319 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5320 DecltypeType *dt; 5321 5322 // C++11 [temp.type]p2: 5323 // If an expression e involves a template parameter, decltype(e) denotes a 5324 // unique dependent type. Two such decltype-specifiers refer to the same 5325 // type only if their expressions are equivalent (14.5.6.1). 5326 if (e->isInstantiationDependent()) { 5327 llvm::FoldingSetNodeID ID; 5328 DependentDecltypeType::Profile(ID, *this, e); 5329 5330 void *InsertPos = nullptr; 5331 DependentDecltypeType *Canon 5332 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5333 if (!Canon) { 5334 // Build a new, canonical decltype(expr) type. 5335 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5336 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5337 } 5338 dt = new (*this, TypeAlignment) 5339 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5340 } else { 5341 dt = new (*this, TypeAlignment) 5342 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5343 } 5344 Types.push_back(dt); 5345 return QualType(dt, 0); 5346 } 5347 5348 /// getUnaryTransformationType - We don't unique these, since the memory 5349 /// savings are minimal and these are rare. 5350 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5351 QualType UnderlyingType, 5352 UnaryTransformType::UTTKind Kind) 5353 const { 5354 UnaryTransformType *ut = nullptr; 5355 5356 if (BaseType->isDependentType()) { 5357 // Look in the folding set for an existing type. 5358 llvm::FoldingSetNodeID ID; 5359 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5360 5361 void *InsertPos = nullptr; 5362 DependentUnaryTransformType *Canon 5363 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5364 5365 if (!Canon) { 5366 // Build a new, canonical __underlying_type(type) type. 5367 Canon = new (*this, TypeAlignment) 5368 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5369 Kind); 5370 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5371 } 5372 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5373 QualType(), Kind, 5374 QualType(Canon, 0)); 5375 } else { 5376 QualType CanonType = getCanonicalType(UnderlyingType); 5377 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5378 UnderlyingType, Kind, 5379 CanonType); 5380 } 5381 Types.push_back(ut); 5382 return QualType(ut, 0); 5383 } 5384 5385 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5386 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5387 /// canonical deduced-but-dependent 'auto' type. 5388 QualType 5389 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5390 bool IsDependent, bool IsPack, 5391 ConceptDecl *TypeConstraintConcept, 5392 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5393 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5394 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5395 !TypeConstraintConcept && !IsDependent) 5396 return getAutoDeductType(); 5397 5398 // Look in the folding set for an existing type. 5399 void *InsertPos = nullptr; 5400 llvm::FoldingSetNodeID ID; 5401 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5402 TypeConstraintConcept, TypeConstraintArgs); 5403 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5404 return QualType(AT, 0); 5405 5406 void *Mem = Allocate(sizeof(AutoType) + 5407 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5408 TypeAlignment); 5409 auto *AT = new (Mem) AutoType( 5410 DeducedType, Keyword, 5411 (IsDependent ? TypeDependence::DependentInstantiation 5412 : TypeDependence::None) | 5413 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5414 TypeConstraintConcept, TypeConstraintArgs); 5415 Types.push_back(AT); 5416 if (InsertPos) 5417 AutoTypes.InsertNode(AT, InsertPos); 5418 return QualType(AT, 0); 5419 } 5420 5421 /// Return the uniqued reference to the deduced template specialization type 5422 /// which has been deduced to the given type, or to the canonical undeduced 5423 /// such type, or the canonical deduced-but-dependent such type. 5424 QualType ASTContext::getDeducedTemplateSpecializationType( 5425 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5426 // Look in the folding set for an existing type. 5427 void *InsertPos = nullptr; 5428 llvm::FoldingSetNodeID ID; 5429 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5430 IsDependent); 5431 if (DeducedTemplateSpecializationType *DTST = 5432 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5433 return QualType(DTST, 0); 5434 5435 auto *DTST = new (*this, TypeAlignment) 5436 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5437 Types.push_back(DTST); 5438 if (InsertPos) 5439 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5440 return QualType(DTST, 0); 5441 } 5442 5443 /// getAtomicType - Return the uniqued reference to the atomic type for 5444 /// the given value type. 5445 QualType ASTContext::getAtomicType(QualType T) const { 5446 // Unique pointers, to guarantee there is only one pointer of a particular 5447 // structure. 5448 llvm::FoldingSetNodeID ID; 5449 AtomicType::Profile(ID, T); 5450 5451 void *InsertPos = nullptr; 5452 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5453 return QualType(AT, 0); 5454 5455 // If the atomic value type isn't canonical, this won't be a canonical type 5456 // either, so fill in the canonical type field. 5457 QualType Canonical; 5458 if (!T.isCanonical()) { 5459 Canonical = getAtomicType(getCanonicalType(T)); 5460 5461 // Get the new insert position for the node we care about. 5462 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5463 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5464 } 5465 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5466 Types.push_back(New); 5467 AtomicTypes.InsertNode(New, InsertPos); 5468 return QualType(New, 0); 5469 } 5470 5471 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5472 QualType ASTContext::getAutoDeductType() const { 5473 if (AutoDeductTy.isNull()) 5474 AutoDeductTy = QualType(new (*this, TypeAlignment) 5475 AutoType(QualType(), AutoTypeKeyword::Auto, 5476 TypeDependence::None, 5477 /*concept*/ nullptr, /*args*/ {}), 5478 0); 5479 return AutoDeductTy; 5480 } 5481 5482 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5483 QualType ASTContext::getAutoRRefDeductType() const { 5484 if (AutoRRefDeductTy.isNull()) 5485 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5486 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5487 return AutoRRefDeductTy; 5488 } 5489 5490 /// getTagDeclType - Return the unique reference to the type for the 5491 /// specified TagDecl (struct/union/class/enum) decl. 5492 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5493 assert(Decl); 5494 // FIXME: What is the design on getTagDeclType when it requires casting 5495 // away const? mutable? 5496 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5497 } 5498 5499 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5500 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5501 /// needs to agree with the definition in <stddef.h>. 5502 CanQualType ASTContext::getSizeType() const { 5503 return getFromTargetType(Target->getSizeType()); 5504 } 5505 5506 /// Return the unique signed counterpart of the integer type 5507 /// corresponding to size_t. 5508 CanQualType ASTContext::getSignedSizeType() const { 5509 return getFromTargetType(Target->getSignedSizeType()); 5510 } 5511 5512 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5513 CanQualType ASTContext::getIntMaxType() const { 5514 return getFromTargetType(Target->getIntMaxType()); 5515 } 5516 5517 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5518 CanQualType ASTContext::getUIntMaxType() const { 5519 return getFromTargetType(Target->getUIntMaxType()); 5520 } 5521 5522 /// getSignedWCharType - Return the type of "signed wchar_t". 5523 /// Used when in C++, as a GCC extension. 5524 QualType ASTContext::getSignedWCharType() const { 5525 // FIXME: derive from "Target" ? 5526 return WCharTy; 5527 } 5528 5529 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5530 /// Used when in C++, as a GCC extension. 5531 QualType ASTContext::getUnsignedWCharType() const { 5532 // FIXME: derive from "Target" ? 5533 return UnsignedIntTy; 5534 } 5535 5536 QualType ASTContext::getIntPtrType() const { 5537 return getFromTargetType(Target->getIntPtrType()); 5538 } 5539 5540 QualType ASTContext::getUIntPtrType() const { 5541 return getCorrespondingUnsignedType(getIntPtrType()); 5542 } 5543 5544 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5545 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5546 QualType ASTContext::getPointerDiffType() const { 5547 return getFromTargetType(Target->getPtrDiffType(0)); 5548 } 5549 5550 /// Return the unique unsigned counterpart of "ptrdiff_t" 5551 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5552 /// in the definition of %tu format specifier. 5553 QualType ASTContext::getUnsignedPointerDiffType() const { 5554 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5555 } 5556 5557 /// Return the unique type for "pid_t" defined in 5558 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5559 QualType ASTContext::getProcessIDType() const { 5560 return getFromTargetType(Target->getProcessIDType()); 5561 } 5562 5563 //===----------------------------------------------------------------------===// 5564 // Type Operators 5565 //===----------------------------------------------------------------------===// 5566 5567 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5568 // Push qualifiers into arrays, and then discard any remaining 5569 // qualifiers. 5570 T = getCanonicalType(T); 5571 T = getVariableArrayDecayedType(T); 5572 const Type *Ty = T.getTypePtr(); 5573 QualType Result; 5574 if (isa<ArrayType>(Ty)) { 5575 Result = getArrayDecayedType(QualType(Ty,0)); 5576 } else if (isa<FunctionType>(Ty)) { 5577 Result = getPointerType(QualType(Ty, 0)); 5578 } else { 5579 Result = QualType(Ty, 0); 5580 } 5581 5582 return CanQualType::CreateUnsafe(Result); 5583 } 5584 5585 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5586 Qualifiers &quals) { 5587 SplitQualType splitType = type.getSplitUnqualifiedType(); 5588 5589 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5590 // the unqualified desugared type and then drops it on the floor. 5591 // We then have to strip that sugar back off with 5592 // getUnqualifiedDesugaredType(), which is silly. 5593 const auto *AT = 5594 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5595 5596 // If we don't have an array, just use the results in splitType. 5597 if (!AT) { 5598 quals = splitType.Quals; 5599 return QualType(splitType.Ty, 0); 5600 } 5601 5602 // Otherwise, recurse on the array's element type. 5603 QualType elementType = AT->getElementType(); 5604 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5605 5606 // If that didn't change the element type, AT has no qualifiers, so we 5607 // can just use the results in splitType. 5608 if (elementType == unqualElementType) { 5609 assert(quals.empty()); // from the recursive call 5610 quals = splitType.Quals; 5611 return QualType(splitType.Ty, 0); 5612 } 5613 5614 // Otherwise, add in the qualifiers from the outermost type, then 5615 // build the type back up. 5616 quals.addConsistentQualifiers(splitType.Quals); 5617 5618 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5619 return getConstantArrayType(unqualElementType, CAT->getSize(), 5620 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5621 } 5622 5623 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5624 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5625 } 5626 5627 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5628 return getVariableArrayType(unqualElementType, 5629 VAT->getSizeExpr(), 5630 VAT->getSizeModifier(), 5631 VAT->getIndexTypeCVRQualifiers(), 5632 VAT->getBracketsRange()); 5633 } 5634 5635 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5636 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5637 DSAT->getSizeModifier(), 0, 5638 SourceRange()); 5639 } 5640 5641 /// Attempt to unwrap two types that may both be array types with the same bound 5642 /// (or both be array types of unknown bound) for the purpose of comparing the 5643 /// cv-decomposition of two types per C++ [conv.qual]. 5644 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5645 bool UnwrappedAny = false; 5646 while (true) { 5647 auto *AT1 = getAsArrayType(T1); 5648 if (!AT1) return UnwrappedAny; 5649 5650 auto *AT2 = getAsArrayType(T2); 5651 if (!AT2) return UnwrappedAny; 5652 5653 // If we don't have two array types with the same constant bound nor two 5654 // incomplete array types, we've unwrapped everything we can. 5655 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5656 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5657 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5658 return UnwrappedAny; 5659 } else if (!isa<IncompleteArrayType>(AT1) || 5660 !isa<IncompleteArrayType>(AT2)) { 5661 return UnwrappedAny; 5662 } 5663 5664 T1 = AT1->getElementType(); 5665 T2 = AT2->getElementType(); 5666 UnwrappedAny = true; 5667 } 5668 } 5669 5670 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5671 /// 5672 /// If T1 and T2 are both pointer types of the same kind, or both array types 5673 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5674 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5675 /// 5676 /// This function will typically be called in a loop that successively 5677 /// "unwraps" pointer and pointer-to-member types to compare them at each 5678 /// level. 5679 /// 5680 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5681 /// pair of types that can't be unwrapped further. 5682 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5683 UnwrapSimilarArrayTypes(T1, T2); 5684 5685 const auto *T1PtrType = T1->getAs<PointerType>(); 5686 const auto *T2PtrType = T2->getAs<PointerType>(); 5687 if (T1PtrType && T2PtrType) { 5688 T1 = T1PtrType->getPointeeType(); 5689 T2 = T2PtrType->getPointeeType(); 5690 return true; 5691 } 5692 5693 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5694 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5695 if (T1MPType && T2MPType && 5696 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5697 QualType(T2MPType->getClass(), 0))) { 5698 T1 = T1MPType->getPointeeType(); 5699 T2 = T2MPType->getPointeeType(); 5700 return true; 5701 } 5702 5703 if (getLangOpts().ObjC) { 5704 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5705 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5706 if (T1OPType && T2OPType) { 5707 T1 = T1OPType->getPointeeType(); 5708 T2 = T2OPType->getPointeeType(); 5709 return true; 5710 } 5711 } 5712 5713 // FIXME: Block pointers, too? 5714 5715 return false; 5716 } 5717 5718 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5719 while (true) { 5720 Qualifiers Quals; 5721 T1 = getUnqualifiedArrayType(T1, Quals); 5722 T2 = getUnqualifiedArrayType(T2, Quals); 5723 if (hasSameType(T1, T2)) 5724 return true; 5725 if (!UnwrapSimilarTypes(T1, T2)) 5726 return false; 5727 } 5728 } 5729 5730 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5731 while (true) { 5732 Qualifiers Quals1, Quals2; 5733 T1 = getUnqualifiedArrayType(T1, Quals1); 5734 T2 = getUnqualifiedArrayType(T2, Quals2); 5735 5736 Quals1.removeCVRQualifiers(); 5737 Quals2.removeCVRQualifiers(); 5738 if (Quals1 != Quals2) 5739 return false; 5740 5741 if (hasSameType(T1, T2)) 5742 return true; 5743 5744 if (!UnwrapSimilarTypes(T1, T2)) 5745 return false; 5746 } 5747 } 5748 5749 DeclarationNameInfo 5750 ASTContext::getNameForTemplate(TemplateName Name, 5751 SourceLocation NameLoc) const { 5752 switch (Name.getKind()) { 5753 case TemplateName::QualifiedTemplate: 5754 case TemplateName::Template: 5755 // DNInfo work in progress: CHECKME: what about DNLoc? 5756 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5757 NameLoc); 5758 5759 case TemplateName::OverloadedTemplate: { 5760 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5761 // DNInfo work in progress: CHECKME: what about DNLoc? 5762 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5763 } 5764 5765 case TemplateName::AssumedTemplate: { 5766 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 5767 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 5768 } 5769 5770 case TemplateName::DependentTemplate: { 5771 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5772 DeclarationName DName; 5773 if (DTN->isIdentifier()) { 5774 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5775 return DeclarationNameInfo(DName, NameLoc); 5776 } else { 5777 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5778 // DNInfo work in progress: FIXME: source locations? 5779 DeclarationNameLoc DNLoc; 5780 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 5781 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 5782 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5783 } 5784 } 5785 5786 case TemplateName::SubstTemplateTemplateParm: { 5787 SubstTemplateTemplateParmStorage *subst 5788 = Name.getAsSubstTemplateTemplateParm(); 5789 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5790 NameLoc); 5791 } 5792 5793 case TemplateName::SubstTemplateTemplateParmPack: { 5794 SubstTemplateTemplateParmPackStorage *subst 5795 = Name.getAsSubstTemplateTemplateParmPack(); 5796 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5797 NameLoc); 5798 } 5799 } 5800 5801 llvm_unreachable("bad template name kind!"); 5802 } 5803 5804 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5805 switch (Name.getKind()) { 5806 case TemplateName::QualifiedTemplate: 5807 case TemplateName::Template: { 5808 TemplateDecl *Template = Name.getAsTemplateDecl(); 5809 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5810 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5811 5812 // The canonical template name is the canonical template declaration. 5813 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5814 } 5815 5816 case TemplateName::OverloadedTemplate: 5817 case TemplateName::AssumedTemplate: 5818 llvm_unreachable("cannot canonicalize unresolved template"); 5819 5820 case TemplateName::DependentTemplate: { 5821 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5822 assert(DTN && "Non-dependent template names must refer to template decls."); 5823 return DTN->CanonicalTemplateName; 5824 } 5825 5826 case TemplateName::SubstTemplateTemplateParm: { 5827 SubstTemplateTemplateParmStorage *subst 5828 = Name.getAsSubstTemplateTemplateParm(); 5829 return getCanonicalTemplateName(subst->getReplacement()); 5830 } 5831 5832 case TemplateName::SubstTemplateTemplateParmPack: { 5833 SubstTemplateTemplateParmPackStorage *subst 5834 = Name.getAsSubstTemplateTemplateParmPack(); 5835 TemplateTemplateParmDecl *canonParameter 5836 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 5837 TemplateArgument canonArgPack 5838 = getCanonicalTemplateArgument(subst->getArgumentPack()); 5839 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 5840 } 5841 } 5842 5843 llvm_unreachable("bad template name!"); 5844 } 5845 5846 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 5847 X = getCanonicalTemplateName(X); 5848 Y = getCanonicalTemplateName(Y); 5849 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 5850 } 5851 5852 TemplateArgument 5853 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 5854 switch (Arg.getKind()) { 5855 case TemplateArgument::Null: 5856 return Arg; 5857 5858 case TemplateArgument::Expression: 5859 return Arg; 5860 5861 case TemplateArgument::Declaration: { 5862 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 5863 return TemplateArgument(D, Arg.getParamTypeForDecl()); 5864 } 5865 5866 case TemplateArgument::NullPtr: 5867 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 5868 /*isNullPtr*/true); 5869 5870 case TemplateArgument::Template: 5871 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 5872 5873 case TemplateArgument::TemplateExpansion: 5874 return TemplateArgument(getCanonicalTemplateName( 5875 Arg.getAsTemplateOrTemplatePattern()), 5876 Arg.getNumTemplateExpansions()); 5877 5878 case TemplateArgument::Integral: 5879 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 5880 5881 case TemplateArgument::Type: 5882 return TemplateArgument(getCanonicalType(Arg.getAsType())); 5883 5884 case TemplateArgument::Pack: { 5885 if (Arg.pack_size() == 0) 5886 return Arg; 5887 5888 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 5889 unsigned Idx = 0; 5890 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 5891 AEnd = Arg.pack_end(); 5892 A != AEnd; (void)++A, ++Idx) 5893 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 5894 5895 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 5896 } 5897 } 5898 5899 // Silence GCC warning 5900 llvm_unreachable("Unhandled template argument kind"); 5901 } 5902 5903 NestedNameSpecifier * 5904 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 5905 if (!NNS) 5906 return nullptr; 5907 5908 switch (NNS->getKind()) { 5909 case NestedNameSpecifier::Identifier: 5910 // Canonicalize the prefix but keep the identifier the same. 5911 return NestedNameSpecifier::Create(*this, 5912 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 5913 NNS->getAsIdentifier()); 5914 5915 case NestedNameSpecifier::Namespace: 5916 // A namespace is canonical; build a nested-name-specifier with 5917 // this namespace and no prefix. 5918 return NestedNameSpecifier::Create(*this, nullptr, 5919 NNS->getAsNamespace()->getOriginalNamespace()); 5920 5921 case NestedNameSpecifier::NamespaceAlias: 5922 // A namespace is canonical; build a nested-name-specifier with 5923 // this namespace and no prefix. 5924 return NestedNameSpecifier::Create(*this, nullptr, 5925 NNS->getAsNamespaceAlias()->getNamespace() 5926 ->getOriginalNamespace()); 5927 5928 case NestedNameSpecifier::TypeSpec: 5929 case NestedNameSpecifier::TypeSpecWithTemplate: { 5930 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 5931 5932 // If we have some kind of dependent-named type (e.g., "typename T::type"), 5933 // break it apart into its prefix and identifier, then reconsititute those 5934 // as the canonical nested-name-specifier. This is required to canonicalize 5935 // a dependent nested-name-specifier involving typedefs of dependent-name 5936 // types, e.g., 5937 // typedef typename T::type T1; 5938 // typedef typename T1::type T2; 5939 if (const auto *DNT = T->getAs<DependentNameType>()) 5940 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 5941 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 5942 5943 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 5944 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 5945 // first place? 5946 return NestedNameSpecifier::Create(*this, nullptr, false, 5947 const_cast<Type *>(T.getTypePtr())); 5948 } 5949 5950 case NestedNameSpecifier::Global: 5951 case NestedNameSpecifier::Super: 5952 // The global specifier and __super specifer are canonical and unique. 5953 return NNS; 5954 } 5955 5956 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 5957 } 5958 5959 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 5960 // Handle the non-qualified case efficiently. 5961 if (!T.hasLocalQualifiers()) { 5962 // Handle the common positive case fast. 5963 if (const auto *AT = dyn_cast<ArrayType>(T)) 5964 return AT; 5965 } 5966 5967 // Handle the common negative case fast. 5968 if (!isa<ArrayType>(T.getCanonicalType())) 5969 return nullptr; 5970 5971 // Apply any qualifiers from the array type to the element type. This 5972 // implements C99 6.7.3p8: "If the specification of an array type includes 5973 // any type qualifiers, the element type is so qualified, not the array type." 5974 5975 // If we get here, we either have type qualifiers on the type, or we have 5976 // sugar such as a typedef in the way. If we have type qualifiers on the type 5977 // we must propagate them down into the element type. 5978 5979 SplitQualType split = T.getSplitDesugaredType(); 5980 Qualifiers qs = split.Quals; 5981 5982 // If we have a simple case, just return now. 5983 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 5984 if (!ATy || qs.empty()) 5985 return ATy; 5986 5987 // Otherwise, we have an array and we have qualifiers on it. Push the 5988 // qualifiers into the array element type and return a new array type. 5989 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 5990 5991 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 5992 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 5993 CAT->getSizeExpr(), 5994 CAT->getSizeModifier(), 5995 CAT->getIndexTypeCVRQualifiers())); 5996 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 5997 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 5998 IAT->getSizeModifier(), 5999 IAT->getIndexTypeCVRQualifiers())); 6000 6001 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6002 return cast<ArrayType>( 6003 getDependentSizedArrayType(NewEltTy, 6004 DSAT->getSizeExpr(), 6005 DSAT->getSizeModifier(), 6006 DSAT->getIndexTypeCVRQualifiers(), 6007 DSAT->getBracketsRange())); 6008 6009 const auto *VAT = cast<VariableArrayType>(ATy); 6010 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6011 VAT->getSizeExpr(), 6012 VAT->getSizeModifier(), 6013 VAT->getIndexTypeCVRQualifiers(), 6014 VAT->getBracketsRange())); 6015 } 6016 6017 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6018 if (T->isArrayType() || T->isFunctionType()) 6019 return getDecayedType(T); 6020 return T; 6021 } 6022 6023 QualType ASTContext::getSignatureParameterType(QualType T) const { 6024 T = getVariableArrayDecayedType(T); 6025 T = getAdjustedParameterType(T); 6026 return T.getUnqualifiedType(); 6027 } 6028 6029 QualType ASTContext::getExceptionObjectType(QualType T) const { 6030 // C++ [except.throw]p3: 6031 // A throw-expression initializes a temporary object, called the exception 6032 // object, the type of which is determined by removing any top-level 6033 // cv-qualifiers from the static type of the operand of throw and adjusting 6034 // the type from "array of T" or "function returning T" to "pointer to T" 6035 // or "pointer to function returning T", [...] 6036 T = getVariableArrayDecayedType(T); 6037 if (T->isArrayType() || T->isFunctionType()) 6038 T = getDecayedType(T); 6039 return T.getUnqualifiedType(); 6040 } 6041 6042 /// getArrayDecayedType - Return the properly qualified result of decaying the 6043 /// specified array type to a pointer. This operation is non-trivial when 6044 /// handling typedefs etc. The canonical type of "T" must be an array type, 6045 /// this returns a pointer to a properly qualified element of the array. 6046 /// 6047 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6048 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6049 // Get the element type with 'getAsArrayType' so that we don't lose any 6050 // typedefs in the element type of the array. This also handles propagation 6051 // of type qualifiers from the array type into the element type if present 6052 // (C99 6.7.3p8). 6053 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6054 assert(PrettyArrayType && "Not an array type!"); 6055 6056 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6057 6058 // int x[restrict 4] -> int *restrict 6059 QualType Result = getQualifiedType(PtrTy, 6060 PrettyArrayType->getIndexTypeQualifiers()); 6061 6062 // int x[_Nullable] -> int * _Nullable 6063 if (auto Nullability = Ty->getNullability(*this)) { 6064 Result = const_cast<ASTContext *>(this)->getAttributedType( 6065 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6066 } 6067 return Result; 6068 } 6069 6070 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6071 return getBaseElementType(array->getElementType()); 6072 } 6073 6074 QualType ASTContext::getBaseElementType(QualType type) const { 6075 Qualifiers qs; 6076 while (true) { 6077 SplitQualType split = type.getSplitDesugaredType(); 6078 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6079 if (!array) break; 6080 6081 type = array->getElementType(); 6082 qs.addConsistentQualifiers(split.Quals); 6083 } 6084 6085 return getQualifiedType(type, qs); 6086 } 6087 6088 /// getConstantArrayElementCount - Returns number of constant array elements. 6089 uint64_t 6090 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6091 uint64_t ElementCount = 1; 6092 do { 6093 ElementCount *= CA->getSize().getZExtValue(); 6094 CA = dyn_cast_or_null<ConstantArrayType>( 6095 CA->getElementType()->getAsArrayTypeUnsafe()); 6096 } while (CA); 6097 return ElementCount; 6098 } 6099 6100 /// getFloatingRank - Return a relative rank for floating point types. 6101 /// This routine will assert if passed a built-in type that isn't a float. 6102 static FloatingRank getFloatingRank(QualType T) { 6103 if (const auto *CT = T->getAs<ComplexType>()) 6104 return getFloatingRank(CT->getElementType()); 6105 6106 switch (T->castAs<BuiltinType>()->getKind()) { 6107 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6108 case BuiltinType::Float16: return Float16Rank; 6109 case BuiltinType::Half: return HalfRank; 6110 case BuiltinType::Float: return FloatRank; 6111 case BuiltinType::Double: return DoubleRank; 6112 case BuiltinType::LongDouble: return LongDoubleRank; 6113 case BuiltinType::Float128: return Float128Rank; 6114 case BuiltinType::BFloat16: return BFloat16Rank; 6115 } 6116 } 6117 6118 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6119 /// point or a complex type (based on typeDomain/typeSize). 6120 /// 'typeDomain' is a real floating point or complex type. 6121 /// 'typeSize' is a real floating point or complex type. 6122 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6123 QualType Domain) const { 6124 FloatingRank EltRank = getFloatingRank(Size); 6125 if (Domain->isComplexType()) { 6126 switch (EltRank) { 6127 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6128 case Float16Rank: 6129 case HalfRank: llvm_unreachable("Complex half is not supported"); 6130 case FloatRank: return FloatComplexTy; 6131 case DoubleRank: return DoubleComplexTy; 6132 case LongDoubleRank: return LongDoubleComplexTy; 6133 case Float128Rank: return Float128ComplexTy; 6134 } 6135 } 6136 6137 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6138 switch (EltRank) { 6139 case Float16Rank: return HalfTy; 6140 case BFloat16Rank: return BFloat16Ty; 6141 case HalfRank: return HalfTy; 6142 case FloatRank: return FloatTy; 6143 case DoubleRank: return DoubleTy; 6144 case LongDoubleRank: return LongDoubleTy; 6145 case Float128Rank: return Float128Ty; 6146 } 6147 llvm_unreachable("getFloatingRank(): illegal value for rank"); 6148 } 6149 6150 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6151 /// point types, ignoring the domain of the type (i.e. 'double' == 6152 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6153 /// LHS < RHS, return -1. 6154 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6155 FloatingRank LHSR = getFloatingRank(LHS); 6156 FloatingRank RHSR = getFloatingRank(RHS); 6157 6158 if (LHSR == RHSR) 6159 return 0; 6160 if (LHSR > RHSR) 6161 return 1; 6162 return -1; 6163 } 6164 6165 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6166 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6167 return 0; 6168 return getFloatingTypeOrder(LHS, RHS); 6169 } 6170 6171 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6172 /// routine will assert if passed a built-in type that isn't an integer or enum, 6173 /// or if it is not canonicalized. 6174 unsigned ASTContext::getIntegerRank(const Type *T) const { 6175 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6176 6177 // Results in this 'losing' to any type of the same size, but winning if 6178 // larger. 6179 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 6180 return 0 + (EIT->getNumBits() << 3); 6181 6182 switch (cast<BuiltinType>(T)->getKind()) { 6183 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6184 case BuiltinType::Bool: 6185 return 1 + (getIntWidth(BoolTy) << 3); 6186 case BuiltinType::Char_S: 6187 case BuiltinType::Char_U: 6188 case BuiltinType::SChar: 6189 case BuiltinType::UChar: 6190 return 2 + (getIntWidth(CharTy) << 3); 6191 case BuiltinType::Short: 6192 case BuiltinType::UShort: 6193 return 3 + (getIntWidth(ShortTy) << 3); 6194 case BuiltinType::Int: 6195 case BuiltinType::UInt: 6196 return 4 + (getIntWidth(IntTy) << 3); 6197 case BuiltinType::Long: 6198 case BuiltinType::ULong: 6199 return 5 + (getIntWidth(LongTy) << 3); 6200 case BuiltinType::LongLong: 6201 case BuiltinType::ULongLong: 6202 return 6 + (getIntWidth(LongLongTy) << 3); 6203 case BuiltinType::Int128: 6204 case BuiltinType::UInt128: 6205 return 7 + (getIntWidth(Int128Ty) << 3); 6206 } 6207 } 6208 6209 /// Whether this is a promotable bitfield reference according 6210 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6211 /// 6212 /// \returns the type this bit-field will promote to, or NULL if no 6213 /// promotion occurs. 6214 QualType ASTContext::isPromotableBitField(Expr *E) const { 6215 if (E->isTypeDependent() || E->isValueDependent()) 6216 return {}; 6217 6218 // C++ [conv.prom]p5: 6219 // If the bit-field has an enumerated type, it is treated as any other 6220 // value of that type for promotion purposes. 6221 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6222 return {}; 6223 6224 // FIXME: We should not do this unless E->refersToBitField() is true. This 6225 // matters in C where getSourceBitField() will find bit-fields for various 6226 // cases where the source expression is not a bit-field designator. 6227 6228 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6229 if (!Field) 6230 return {}; 6231 6232 QualType FT = Field->getType(); 6233 6234 uint64_t BitWidth = Field->getBitWidthValue(*this); 6235 uint64_t IntSize = getTypeSize(IntTy); 6236 // C++ [conv.prom]p5: 6237 // A prvalue for an integral bit-field can be converted to a prvalue of type 6238 // int if int can represent all the values of the bit-field; otherwise, it 6239 // can be converted to unsigned int if unsigned int can represent all the 6240 // values of the bit-field. If the bit-field is larger yet, no integral 6241 // promotion applies to it. 6242 // C11 6.3.1.1/2: 6243 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6244 // If an int can represent all values of the original type (as restricted by 6245 // the width, for a bit-field), the value is converted to an int; otherwise, 6246 // it is converted to an unsigned int. 6247 // 6248 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6249 // We perform that promotion here to match GCC and C++. 6250 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6251 // greater than that of 'int'. We perform that promotion to match GCC. 6252 if (BitWidth < IntSize) 6253 return IntTy; 6254 6255 if (BitWidth == IntSize) 6256 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6257 6258 // Bit-fields wider than int are not subject to promotions, and therefore act 6259 // like the base type. GCC has some weird bugs in this area that we 6260 // deliberately do not follow (GCC follows a pre-standard resolution to 6261 // C's DR315 which treats bit-width as being part of the type, and this leaks 6262 // into their semantics in some cases). 6263 return {}; 6264 } 6265 6266 /// getPromotedIntegerType - Returns the type that Promotable will 6267 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6268 /// integer type. 6269 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6270 assert(!Promotable.isNull()); 6271 assert(Promotable->isPromotableIntegerType()); 6272 if (const auto *ET = Promotable->getAs<EnumType>()) 6273 return ET->getDecl()->getPromotionType(); 6274 6275 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6276 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6277 // (3.9.1) can be converted to a prvalue of the first of the following 6278 // types that can represent all the values of its underlying type: 6279 // int, unsigned int, long int, unsigned long int, long long int, or 6280 // unsigned long long int [...] 6281 // FIXME: Is there some better way to compute this? 6282 if (BT->getKind() == BuiltinType::WChar_S || 6283 BT->getKind() == BuiltinType::WChar_U || 6284 BT->getKind() == BuiltinType::Char8 || 6285 BT->getKind() == BuiltinType::Char16 || 6286 BT->getKind() == BuiltinType::Char32) { 6287 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6288 uint64_t FromSize = getTypeSize(BT); 6289 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6290 LongLongTy, UnsignedLongLongTy }; 6291 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6292 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6293 if (FromSize < ToSize || 6294 (FromSize == ToSize && 6295 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6296 return PromoteTypes[Idx]; 6297 } 6298 llvm_unreachable("char type should fit into long long"); 6299 } 6300 } 6301 6302 // At this point, we should have a signed or unsigned integer type. 6303 if (Promotable->isSignedIntegerType()) 6304 return IntTy; 6305 uint64_t PromotableSize = getIntWidth(Promotable); 6306 uint64_t IntSize = getIntWidth(IntTy); 6307 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6308 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6309 } 6310 6311 /// Recurses in pointer/array types until it finds an objc retainable 6312 /// type and returns its ownership. 6313 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6314 while (!T.isNull()) { 6315 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6316 return T.getObjCLifetime(); 6317 if (T->isArrayType()) 6318 T = getBaseElementType(T); 6319 else if (const auto *PT = T->getAs<PointerType>()) 6320 T = PT->getPointeeType(); 6321 else if (const auto *RT = T->getAs<ReferenceType>()) 6322 T = RT->getPointeeType(); 6323 else 6324 break; 6325 } 6326 6327 return Qualifiers::OCL_None; 6328 } 6329 6330 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6331 // Incomplete enum types are not treated as integer types. 6332 // FIXME: In C++, enum types are never integer types. 6333 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6334 return ET->getDecl()->getIntegerType().getTypePtr(); 6335 return nullptr; 6336 } 6337 6338 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6339 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6340 /// LHS < RHS, return -1. 6341 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6342 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6343 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6344 6345 // Unwrap enums to their underlying type. 6346 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6347 LHSC = getIntegerTypeForEnum(ET); 6348 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 6349 RHSC = getIntegerTypeForEnum(ET); 6350 6351 if (LHSC == RHSC) return 0; 6352 6353 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 6354 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 6355 6356 unsigned LHSRank = getIntegerRank(LHSC); 6357 unsigned RHSRank = getIntegerRank(RHSC); 6358 6359 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 6360 if (LHSRank == RHSRank) return 0; 6361 return LHSRank > RHSRank ? 1 : -1; 6362 } 6363 6364 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 6365 if (LHSUnsigned) { 6366 // If the unsigned [LHS] type is larger, return it. 6367 if (LHSRank >= RHSRank) 6368 return 1; 6369 6370 // If the signed type can represent all values of the unsigned type, it 6371 // wins. Because we are dealing with 2's complement and types that are 6372 // powers of two larger than each other, this is always safe. 6373 return -1; 6374 } 6375 6376 // If the unsigned [RHS] type is larger, return it. 6377 if (RHSRank >= LHSRank) 6378 return -1; 6379 6380 // If the signed type can represent all values of the unsigned type, it 6381 // wins. Because we are dealing with 2's complement and types that are 6382 // powers of two larger than each other, this is always safe. 6383 return 1; 6384 } 6385 6386 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 6387 if (CFConstantStringTypeDecl) 6388 return CFConstantStringTypeDecl; 6389 6390 assert(!CFConstantStringTagDecl && 6391 "tag and typedef should be initialized together"); 6392 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 6393 CFConstantStringTagDecl->startDefinition(); 6394 6395 struct { 6396 QualType Type; 6397 const char *Name; 6398 } Fields[5]; 6399 unsigned Count = 0; 6400 6401 /// Objective-C ABI 6402 /// 6403 /// typedef struct __NSConstantString_tag { 6404 /// const int *isa; 6405 /// int flags; 6406 /// const char *str; 6407 /// long length; 6408 /// } __NSConstantString; 6409 /// 6410 /// Swift ABI (4.1, 4.2) 6411 /// 6412 /// typedef struct __NSConstantString_tag { 6413 /// uintptr_t _cfisa; 6414 /// uintptr_t _swift_rc; 6415 /// _Atomic(uint64_t) _cfinfoa; 6416 /// const char *_ptr; 6417 /// uint32_t _length; 6418 /// } __NSConstantString; 6419 /// 6420 /// Swift ABI (5.0) 6421 /// 6422 /// typedef struct __NSConstantString_tag { 6423 /// uintptr_t _cfisa; 6424 /// uintptr_t _swift_rc; 6425 /// _Atomic(uint64_t) _cfinfoa; 6426 /// const char *_ptr; 6427 /// uintptr_t _length; 6428 /// } __NSConstantString; 6429 6430 const auto CFRuntime = getLangOpts().CFRuntime; 6431 if (static_cast<unsigned>(CFRuntime) < 6432 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 6433 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 6434 Fields[Count++] = { IntTy, "flags" }; 6435 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 6436 Fields[Count++] = { LongTy, "length" }; 6437 } else { 6438 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 6439 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 6440 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 6441 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 6442 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6443 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6444 Fields[Count++] = { IntTy, "_ptr" }; 6445 else 6446 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 6447 } 6448 6449 // Create fields 6450 for (unsigned i = 0; i < Count; ++i) { 6451 FieldDecl *Field = 6452 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 6453 SourceLocation(), &Idents.get(Fields[i].Name), 6454 Fields[i].Type, /*TInfo=*/nullptr, 6455 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6456 Field->setAccess(AS_public); 6457 CFConstantStringTagDecl->addDecl(Field); 6458 } 6459 6460 CFConstantStringTagDecl->completeDefinition(); 6461 // This type is designed to be compatible with NSConstantString, but cannot 6462 // use the same name, since NSConstantString is an interface. 6463 auto tagType = getTagDeclType(CFConstantStringTagDecl); 6464 CFConstantStringTypeDecl = 6465 buildImplicitTypedef(tagType, "__NSConstantString"); 6466 6467 return CFConstantStringTypeDecl; 6468 } 6469 6470 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 6471 if (!CFConstantStringTagDecl) 6472 getCFConstantStringDecl(); // Build the tag and the typedef. 6473 return CFConstantStringTagDecl; 6474 } 6475 6476 // getCFConstantStringType - Return the type used for constant CFStrings. 6477 QualType ASTContext::getCFConstantStringType() const { 6478 return getTypedefType(getCFConstantStringDecl()); 6479 } 6480 6481 QualType ASTContext::getObjCSuperType() const { 6482 if (ObjCSuperType.isNull()) { 6483 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 6484 TUDecl->addDecl(ObjCSuperTypeDecl); 6485 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 6486 } 6487 return ObjCSuperType; 6488 } 6489 6490 void ASTContext::setCFConstantStringType(QualType T) { 6491 const auto *TD = T->castAs<TypedefType>(); 6492 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 6493 const auto *TagType = 6494 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 6495 CFConstantStringTagDecl = TagType->getDecl(); 6496 } 6497 6498 QualType ASTContext::getBlockDescriptorType() const { 6499 if (BlockDescriptorType) 6500 return getTagDeclType(BlockDescriptorType); 6501 6502 RecordDecl *RD; 6503 // FIXME: Needs the FlagAppleBlock bit. 6504 RD = buildImplicitRecord("__block_descriptor"); 6505 RD->startDefinition(); 6506 6507 QualType FieldTypes[] = { 6508 UnsignedLongTy, 6509 UnsignedLongTy, 6510 }; 6511 6512 static const char *const FieldNames[] = { 6513 "reserved", 6514 "Size" 6515 }; 6516 6517 for (size_t i = 0; i < 2; ++i) { 6518 FieldDecl *Field = FieldDecl::Create( 6519 *this, RD, SourceLocation(), SourceLocation(), 6520 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6521 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6522 Field->setAccess(AS_public); 6523 RD->addDecl(Field); 6524 } 6525 6526 RD->completeDefinition(); 6527 6528 BlockDescriptorType = RD; 6529 6530 return getTagDeclType(BlockDescriptorType); 6531 } 6532 6533 QualType ASTContext::getBlockDescriptorExtendedType() const { 6534 if (BlockDescriptorExtendedType) 6535 return getTagDeclType(BlockDescriptorExtendedType); 6536 6537 RecordDecl *RD; 6538 // FIXME: Needs the FlagAppleBlock bit. 6539 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 6540 RD->startDefinition(); 6541 6542 QualType FieldTypes[] = { 6543 UnsignedLongTy, 6544 UnsignedLongTy, 6545 getPointerType(VoidPtrTy), 6546 getPointerType(VoidPtrTy) 6547 }; 6548 6549 static const char *const FieldNames[] = { 6550 "reserved", 6551 "Size", 6552 "CopyFuncPtr", 6553 "DestroyFuncPtr" 6554 }; 6555 6556 for (size_t i = 0; i < 4; ++i) { 6557 FieldDecl *Field = FieldDecl::Create( 6558 *this, RD, SourceLocation(), SourceLocation(), 6559 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6560 /*BitWidth=*/nullptr, 6561 /*Mutable=*/false, ICIS_NoInit); 6562 Field->setAccess(AS_public); 6563 RD->addDecl(Field); 6564 } 6565 6566 RD->completeDefinition(); 6567 6568 BlockDescriptorExtendedType = RD; 6569 return getTagDeclType(BlockDescriptorExtendedType); 6570 } 6571 6572 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 6573 const auto *BT = dyn_cast<BuiltinType>(T); 6574 6575 if (!BT) { 6576 if (isa<PipeType>(T)) 6577 return OCLTK_Pipe; 6578 6579 return OCLTK_Default; 6580 } 6581 6582 switch (BT->getKind()) { 6583 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6584 case BuiltinType::Id: \ 6585 return OCLTK_Image; 6586 #include "clang/Basic/OpenCLImageTypes.def" 6587 6588 case BuiltinType::OCLClkEvent: 6589 return OCLTK_ClkEvent; 6590 6591 case BuiltinType::OCLEvent: 6592 return OCLTK_Event; 6593 6594 case BuiltinType::OCLQueue: 6595 return OCLTK_Queue; 6596 6597 case BuiltinType::OCLReserveID: 6598 return OCLTK_ReserveID; 6599 6600 case BuiltinType::OCLSampler: 6601 return OCLTK_Sampler; 6602 6603 default: 6604 return OCLTK_Default; 6605 } 6606 } 6607 6608 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 6609 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 6610 } 6611 6612 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 6613 /// requires copy/dispose. Note that this must match the logic 6614 /// in buildByrefHelpers. 6615 bool ASTContext::BlockRequiresCopying(QualType Ty, 6616 const VarDecl *D) { 6617 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 6618 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 6619 if (!copyExpr && record->hasTrivialDestructor()) return false; 6620 6621 return true; 6622 } 6623 6624 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 6625 // move or destroy. 6626 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 6627 return true; 6628 6629 if (!Ty->isObjCRetainableType()) return false; 6630 6631 Qualifiers qs = Ty.getQualifiers(); 6632 6633 // If we have lifetime, that dominates. 6634 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 6635 switch (lifetime) { 6636 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 6637 6638 // These are just bits as far as the runtime is concerned. 6639 case Qualifiers::OCL_ExplicitNone: 6640 case Qualifiers::OCL_Autoreleasing: 6641 return false; 6642 6643 // These cases should have been taken care of when checking the type's 6644 // non-triviality. 6645 case Qualifiers::OCL_Weak: 6646 case Qualifiers::OCL_Strong: 6647 llvm_unreachable("impossible"); 6648 } 6649 llvm_unreachable("fell out of lifetime switch!"); 6650 } 6651 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6652 Ty->isObjCObjectPointerType()); 6653 } 6654 6655 bool ASTContext::getByrefLifetime(QualType Ty, 6656 Qualifiers::ObjCLifetime &LifeTime, 6657 bool &HasByrefExtendedLayout) const { 6658 if (!getLangOpts().ObjC || 6659 getLangOpts().getGC() != LangOptions::NonGC) 6660 return false; 6661 6662 HasByrefExtendedLayout = false; 6663 if (Ty->isRecordType()) { 6664 HasByrefExtendedLayout = true; 6665 LifeTime = Qualifiers::OCL_None; 6666 } else if ((LifeTime = Ty.getObjCLifetime())) { 6667 // Honor the ARC qualifiers. 6668 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6669 // The MRR rule. 6670 LifeTime = Qualifiers::OCL_ExplicitNone; 6671 } else { 6672 LifeTime = Qualifiers::OCL_None; 6673 } 6674 return true; 6675 } 6676 6677 CanQualType ASTContext::getNSUIntegerType() const { 6678 assert(Target && "Expected target to be initialized"); 6679 const llvm::Triple &T = Target->getTriple(); 6680 // Windows is LLP64 rather than LP64 6681 if (T.isOSWindows() && T.isArch64Bit()) 6682 return UnsignedLongLongTy; 6683 return UnsignedLongTy; 6684 } 6685 6686 CanQualType ASTContext::getNSIntegerType() const { 6687 assert(Target && "Expected target to be initialized"); 6688 const llvm::Triple &T = Target->getTriple(); 6689 // Windows is LLP64 rather than LP64 6690 if (T.isOSWindows() && T.isArch64Bit()) 6691 return LongLongTy; 6692 return LongTy; 6693 } 6694 6695 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6696 if (!ObjCInstanceTypeDecl) 6697 ObjCInstanceTypeDecl = 6698 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6699 return ObjCInstanceTypeDecl; 6700 } 6701 6702 // This returns true if a type has been typedefed to BOOL: 6703 // typedef <type> BOOL; 6704 static bool isTypeTypedefedAsBOOL(QualType T) { 6705 if (const auto *TT = dyn_cast<TypedefType>(T)) 6706 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6707 return II->isStr("BOOL"); 6708 6709 return false; 6710 } 6711 6712 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6713 /// purpose. 6714 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6715 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6716 return CharUnits::Zero(); 6717 6718 CharUnits sz = getTypeSizeInChars(type); 6719 6720 // Make all integer and enum types at least as large as an int 6721 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6722 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6723 // Treat arrays as pointers, since that's how they're passed in. 6724 else if (type->isArrayType()) 6725 sz = getTypeSizeInChars(VoidPtrTy); 6726 return sz; 6727 } 6728 6729 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6730 return getTargetInfo().getCXXABI().isMicrosoft() && 6731 VD->isStaticDataMember() && 6732 VD->getType()->isIntegralOrEnumerationType() && 6733 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6734 } 6735 6736 ASTContext::InlineVariableDefinitionKind 6737 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6738 if (!VD->isInline()) 6739 return InlineVariableDefinitionKind::None; 6740 6741 // In almost all cases, it's a weak definition. 6742 auto *First = VD->getFirstDecl(); 6743 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6744 return InlineVariableDefinitionKind::Weak; 6745 6746 // If there's a file-context declaration in this translation unit, it's a 6747 // non-discardable definition. 6748 for (auto *D : VD->redecls()) 6749 if (D->getLexicalDeclContext()->isFileContext() && 6750 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6751 return InlineVariableDefinitionKind::Strong; 6752 6753 // If we've not seen one yet, we don't know. 6754 return InlineVariableDefinitionKind::WeakUnknown; 6755 } 6756 6757 static std::string charUnitsToString(const CharUnits &CU) { 6758 return llvm::itostr(CU.getQuantity()); 6759 } 6760 6761 /// getObjCEncodingForBlock - Return the encoded type for this block 6762 /// declaration. 6763 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6764 std::string S; 6765 6766 const BlockDecl *Decl = Expr->getBlockDecl(); 6767 QualType BlockTy = 6768 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 6769 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 6770 // Encode result type. 6771 if (getLangOpts().EncodeExtendedBlockSig) 6772 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 6773 true /*Extended*/); 6774 else 6775 getObjCEncodingForType(BlockReturnTy, S); 6776 // Compute size of all parameters. 6777 // Start with computing size of a pointer in number of bytes. 6778 // FIXME: There might(should) be a better way of doing this computation! 6779 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6780 CharUnits ParmOffset = PtrSize; 6781 for (auto PI : Decl->parameters()) { 6782 QualType PType = PI->getType(); 6783 CharUnits sz = getObjCEncodingTypeSize(PType); 6784 if (sz.isZero()) 6785 continue; 6786 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6787 ParmOffset += sz; 6788 } 6789 // Size of the argument frame 6790 S += charUnitsToString(ParmOffset); 6791 // Block pointer and offset. 6792 S += "@?0"; 6793 6794 // Argument types. 6795 ParmOffset = PtrSize; 6796 for (auto PVDecl : Decl->parameters()) { 6797 QualType PType = PVDecl->getOriginalType(); 6798 if (const auto *AT = 6799 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6800 // Use array's original type only if it has known number of 6801 // elements. 6802 if (!isa<ConstantArrayType>(AT)) 6803 PType = PVDecl->getType(); 6804 } else if (PType->isFunctionType()) 6805 PType = PVDecl->getType(); 6806 if (getLangOpts().EncodeExtendedBlockSig) 6807 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6808 S, true /*Extended*/); 6809 else 6810 getObjCEncodingForType(PType, S); 6811 S += charUnitsToString(ParmOffset); 6812 ParmOffset += getObjCEncodingTypeSize(PType); 6813 } 6814 6815 return S; 6816 } 6817 6818 std::string 6819 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6820 std::string S; 6821 // Encode result type. 6822 getObjCEncodingForType(Decl->getReturnType(), S); 6823 CharUnits ParmOffset; 6824 // Compute size of all parameters. 6825 for (auto PI : Decl->parameters()) { 6826 QualType PType = PI->getType(); 6827 CharUnits sz = getObjCEncodingTypeSize(PType); 6828 if (sz.isZero()) 6829 continue; 6830 6831 assert(sz.isPositive() && 6832 "getObjCEncodingForFunctionDecl - Incomplete param type"); 6833 ParmOffset += sz; 6834 } 6835 S += charUnitsToString(ParmOffset); 6836 ParmOffset = CharUnits::Zero(); 6837 6838 // Argument types. 6839 for (auto PVDecl : Decl->parameters()) { 6840 QualType PType = PVDecl->getOriginalType(); 6841 if (const auto *AT = 6842 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6843 // Use array's original type only if it has known number of 6844 // elements. 6845 if (!isa<ConstantArrayType>(AT)) 6846 PType = PVDecl->getType(); 6847 } else if (PType->isFunctionType()) 6848 PType = PVDecl->getType(); 6849 getObjCEncodingForType(PType, S); 6850 S += charUnitsToString(ParmOffset); 6851 ParmOffset += getObjCEncodingTypeSize(PType); 6852 } 6853 6854 return S; 6855 } 6856 6857 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 6858 /// method parameter or return type. If Extended, include class names and 6859 /// block object types. 6860 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 6861 QualType T, std::string& S, 6862 bool Extended) const { 6863 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 6864 getObjCEncodingForTypeQualifier(QT, S); 6865 // Encode parameter type. 6866 ObjCEncOptions Options = ObjCEncOptions() 6867 .setExpandPointedToStructures() 6868 .setExpandStructures() 6869 .setIsOutermostType(); 6870 if (Extended) 6871 Options.setEncodeBlockParameters().setEncodeClassNames(); 6872 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 6873 } 6874 6875 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 6876 /// declaration. 6877 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 6878 bool Extended) const { 6879 // FIXME: This is not very efficient. 6880 // Encode return type. 6881 std::string S; 6882 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 6883 Decl->getReturnType(), S, Extended); 6884 // Compute size of all parameters. 6885 // Start with computing size of a pointer in number of bytes. 6886 // FIXME: There might(should) be a better way of doing this computation! 6887 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6888 // The first two arguments (self and _cmd) are pointers; account for 6889 // their size. 6890 CharUnits ParmOffset = 2 * PtrSize; 6891 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6892 E = Decl->sel_param_end(); PI != E; ++PI) { 6893 QualType PType = (*PI)->getType(); 6894 CharUnits sz = getObjCEncodingTypeSize(PType); 6895 if (sz.isZero()) 6896 continue; 6897 6898 assert(sz.isPositive() && 6899 "getObjCEncodingForMethodDecl - Incomplete param type"); 6900 ParmOffset += sz; 6901 } 6902 S += charUnitsToString(ParmOffset); 6903 S += "@0:"; 6904 S += charUnitsToString(PtrSize); 6905 6906 // Argument types. 6907 ParmOffset = 2 * PtrSize; 6908 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6909 E = Decl->sel_param_end(); PI != E; ++PI) { 6910 const ParmVarDecl *PVDecl = *PI; 6911 QualType PType = PVDecl->getOriginalType(); 6912 if (const auto *AT = 6913 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6914 // Use array's original type only if it has known number of 6915 // elements. 6916 if (!isa<ConstantArrayType>(AT)) 6917 PType = PVDecl->getType(); 6918 } else if (PType->isFunctionType()) 6919 PType = PVDecl->getType(); 6920 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 6921 PType, S, Extended); 6922 S += charUnitsToString(ParmOffset); 6923 ParmOffset += getObjCEncodingTypeSize(PType); 6924 } 6925 6926 return S; 6927 } 6928 6929 ObjCPropertyImplDecl * 6930 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 6931 const ObjCPropertyDecl *PD, 6932 const Decl *Container) const { 6933 if (!Container) 6934 return nullptr; 6935 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 6936 for (auto *PID : CID->property_impls()) 6937 if (PID->getPropertyDecl() == PD) 6938 return PID; 6939 } else { 6940 const auto *OID = cast<ObjCImplementationDecl>(Container); 6941 for (auto *PID : OID->property_impls()) 6942 if (PID->getPropertyDecl() == PD) 6943 return PID; 6944 } 6945 return nullptr; 6946 } 6947 6948 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 6949 /// property declaration. If non-NULL, Container must be either an 6950 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 6951 /// NULL when getting encodings for protocol properties. 6952 /// Property attributes are stored as a comma-delimited C string. The simple 6953 /// attributes readonly and bycopy are encoded as single characters. The 6954 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 6955 /// encoded as single characters, followed by an identifier. Property types 6956 /// are also encoded as a parametrized attribute. The characters used to encode 6957 /// these attributes are defined by the following enumeration: 6958 /// @code 6959 /// enum PropertyAttributes { 6960 /// kPropertyReadOnly = 'R', // property is read-only. 6961 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 6962 /// kPropertyByref = '&', // property is a reference to the value last assigned 6963 /// kPropertyDynamic = 'D', // property is dynamic 6964 /// kPropertyGetter = 'G', // followed by getter selector name 6965 /// kPropertySetter = 'S', // followed by setter selector name 6966 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 6967 /// kPropertyType = 'T' // followed by old-style type encoding. 6968 /// kPropertyWeak = 'W' // 'weak' property 6969 /// kPropertyStrong = 'P' // property GC'able 6970 /// kPropertyNonAtomic = 'N' // property non-atomic 6971 /// }; 6972 /// @endcode 6973 std::string 6974 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 6975 const Decl *Container) const { 6976 // Collect information from the property implementation decl(s). 6977 bool Dynamic = false; 6978 ObjCPropertyImplDecl *SynthesizePID = nullptr; 6979 6980 if (ObjCPropertyImplDecl *PropertyImpDecl = 6981 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 6982 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 6983 Dynamic = true; 6984 else 6985 SynthesizePID = PropertyImpDecl; 6986 } 6987 6988 // FIXME: This is not very efficient. 6989 std::string S = "T"; 6990 6991 // Encode result type. 6992 // GCC has some special rules regarding encoding of properties which 6993 // closely resembles encoding of ivars. 6994 getObjCEncodingForPropertyType(PD->getType(), S); 6995 6996 if (PD->isReadOnly()) { 6997 S += ",R"; 6998 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 6999 S += ",C"; 7000 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7001 S += ",&"; 7002 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7003 S += ",W"; 7004 } else { 7005 switch (PD->getSetterKind()) { 7006 case ObjCPropertyDecl::Assign: break; 7007 case ObjCPropertyDecl::Copy: S += ",C"; break; 7008 case ObjCPropertyDecl::Retain: S += ",&"; break; 7009 case ObjCPropertyDecl::Weak: S += ",W"; break; 7010 } 7011 } 7012 7013 // It really isn't clear at all what this means, since properties 7014 // are "dynamic by default". 7015 if (Dynamic) 7016 S += ",D"; 7017 7018 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7019 S += ",N"; 7020 7021 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7022 S += ",G"; 7023 S += PD->getGetterName().getAsString(); 7024 } 7025 7026 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7027 S += ",S"; 7028 S += PD->getSetterName().getAsString(); 7029 } 7030 7031 if (SynthesizePID) { 7032 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7033 S += ",V"; 7034 S += OID->getNameAsString(); 7035 } 7036 7037 // FIXME: OBJCGC: weak & strong 7038 return S; 7039 } 7040 7041 /// getLegacyIntegralTypeEncoding - 7042 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7043 /// 'l' or 'L' , but not always. For typedefs, we need to use 7044 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7045 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7046 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7047 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7048 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7049 PointeeTy = UnsignedIntTy; 7050 else 7051 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7052 PointeeTy = IntTy; 7053 } 7054 } 7055 } 7056 7057 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7058 const FieldDecl *Field, 7059 QualType *NotEncodedT) const { 7060 // We follow the behavior of gcc, expanding structures which are 7061 // directly pointed to, and expanding embedded structures. Note that 7062 // these rules are sufficient to prevent recursive encoding of the 7063 // same type. 7064 getObjCEncodingForTypeImpl(T, S, 7065 ObjCEncOptions() 7066 .setExpandPointedToStructures() 7067 .setExpandStructures() 7068 .setIsOutermostType(), 7069 Field, NotEncodedT); 7070 } 7071 7072 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7073 std::string& S) const { 7074 // Encode result type. 7075 // GCC has some special rules regarding encoding of properties which 7076 // closely resembles encoding of ivars. 7077 getObjCEncodingForTypeImpl(T, S, 7078 ObjCEncOptions() 7079 .setExpandPointedToStructures() 7080 .setExpandStructures() 7081 .setIsOutermostType() 7082 .setEncodingProperty(), 7083 /*Field=*/nullptr); 7084 } 7085 7086 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7087 const BuiltinType *BT) { 7088 BuiltinType::Kind kind = BT->getKind(); 7089 switch (kind) { 7090 case BuiltinType::Void: return 'v'; 7091 case BuiltinType::Bool: return 'B'; 7092 case BuiltinType::Char8: 7093 case BuiltinType::Char_U: 7094 case BuiltinType::UChar: return 'C'; 7095 case BuiltinType::Char16: 7096 case BuiltinType::UShort: return 'S'; 7097 case BuiltinType::Char32: 7098 case BuiltinType::UInt: return 'I'; 7099 case BuiltinType::ULong: 7100 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7101 case BuiltinType::UInt128: return 'T'; 7102 case BuiltinType::ULongLong: return 'Q'; 7103 case BuiltinType::Char_S: 7104 case BuiltinType::SChar: return 'c'; 7105 case BuiltinType::Short: return 's'; 7106 case BuiltinType::WChar_S: 7107 case BuiltinType::WChar_U: 7108 case BuiltinType::Int: return 'i'; 7109 case BuiltinType::Long: 7110 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7111 case BuiltinType::LongLong: return 'q'; 7112 case BuiltinType::Int128: return 't'; 7113 case BuiltinType::Float: return 'f'; 7114 case BuiltinType::Double: return 'd'; 7115 case BuiltinType::LongDouble: return 'D'; 7116 case BuiltinType::NullPtr: return '*'; // like char* 7117 7118 case BuiltinType::BFloat16: 7119 case BuiltinType::Float16: 7120 case BuiltinType::Float128: 7121 case BuiltinType::Half: 7122 case BuiltinType::ShortAccum: 7123 case BuiltinType::Accum: 7124 case BuiltinType::LongAccum: 7125 case BuiltinType::UShortAccum: 7126 case BuiltinType::UAccum: 7127 case BuiltinType::ULongAccum: 7128 case BuiltinType::ShortFract: 7129 case BuiltinType::Fract: 7130 case BuiltinType::LongFract: 7131 case BuiltinType::UShortFract: 7132 case BuiltinType::UFract: 7133 case BuiltinType::ULongFract: 7134 case BuiltinType::SatShortAccum: 7135 case BuiltinType::SatAccum: 7136 case BuiltinType::SatLongAccum: 7137 case BuiltinType::SatUShortAccum: 7138 case BuiltinType::SatUAccum: 7139 case BuiltinType::SatULongAccum: 7140 case BuiltinType::SatShortFract: 7141 case BuiltinType::SatFract: 7142 case BuiltinType::SatLongFract: 7143 case BuiltinType::SatUShortFract: 7144 case BuiltinType::SatUFract: 7145 case BuiltinType::SatULongFract: 7146 // FIXME: potentially need @encodes for these! 7147 return ' '; 7148 7149 #define SVE_TYPE(Name, Id, SingletonId) \ 7150 case BuiltinType::Id: 7151 #include "clang/Basic/AArch64SVEACLETypes.def" 7152 { 7153 DiagnosticsEngine &Diags = C->getDiagnostics(); 7154 unsigned DiagID = Diags.getCustomDiagID( 7155 DiagnosticsEngine::Error, "cannot yet @encode type %0"); 7156 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7157 return ' '; 7158 } 7159 7160 case BuiltinType::ObjCId: 7161 case BuiltinType::ObjCClass: 7162 case BuiltinType::ObjCSel: 7163 llvm_unreachable("@encoding ObjC primitive type"); 7164 7165 // OpenCL and placeholder types don't need @encodings. 7166 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7167 case BuiltinType::Id: 7168 #include "clang/Basic/OpenCLImageTypes.def" 7169 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7170 case BuiltinType::Id: 7171 #include "clang/Basic/OpenCLExtensionTypes.def" 7172 case BuiltinType::OCLEvent: 7173 case BuiltinType::OCLClkEvent: 7174 case BuiltinType::OCLQueue: 7175 case BuiltinType::OCLReserveID: 7176 case BuiltinType::OCLSampler: 7177 case BuiltinType::Dependent: 7178 #define BUILTIN_TYPE(KIND, ID) 7179 #define PLACEHOLDER_TYPE(KIND, ID) \ 7180 case BuiltinType::KIND: 7181 #include "clang/AST/BuiltinTypes.def" 7182 llvm_unreachable("invalid builtin type for @encode"); 7183 } 7184 llvm_unreachable("invalid BuiltinType::Kind value"); 7185 } 7186 7187 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7188 EnumDecl *Enum = ET->getDecl(); 7189 7190 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7191 if (!Enum->isFixed()) 7192 return 'i'; 7193 7194 // The encoding of a fixed enum type matches its fixed underlying type. 7195 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7196 return getObjCEncodingForPrimitiveType(C, BT); 7197 } 7198 7199 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7200 QualType T, const FieldDecl *FD) { 7201 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7202 S += 'b'; 7203 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7204 // The GNU runtime requires more information; bitfields are encoded as b, 7205 // then the offset (in bits) of the first element, then the type of the 7206 // bitfield, then the size in bits. For example, in this structure: 7207 // 7208 // struct 7209 // { 7210 // int integer; 7211 // int flags:2; 7212 // }; 7213 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7214 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7215 // information is not especially sensible, but we're stuck with it for 7216 // compatibility with GCC, although providing it breaks anything that 7217 // actually uses runtime introspection and wants to work on both runtimes... 7218 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7219 uint64_t Offset; 7220 7221 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7222 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7223 IVD); 7224 } else { 7225 const RecordDecl *RD = FD->getParent(); 7226 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7227 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7228 } 7229 7230 S += llvm::utostr(Offset); 7231 7232 if (const auto *ET = T->getAs<EnumType>()) 7233 S += ObjCEncodingForEnumType(Ctx, ET); 7234 else { 7235 const auto *BT = T->castAs<BuiltinType>(); 7236 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7237 } 7238 } 7239 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7240 } 7241 7242 // FIXME: Use SmallString for accumulating string. 7243 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7244 const ObjCEncOptions Options, 7245 const FieldDecl *FD, 7246 QualType *NotEncodedT) const { 7247 CanQualType CT = getCanonicalType(T); 7248 switch (CT->getTypeClass()) { 7249 case Type::Builtin: 7250 case Type::Enum: 7251 if (FD && FD->isBitField()) 7252 return EncodeBitField(this, S, T, FD); 7253 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7254 S += getObjCEncodingForPrimitiveType(this, BT); 7255 else 7256 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7257 return; 7258 7259 case Type::Complex: 7260 S += 'j'; 7261 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7262 ObjCEncOptions(), 7263 /*Field=*/nullptr); 7264 return; 7265 7266 case Type::Atomic: 7267 S += 'A'; 7268 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7269 ObjCEncOptions(), 7270 /*Field=*/nullptr); 7271 return; 7272 7273 // encoding for pointer or reference types. 7274 case Type::Pointer: 7275 case Type::LValueReference: 7276 case Type::RValueReference: { 7277 QualType PointeeTy; 7278 if (isa<PointerType>(CT)) { 7279 const auto *PT = T->castAs<PointerType>(); 7280 if (PT->isObjCSelType()) { 7281 S += ':'; 7282 return; 7283 } 7284 PointeeTy = PT->getPointeeType(); 7285 } else { 7286 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7287 } 7288 7289 bool isReadOnly = false; 7290 // For historical/compatibility reasons, the read-only qualifier of the 7291 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7292 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7293 // Also, do not emit the 'r' for anything but the outermost type! 7294 if (isa<TypedefType>(T.getTypePtr())) { 7295 if (Options.IsOutermostType() && T.isConstQualified()) { 7296 isReadOnly = true; 7297 S += 'r'; 7298 } 7299 } else if (Options.IsOutermostType()) { 7300 QualType P = PointeeTy; 7301 while (auto PT = P->getAs<PointerType>()) 7302 P = PT->getPointeeType(); 7303 if (P.isConstQualified()) { 7304 isReadOnly = true; 7305 S += 'r'; 7306 } 7307 } 7308 if (isReadOnly) { 7309 // Another legacy compatibility encoding. Some ObjC qualifier and type 7310 // combinations need to be rearranged. 7311 // Rewrite "in const" from "nr" to "rn" 7312 if (StringRef(S).endswith("nr")) 7313 S.replace(S.end()-2, S.end(), "rn"); 7314 } 7315 7316 if (PointeeTy->isCharType()) { 7317 // char pointer types should be encoded as '*' unless it is a 7318 // type that has been typedef'd to 'BOOL'. 7319 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 7320 S += '*'; 7321 return; 7322 } 7323 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 7324 // GCC binary compat: Need to convert "struct objc_class *" to "#". 7325 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 7326 S += '#'; 7327 return; 7328 } 7329 // GCC binary compat: Need to convert "struct objc_object *" to "@". 7330 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 7331 S += '@'; 7332 return; 7333 } 7334 // fall through... 7335 } 7336 S += '^'; 7337 getLegacyIntegralTypeEncoding(PointeeTy); 7338 7339 ObjCEncOptions NewOptions; 7340 if (Options.ExpandPointedToStructures()) 7341 NewOptions.setExpandStructures(); 7342 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 7343 /*Field=*/nullptr, NotEncodedT); 7344 return; 7345 } 7346 7347 case Type::ConstantArray: 7348 case Type::IncompleteArray: 7349 case Type::VariableArray: { 7350 const auto *AT = cast<ArrayType>(CT); 7351 7352 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 7353 // Incomplete arrays are encoded as a pointer to the array element. 7354 S += '^'; 7355 7356 getObjCEncodingForTypeImpl( 7357 AT->getElementType(), S, 7358 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 7359 } else { 7360 S += '['; 7361 7362 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7363 S += llvm::utostr(CAT->getSize().getZExtValue()); 7364 else { 7365 //Variable length arrays are encoded as a regular array with 0 elements. 7366 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 7367 "Unknown array type!"); 7368 S += '0'; 7369 } 7370 7371 getObjCEncodingForTypeImpl( 7372 AT->getElementType(), S, 7373 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 7374 NotEncodedT); 7375 S += ']'; 7376 } 7377 return; 7378 } 7379 7380 case Type::FunctionNoProto: 7381 case Type::FunctionProto: 7382 S += '?'; 7383 return; 7384 7385 case Type::Record: { 7386 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 7387 S += RDecl->isUnion() ? '(' : '{'; 7388 // Anonymous structures print as '?' 7389 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 7390 S += II->getName(); 7391 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 7392 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 7393 llvm::raw_string_ostream OS(S); 7394 printTemplateArgumentList(OS, TemplateArgs.asArray(), 7395 getPrintingPolicy()); 7396 } 7397 } else { 7398 S += '?'; 7399 } 7400 if (Options.ExpandStructures()) { 7401 S += '='; 7402 if (!RDecl->isUnion()) { 7403 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 7404 } else { 7405 for (const auto *Field : RDecl->fields()) { 7406 if (FD) { 7407 S += '"'; 7408 S += Field->getNameAsString(); 7409 S += '"'; 7410 } 7411 7412 // Special case bit-fields. 7413 if (Field->isBitField()) { 7414 getObjCEncodingForTypeImpl(Field->getType(), S, 7415 ObjCEncOptions().setExpandStructures(), 7416 Field); 7417 } else { 7418 QualType qt = Field->getType(); 7419 getLegacyIntegralTypeEncoding(qt); 7420 getObjCEncodingForTypeImpl( 7421 qt, S, 7422 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 7423 NotEncodedT); 7424 } 7425 } 7426 } 7427 } 7428 S += RDecl->isUnion() ? ')' : '}'; 7429 return; 7430 } 7431 7432 case Type::BlockPointer: { 7433 const auto *BT = T->castAs<BlockPointerType>(); 7434 S += "@?"; // Unlike a pointer-to-function, which is "^?". 7435 if (Options.EncodeBlockParameters()) { 7436 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 7437 7438 S += '<'; 7439 // Block return type 7440 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 7441 Options.forComponentType(), FD, NotEncodedT); 7442 // Block self 7443 S += "@?"; 7444 // Block parameters 7445 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 7446 for (const auto &I : FPT->param_types()) 7447 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 7448 NotEncodedT); 7449 } 7450 S += '>'; 7451 } 7452 return; 7453 } 7454 7455 case Type::ObjCObject: { 7456 // hack to match legacy encoding of *id and *Class 7457 QualType Ty = getObjCObjectPointerType(CT); 7458 if (Ty->isObjCIdType()) { 7459 S += "{objc_object=}"; 7460 return; 7461 } 7462 else if (Ty->isObjCClassType()) { 7463 S += "{objc_class=}"; 7464 return; 7465 } 7466 // TODO: Double check to make sure this intentionally falls through. 7467 LLVM_FALLTHROUGH; 7468 } 7469 7470 case Type::ObjCInterface: { 7471 // Ignore protocol qualifiers when mangling at this level. 7472 // @encode(class_name) 7473 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 7474 S += '{'; 7475 S += OI->getObjCRuntimeNameAsString(); 7476 if (Options.ExpandStructures()) { 7477 S += '='; 7478 SmallVector<const ObjCIvarDecl*, 32> Ivars; 7479 DeepCollectObjCIvars(OI, true, Ivars); 7480 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 7481 const FieldDecl *Field = Ivars[i]; 7482 if (Field->isBitField()) 7483 getObjCEncodingForTypeImpl(Field->getType(), S, 7484 ObjCEncOptions().setExpandStructures(), 7485 Field); 7486 else 7487 getObjCEncodingForTypeImpl(Field->getType(), S, 7488 ObjCEncOptions().setExpandStructures(), FD, 7489 NotEncodedT); 7490 } 7491 } 7492 S += '}'; 7493 return; 7494 } 7495 7496 case Type::ObjCObjectPointer: { 7497 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 7498 if (OPT->isObjCIdType()) { 7499 S += '@'; 7500 return; 7501 } 7502 7503 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 7504 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 7505 // Since this is a binary compatibility issue, need to consult with 7506 // runtime folks. Fortunately, this is a *very* obscure construct. 7507 S += '#'; 7508 return; 7509 } 7510 7511 if (OPT->isObjCQualifiedIdType()) { 7512 getObjCEncodingForTypeImpl( 7513 getObjCIdType(), S, 7514 Options.keepingOnly(ObjCEncOptions() 7515 .setExpandPointedToStructures() 7516 .setExpandStructures()), 7517 FD); 7518 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 7519 // Note that we do extended encoding of protocol qualifer list 7520 // Only when doing ivar or property encoding. 7521 S += '"'; 7522 for (const auto *I : OPT->quals()) { 7523 S += '<'; 7524 S += I->getObjCRuntimeNameAsString(); 7525 S += '>'; 7526 } 7527 S += '"'; 7528 } 7529 return; 7530 } 7531 7532 S += '@'; 7533 if (OPT->getInterfaceDecl() && 7534 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 7535 S += '"'; 7536 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 7537 for (const auto *I : OPT->quals()) { 7538 S += '<'; 7539 S += I->getObjCRuntimeNameAsString(); 7540 S += '>'; 7541 } 7542 S += '"'; 7543 } 7544 return; 7545 } 7546 7547 // gcc just blithely ignores member pointers. 7548 // FIXME: we should do better than that. 'M' is available. 7549 case Type::MemberPointer: 7550 // This matches gcc's encoding, even though technically it is insufficient. 7551 //FIXME. We should do a better job than gcc. 7552 case Type::Vector: 7553 case Type::ExtVector: 7554 // Until we have a coherent encoding of these three types, issue warning. 7555 if (NotEncodedT) 7556 *NotEncodedT = T; 7557 return; 7558 7559 case Type::ConstantMatrix: 7560 if (NotEncodedT) 7561 *NotEncodedT = T; 7562 return; 7563 7564 // We could see an undeduced auto type here during error recovery. 7565 // Just ignore it. 7566 case Type::Auto: 7567 case Type::DeducedTemplateSpecialization: 7568 return; 7569 7570 case Type::Pipe: 7571 case Type::ExtInt: 7572 #define ABSTRACT_TYPE(KIND, BASE) 7573 #define TYPE(KIND, BASE) 7574 #define DEPENDENT_TYPE(KIND, BASE) \ 7575 case Type::KIND: 7576 #define NON_CANONICAL_TYPE(KIND, BASE) \ 7577 case Type::KIND: 7578 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 7579 case Type::KIND: 7580 #include "clang/AST/TypeNodes.inc" 7581 llvm_unreachable("@encode for dependent type!"); 7582 } 7583 llvm_unreachable("bad type kind!"); 7584 } 7585 7586 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 7587 std::string &S, 7588 const FieldDecl *FD, 7589 bool includeVBases, 7590 QualType *NotEncodedT) const { 7591 assert(RDecl && "Expected non-null RecordDecl"); 7592 assert(!RDecl->isUnion() && "Should not be called for unions"); 7593 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 7594 return; 7595 7596 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 7597 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 7598 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 7599 7600 if (CXXRec) { 7601 for (const auto &BI : CXXRec->bases()) { 7602 if (!BI.isVirtual()) { 7603 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7604 if (base->isEmpty()) 7605 continue; 7606 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 7607 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7608 std::make_pair(offs, base)); 7609 } 7610 } 7611 } 7612 7613 unsigned i = 0; 7614 for (auto *Field : RDecl->fields()) { 7615 uint64_t offs = layout.getFieldOffset(i); 7616 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7617 std::make_pair(offs, Field)); 7618 ++i; 7619 } 7620 7621 if (CXXRec && includeVBases) { 7622 for (const auto &BI : CXXRec->vbases()) { 7623 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7624 if (base->isEmpty()) 7625 continue; 7626 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 7627 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 7628 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 7629 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 7630 std::make_pair(offs, base)); 7631 } 7632 } 7633 7634 CharUnits size; 7635 if (CXXRec) { 7636 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 7637 } else { 7638 size = layout.getSize(); 7639 } 7640 7641 #ifndef NDEBUG 7642 uint64_t CurOffs = 0; 7643 #endif 7644 std::multimap<uint64_t, NamedDecl *>::iterator 7645 CurLayObj = FieldOrBaseOffsets.begin(); 7646 7647 if (CXXRec && CXXRec->isDynamicClass() && 7648 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 7649 if (FD) { 7650 S += "\"_vptr$"; 7651 std::string recname = CXXRec->getNameAsString(); 7652 if (recname.empty()) recname = "?"; 7653 S += recname; 7654 S += '"'; 7655 } 7656 S += "^^?"; 7657 #ifndef NDEBUG 7658 CurOffs += getTypeSize(VoidPtrTy); 7659 #endif 7660 } 7661 7662 if (!RDecl->hasFlexibleArrayMember()) { 7663 // Mark the end of the structure. 7664 uint64_t offs = toBits(size); 7665 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7666 std::make_pair(offs, nullptr)); 7667 } 7668 7669 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7670 #ifndef NDEBUG 7671 assert(CurOffs <= CurLayObj->first); 7672 if (CurOffs < CurLayObj->first) { 7673 uint64_t padding = CurLayObj->first - CurOffs; 7674 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7675 // packing/alignment of members is different that normal, in which case 7676 // the encoding will be out-of-sync with the real layout. 7677 // If the runtime switches to just consider the size of types without 7678 // taking into account alignment, we could make padding explicit in the 7679 // encoding (e.g. using arrays of chars). The encoding strings would be 7680 // longer then though. 7681 CurOffs += padding; 7682 } 7683 #endif 7684 7685 NamedDecl *dcl = CurLayObj->second; 7686 if (!dcl) 7687 break; // reached end of structure. 7688 7689 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7690 // We expand the bases without their virtual bases since those are going 7691 // in the initial structure. Note that this differs from gcc which 7692 // expands virtual bases each time one is encountered in the hierarchy, 7693 // making the encoding type bigger than it really is. 7694 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7695 NotEncodedT); 7696 assert(!base->isEmpty()); 7697 #ifndef NDEBUG 7698 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7699 #endif 7700 } else { 7701 const auto *field = cast<FieldDecl>(dcl); 7702 if (FD) { 7703 S += '"'; 7704 S += field->getNameAsString(); 7705 S += '"'; 7706 } 7707 7708 if (field->isBitField()) { 7709 EncodeBitField(this, S, field->getType(), field); 7710 #ifndef NDEBUG 7711 CurOffs += field->getBitWidthValue(*this); 7712 #endif 7713 } else { 7714 QualType qt = field->getType(); 7715 getLegacyIntegralTypeEncoding(qt); 7716 getObjCEncodingForTypeImpl( 7717 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 7718 FD, NotEncodedT); 7719 #ifndef NDEBUG 7720 CurOffs += getTypeSize(field->getType()); 7721 #endif 7722 } 7723 } 7724 } 7725 } 7726 7727 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7728 std::string& S) const { 7729 if (QT & Decl::OBJC_TQ_In) 7730 S += 'n'; 7731 if (QT & Decl::OBJC_TQ_Inout) 7732 S += 'N'; 7733 if (QT & Decl::OBJC_TQ_Out) 7734 S += 'o'; 7735 if (QT & Decl::OBJC_TQ_Bycopy) 7736 S += 'O'; 7737 if (QT & Decl::OBJC_TQ_Byref) 7738 S += 'R'; 7739 if (QT & Decl::OBJC_TQ_Oneway) 7740 S += 'V'; 7741 } 7742 7743 TypedefDecl *ASTContext::getObjCIdDecl() const { 7744 if (!ObjCIdDecl) { 7745 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7746 T = getObjCObjectPointerType(T); 7747 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7748 } 7749 return ObjCIdDecl; 7750 } 7751 7752 TypedefDecl *ASTContext::getObjCSelDecl() const { 7753 if (!ObjCSelDecl) { 7754 QualType T = getPointerType(ObjCBuiltinSelTy); 7755 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7756 } 7757 return ObjCSelDecl; 7758 } 7759 7760 TypedefDecl *ASTContext::getObjCClassDecl() const { 7761 if (!ObjCClassDecl) { 7762 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7763 T = getObjCObjectPointerType(T); 7764 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7765 } 7766 return ObjCClassDecl; 7767 } 7768 7769 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7770 if (!ObjCProtocolClassDecl) { 7771 ObjCProtocolClassDecl 7772 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7773 SourceLocation(), 7774 &Idents.get("Protocol"), 7775 /*typeParamList=*/nullptr, 7776 /*PrevDecl=*/nullptr, 7777 SourceLocation(), true); 7778 } 7779 7780 return ObjCProtocolClassDecl; 7781 } 7782 7783 //===----------------------------------------------------------------------===// 7784 // __builtin_va_list Construction Functions 7785 //===----------------------------------------------------------------------===// 7786 7787 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 7788 StringRef Name) { 7789 // typedef char* __builtin[_ms]_va_list; 7790 QualType T = Context->getPointerType(Context->CharTy); 7791 return Context->buildImplicitTypedef(T, Name); 7792 } 7793 7794 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 7795 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 7796 } 7797 7798 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 7799 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 7800 } 7801 7802 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 7803 // typedef void* __builtin_va_list; 7804 QualType T = Context->getPointerType(Context->VoidTy); 7805 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7806 } 7807 7808 static TypedefDecl * 7809 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 7810 // struct __va_list 7811 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 7812 if (Context->getLangOpts().CPlusPlus) { 7813 // namespace std { struct __va_list { 7814 NamespaceDecl *NS; 7815 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7816 Context->getTranslationUnitDecl(), 7817 /*Inline*/ false, SourceLocation(), 7818 SourceLocation(), &Context->Idents.get("std"), 7819 /*PrevDecl*/ nullptr); 7820 NS->setImplicit(); 7821 VaListTagDecl->setDeclContext(NS); 7822 } 7823 7824 VaListTagDecl->startDefinition(); 7825 7826 const size_t NumFields = 5; 7827 QualType FieldTypes[NumFields]; 7828 const char *FieldNames[NumFields]; 7829 7830 // void *__stack; 7831 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 7832 FieldNames[0] = "__stack"; 7833 7834 // void *__gr_top; 7835 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 7836 FieldNames[1] = "__gr_top"; 7837 7838 // void *__vr_top; 7839 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7840 FieldNames[2] = "__vr_top"; 7841 7842 // int __gr_offs; 7843 FieldTypes[3] = Context->IntTy; 7844 FieldNames[3] = "__gr_offs"; 7845 7846 // int __vr_offs; 7847 FieldTypes[4] = Context->IntTy; 7848 FieldNames[4] = "__vr_offs"; 7849 7850 // Create fields 7851 for (unsigned i = 0; i < NumFields; ++i) { 7852 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7853 VaListTagDecl, 7854 SourceLocation(), 7855 SourceLocation(), 7856 &Context->Idents.get(FieldNames[i]), 7857 FieldTypes[i], /*TInfo=*/nullptr, 7858 /*BitWidth=*/nullptr, 7859 /*Mutable=*/false, 7860 ICIS_NoInit); 7861 Field->setAccess(AS_public); 7862 VaListTagDecl->addDecl(Field); 7863 } 7864 VaListTagDecl->completeDefinition(); 7865 Context->VaListTagDecl = VaListTagDecl; 7866 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7867 7868 // } __builtin_va_list; 7869 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 7870 } 7871 7872 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 7873 // typedef struct __va_list_tag { 7874 RecordDecl *VaListTagDecl; 7875 7876 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7877 VaListTagDecl->startDefinition(); 7878 7879 const size_t NumFields = 5; 7880 QualType FieldTypes[NumFields]; 7881 const char *FieldNames[NumFields]; 7882 7883 // unsigned char gpr; 7884 FieldTypes[0] = Context->UnsignedCharTy; 7885 FieldNames[0] = "gpr"; 7886 7887 // unsigned char fpr; 7888 FieldTypes[1] = Context->UnsignedCharTy; 7889 FieldNames[1] = "fpr"; 7890 7891 // unsigned short reserved; 7892 FieldTypes[2] = Context->UnsignedShortTy; 7893 FieldNames[2] = "reserved"; 7894 7895 // void* overflow_arg_area; 7896 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7897 FieldNames[3] = "overflow_arg_area"; 7898 7899 // void* reg_save_area; 7900 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 7901 FieldNames[4] = "reg_save_area"; 7902 7903 // Create fields 7904 for (unsigned i = 0; i < NumFields; ++i) { 7905 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 7906 SourceLocation(), 7907 SourceLocation(), 7908 &Context->Idents.get(FieldNames[i]), 7909 FieldTypes[i], /*TInfo=*/nullptr, 7910 /*BitWidth=*/nullptr, 7911 /*Mutable=*/false, 7912 ICIS_NoInit); 7913 Field->setAccess(AS_public); 7914 VaListTagDecl->addDecl(Field); 7915 } 7916 VaListTagDecl->completeDefinition(); 7917 Context->VaListTagDecl = VaListTagDecl; 7918 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7919 7920 // } __va_list_tag; 7921 TypedefDecl *VaListTagTypedefDecl = 7922 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 7923 7924 QualType VaListTagTypedefType = 7925 Context->getTypedefType(VaListTagTypedefDecl); 7926 7927 // typedef __va_list_tag __builtin_va_list[1]; 7928 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7929 QualType VaListTagArrayType 7930 = Context->getConstantArrayType(VaListTagTypedefType, 7931 Size, nullptr, ArrayType::Normal, 0); 7932 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7933 } 7934 7935 static TypedefDecl * 7936 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 7937 // struct __va_list_tag { 7938 RecordDecl *VaListTagDecl; 7939 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7940 VaListTagDecl->startDefinition(); 7941 7942 const size_t NumFields = 4; 7943 QualType FieldTypes[NumFields]; 7944 const char *FieldNames[NumFields]; 7945 7946 // unsigned gp_offset; 7947 FieldTypes[0] = Context->UnsignedIntTy; 7948 FieldNames[0] = "gp_offset"; 7949 7950 // unsigned fp_offset; 7951 FieldTypes[1] = Context->UnsignedIntTy; 7952 FieldNames[1] = "fp_offset"; 7953 7954 // void* overflow_arg_area; 7955 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7956 FieldNames[2] = "overflow_arg_area"; 7957 7958 // void* reg_save_area; 7959 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7960 FieldNames[3] = "reg_save_area"; 7961 7962 // Create fields 7963 for (unsigned i = 0; i < NumFields; ++i) { 7964 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7965 VaListTagDecl, 7966 SourceLocation(), 7967 SourceLocation(), 7968 &Context->Idents.get(FieldNames[i]), 7969 FieldTypes[i], /*TInfo=*/nullptr, 7970 /*BitWidth=*/nullptr, 7971 /*Mutable=*/false, 7972 ICIS_NoInit); 7973 Field->setAccess(AS_public); 7974 VaListTagDecl->addDecl(Field); 7975 } 7976 VaListTagDecl->completeDefinition(); 7977 Context->VaListTagDecl = VaListTagDecl; 7978 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7979 7980 // }; 7981 7982 // typedef struct __va_list_tag __builtin_va_list[1]; 7983 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7984 QualType VaListTagArrayType = Context->getConstantArrayType( 7985 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 7986 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7987 } 7988 7989 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 7990 // typedef int __builtin_va_list[4]; 7991 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 7992 QualType IntArrayType = Context->getConstantArrayType( 7993 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 7994 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 7995 } 7996 7997 static TypedefDecl * 7998 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 7999 // struct __va_list 8000 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8001 if (Context->getLangOpts().CPlusPlus) { 8002 // namespace std { struct __va_list { 8003 NamespaceDecl *NS; 8004 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8005 Context->getTranslationUnitDecl(), 8006 /*Inline*/false, SourceLocation(), 8007 SourceLocation(), &Context->Idents.get("std"), 8008 /*PrevDecl*/ nullptr); 8009 NS->setImplicit(); 8010 VaListDecl->setDeclContext(NS); 8011 } 8012 8013 VaListDecl->startDefinition(); 8014 8015 // void * __ap; 8016 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8017 VaListDecl, 8018 SourceLocation(), 8019 SourceLocation(), 8020 &Context->Idents.get("__ap"), 8021 Context->getPointerType(Context->VoidTy), 8022 /*TInfo=*/nullptr, 8023 /*BitWidth=*/nullptr, 8024 /*Mutable=*/false, 8025 ICIS_NoInit); 8026 Field->setAccess(AS_public); 8027 VaListDecl->addDecl(Field); 8028 8029 // }; 8030 VaListDecl->completeDefinition(); 8031 Context->VaListTagDecl = VaListDecl; 8032 8033 // typedef struct __va_list __builtin_va_list; 8034 QualType T = Context->getRecordType(VaListDecl); 8035 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8036 } 8037 8038 static TypedefDecl * 8039 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8040 // struct __va_list_tag { 8041 RecordDecl *VaListTagDecl; 8042 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8043 VaListTagDecl->startDefinition(); 8044 8045 const size_t NumFields = 4; 8046 QualType FieldTypes[NumFields]; 8047 const char *FieldNames[NumFields]; 8048 8049 // long __gpr; 8050 FieldTypes[0] = Context->LongTy; 8051 FieldNames[0] = "__gpr"; 8052 8053 // long __fpr; 8054 FieldTypes[1] = Context->LongTy; 8055 FieldNames[1] = "__fpr"; 8056 8057 // void *__overflow_arg_area; 8058 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8059 FieldNames[2] = "__overflow_arg_area"; 8060 8061 // void *__reg_save_area; 8062 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8063 FieldNames[3] = "__reg_save_area"; 8064 8065 // Create fields 8066 for (unsigned i = 0; i < NumFields; ++i) { 8067 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8068 VaListTagDecl, 8069 SourceLocation(), 8070 SourceLocation(), 8071 &Context->Idents.get(FieldNames[i]), 8072 FieldTypes[i], /*TInfo=*/nullptr, 8073 /*BitWidth=*/nullptr, 8074 /*Mutable=*/false, 8075 ICIS_NoInit); 8076 Field->setAccess(AS_public); 8077 VaListTagDecl->addDecl(Field); 8078 } 8079 VaListTagDecl->completeDefinition(); 8080 Context->VaListTagDecl = VaListTagDecl; 8081 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8082 8083 // }; 8084 8085 // typedef __va_list_tag __builtin_va_list[1]; 8086 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8087 QualType VaListTagArrayType = Context->getConstantArrayType( 8088 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8089 8090 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8091 } 8092 8093 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8094 // typedef struct __va_list_tag { 8095 RecordDecl *VaListTagDecl; 8096 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8097 VaListTagDecl->startDefinition(); 8098 8099 const size_t NumFields = 3; 8100 QualType FieldTypes[NumFields]; 8101 const char *FieldNames[NumFields]; 8102 8103 // void *CurrentSavedRegisterArea; 8104 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8105 FieldNames[0] = "__current_saved_reg_area_pointer"; 8106 8107 // void *SavedRegAreaEnd; 8108 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8109 FieldNames[1] = "__saved_reg_area_end_pointer"; 8110 8111 // void *OverflowArea; 8112 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8113 FieldNames[2] = "__overflow_area_pointer"; 8114 8115 // Create fields 8116 for (unsigned i = 0; i < NumFields; ++i) { 8117 FieldDecl *Field = FieldDecl::Create( 8118 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8119 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8120 /*TInfo=*/0, 8121 /*BitWidth=*/0, 8122 /*Mutable=*/false, ICIS_NoInit); 8123 Field->setAccess(AS_public); 8124 VaListTagDecl->addDecl(Field); 8125 } 8126 VaListTagDecl->completeDefinition(); 8127 Context->VaListTagDecl = VaListTagDecl; 8128 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8129 8130 // } __va_list_tag; 8131 TypedefDecl *VaListTagTypedefDecl = 8132 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8133 8134 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8135 8136 // typedef __va_list_tag __builtin_va_list[1]; 8137 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8138 QualType VaListTagArrayType = Context->getConstantArrayType( 8139 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8140 8141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8142 } 8143 8144 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8145 TargetInfo::BuiltinVaListKind Kind) { 8146 switch (Kind) { 8147 case TargetInfo::CharPtrBuiltinVaList: 8148 return CreateCharPtrBuiltinVaListDecl(Context); 8149 case TargetInfo::VoidPtrBuiltinVaList: 8150 return CreateVoidPtrBuiltinVaListDecl(Context); 8151 case TargetInfo::AArch64ABIBuiltinVaList: 8152 return CreateAArch64ABIBuiltinVaListDecl(Context); 8153 case TargetInfo::PowerABIBuiltinVaList: 8154 return CreatePowerABIBuiltinVaListDecl(Context); 8155 case TargetInfo::X86_64ABIBuiltinVaList: 8156 return CreateX86_64ABIBuiltinVaListDecl(Context); 8157 case TargetInfo::PNaClABIBuiltinVaList: 8158 return CreatePNaClABIBuiltinVaListDecl(Context); 8159 case TargetInfo::AAPCSABIBuiltinVaList: 8160 return CreateAAPCSABIBuiltinVaListDecl(Context); 8161 case TargetInfo::SystemZBuiltinVaList: 8162 return CreateSystemZBuiltinVaListDecl(Context); 8163 case TargetInfo::HexagonBuiltinVaList: 8164 return CreateHexagonBuiltinVaListDecl(Context); 8165 } 8166 8167 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8168 } 8169 8170 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8171 if (!BuiltinVaListDecl) { 8172 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8173 assert(BuiltinVaListDecl->isImplicit()); 8174 } 8175 8176 return BuiltinVaListDecl; 8177 } 8178 8179 Decl *ASTContext::getVaListTagDecl() const { 8180 // Force the creation of VaListTagDecl by building the __builtin_va_list 8181 // declaration. 8182 if (!VaListTagDecl) 8183 (void)getBuiltinVaListDecl(); 8184 8185 return VaListTagDecl; 8186 } 8187 8188 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8189 if (!BuiltinMSVaListDecl) 8190 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8191 8192 return BuiltinMSVaListDecl; 8193 } 8194 8195 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8196 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8197 } 8198 8199 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8200 assert(ObjCConstantStringType.isNull() && 8201 "'NSConstantString' type already set!"); 8202 8203 ObjCConstantStringType = getObjCInterfaceType(Decl); 8204 } 8205 8206 /// Retrieve the template name that corresponds to a non-empty 8207 /// lookup. 8208 TemplateName 8209 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8210 UnresolvedSetIterator End) const { 8211 unsigned size = End - Begin; 8212 assert(size > 1 && "set is not overloaded!"); 8213 8214 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8215 size * sizeof(FunctionTemplateDecl*)); 8216 auto *OT = new (memory) OverloadedTemplateStorage(size); 8217 8218 NamedDecl **Storage = OT->getStorage(); 8219 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8220 NamedDecl *D = *I; 8221 assert(isa<FunctionTemplateDecl>(D) || 8222 isa<UnresolvedUsingValueDecl>(D) || 8223 (isa<UsingShadowDecl>(D) && 8224 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8225 *Storage++ = D; 8226 } 8227 8228 return TemplateName(OT); 8229 } 8230 8231 /// Retrieve a template name representing an unqualified-id that has been 8232 /// assumed to name a template for ADL purposes. 8233 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8234 auto *OT = new (*this) AssumedTemplateStorage(Name); 8235 return TemplateName(OT); 8236 } 8237 8238 /// Retrieve the template name that represents a qualified 8239 /// template name such as \c std::vector. 8240 TemplateName 8241 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8242 bool TemplateKeyword, 8243 TemplateDecl *Template) const { 8244 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8245 8246 // FIXME: Canonicalization? 8247 llvm::FoldingSetNodeID ID; 8248 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8249 8250 void *InsertPos = nullptr; 8251 QualifiedTemplateName *QTN = 8252 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8253 if (!QTN) { 8254 QTN = new (*this, alignof(QualifiedTemplateName)) 8255 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8256 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8257 } 8258 8259 return TemplateName(QTN); 8260 } 8261 8262 /// Retrieve the template name that represents a dependent 8263 /// template name such as \c MetaFun::template apply. 8264 TemplateName 8265 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8266 const IdentifierInfo *Name) const { 8267 assert((!NNS || NNS->isDependent()) && 8268 "Nested name specifier must be dependent"); 8269 8270 llvm::FoldingSetNodeID ID; 8271 DependentTemplateName::Profile(ID, NNS, Name); 8272 8273 void *InsertPos = nullptr; 8274 DependentTemplateName *QTN = 8275 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8276 8277 if (QTN) 8278 return TemplateName(QTN); 8279 8280 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8281 if (CanonNNS == NNS) { 8282 QTN = new (*this, alignof(DependentTemplateName)) 8283 DependentTemplateName(NNS, Name); 8284 } else { 8285 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8286 QTN = new (*this, alignof(DependentTemplateName)) 8287 DependentTemplateName(NNS, Name, Canon); 8288 DependentTemplateName *CheckQTN = 8289 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8290 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8291 (void)CheckQTN; 8292 } 8293 8294 DependentTemplateNames.InsertNode(QTN, InsertPos); 8295 return TemplateName(QTN); 8296 } 8297 8298 /// Retrieve the template name that represents a dependent 8299 /// template name such as \c MetaFun::template operator+. 8300 TemplateName 8301 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8302 OverloadedOperatorKind Operator) const { 8303 assert((!NNS || NNS->isDependent()) && 8304 "Nested name specifier must be dependent"); 8305 8306 llvm::FoldingSetNodeID ID; 8307 DependentTemplateName::Profile(ID, NNS, Operator); 8308 8309 void *InsertPos = nullptr; 8310 DependentTemplateName *QTN 8311 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8312 8313 if (QTN) 8314 return TemplateName(QTN); 8315 8316 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8317 if (CanonNNS == NNS) { 8318 QTN = new (*this, alignof(DependentTemplateName)) 8319 DependentTemplateName(NNS, Operator); 8320 } else { 8321 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 8322 QTN = new (*this, alignof(DependentTemplateName)) 8323 DependentTemplateName(NNS, Operator, Canon); 8324 8325 DependentTemplateName *CheckQTN 8326 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8327 assert(!CheckQTN && "Dependent template name canonicalization broken"); 8328 (void)CheckQTN; 8329 } 8330 8331 DependentTemplateNames.InsertNode(QTN, InsertPos); 8332 return TemplateName(QTN); 8333 } 8334 8335 TemplateName 8336 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 8337 TemplateName replacement) const { 8338 llvm::FoldingSetNodeID ID; 8339 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 8340 8341 void *insertPos = nullptr; 8342 SubstTemplateTemplateParmStorage *subst 8343 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 8344 8345 if (!subst) { 8346 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 8347 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 8348 } 8349 8350 return TemplateName(subst); 8351 } 8352 8353 TemplateName 8354 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 8355 const TemplateArgument &ArgPack) const { 8356 auto &Self = const_cast<ASTContext &>(*this); 8357 llvm::FoldingSetNodeID ID; 8358 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 8359 8360 void *InsertPos = nullptr; 8361 SubstTemplateTemplateParmPackStorage *Subst 8362 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 8363 8364 if (!Subst) { 8365 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 8366 ArgPack.pack_size(), 8367 ArgPack.pack_begin()); 8368 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 8369 } 8370 8371 return TemplateName(Subst); 8372 } 8373 8374 /// getFromTargetType - Given one of the integer types provided by 8375 /// TargetInfo, produce the corresponding type. The unsigned @p Type 8376 /// is actually a value of type @c TargetInfo::IntType. 8377 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 8378 switch (Type) { 8379 case TargetInfo::NoInt: return {}; 8380 case TargetInfo::SignedChar: return SignedCharTy; 8381 case TargetInfo::UnsignedChar: return UnsignedCharTy; 8382 case TargetInfo::SignedShort: return ShortTy; 8383 case TargetInfo::UnsignedShort: return UnsignedShortTy; 8384 case TargetInfo::SignedInt: return IntTy; 8385 case TargetInfo::UnsignedInt: return UnsignedIntTy; 8386 case TargetInfo::SignedLong: return LongTy; 8387 case TargetInfo::UnsignedLong: return UnsignedLongTy; 8388 case TargetInfo::SignedLongLong: return LongLongTy; 8389 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 8390 } 8391 8392 llvm_unreachable("Unhandled TargetInfo::IntType value"); 8393 } 8394 8395 //===----------------------------------------------------------------------===// 8396 // Type Predicates. 8397 //===----------------------------------------------------------------------===// 8398 8399 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 8400 /// garbage collection attribute. 8401 /// 8402 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 8403 if (getLangOpts().getGC() == LangOptions::NonGC) 8404 return Qualifiers::GCNone; 8405 8406 assert(getLangOpts().ObjC); 8407 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 8408 8409 // Default behaviour under objective-C's gc is for ObjC pointers 8410 // (or pointers to them) be treated as though they were declared 8411 // as __strong. 8412 if (GCAttrs == Qualifiers::GCNone) { 8413 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 8414 return Qualifiers::Strong; 8415 else if (Ty->isPointerType()) 8416 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 8417 } else { 8418 // It's not valid to set GC attributes on anything that isn't a 8419 // pointer. 8420 #ifndef NDEBUG 8421 QualType CT = Ty->getCanonicalTypeInternal(); 8422 while (const auto *AT = dyn_cast<ArrayType>(CT)) 8423 CT = AT->getElementType(); 8424 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 8425 #endif 8426 } 8427 return GCAttrs; 8428 } 8429 8430 //===----------------------------------------------------------------------===// 8431 // Type Compatibility Testing 8432 //===----------------------------------------------------------------------===// 8433 8434 /// areCompatVectorTypes - Return true if the two specified vector types are 8435 /// compatible. 8436 static bool areCompatVectorTypes(const VectorType *LHS, 8437 const VectorType *RHS) { 8438 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8439 return LHS->getElementType() == RHS->getElementType() && 8440 LHS->getNumElements() == RHS->getNumElements(); 8441 } 8442 8443 /// areCompatMatrixTypes - Return true if the two specified matrix types are 8444 /// compatible. 8445 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 8446 const ConstantMatrixType *RHS) { 8447 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8448 return LHS->getElementType() == RHS->getElementType() && 8449 LHS->getNumRows() == RHS->getNumRows() && 8450 LHS->getNumColumns() == RHS->getNumColumns(); 8451 } 8452 8453 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 8454 QualType SecondVec) { 8455 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 8456 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 8457 8458 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 8459 return true; 8460 8461 // Treat Neon vector types and most AltiVec vector types as if they are the 8462 // equivalent GCC vector types. 8463 const auto *First = FirstVec->castAs<VectorType>(); 8464 const auto *Second = SecondVec->castAs<VectorType>(); 8465 if (First->getNumElements() == Second->getNumElements() && 8466 hasSameType(First->getElementType(), Second->getElementType()) && 8467 First->getVectorKind() != VectorType::AltiVecPixel && 8468 First->getVectorKind() != VectorType::AltiVecBool && 8469 Second->getVectorKind() != VectorType::AltiVecPixel && 8470 Second->getVectorKind() != VectorType::AltiVecBool) 8471 return true; 8472 8473 return false; 8474 } 8475 8476 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 8477 while (true) { 8478 // __strong id 8479 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 8480 if (Attr->getAttrKind() == attr::ObjCOwnership) 8481 return true; 8482 8483 Ty = Attr->getModifiedType(); 8484 8485 // X *__strong (...) 8486 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 8487 Ty = Paren->getInnerType(); 8488 8489 // We do not want to look through typedefs, typeof(expr), 8490 // typeof(type), or any other way that the type is somehow 8491 // abstracted. 8492 } else { 8493 return false; 8494 } 8495 } 8496 } 8497 8498 //===----------------------------------------------------------------------===// 8499 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 8500 //===----------------------------------------------------------------------===// 8501 8502 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 8503 /// inheritance hierarchy of 'rProto'. 8504 bool 8505 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 8506 ObjCProtocolDecl *rProto) const { 8507 if (declaresSameEntity(lProto, rProto)) 8508 return true; 8509 for (auto *PI : rProto->protocols()) 8510 if (ProtocolCompatibleWithProtocol(lProto, PI)) 8511 return true; 8512 return false; 8513 } 8514 8515 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 8516 /// Class<pr1, ...>. 8517 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 8518 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 8519 for (auto *lhsProto : lhs->quals()) { 8520 bool match = false; 8521 for (auto *rhsProto : rhs->quals()) { 8522 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 8523 match = true; 8524 break; 8525 } 8526 } 8527 if (!match) 8528 return false; 8529 } 8530 return true; 8531 } 8532 8533 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 8534 /// ObjCQualifiedIDType. 8535 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 8536 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 8537 bool compare) { 8538 // Allow id<P..> and an 'id' in all cases. 8539 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 8540 return true; 8541 8542 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 8543 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 8544 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 8545 return false; 8546 8547 if (lhs->isObjCQualifiedIdType()) { 8548 if (rhs->qual_empty()) { 8549 // If the RHS is a unqualified interface pointer "NSString*", 8550 // make sure we check the class hierarchy. 8551 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8552 for (auto *I : lhs->quals()) { 8553 // when comparing an id<P> on lhs with a static type on rhs, 8554 // see if static class implements all of id's protocols, directly or 8555 // through its super class and categories. 8556 if (!rhsID->ClassImplementsProtocol(I, true)) 8557 return false; 8558 } 8559 } 8560 // If there are no qualifiers and no interface, we have an 'id'. 8561 return true; 8562 } 8563 // Both the right and left sides have qualifiers. 8564 for (auto *lhsProto : lhs->quals()) { 8565 bool match = false; 8566 8567 // when comparing an id<P> on lhs with a static type on rhs, 8568 // see if static class implements all of id's protocols, directly or 8569 // through its super class and categories. 8570 for (auto *rhsProto : rhs->quals()) { 8571 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8572 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8573 match = true; 8574 break; 8575 } 8576 } 8577 // If the RHS is a qualified interface pointer "NSString<P>*", 8578 // make sure we check the class hierarchy. 8579 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8580 for (auto *I : lhs->quals()) { 8581 // when comparing an id<P> on lhs with a static type on rhs, 8582 // see if static class implements all of id's protocols, directly or 8583 // through its super class and categories. 8584 if (rhsID->ClassImplementsProtocol(I, true)) { 8585 match = true; 8586 break; 8587 } 8588 } 8589 } 8590 if (!match) 8591 return false; 8592 } 8593 8594 return true; 8595 } 8596 8597 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 8598 8599 if (lhs->getInterfaceType()) { 8600 // If both the right and left sides have qualifiers. 8601 for (auto *lhsProto : lhs->quals()) { 8602 bool match = false; 8603 8604 // when comparing an id<P> on rhs with a static type on lhs, 8605 // see if static class implements all of id's protocols, directly or 8606 // through its super class and categories. 8607 // First, lhs protocols in the qualifier list must be found, direct 8608 // or indirect in rhs's qualifier list or it is a mismatch. 8609 for (auto *rhsProto : rhs->quals()) { 8610 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8611 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8612 match = true; 8613 break; 8614 } 8615 } 8616 if (!match) 8617 return false; 8618 } 8619 8620 // Static class's protocols, or its super class or category protocols 8621 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 8622 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 8623 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 8624 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 8625 // This is rather dubious but matches gcc's behavior. If lhs has 8626 // no type qualifier and its class has no static protocol(s) 8627 // assume that it is mismatch. 8628 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 8629 return false; 8630 for (auto *lhsProto : LHSInheritedProtocols) { 8631 bool match = false; 8632 for (auto *rhsProto : rhs->quals()) { 8633 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8634 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8635 match = true; 8636 break; 8637 } 8638 } 8639 if (!match) 8640 return false; 8641 } 8642 } 8643 return true; 8644 } 8645 return false; 8646 } 8647 8648 /// canAssignObjCInterfaces - Return true if the two interface types are 8649 /// compatible for assignment from RHS to LHS. This handles validation of any 8650 /// protocol qualifiers on the LHS or RHS. 8651 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 8652 const ObjCObjectPointerType *RHSOPT) { 8653 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8654 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8655 8656 // If either type represents the built-in 'id' type, return true. 8657 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 8658 return true; 8659 8660 // Function object that propagates a successful result or handles 8661 // __kindof types. 8662 auto finish = [&](bool succeeded) -> bool { 8663 if (succeeded) 8664 return true; 8665 8666 if (!RHS->isKindOfType()) 8667 return false; 8668 8669 // Strip off __kindof and protocol qualifiers, then check whether 8670 // we can assign the other way. 8671 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8672 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 8673 }; 8674 8675 // Casts from or to id<P> are allowed when the other side has compatible 8676 // protocols. 8677 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 8678 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 8679 } 8680 8681 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 8682 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 8683 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 8684 } 8685 8686 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 8687 if (LHS->isObjCClass() && RHS->isObjCClass()) { 8688 return true; 8689 } 8690 8691 // If we have 2 user-defined types, fall into that path. 8692 if (LHS->getInterface() && RHS->getInterface()) { 8693 return finish(canAssignObjCInterfaces(LHS, RHS)); 8694 } 8695 8696 return false; 8697 } 8698 8699 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 8700 /// for providing type-safety for objective-c pointers used to pass/return 8701 /// arguments in block literals. When passed as arguments, passing 'A*' where 8702 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 8703 /// not OK. For the return type, the opposite is not OK. 8704 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 8705 const ObjCObjectPointerType *LHSOPT, 8706 const ObjCObjectPointerType *RHSOPT, 8707 bool BlockReturnType) { 8708 8709 // Function object that propagates a successful result or handles 8710 // __kindof types. 8711 auto finish = [&](bool succeeded) -> bool { 8712 if (succeeded) 8713 return true; 8714 8715 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 8716 if (!Expected->isKindOfType()) 8717 return false; 8718 8719 // Strip off __kindof and protocol qualifiers, then check whether 8720 // we can assign the other way. 8721 return canAssignObjCInterfacesInBlockPointer( 8722 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8723 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 8724 BlockReturnType); 8725 }; 8726 8727 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 8728 return true; 8729 8730 if (LHSOPT->isObjCBuiltinType()) { 8731 return finish(RHSOPT->isObjCBuiltinType() || 8732 RHSOPT->isObjCQualifiedIdType()); 8733 } 8734 8735 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 8736 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 8737 // Use for block parameters previous type checking for compatibility. 8738 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 8739 // Or corrected type checking as in non-compat mode. 8740 (!BlockReturnType && 8741 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 8742 else 8743 return finish(ObjCQualifiedIdTypesAreCompatible( 8744 (BlockReturnType ? LHSOPT : RHSOPT), 8745 (BlockReturnType ? RHSOPT : LHSOPT), false)); 8746 } 8747 8748 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 8749 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 8750 if (LHS && RHS) { // We have 2 user-defined types. 8751 if (LHS != RHS) { 8752 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 8753 return finish(BlockReturnType); 8754 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 8755 return finish(!BlockReturnType); 8756 } 8757 else 8758 return true; 8759 } 8760 return false; 8761 } 8762 8763 /// Comparison routine for Objective-C protocols to be used with 8764 /// llvm::array_pod_sort. 8765 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 8766 ObjCProtocolDecl * const *rhs) { 8767 return (*lhs)->getName().compare((*rhs)->getName()); 8768 } 8769 8770 /// getIntersectionOfProtocols - This routine finds the intersection of set 8771 /// of protocols inherited from two distinct objective-c pointer objects with 8772 /// the given common base. 8773 /// It is used to build composite qualifier list of the composite type of 8774 /// the conditional expression involving two objective-c pointer objects. 8775 static 8776 void getIntersectionOfProtocols(ASTContext &Context, 8777 const ObjCInterfaceDecl *CommonBase, 8778 const ObjCObjectPointerType *LHSOPT, 8779 const ObjCObjectPointerType *RHSOPT, 8780 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 8781 8782 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8783 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8784 assert(LHS->getInterface() && "LHS must have an interface base"); 8785 assert(RHS->getInterface() && "RHS must have an interface base"); 8786 8787 // Add all of the protocols for the LHS. 8788 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 8789 8790 // Start with the protocol qualifiers. 8791 for (auto proto : LHS->quals()) { 8792 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 8793 } 8794 8795 // Also add the protocols associated with the LHS interface. 8796 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 8797 8798 // Add all of the protocols for the RHS. 8799 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 8800 8801 // Start with the protocol qualifiers. 8802 for (auto proto : RHS->quals()) { 8803 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 8804 } 8805 8806 // Also add the protocols associated with the RHS interface. 8807 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 8808 8809 // Compute the intersection of the collected protocol sets. 8810 for (auto proto : LHSProtocolSet) { 8811 if (RHSProtocolSet.count(proto)) 8812 IntersectionSet.push_back(proto); 8813 } 8814 8815 // Compute the set of protocols that is implied by either the common type or 8816 // the protocols within the intersection. 8817 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 8818 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 8819 8820 // Remove any implied protocols from the list of inherited protocols. 8821 if (!ImpliedProtocols.empty()) { 8822 IntersectionSet.erase( 8823 std::remove_if(IntersectionSet.begin(), 8824 IntersectionSet.end(), 8825 [&](ObjCProtocolDecl *proto) -> bool { 8826 return ImpliedProtocols.count(proto) > 0; 8827 }), 8828 IntersectionSet.end()); 8829 } 8830 8831 // Sort the remaining protocols by name. 8832 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 8833 compareObjCProtocolsByName); 8834 } 8835 8836 /// Determine whether the first type is a subtype of the second. 8837 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 8838 QualType rhs) { 8839 // Common case: two object pointers. 8840 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 8841 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 8842 if (lhsOPT && rhsOPT) 8843 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 8844 8845 // Two block pointers. 8846 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 8847 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 8848 if (lhsBlock && rhsBlock) 8849 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 8850 8851 // If either is an unqualified 'id' and the other is a block, it's 8852 // acceptable. 8853 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 8854 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 8855 return true; 8856 8857 return false; 8858 } 8859 8860 // Check that the given Objective-C type argument lists are equivalent. 8861 static bool sameObjCTypeArgs(ASTContext &ctx, 8862 const ObjCInterfaceDecl *iface, 8863 ArrayRef<QualType> lhsArgs, 8864 ArrayRef<QualType> rhsArgs, 8865 bool stripKindOf) { 8866 if (lhsArgs.size() != rhsArgs.size()) 8867 return false; 8868 8869 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 8870 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 8871 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 8872 continue; 8873 8874 switch (typeParams->begin()[i]->getVariance()) { 8875 case ObjCTypeParamVariance::Invariant: 8876 if (!stripKindOf || 8877 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 8878 rhsArgs[i].stripObjCKindOfType(ctx))) { 8879 return false; 8880 } 8881 break; 8882 8883 case ObjCTypeParamVariance::Covariant: 8884 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 8885 return false; 8886 break; 8887 8888 case ObjCTypeParamVariance::Contravariant: 8889 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 8890 return false; 8891 break; 8892 } 8893 } 8894 8895 return true; 8896 } 8897 8898 QualType ASTContext::areCommonBaseCompatible( 8899 const ObjCObjectPointerType *Lptr, 8900 const ObjCObjectPointerType *Rptr) { 8901 const ObjCObjectType *LHS = Lptr->getObjectType(); 8902 const ObjCObjectType *RHS = Rptr->getObjectType(); 8903 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 8904 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 8905 8906 if (!LDecl || !RDecl) 8907 return {}; 8908 8909 // When either LHS or RHS is a kindof type, we should return a kindof type. 8910 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 8911 // kindof(A). 8912 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 8913 8914 // Follow the left-hand side up the class hierarchy until we either hit a 8915 // root or find the RHS. Record the ancestors in case we don't find it. 8916 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 8917 LHSAncestors; 8918 while (true) { 8919 // Record this ancestor. We'll need this if the common type isn't in the 8920 // path from the LHS to the root. 8921 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 8922 8923 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 8924 // Get the type arguments. 8925 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 8926 bool anyChanges = false; 8927 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8928 // Both have type arguments, compare them. 8929 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8930 LHS->getTypeArgs(), RHS->getTypeArgs(), 8931 /*stripKindOf=*/true)) 8932 return {}; 8933 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8934 // If only one has type arguments, the result will not have type 8935 // arguments. 8936 LHSTypeArgs = {}; 8937 anyChanges = true; 8938 } 8939 8940 // Compute the intersection of protocols. 8941 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8942 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 8943 Protocols); 8944 if (!Protocols.empty()) 8945 anyChanges = true; 8946 8947 // If anything in the LHS will have changed, build a new result type. 8948 // If we need to return a kindof type but LHS is not a kindof type, we 8949 // build a new result type. 8950 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 8951 QualType Result = getObjCInterfaceType(LHS->getInterface()); 8952 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 8953 anyKindOf || LHS->isKindOfType()); 8954 return getObjCObjectPointerType(Result); 8955 } 8956 8957 return getObjCObjectPointerType(QualType(LHS, 0)); 8958 } 8959 8960 // Find the superclass. 8961 QualType LHSSuperType = LHS->getSuperClassType(); 8962 if (LHSSuperType.isNull()) 8963 break; 8964 8965 LHS = LHSSuperType->castAs<ObjCObjectType>(); 8966 } 8967 8968 // We didn't find anything by following the LHS to its root; now check 8969 // the RHS against the cached set of ancestors. 8970 while (true) { 8971 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 8972 if (KnownLHS != LHSAncestors.end()) { 8973 LHS = KnownLHS->second; 8974 8975 // Get the type arguments. 8976 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 8977 bool anyChanges = false; 8978 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8979 // Both have type arguments, compare them. 8980 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8981 LHS->getTypeArgs(), RHS->getTypeArgs(), 8982 /*stripKindOf=*/true)) 8983 return {}; 8984 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8985 // If only one has type arguments, the result will not have type 8986 // arguments. 8987 RHSTypeArgs = {}; 8988 anyChanges = true; 8989 } 8990 8991 // Compute the intersection of protocols. 8992 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8993 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 8994 Protocols); 8995 if (!Protocols.empty()) 8996 anyChanges = true; 8997 8998 // If we need to return a kindof type but RHS is not a kindof type, we 8999 // build a new result type. 9000 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9001 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9002 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9003 anyKindOf || RHS->isKindOfType()); 9004 return getObjCObjectPointerType(Result); 9005 } 9006 9007 return getObjCObjectPointerType(QualType(RHS, 0)); 9008 } 9009 9010 // Find the superclass of the RHS. 9011 QualType RHSSuperType = RHS->getSuperClassType(); 9012 if (RHSSuperType.isNull()) 9013 break; 9014 9015 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9016 } 9017 9018 return {}; 9019 } 9020 9021 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9022 const ObjCObjectType *RHS) { 9023 assert(LHS->getInterface() && "LHS is not an interface type"); 9024 assert(RHS->getInterface() && "RHS is not an interface type"); 9025 9026 // Verify that the base decls are compatible: the RHS must be a subclass of 9027 // the LHS. 9028 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9029 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9030 if (!IsSuperClass) 9031 return false; 9032 9033 // If the LHS has protocol qualifiers, determine whether all of them are 9034 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9035 // LHS). 9036 if (LHS->getNumProtocols() > 0) { 9037 // OK if conversion of LHS to SuperClass results in narrowing of types 9038 // ; i.e., SuperClass may implement at least one of the protocols 9039 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9040 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9041 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9042 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9043 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9044 // qualifiers. 9045 for (auto *RHSPI : RHS->quals()) 9046 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9047 // If there is no protocols associated with RHS, it is not a match. 9048 if (SuperClassInheritedProtocols.empty()) 9049 return false; 9050 9051 for (const auto *LHSProto : LHS->quals()) { 9052 bool SuperImplementsProtocol = false; 9053 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9054 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9055 SuperImplementsProtocol = true; 9056 break; 9057 } 9058 if (!SuperImplementsProtocol) 9059 return false; 9060 } 9061 } 9062 9063 // If the LHS is specialized, we may need to check type arguments. 9064 if (LHS->isSpecialized()) { 9065 // Follow the superclass chain until we've matched the LHS class in the 9066 // hierarchy. This substitutes type arguments through. 9067 const ObjCObjectType *RHSSuper = RHS; 9068 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9069 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9070 9071 // If the RHS is specializd, compare type arguments. 9072 if (RHSSuper->isSpecialized() && 9073 !sameObjCTypeArgs(*this, LHS->getInterface(), 9074 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9075 /*stripKindOf=*/true)) { 9076 return false; 9077 } 9078 } 9079 9080 return true; 9081 } 9082 9083 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9084 // get the "pointed to" types 9085 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9086 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9087 9088 if (!LHSOPT || !RHSOPT) 9089 return false; 9090 9091 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9092 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9093 } 9094 9095 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9096 return canAssignObjCInterfaces( 9097 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9098 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9099 } 9100 9101 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9102 /// both shall have the identically qualified version of a compatible type. 9103 /// C99 6.2.7p1: Two types have compatible types if their types are the 9104 /// same. See 6.7.[2,3,5] for additional rules. 9105 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9106 bool CompareUnqualified) { 9107 if (getLangOpts().CPlusPlus) 9108 return hasSameType(LHS, RHS); 9109 9110 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9111 } 9112 9113 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9114 return typesAreCompatible(LHS, RHS); 9115 } 9116 9117 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9118 return !mergeTypes(LHS, RHS, true).isNull(); 9119 } 9120 9121 /// mergeTransparentUnionType - if T is a transparent union type and a member 9122 /// of T is compatible with SubType, return the merged type, else return 9123 /// QualType() 9124 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9125 bool OfBlockPointer, 9126 bool Unqualified) { 9127 if (const RecordType *UT = T->getAsUnionType()) { 9128 RecordDecl *UD = UT->getDecl(); 9129 if (UD->hasAttr<TransparentUnionAttr>()) { 9130 for (const auto *I : UD->fields()) { 9131 QualType ET = I->getType().getUnqualifiedType(); 9132 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9133 if (!MT.isNull()) 9134 return MT; 9135 } 9136 } 9137 } 9138 9139 return {}; 9140 } 9141 9142 /// mergeFunctionParameterTypes - merge two types which appear as function 9143 /// parameter types 9144 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9145 bool OfBlockPointer, 9146 bool Unqualified) { 9147 // GNU extension: two types are compatible if they appear as a function 9148 // argument, one of the types is a transparent union type and the other 9149 // type is compatible with a union member 9150 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9151 Unqualified); 9152 if (!lmerge.isNull()) 9153 return lmerge; 9154 9155 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9156 Unqualified); 9157 if (!rmerge.isNull()) 9158 return rmerge; 9159 9160 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9161 } 9162 9163 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9164 bool OfBlockPointer, bool Unqualified, 9165 bool AllowCXX) { 9166 const auto *lbase = lhs->castAs<FunctionType>(); 9167 const auto *rbase = rhs->castAs<FunctionType>(); 9168 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9169 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9170 bool allLTypes = true; 9171 bool allRTypes = true; 9172 9173 // Check return type 9174 QualType retType; 9175 if (OfBlockPointer) { 9176 QualType RHS = rbase->getReturnType(); 9177 QualType LHS = lbase->getReturnType(); 9178 bool UnqualifiedResult = Unqualified; 9179 if (!UnqualifiedResult) 9180 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9181 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9182 } 9183 else 9184 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9185 Unqualified); 9186 if (retType.isNull()) 9187 return {}; 9188 9189 if (Unqualified) 9190 retType = retType.getUnqualifiedType(); 9191 9192 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9193 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9194 if (Unqualified) { 9195 LRetType = LRetType.getUnqualifiedType(); 9196 RRetType = RRetType.getUnqualifiedType(); 9197 } 9198 9199 if (getCanonicalType(retType) != LRetType) 9200 allLTypes = false; 9201 if (getCanonicalType(retType) != RRetType) 9202 allRTypes = false; 9203 9204 // FIXME: double check this 9205 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 9206 // rbase->getRegParmAttr() != 0 && 9207 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 9208 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 9209 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 9210 9211 // Compatible functions must have compatible calling conventions 9212 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 9213 return {}; 9214 9215 // Regparm is part of the calling convention. 9216 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 9217 return {}; 9218 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 9219 return {}; 9220 9221 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 9222 return {}; 9223 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 9224 return {}; 9225 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 9226 return {}; 9227 9228 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 9229 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 9230 9231 if (lbaseInfo.getNoReturn() != NoReturn) 9232 allLTypes = false; 9233 if (rbaseInfo.getNoReturn() != NoReturn) 9234 allRTypes = false; 9235 9236 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 9237 9238 if (lproto && rproto) { // two C99 style function prototypes 9239 assert((AllowCXX || 9240 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 9241 "C++ shouldn't be here"); 9242 // Compatible functions must have the same number of parameters 9243 if (lproto->getNumParams() != rproto->getNumParams()) 9244 return {}; 9245 9246 // Variadic and non-variadic functions aren't compatible 9247 if (lproto->isVariadic() != rproto->isVariadic()) 9248 return {}; 9249 9250 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 9251 return {}; 9252 9253 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 9254 bool canUseLeft, canUseRight; 9255 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 9256 newParamInfos)) 9257 return {}; 9258 9259 if (!canUseLeft) 9260 allLTypes = false; 9261 if (!canUseRight) 9262 allRTypes = false; 9263 9264 // Check parameter type compatibility 9265 SmallVector<QualType, 10> types; 9266 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 9267 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 9268 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 9269 QualType paramType = mergeFunctionParameterTypes( 9270 lParamType, rParamType, OfBlockPointer, Unqualified); 9271 if (paramType.isNull()) 9272 return {}; 9273 9274 if (Unqualified) 9275 paramType = paramType.getUnqualifiedType(); 9276 9277 types.push_back(paramType); 9278 if (Unqualified) { 9279 lParamType = lParamType.getUnqualifiedType(); 9280 rParamType = rParamType.getUnqualifiedType(); 9281 } 9282 9283 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 9284 allLTypes = false; 9285 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 9286 allRTypes = false; 9287 } 9288 9289 if (allLTypes) return lhs; 9290 if (allRTypes) return rhs; 9291 9292 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 9293 EPI.ExtInfo = einfo; 9294 EPI.ExtParameterInfos = 9295 newParamInfos.empty() ? nullptr : newParamInfos.data(); 9296 return getFunctionType(retType, types, EPI); 9297 } 9298 9299 if (lproto) allRTypes = false; 9300 if (rproto) allLTypes = false; 9301 9302 const FunctionProtoType *proto = lproto ? lproto : rproto; 9303 if (proto) { 9304 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 9305 if (proto->isVariadic()) 9306 return {}; 9307 // Check that the types are compatible with the types that 9308 // would result from default argument promotions (C99 6.7.5.3p15). 9309 // The only types actually affected are promotable integer 9310 // types and floats, which would be passed as a different 9311 // type depending on whether the prototype is visible. 9312 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 9313 QualType paramTy = proto->getParamType(i); 9314 9315 // Look at the converted type of enum types, since that is the type used 9316 // to pass enum values. 9317 if (const auto *Enum = paramTy->getAs<EnumType>()) { 9318 paramTy = Enum->getDecl()->getIntegerType(); 9319 if (paramTy.isNull()) 9320 return {}; 9321 } 9322 9323 if (paramTy->isPromotableIntegerType() || 9324 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 9325 return {}; 9326 } 9327 9328 if (allLTypes) return lhs; 9329 if (allRTypes) return rhs; 9330 9331 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 9332 EPI.ExtInfo = einfo; 9333 return getFunctionType(retType, proto->getParamTypes(), EPI); 9334 } 9335 9336 if (allLTypes) return lhs; 9337 if (allRTypes) return rhs; 9338 return getFunctionNoProtoType(retType, einfo); 9339 } 9340 9341 /// Given that we have an enum type and a non-enum type, try to merge them. 9342 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 9343 QualType other, bool isBlockReturnType) { 9344 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 9345 // a signed integer type, or an unsigned integer type. 9346 // Compatibility is based on the underlying type, not the promotion 9347 // type. 9348 QualType underlyingType = ET->getDecl()->getIntegerType(); 9349 if (underlyingType.isNull()) 9350 return {}; 9351 if (Context.hasSameType(underlyingType, other)) 9352 return other; 9353 9354 // In block return types, we're more permissive and accept any 9355 // integral type of the same size. 9356 if (isBlockReturnType && other->isIntegerType() && 9357 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 9358 return other; 9359 9360 return {}; 9361 } 9362 9363 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 9364 bool OfBlockPointer, 9365 bool Unqualified, bool BlockReturnType) { 9366 // C++ [expr]: If an expression initially has the type "reference to T", the 9367 // type is adjusted to "T" prior to any further analysis, the expression 9368 // designates the object or function denoted by the reference, and the 9369 // expression is an lvalue unless the reference is an rvalue reference and 9370 // the expression is a function call (possibly inside parentheses). 9371 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 9372 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 9373 9374 if (Unqualified) { 9375 LHS = LHS.getUnqualifiedType(); 9376 RHS = RHS.getUnqualifiedType(); 9377 } 9378 9379 QualType LHSCan = getCanonicalType(LHS), 9380 RHSCan = getCanonicalType(RHS); 9381 9382 // If two types are identical, they are compatible. 9383 if (LHSCan == RHSCan) 9384 return LHS; 9385 9386 // If the qualifiers are different, the types aren't compatible... mostly. 9387 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9388 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9389 if (LQuals != RQuals) { 9390 // If any of these qualifiers are different, we have a type 9391 // mismatch. 9392 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9393 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 9394 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 9395 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 9396 return {}; 9397 9398 // Exactly one GC qualifier difference is allowed: __strong is 9399 // okay if the other type has no GC qualifier but is an Objective 9400 // C object pointer (i.e. implicitly strong by default). We fix 9401 // this by pretending that the unqualified type was actually 9402 // qualified __strong. 9403 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9404 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9405 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9406 9407 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9408 return {}; 9409 9410 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 9411 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 9412 } 9413 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 9414 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 9415 } 9416 return {}; 9417 } 9418 9419 // Okay, qualifiers are equal. 9420 9421 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 9422 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 9423 9424 // We want to consider the two function types to be the same for these 9425 // comparisons, just force one to the other. 9426 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 9427 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 9428 9429 // Same as above for arrays 9430 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 9431 LHSClass = Type::ConstantArray; 9432 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 9433 RHSClass = Type::ConstantArray; 9434 9435 // ObjCInterfaces are just specialized ObjCObjects. 9436 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 9437 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 9438 9439 // Canonicalize ExtVector -> Vector. 9440 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 9441 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 9442 9443 // If the canonical type classes don't match. 9444 if (LHSClass != RHSClass) { 9445 // Note that we only have special rules for turning block enum 9446 // returns into block int returns, not vice-versa. 9447 if (const auto *ETy = LHS->getAs<EnumType>()) { 9448 return mergeEnumWithInteger(*this, ETy, RHS, false); 9449 } 9450 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 9451 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 9452 } 9453 // allow block pointer type to match an 'id' type. 9454 if (OfBlockPointer && !BlockReturnType) { 9455 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 9456 return LHS; 9457 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 9458 return RHS; 9459 } 9460 9461 return {}; 9462 } 9463 9464 // The canonical type classes match. 9465 switch (LHSClass) { 9466 #define TYPE(Class, Base) 9467 #define ABSTRACT_TYPE(Class, Base) 9468 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 9469 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 9470 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 9471 #include "clang/AST/TypeNodes.inc" 9472 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 9473 9474 case Type::Auto: 9475 case Type::DeducedTemplateSpecialization: 9476 case Type::LValueReference: 9477 case Type::RValueReference: 9478 case Type::MemberPointer: 9479 llvm_unreachable("C++ should never be in mergeTypes"); 9480 9481 case Type::ObjCInterface: 9482 case Type::IncompleteArray: 9483 case Type::VariableArray: 9484 case Type::FunctionProto: 9485 case Type::ExtVector: 9486 llvm_unreachable("Types are eliminated above"); 9487 9488 case Type::Pointer: 9489 { 9490 // Merge two pointer types, while trying to preserve typedef info 9491 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 9492 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 9493 if (Unqualified) { 9494 LHSPointee = LHSPointee.getUnqualifiedType(); 9495 RHSPointee = RHSPointee.getUnqualifiedType(); 9496 } 9497 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 9498 Unqualified); 9499 if (ResultType.isNull()) 9500 return {}; 9501 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9502 return LHS; 9503 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9504 return RHS; 9505 return getPointerType(ResultType); 9506 } 9507 case Type::BlockPointer: 9508 { 9509 // Merge two block pointer types, while trying to preserve typedef info 9510 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 9511 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 9512 if (Unqualified) { 9513 LHSPointee = LHSPointee.getUnqualifiedType(); 9514 RHSPointee = RHSPointee.getUnqualifiedType(); 9515 } 9516 if (getLangOpts().OpenCL) { 9517 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 9518 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 9519 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 9520 // 6.12.5) thus the following check is asymmetric. 9521 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 9522 return {}; 9523 LHSPteeQual.removeAddressSpace(); 9524 RHSPteeQual.removeAddressSpace(); 9525 LHSPointee = 9526 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 9527 RHSPointee = 9528 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 9529 } 9530 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 9531 Unqualified); 9532 if (ResultType.isNull()) 9533 return {}; 9534 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9535 return LHS; 9536 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9537 return RHS; 9538 return getBlockPointerType(ResultType); 9539 } 9540 case Type::Atomic: 9541 { 9542 // Merge two pointer types, while trying to preserve typedef info 9543 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 9544 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 9545 if (Unqualified) { 9546 LHSValue = LHSValue.getUnqualifiedType(); 9547 RHSValue = RHSValue.getUnqualifiedType(); 9548 } 9549 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 9550 Unqualified); 9551 if (ResultType.isNull()) 9552 return {}; 9553 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 9554 return LHS; 9555 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 9556 return RHS; 9557 return getAtomicType(ResultType); 9558 } 9559 case Type::ConstantArray: 9560 { 9561 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 9562 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 9563 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 9564 return {}; 9565 9566 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 9567 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 9568 if (Unqualified) { 9569 LHSElem = LHSElem.getUnqualifiedType(); 9570 RHSElem = RHSElem.getUnqualifiedType(); 9571 } 9572 9573 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 9574 if (ResultType.isNull()) 9575 return {}; 9576 9577 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 9578 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 9579 9580 // If either side is a variable array, and both are complete, check whether 9581 // the current dimension is definite. 9582 if (LVAT || RVAT) { 9583 auto SizeFetch = [this](const VariableArrayType* VAT, 9584 const ConstantArrayType* CAT) 9585 -> std::pair<bool,llvm::APInt> { 9586 if (VAT) { 9587 llvm::APSInt TheInt; 9588 Expr *E = VAT->getSizeExpr(); 9589 if (E && E->isIntegerConstantExpr(TheInt, *this)) 9590 return std::make_pair(true, TheInt); 9591 else 9592 return std::make_pair(false, TheInt); 9593 } else if (CAT) { 9594 return std::make_pair(true, CAT->getSize()); 9595 } else { 9596 return std::make_pair(false, llvm::APInt()); 9597 } 9598 }; 9599 9600 bool HaveLSize, HaveRSize; 9601 llvm::APInt LSize, RSize; 9602 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 9603 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 9604 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 9605 return {}; // Definite, but unequal, array dimension 9606 } 9607 9608 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9609 return LHS; 9610 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9611 return RHS; 9612 if (LCAT) 9613 return getConstantArrayType(ResultType, LCAT->getSize(), 9614 LCAT->getSizeExpr(), 9615 ArrayType::ArraySizeModifier(), 0); 9616 if (RCAT) 9617 return getConstantArrayType(ResultType, RCAT->getSize(), 9618 RCAT->getSizeExpr(), 9619 ArrayType::ArraySizeModifier(), 0); 9620 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9621 return LHS; 9622 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9623 return RHS; 9624 if (LVAT) { 9625 // FIXME: This isn't correct! But tricky to implement because 9626 // the array's size has to be the size of LHS, but the type 9627 // has to be different. 9628 return LHS; 9629 } 9630 if (RVAT) { 9631 // FIXME: This isn't correct! But tricky to implement because 9632 // the array's size has to be the size of RHS, but the type 9633 // has to be different. 9634 return RHS; 9635 } 9636 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 9637 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 9638 return getIncompleteArrayType(ResultType, 9639 ArrayType::ArraySizeModifier(), 0); 9640 } 9641 case Type::FunctionNoProto: 9642 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 9643 case Type::Record: 9644 case Type::Enum: 9645 return {}; 9646 case Type::Builtin: 9647 // Only exactly equal builtin types are compatible, which is tested above. 9648 return {}; 9649 case Type::Complex: 9650 // Distinct complex types are incompatible. 9651 return {}; 9652 case Type::Vector: 9653 // FIXME: The merged type should be an ExtVector! 9654 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 9655 RHSCan->castAs<VectorType>())) 9656 return LHS; 9657 return {}; 9658 case Type::ConstantMatrix: 9659 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 9660 RHSCan->castAs<ConstantMatrixType>())) 9661 return LHS; 9662 return {}; 9663 case Type::ObjCObject: { 9664 // Check if the types are assignment compatible. 9665 // FIXME: This should be type compatibility, e.g. whether 9666 // "LHS x; RHS x;" at global scope is legal. 9667 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 9668 RHS->castAs<ObjCObjectType>())) 9669 return LHS; 9670 return {}; 9671 } 9672 case Type::ObjCObjectPointer: 9673 if (OfBlockPointer) { 9674 if (canAssignObjCInterfacesInBlockPointer( 9675 LHS->castAs<ObjCObjectPointerType>(), 9676 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 9677 return LHS; 9678 return {}; 9679 } 9680 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 9681 RHS->castAs<ObjCObjectPointerType>())) 9682 return LHS; 9683 return {}; 9684 case Type::Pipe: 9685 assert(LHS != RHS && 9686 "Equivalent pipe types should have already been handled!"); 9687 return {}; 9688 case Type::ExtInt: { 9689 // Merge two ext-int types, while trying to preserve typedef info. 9690 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned(); 9691 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned(); 9692 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits(); 9693 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits(); 9694 9695 // Like unsigned/int, shouldn't have a type if they dont match. 9696 if (LHSUnsigned != RHSUnsigned) 9697 return {}; 9698 9699 if (LHSBits != RHSBits) 9700 return {}; 9701 return LHS; 9702 } 9703 } 9704 9705 llvm_unreachable("Invalid Type::Class!"); 9706 } 9707 9708 bool ASTContext::mergeExtParameterInfo( 9709 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 9710 bool &CanUseFirst, bool &CanUseSecond, 9711 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 9712 assert(NewParamInfos.empty() && "param info list not empty"); 9713 CanUseFirst = CanUseSecond = true; 9714 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 9715 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 9716 9717 // Fast path: if the first type doesn't have ext parameter infos, 9718 // we match if and only if the second type also doesn't have them. 9719 if (!FirstHasInfo && !SecondHasInfo) 9720 return true; 9721 9722 bool NeedParamInfo = false; 9723 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 9724 : SecondFnType->getExtParameterInfos().size(); 9725 9726 for (size_t I = 0; I < E; ++I) { 9727 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 9728 if (FirstHasInfo) 9729 FirstParam = FirstFnType->getExtParameterInfo(I); 9730 if (SecondHasInfo) 9731 SecondParam = SecondFnType->getExtParameterInfo(I); 9732 9733 // Cannot merge unless everything except the noescape flag matches. 9734 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 9735 return false; 9736 9737 bool FirstNoEscape = FirstParam.isNoEscape(); 9738 bool SecondNoEscape = SecondParam.isNoEscape(); 9739 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 9740 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 9741 if (NewParamInfos.back().getOpaqueValue()) 9742 NeedParamInfo = true; 9743 if (FirstNoEscape != IsNoEscape) 9744 CanUseFirst = false; 9745 if (SecondNoEscape != IsNoEscape) 9746 CanUseSecond = false; 9747 } 9748 9749 if (!NeedParamInfo) 9750 NewParamInfos.clear(); 9751 9752 return true; 9753 } 9754 9755 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 9756 ObjCLayouts[CD] = nullptr; 9757 } 9758 9759 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 9760 /// 'RHS' attributes and returns the merged version; including for function 9761 /// return types. 9762 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 9763 QualType LHSCan = getCanonicalType(LHS), 9764 RHSCan = getCanonicalType(RHS); 9765 // If two types are identical, they are compatible. 9766 if (LHSCan == RHSCan) 9767 return LHS; 9768 if (RHSCan->isFunctionType()) { 9769 if (!LHSCan->isFunctionType()) 9770 return {}; 9771 QualType OldReturnType = 9772 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 9773 QualType NewReturnType = 9774 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 9775 QualType ResReturnType = 9776 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 9777 if (ResReturnType.isNull()) 9778 return {}; 9779 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 9780 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 9781 // In either case, use OldReturnType to build the new function type. 9782 const auto *F = LHS->castAs<FunctionType>(); 9783 if (const auto *FPT = cast<FunctionProtoType>(F)) { 9784 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9785 EPI.ExtInfo = getFunctionExtInfo(LHS); 9786 QualType ResultType = 9787 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 9788 return ResultType; 9789 } 9790 } 9791 return {}; 9792 } 9793 9794 // If the qualifiers are different, the types can still be merged. 9795 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9796 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9797 if (LQuals != RQuals) { 9798 // If any of these qualifiers are different, we have a type mismatch. 9799 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9800 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 9801 return {}; 9802 9803 // Exactly one GC qualifier difference is allowed: __strong is 9804 // okay if the other type has no GC qualifier but is an Objective 9805 // C object pointer (i.e. implicitly strong by default). We fix 9806 // this by pretending that the unqualified type was actually 9807 // qualified __strong. 9808 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9809 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9810 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9811 9812 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9813 return {}; 9814 9815 if (GC_L == Qualifiers::Strong) 9816 return LHS; 9817 if (GC_R == Qualifiers::Strong) 9818 return RHS; 9819 return {}; 9820 } 9821 9822 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 9823 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9824 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 9825 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 9826 if (ResQT == LHSBaseQT) 9827 return LHS; 9828 if (ResQT == RHSBaseQT) 9829 return RHS; 9830 } 9831 return {}; 9832 } 9833 9834 //===----------------------------------------------------------------------===// 9835 // Integer Predicates 9836 //===----------------------------------------------------------------------===// 9837 9838 unsigned ASTContext::getIntWidth(QualType T) const { 9839 if (const auto *ET = T->getAs<EnumType>()) 9840 T = ET->getDecl()->getIntegerType(); 9841 if (T->isBooleanType()) 9842 return 1; 9843 if(const auto *EIT = T->getAs<ExtIntType>()) 9844 return EIT->getNumBits(); 9845 // For builtin types, just use the standard type sizing method 9846 return (unsigned)getTypeSize(T); 9847 } 9848 9849 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 9850 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 9851 "Unexpected type"); 9852 9853 // Turn <4 x signed int> -> <4 x unsigned int> 9854 if (const auto *VTy = T->getAs<VectorType>()) 9855 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 9856 VTy->getNumElements(), VTy->getVectorKind()); 9857 9858 // For enums, we return the unsigned version of the base type. 9859 if (const auto *ETy = T->getAs<EnumType>()) 9860 T = ETy->getDecl()->getIntegerType(); 9861 9862 switch (T->castAs<BuiltinType>()->getKind()) { 9863 case BuiltinType::Char_S: 9864 case BuiltinType::SChar: 9865 return UnsignedCharTy; 9866 case BuiltinType::Short: 9867 return UnsignedShortTy; 9868 case BuiltinType::Int: 9869 return UnsignedIntTy; 9870 case BuiltinType::Long: 9871 return UnsignedLongTy; 9872 case BuiltinType::LongLong: 9873 return UnsignedLongLongTy; 9874 case BuiltinType::Int128: 9875 return UnsignedInt128Ty; 9876 9877 case BuiltinType::ShortAccum: 9878 return UnsignedShortAccumTy; 9879 case BuiltinType::Accum: 9880 return UnsignedAccumTy; 9881 case BuiltinType::LongAccum: 9882 return UnsignedLongAccumTy; 9883 case BuiltinType::SatShortAccum: 9884 return SatUnsignedShortAccumTy; 9885 case BuiltinType::SatAccum: 9886 return SatUnsignedAccumTy; 9887 case BuiltinType::SatLongAccum: 9888 return SatUnsignedLongAccumTy; 9889 case BuiltinType::ShortFract: 9890 return UnsignedShortFractTy; 9891 case BuiltinType::Fract: 9892 return UnsignedFractTy; 9893 case BuiltinType::LongFract: 9894 return UnsignedLongFractTy; 9895 case BuiltinType::SatShortFract: 9896 return SatUnsignedShortFractTy; 9897 case BuiltinType::SatFract: 9898 return SatUnsignedFractTy; 9899 case BuiltinType::SatLongFract: 9900 return SatUnsignedLongFractTy; 9901 default: 9902 llvm_unreachable("Unexpected signed integer or fixed point type"); 9903 } 9904 } 9905 9906 ASTMutationListener::~ASTMutationListener() = default; 9907 9908 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 9909 QualType ReturnType) {} 9910 9911 //===----------------------------------------------------------------------===// 9912 // Builtin Type Computation 9913 //===----------------------------------------------------------------------===// 9914 9915 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 9916 /// pointer over the consumed characters. This returns the resultant type. If 9917 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 9918 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 9919 /// a vector of "i*". 9920 /// 9921 /// RequiresICE is filled in on return to indicate whether the value is required 9922 /// to be an Integer Constant Expression. 9923 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 9924 ASTContext::GetBuiltinTypeError &Error, 9925 bool &RequiresICE, 9926 bool AllowTypeModifiers) { 9927 // Modifiers. 9928 int HowLong = 0; 9929 bool Signed = false, Unsigned = false; 9930 RequiresICE = false; 9931 9932 // Read the prefixed modifiers first. 9933 bool Done = false; 9934 #ifndef NDEBUG 9935 bool IsSpecial = false; 9936 #endif 9937 while (!Done) { 9938 switch (*Str++) { 9939 default: Done = true; --Str; break; 9940 case 'I': 9941 RequiresICE = true; 9942 break; 9943 case 'S': 9944 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 9945 assert(!Signed && "Can't use 'S' modifier multiple times!"); 9946 Signed = true; 9947 break; 9948 case 'U': 9949 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 9950 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 9951 Unsigned = true; 9952 break; 9953 case 'L': 9954 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 9955 assert(HowLong <= 2 && "Can't have LLLL modifier"); 9956 ++HowLong; 9957 break; 9958 case 'N': 9959 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 9960 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 9961 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 9962 #ifndef NDEBUG 9963 IsSpecial = true; 9964 #endif 9965 if (Context.getTargetInfo().getLongWidth() == 32) 9966 ++HowLong; 9967 break; 9968 case 'W': 9969 // This modifier represents int64 type. 9970 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 9971 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 9972 #ifndef NDEBUG 9973 IsSpecial = true; 9974 #endif 9975 switch (Context.getTargetInfo().getInt64Type()) { 9976 default: 9977 llvm_unreachable("Unexpected integer type"); 9978 case TargetInfo::SignedLong: 9979 HowLong = 1; 9980 break; 9981 case TargetInfo::SignedLongLong: 9982 HowLong = 2; 9983 break; 9984 } 9985 break; 9986 case 'Z': 9987 // This modifier represents int32 type. 9988 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 9989 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 9990 #ifndef NDEBUG 9991 IsSpecial = true; 9992 #endif 9993 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 9994 default: 9995 llvm_unreachable("Unexpected integer type"); 9996 case TargetInfo::SignedInt: 9997 HowLong = 0; 9998 break; 9999 case TargetInfo::SignedLong: 10000 HowLong = 1; 10001 break; 10002 case TargetInfo::SignedLongLong: 10003 HowLong = 2; 10004 break; 10005 } 10006 break; 10007 case 'O': 10008 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10009 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10010 #ifndef NDEBUG 10011 IsSpecial = true; 10012 #endif 10013 if (Context.getLangOpts().OpenCL) 10014 HowLong = 1; 10015 else 10016 HowLong = 2; 10017 break; 10018 } 10019 } 10020 10021 QualType Type; 10022 10023 // Read the base type. 10024 switch (*Str++) { 10025 default: llvm_unreachable("Unknown builtin type letter!"); 10026 case 'y': 10027 assert(HowLong == 0 && !Signed && !Unsigned && 10028 "Bad modifiers used with 'y'!"); 10029 Type = Context.BFloat16Ty; 10030 break; 10031 case 'v': 10032 assert(HowLong == 0 && !Signed && !Unsigned && 10033 "Bad modifiers used with 'v'!"); 10034 Type = Context.VoidTy; 10035 break; 10036 case 'h': 10037 assert(HowLong == 0 && !Signed && !Unsigned && 10038 "Bad modifiers used with 'h'!"); 10039 Type = Context.HalfTy; 10040 break; 10041 case 'f': 10042 assert(HowLong == 0 && !Signed && !Unsigned && 10043 "Bad modifiers used with 'f'!"); 10044 Type = Context.FloatTy; 10045 break; 10046 case 'd': 10047 assert(HowLong < 3 && !Signed && !Unsigned && 10048 "Bad modifiers used with 'd'!"); 10049 if (HowLong == 1) 10050 Type = Context.LongDoubleTy; 10051 else if (HowLong == 2) 10052 Type = Context.Float128Ty; 10053 else 10054 Type = Context.DoubleTy; 10055 break; 10056 case 's': 10057 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10058 if (Unsigned) 10059 Type = Context.UnsignedShortTy; 10060 else 10061 Type = Context.ShortTy; 10062 break; 10063 case 'i': 10064 if (HowLong == 3) 10065 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10066 else if (HowLong == 2) 10067 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10068 else if (HowLong == 1) 10069 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10070 else 10071 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10072 break; 10073 case 'c': 10074 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10075 if (Signed) 10076 Type = Context.SignedCharTy; 10077 else if (Unsigned) 10078 Type = Context.UnsignedCharTy; 10079 else 10080 Type = Context.CharTy; 10081 break; 10082 case 'b': // boolean 10083 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10084 Type = Context.BoolTy; 10085 break; 10086 case 'z': // size_t. 10087 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10088 Type = Context.getSizeType(); 10089 break; 10090 case 'w': // wchar_t. 10091 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10092 Type = Context.getWideCharType(); 10093 break; 10094 case 'F': 10095 Type = Context.getCFConstantStringType(); 10096 break; 10097 case 'G': 10098 Type = Context.getObjCIdType(); 10099 break; 10100 case 'H': 10101 Type = Context.getObjCSelType(); 10102 break; 10103 case 'M': 10104 Type = Context.getObjCSuperType(); 10105 break; 10106 case 'a': 10107 Type = Context.getBuiltinVaListType(); 10108 assert(!Type.isNull() && "builtin va list type not initialized!"); 10109 break; 10110 case 'A': 10111 // This is a "reference" to a va_list; however, what exactly 10112 // this means depends on how va_list is defined. There are two 10113 // different kinds of va_list: ones passed by value, and ones 10114 // passed by reference. An example of a by-value va_list is 10115 // x86, where va_list is a char*. An example of by-ref va_list 10116 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 10117 // we want this argument to be a char*&; for x86-64, we want 10118 // it to be a __va_list_tag*. 10119 Type = Context.getBuiltinVaListType(); 10120 assert(!Type.isNull() && "builtin va list type not initialized!"); 10121 if (Type->isArrayType()) 10122 Type = Context.getArrayDecayedType(Type); 10123 else 10124 Type = Context.getLValueReferenceType(Type); 10125 break; 10126 case 'q': { 10127 char *End; 10128 unsigned NumElements = strtoul(Str, &End, 10); 10129 assert(End != Str && "Missing vector size"); 10130 Str = End; 10131 10132 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10133 RequiresICE, false); 10134 assert(!RequiresICE && "Can't require vector ICE"); 10135 10136 Type = Context.getScalableVectorType(ElementType, NumElements); 10137 break; 10138 } 10139 case 'V': { 10140 char *End; 10141 unsigned NumElements = strtoul(Str, &End, 10); 10142 assert(End != Str && "Missing vector size"); 10143 Str = End; 10144 10145 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10146 RequiresICE, false); 10147 assert(!RequiresICE && "Can't require vector ICE"); 10148 10149 // TODO: No way to make AltiVec vectors in builtins yet. 10150 Type = Context.getVectorType(ElementType, NumElements, 10151 VectorType::GenericVector); 10152 break; 10153 } 10154 case 'E': { 10155 char *End; 10156 10157 unsigned NumElements = strtoul(Str, &End, 10); 10158 assert(End != Str && "Missing vector size"); 10159 10160 Str = End; 10161 10162 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10163 false); 10164 Type = Context.getExtVectorType(ElementType, NumElements); 10165 break; 10166 } 10167 case 'X': { 10168 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10169 false); 10170 assert(!RequiresICE && "Can't require complex ICE"); 10171 Type = Context.getComplexType(ElementType); 10172 break; 10173 } 10174 case 'Y': 10175 Type = Context.getPointerDiffType(); 10176 break; 10177 case 'P': 10178 Type = Context.getFILEType(); 10179 if (Type.isNull()) { 10180 Error = ASTContext::GE_Missing_stdio; 10181 return {}; 10182 } 10183 break; 10184 case 'J': 10185 if (Signed) 10186 Type = Context.getsigjmp_bufType(); 10187 else 10188 Type = Context.getjmp_bufType(); 10189 10190 if (Type.isNull()) { 10191 Error = ASTContext::GE_Missing_setjmp; 10192 return {}; 10193 } 10194 break; 10195 case 'K': 10196 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 10197 Type = Context.getucontext_tType(); 10198 10199 if (Type.isNull()) { 10200 Error = ASTContext::GE_Missing_ucontext; 10201 return {}; 10202 } 10203 break; 10204 case 'p': 10205 Type = Context.getProcessIDType(); 10206 break; 10207 } 10208 10209 // If there are modifiers and if we're allowed to parse them, go for it. 10210 Done = !AllowTypeModifiers; 10211 while (!Done) { 10212 switch (char c = *Str++) { 10213 default: Done = true; --Str; break; 10214 case '*': 10215 case '&': { 10216 // Both pointers and references can have their pointee types 10217 // qualified with an address space. 10218 char *End; 10219 unsigned AddrSpace = strtoul(Str, &End, 10); 10220 if (End != Str) { 10221 // Note AddrSpace == 0 is not the same as an unspecified address space. 10222 Type = Context.getAddrSpaceQualType( 10223 Type, 10224 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 10225 Str = End; 10226 } 10227 if (c == '*') 10228 Type = Context.getPointerType(Type); 10229 else 10230 Type = Context.getLValueReferenceType(Type); 10231 break; 10232 } 10233 // FIXME: There's no way to have a built-in with an rvalue ref arg. 10234 case 'C': 10235 Type = Type.withConst(); 10236 break; 10237 case 'D': 10238 Type = Context.getVolatileType(Type); 10239 break; 10240 case 'R': 10241 Type = Type.withRestrict(); 10242 break; 10243 } 10244 } 10245 10246 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 10247 "Integer constant 'I' type must be an integer"); 10248 10249 return Type; 10250 } 10251 10252 /// GetBuiltinType - Return the type for the specified builtin. 10253 QualType ASTContext::GetBuiltinType(unsigned Id, 10254 GetBuiltinTypeError &Error, 10255 unsigned *IntegerConstantArgs) const { 10256 const char *TypeStr = BuiltinInfo.getTypeString(Id); 10257 if (TypeStr[0] == '\0') { 10258 Error = GE_Missing_type; 10259 return {}; 10260 } 10261 10262 SmallVector<QualType, 8> ArgTypes; 10263 10264 bool RequiresICE = false; 10265 Error = GE_None; 10266 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 10267 RequiresICE, true); 10268 if (Error != GE_None) 10269 return {}; 10270 10271 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 10272 10273 while (TypeStr[0] && TypeStr[0] != '.') { 10274 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 10275 if (Error != GE_None) 10276 return {}; 10277 10278 // If this argument is required to be an IntegerConstantExpression and the 10279 // caller cares, fill in the bitmask we return. 10280 if (RequiresICE && IntegerConstantArgs) 10281 *IntegerConstantArgs |= 1 << ArgTypes.size(); 10282 10283 // Do array -> pointer decay. The builtin should use the decayed type. 10284 if (Ty->isArrayType()) 10285 Ty = getArrayDecayedType(Ty); 10286 10287 ArgTypes.push_back(Ty); 10288 } 10289 10290 if (Id == Builtin::BI__GetExceptionInfo) 10291 return {}; 10292 10293 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 10294 "'.' should only occur at end of builtin type list!"); 10295 10296 bool Variadic = (TypeStr[0] == '.'); 10297 10298 FunctionType::ExtInfo EI(getDefaultCallingConvention( 10299 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 10300 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 10301 10302 10303 // We really shouldn't be making a no-proto type here. 10304 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 10305 return getFunctionNoProtoType(ResType, EI); 10306 10307 FunctionProtoType::ExtProtoInfo EPI; 10308 EPI.ExtInfo = EI; 10309 EPI.Variadic = Variadic; 10310 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 10311 EPI.ExceptionSpec.Type = 10312 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 10313 10314 return getFunctionType(ResType, ArgTypes, EPI); 10315 } 10316 10317 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 10318 const FunctionDecl *FD) { 10319 if (!FD->isExternallyVisible()) 10320 return GVA_Internal; 10321 10322 // Non-user-provided functions get emitted as weak definitions with every 10323 // use, no matter whether they've been explicitly instantiated etc. 10324 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 10325 if (!MD->isUserProvided()) 10326 return GVA_DiscardableODR; 10327 10328 GVALinkage External; 10329 switch (FD->getTemplateSpecializationKind()) { 10330 case TSK_Undeclared: 10331 case TSK_ExplicitSpecialization: 10332 External = GVA_StrongExternal; 10333 break; 10334 10335 case TSK_ExplicitInstantiationDefinition: 10336 return GVA_StrongODR; 10337 10338 // C++11 [temp.explicit]p10: 10339 // [ Note: The intent is that an inline function that is the subject of 10340 // an explicit instantiation declaration will still be implicitly 10341 // instantiated when used so that the body can be considered for 10342 // inlining, but that no out-of-line copy of the inline function would be 10343 // generated in the translation unit. -- end note ] 10344 case TSK_ExplicitInstantiationDeclaration: 10345 return GVA_AvailableExternally; 10346 10347 case TSK_ImplicitInstantiation: 10348 External = GVA_DiscardableODR; 10349 break; 10350 } 10351 10352 if (!FD->isInlined()) 10353 return External; 10354 10355 if ((!Context.getLangOpts().CPlusPlus && 10356 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 10357 !FD->hasAttr<DLLExportAttr>()) || 10358 FD->hasAttr<GNUInlineAttr>()) { 10359 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 10360 10361 // GNU or C99 inline semantics. Determine whether this symbol should be 10362 // externally visible. 10363 if (FD->isInlineDefinitionExternallyVisible()) 10364 return External; 10365 10366 // C99 inline semantics, where the symbol is not externally visible. 10367 return GVA_AvailableExternally; 10368 } 10369 10370 // Functions specified with extern and inline in -fms-compatibility mode 10371 // forcibly get emitted. While the body of the function cannot be later 10372 // replaced, the function definition cannot be discarded. 10373 if (FD->isMSExternInline()) 10374 return GVA_StrongODR; 10375 10376 return GVA_DiscardableODR; 10377 } 10378 10379 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 10380 const Decl *D, GVALinkage L) { 10381 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 10382 // dllexport/dllimport on inline functions. 10383 if (D->hasAttr<DLLImportAttr>()) { 10384 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 10385 return GVA_AvailableExternally; 10386 } else if (D->hasAttr<DLLExportAttr>()) { 10387 if (L == GVA_DiscardableODR) 10388 return GVA_StrongODR; 10389 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && 10390 D->hasAttr<CUDAGlobalAttr>()) { 10391 // Device-side functions with __global__ attribute must always be 10392 // visible externally so they can be launched from host. 10393 if (L == GVA_DiscardableODR || L == GVA_Internal) 10394 return GVA_StrongODR; 10395 } 10396 return L; 10397 } 10398 10399 /// Adjust the GVALinkage for a declaration based on what an external AST source 10400 /// knows about whether there can be other definitions of this declaration. 10401 static GVALinkage 10402 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 10403 GVALinkage L) { 10404 ExternalASTSource *Source = Ctx.getExternalSource(); 10405 if (!Source) 10406 return L; 10407 10408 switch (Source->hasExternalDefinitions(D)) { 10409 case ExternalASTSource::EK_Never: 10410 // Other translation units rely on us to provide the definition. 10411 if (L == GVA_DiscardableODR) 10412 return GVA_StrongODR; 10413 break; 10414 10415 case ExternalASTSource::EK_Always: 10416 return GVA_AvailableExternally; 10417 10418 case ExternalASTSource::EK_ReplyHazy: 10419 break; 10420 } 10421 return L; 10422 } 10423 10424 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 10425 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 10426 adjustGVALinkageForAttributes(*this, FD, 10427 basicGVALinkageForFunction(*this, FD))); 10428 } 10429 10430 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 10431 const VarDecl *VD) { 10432 if (!VD->isExternallyVisible()) 10433 return GVA_Internal; 10434 10435 if (VD->isStaticLocal()) { 10436 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 10437 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 10438 LexicalContext = LexicalContext->getLexicalParent(); 10439 10440 // ObjC Blocks can create local variables that don't have a FunctionDecl 10441 // LexicalContext. 10442 if (!LexicalContext) 10443 return GVA_DiscardableODR; 10444 10445 // Otherwise, let the static local variable inherit its linkage from the 10446 // nearest enclosing function. 10447 auto StaticLocalLinkage = 10448 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 10449 10450 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 10451 // be emitted in any object with references to the symbol for the object it 10452 // contains, whether inline or out-of-line." 10453 // Similar behavior is observed with MSVC. An alternative ABI could use 10454 // StrongODR/AvailableExternally to match the function, but none are 10455 // known/supported currently. 10456 if (StaticLocalLinkage == GVA_StrongODR || 10457 StaticLocalLinkage == GVA_AvailableExternally) 10458 return GVA_DiscardableODR; 10459 return StaticLocalLinkage; 10460 } 10461 10462 // MSVC treats in-class initialized static data members as definitions. 10463 // By giving them non-strong linkage, out-of-line definitions won't 10464 // cause link errors. 10465 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 10466 return GVA_DiscardableODR; 10467 10468 // Most non-template variables have strong linkage; inline variables are 10469 // linkonce_odr or (occasionally, for compatibility) weak_odr. 10470 GVALinkage StrongLinkage; 10471 switch (Context.getInlineVariableDefinitionKind(VD)) { 10472 case ASTContext::InlineVariableDefinitionKind::None: 10473 StrongLinkage = GVA_StrongExternal; 10474 break; 10475 case ASTContext::InlineVariableDefinitionKind::Weak: 10476 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 10477 StrongLinkage = GVA_DiscardableODR; 10478 break; 10479 case ASTContext::InlineVariableDefinitionKind::Strong: 10480 StrongLinkage = GVA_StrongODR; 10481 break; 10482 } 10483 10484 switch (VD->getTemplateSpecializationKind()) { 10485 case TSK_Undeclared: 10486 return StrongLinkage; 10487 10488 case TSK_ExplicitSpecialization: 10489 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 10490 VD->isStaticDataMember() 10491 ? GVA_StrongODR 10492 : StrongLinkage; 10493 10494 case TSK_ExplicitInstantiationDefinition: 10495 return GVA_StrongODR; 10496 10497 case TSK_ExplicitInstantiationDeclaration: 10498 return GVA_AvailableExternally; 10499 10500 case TSK_ImplicitInstantiation: 10501 return GVA_DiscardableODR; 10502 } 10503 10504 llvm_unreachable("Invalid Linkage!"); 10505 } 10506 10507 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 10508 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 10509 adjustGVALinkageForAttributes(*this, VD, 10510 basicGVALinkageForVariable(*this, VD))); 10511 } 10512 10513 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 10514 if (const auto *VD = dyn_cast<VarDecl>(D)) { 10515 if (!VD->isFileVarDecl()) 10516 return false; 10517 // Global named register variables (GNU extension) are never emitted. 10518 if (VD->getStorageClass() == SC_Register) 10519 return false; 10520 if (VD->getDescribedVarTemplate() || 10521 isa<VarTemplatePartialSpecializationDecl>(VD)) 10522 return false; 10523 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10524 // We never need to emit an uninstantiated function template. 10525 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10526 return false; 10527 } else if (isa<PragmaCommentDecl>(D)) 10528 return true; 10529 else if (isa<PragmaDetectMismatchDecl>(D)) 10530 return true; 10531 else if (isa<OMPRequiresDecl>(D)) 10532 return true; 10533 else if (isa<OMPThreadPrivateDecl>(D)) 10534 return !D->getDeclContext()->isDependentContext(); 10535 else if (isa<OMPAllocateDecl>(D)) 10536 return !D->getDeclContext()->isDependentContext(); 10537 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 10538 return !D->getDeclContext()->isDependentContext(); 10539 else if (isa<ImportDecl>(D)) 10540 return true; 10541 else 10542 return false; 10543 10544 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) { 10545 assert(getExternalSource() && "It's from an AST file; must have a source."); 10546 // On Windows, PCH files are built together with an object file. If this 10547 // declaration comes from such a PCH and DeclMustBeEmitted would return 10548 // true, it would have returned true and the decl would have been emitted 10549 // into that object file, so it doesn't need to be emitted here. 10550 // Note that decls are still emitted if they're referenced, as usual; 10551 // DeclMustBeEmitted is used to decide whether a decl must be emitted even 10552 // if it's not referenced. 10553 // 10554 // Explicit template instantiation definitions are tricky. If there was an 10555 // explicit template instantiation decl in the PCH before, it will look like 10556 // the definition comes from there, even if that was just the declaration. 10557 // (Explicit instantiation defs of variable templates always get emitted.) 10558 bool IsExpInstDef = 10559 isa<FunctionDecl>(D) && 10560 cast<FunctionDecl>(D)->getTemplateSpecializationKind() == 10561 TSK_ExplicitInstantiationDefinition; 10562 10563 // Implicit member function definitions, such as operator= might not be 10564 // marked as template specializations, since they're not coming from a 10565 // template but synthesized directly on the class. 10566 IsExpInstDef |= 10567 isa<CXXMethodDecl>(D) && 10568 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() == 10569 TSK_ExplicitInstantiationDefinition; 10570 10571 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef) 10572 return false; 10573 } 10574 10575 // If this is a member of a class template, we do not need to emit it. 10576 if (D->getDeclContext()->isDependentContext()) 10577 return false; 10578 10579 // Weak references don't produce any output by themselves. 10580 if (D->hasAttr<WeakRefAttr>()) 10581 return false; 10582 10583 // Aliases and used decls are required. 10584 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 10585 return true; 10586 10587 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10588 // Forward declarations aren't required. 10589 if (!FD->doesThisDeclarationHaveABody()) 10590 return FD->doesDeclarationForceExternallyVisibleDefinition(); 10591 10592 // Constructors and destructors are required. 10593 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 10594 return true; 10595 10596 // The key function for a class is required. This rule only comes 10597 // into play when inline functions can be key functions, though. 10598 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10599 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10600 const CXXRecordDecl *RD = MD->getParent(); 10601 if (MD->isOutOfLine() && RD->isDynamicClass()) { 10602 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 10603 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 10604 return true; 10605 } 10606 } 10607 } 10608 10609 GVALinkage Linkage = GetGVALinkageForFunction(FD); 10610 10611 // static, static inline, always_inline, and extern inline functions can 10612 // always be deferred. Normal inline functions can be deferred in C99/C++. 10613 // Implicit template instantiations can also be deferred in C++. 10614 return !isDiscardableGVALinkage(Linkage); 10615 } 10616 10617 const auto *VD = cast<VarDecl>(D); 10618 assert(VD->isFileVarDecl() && "Expected file scoped var"); 10619 10620 // If the decl is marked as `declare target to`, it should be emitted for the 10621 // host and for the device. 10622 if (LangOpts.OpenMP && 10623 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 10624 return true; 10625 10626 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 10627 !isMSStaticDataMemberInlineDefinition(VD)) 10628 return false; 10629 10630 // Variables that can be needed in other TUs are required. 10631 auto Linkage = GetGVALinkageForVariable(VD); 10632 if (!isDiscardableGVALinkage(Linkage)) 10633 return true; 10634 10635 // We never need to emit a variable that is available in another TU. 10636 if (Linkage == GVA_AvailableExternally) 10637 return false; 10638 10639 // Variables that have destruction with side-effects are required. 10640 if (VD->needsDestruction(*this)) 10641 return true; 10642 10643 // Variables that have initialization with side-effects are required. 10644 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 10645 // We can get a value-dependent initializer during error recovery. 10646 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 10647 return true; 10648 10649 // Likewise, variables with tuple-like bindings are required if their 10650 // bindings have side-effects. 10651 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 10652 for (const auto *BD : DD->bindings()) 10653 if (const auto *BindingVD = BD->getHoldingVar()) 10654 if (DeclMustBeEmitted(BindingVD)) 10655 return true; 10656 10657 return false; 10658 } 10659 10660 void ASTContext::forEachMultiversionedFunctionVersion( 10661 const FunctionDecl *FD, 10662 llvm::function_ref<void(FunctionDecl *)> Pred) const { 10663 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 10664 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 10665 FD = FD->getMostRecentDecl(); 10666 for (auto *CurDecl : 10667 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 10668 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 10669 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 10670 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 10671 SeenDecls.insert(CurFD); 10672 Pred(CurFD); 10673 } 10674 } 10675 } 10676 10677 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 10678 bool IsCXXMethod, 10679 bool IsBuiltin) const { 10680 // Pass through to the C++ ABI object 10681 if (IsCXXMethod) 10682 return ABI->getDefaultMethodCallConv(IsVariadic); 10683 10684 // Builtins ignore user-specified default calling convention and remain the 10685 // Target's default calling convention. 10686 if (!IsBuiltin) { 10687 switch (LangOpts.getDefaultCallingConv()) { 10688 case LangOptions::DCC_None: 10689 break; 10690 case LangOptions::DCC_CDecl: 10691 return CC_C; 10692 case LangOptions::DCC_FastCall: 10693 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 10694 return CC_X86FastCall; 10695 break; 10696 case LangOptions::DCC_StdCall: 10697 if (!IsVariadic) 10698 return CC_X86StdCall; 10699 break; 10700 case LangOptions::DCC_VectorCall: 10701 // __vectorcall cannot be applied to variadic functions. 10702 if (!IsVariadic) 10703 return CC_X86VectorCall; 10704 break; 10705 case LangOptions::DCC_RegCall: 10706 // __regcall cannot be applied to variadic functions. 10707 if (!IsVariadic) 10708 return CC_X86RegCall; 10709 break; 10710 } 10711 } 10712 return Target->getDefaultCallingConv(); 10713 } 10714 10715 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 10716 // Pass through to the C++ ABI object 10717 return ABI->isNearlyEmpty(RD); 10718 } 10719 10720 VTableContextBase *ASTContext::getVTableContext() { 10721 if (!VTContext.get()) { 10722 auto ABI = Target->getCXXABI(); 10723 if (ABI.isMicrosoft()) 10724 VTContext.reset(new MicrosoftVTableContext(*this)); 10725 else { 10726 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 10727 ? ItaniumVTableContext::Relative 10728 : ItaniumVTableContext::Pointer; 10729 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 10730 } 10731 } 10732 return VTContext.get(); 10733 } 10734 10735 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 10736 if (!T) 10737 T = Target; 10738 switch (T->getCXXABI().getKind()) { 10739 case TargetCXXABI::Fuchsia: 10740 case TargetCXXABI::GenericAArch64: 10741 case TargetCXXABI::GenericItanium: 10742 case TargetCXXABI::GenericARM: 10743 case TargetCXXABI::GenericMIPS: 10744 case TargetCXXABI::iOS: 10745 case TargetCXXABI::iOS64: 10746 case TargetCXXABI::WebAssembly: 10747 case TargetCXXABI::WatchOS: 10748 case TargetCXXABI::XL: 10749 return ItaniumMangleContext::create(*this, getDiagnostics()); 10750 case TargetCXXABI::Microsoft: 10751 return MicrosoftMangleContext::create(*this, getDiagnostics()); 10752 } 10753 llvm_unreachable("Unsupported ABI"); 10754 } 10755 10756 CXXABI::~CXXABI() = default; 10757 10758 size_t ASTContext::getSideTableAllocatedMemory() const { 10759 return ASTRecordLayouts.getMemorySize() + 10760 llvm::capacity_in_bytes(ObjCLayouts) + 10761 llvm::capacity_in_bytes(KeyFunctions) + 10762 llvm::capacity_in_bytes(ObjCImpls) + 10763 llvm::capacity_in_bytes(BlockVarCopyInits) + 10764 llvm::capacity_in_bytes(DeclAttrs) + 10765 llvm::capacity_in_bytes(TemplateOrInstantiation) + 10766 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 10767 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 10768 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 10769 llvm::capacity_in_bytes(OverriddenMethods) + 10770 llvm::capacity_in_bytes(Types) + 10771 llvm::capacity_in_bytes(VariableArrayTypes); 10772 } 10773 10774 /// getIntTypeForBitwidth - 10775 /// sets integer QualTy according to specified details: 10776 /// bitwidth, signed/unsigned. 10777 /// Returns empty type if there is no appropriate target types. 10778 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 10779 unsigned Signed) const { 10780 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 10781 CanQualType QualTy = getFromTargetType(Ty); 10782 if (!QualTy && DestWidth == 128) 10783 return Signed ? Int128Ty : UnsignedInt128Ty; 10784 return QualTy; 10785 } 10786 10787 /// getRealTypeForBitwidth - 10788 /// sets floating point QualTy according to specified bitwidth. 10789 /// Returns empty type if there is no appropriate target types. 10790 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 10791 bool ExplicitIEEE) const { 10792 TargetInfo::RealType Ty = 10793 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE); 10794 switch (Ty) { 10795 case TargetInfo::Float: 10796 return FloatTy; 10797 case TargetInfo::Double: 10798 return DoubleTy; 10799 case TargetInfo::LongDouble: 10800 return LongDoubleTy; 10801 case TargetInfo::Float128: 10802 return Float128Ty; 10803 case TargetInfo::NoFloat: 10804 return {}; 10805 } 10806 10807 llvm_unreachable("Unhandled TargetInfo::RealType value"); 10808 } 10809 10810 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 10811 if (Number > 1) 10812 MangleNumbers[ND] = Number; 10813 } 10814 10815 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 10816 auto I = MangleNumbers.find(ND); 10817 return I != MangleNumbers.end() ? I->second : 1; 10818 } 10819 10820 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 10821 if (Number > 1) 10822 StaticLocalNumbers[VD] = Number; 10823 } 10824 10825 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 10826 auto I = StaticLocalNumbers.find(VD); 10827 return I != StaticLocalNumbers.end() ? I->second : 1; 10828 } 10829 10830 MangleNumberingContext & 10831 ASTContext::getManglingNumberContext(const DeclContext *DC) { 10832 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10833 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 10834 if (!MCtx) 10835 MCtx = createMangleNumberingContext(); 10836 return *MCtx; 10837 } 10838 10839 MangleNumberingContext & 10840 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 10841 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 10842 std::unique_ptr<MangleNumberingContext> &MCtx = 10843 ExtraMangleNumberingContexts[D]; 10844 if (!MCtx) 10845 MCtx = createMangleNumberingContext(); 10846 return *MCtx; 10847 } 10848 10849 std::unique_ptr<MangleNumberingContext> 10850 ASTContext::createMangleNumberingContext() const { 10851 return ABI->createMangleNumberingContext(); 10852 } 10853 10854 const CXXConstructorDecl * 10855 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 10856 return ABI->getCopyConstructorForExceptionObject( 10857 cast<CXXRecordDecl>(RD->getFirstDecl())); 10858 } 10859 10860 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 10861 CXXConstructorDecl *CD) { 10862 return ABI->addCopyConstructorForExceptionObject( 10863 cast<CXXRecordDecl>(RD->getFirstDecl()), 10864 cast<CXXConstructorDecl>(CD->getFirstDecl())); 10865 } 10866 10867 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 10868 TypedefNameDecl *DD) { 10869 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 10870 } 10871 10872 TypedefNameDecl * 10873 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 10874 return ABI->getTypedefNameForUnnamedTagDecl(TD); 10875 } 10876 10877 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 10878 DeclaratorDecl *DD) { 10879 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 10880 } 10881 10882 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 10883 return ABI->getDeclaratorForUnnamedTagDecl(TD); 10884 } 10885 10886 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 10887 ParamIndices[D] = index; 10888 } 10889 10890 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 10891 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 10892 assert(I != ParamIndices.end() && 10893 "ParmIndices lacks entry set by ParmVarDecl"); 10894 return I->second; 10895 } 10896 10897 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 10898 unsigned Length) const { 10899 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 10900 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 10901 EltTy = EltTy.withConst(); 10902 10903 EltTy = adjustStringLiteralBaseType(EltTy); 10904 10905 // Get an array type for the string, according to C99 6.4.5. This includes 10906 // the null terminator character. 10907 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 10908 ArrayType::Normal, /*IndexTypeQuals*/ 0); 10909 } 10910 10911 StringLiteral * 10912 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 10913 StringLiteral *&Result = StringLiteralCache[Key]; 10914 if (!Result) 10915 Result = StringLiteral::Create( 10916 *this, Key, StringLiteral::Ascii, 10917 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 10918 SourceLocation()); 10919 return Result; 10920 } 10921 10922 MSGuidDecl * 10923 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 10924 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 10925 10926 llvm::FoldingSetNodeID ID; 10927 MSGuidDecl::Profile(ID, Parts); 10928 10929 void *InsertPos; 10930 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 10931 return Existing; 10932 10933 QualType GUIDType = getMSGuidType().withConst(); 10934 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 10935 MSGuidDecls.InsertNode(New, InsertPos); 10936 return New; 10937 } 10938 10939 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 10940 const llvm::Triple &T = getTargetInfo().getTriple(); 10941 if (!T.isOSDarwin()) 10942 return false; 10943 10944 if (!(T.isiOS() && T.isOSVersionLT(7)) && 10945 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 10946 return false; 10947 10948 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 10949 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 10950 uint64_t Size = sizeChars.getQuantity(); 10951 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 10952 unsigned Align = alignChars.getQuantity(); 10953 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 10954 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 10955 } 10956 10957 bool 10958 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 10959 const ObjCMethodDecl *MethodImpl) { 10960 // No point trying to match an unavailable/deprecated mothod. 10961 if (MethodDecl->hasAttr<UnavailableAttr>() 10962 || MethodDecl->hasAttr<DeprecatedAttr>()) 10963 return false; 10964 if (MethodDecl->getObjCDeclQualifier() != 10965 MethodImpl->getObjCDeclQualifier()) 10966 return false; 10967 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 10968 return false; 10969 10970 if (MethodDecl->param_size() != MethodImpl->param_size()) 10971 return false; 10972 10973 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 10974 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 10975 EF = MethodDecl->param_end(); 10976 IM != EM && IF != EF; ++IM, ++IF) { 10977 const ParmVarDecl *DeclVar = (*IF); 10978 const ParmVarDecl *ImplVar = (*IM); 10979 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 10980 return false; 10981 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 10982 return false; 10983 } 10984 10985 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 10986 } 10987 10988 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 10989 LangAS AS; 10990 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 10991 AS = LangAS::Default; 10992 else 10993 AS = QT->getPointeeType().getAddressSpace(); 10994 10995 return getTargetInfo().getNullPointerValue(AS); 10996 } 10997 10998 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 10999 if (isTargetAddressSpace(AS)) 11000 return toTargetAddressSpace(AS); 11001 else 11002 return (*AddrSpaceMap)[(unsigned)AS]; 11003 } 11004 11005 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11006 assert(Ty->isFixedPointType()); 11007 11008 if (Ty->isSaturatedFixedPointType()) return Ty; 11009 11010 switch (Ty->castAs<BuiltinType>()->getKind()) { 11011 default: 11012 llvm_unreachable("Not a fixed point type!"); 11013 case BuiltinType::ShortAccum: 11014 return SatShortAccumTy; 11015 case BuiltinType::Accum: 11016 return SatAccumTy; 11017 case BuiltinType::LongAccum: 11018 return SatLongAccumTy; 11019 case BuiltinType::UShortAccum: 11020 return SatUnsignedShortAccumTy; 11021 case BuiltinType::UAccum: 11022 return SatUnsignedAccumTy; 11023 case BuiltinType::ULongAccum: 11024 return SatUnsignedLongAccumTy; 11025 case BuiltinType::ShortFract: 11026 return SatShortFractTy; 11027 case BuiltinType::Fract: 11028 return SatFractTy; 11029 case BuiltinType::LongFract: 11030 return SatLongFractTy; 11031 case BuiltinType::UShortFract: 11032 return SatUnsignedShortFractTy; 11033 case BuiltinType::UFract: 11034 return SatUnsignedFractTy; 11035 case BuiltinType::ULongFract: 11036 return SatUnsignedLongFractTy; 11037 } 11038 } 11039 11040 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11041 if (LangOpts.OpenCL) 11042 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11043 11044 if (LangOpts.CUDA) 11045 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11046 11047 return getLangASFromTargetAS(AS); 11048 } 11049 11050 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11051 // doesn't include ASTContext.h 11052 template 11053 clang::LazyGenerationalUpdatePtr< 11054 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11055 clang::LazyGenerationalUpdatePtr< 11056 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11057 const clang::ASTContext &Ctx, Decl *Value); 11058 11059 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 11060 assert(Ty->isFixedPointType()); 11061 11062 const TargetInfo &Target = getTargetInfo(); 11063 switch (Ty->castAs<BuiltinType>()->getKind()) { 11064 default: 11065 llvm_unreachable("Not a fixed point type!"); 11066 case BuiltinType::ShortAccum: 11067 case BuiltinType::SatShortAccum: 11068 return Target.getShortAccumScale(); 11069 case BuiltinType::Accum: 11070 case BuiltinType::SatAccum: 11071 return Target.getAccumScale(); 11072 case BuiltinType::LongAccum: 11073 case BuiltinType::SatLongAccum: 11074 return Target.getLongAccumScale(); 11075 case BuiltinType::UShortAccum: 11076 case BuiltinType::SatUShortAccum: 11077 return Target.getUnsignedShortAccumScale(); 11078 case BuiltinType::UAccum: 11079 case BuiltinType::SatUAccum: 11080 return Target.getUnsignedAccumScale(); 11081 case BuiltinType::ULongAccum: 11082 case BuiltinType::SatULongAccum: 11083 return Target.getUnsignedLongAccumScale(); 11084 case BuiltinType::ShortFract: 11085 case BuiltinType::SatShortFract: 11086 return Target.getShortFractScale(); 11087 case BuiltinType::Fract: 11088 case BuiltinType::SatFract: 11089 return Target.getFractScale(); 11090 case BuiltinType::LongFract: 11091 case BuiltinType::SatLongFract: 11092 return Target.getLongFractScale(); 11093 case BuiltinType::UShortFract: 11094 case BuiltinType::SatUShortFract: 11095 return Target.getUnsignedShortFractScale(); 11096 case BuiltinType::UFract: 11097 case BuiltinType::SatUFract: 11098 return Target.getUnsignedFractScale(); 11099 case BuiltinType::ULongFract: 11100 case BuiltinType::SatULongFract: 11101 return Target.getUnsignedLongFractScale(); 11102 } 11103 } 11104 11105 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 11106 assert(Ty->isFixedPointType()); 11107 11108 const TargetInfo &Target = getTargetInfo(); 11109 switch (Ty->castAs<BuiltinType>()->getKind()) { 11110 default: 11111 llvm_unreachable("Not a fixed point type!"); 11112 case BuiltinType::ShortAccum: 11113 case BuiltinType::SatShortAccum: 11114 return Target.getShortAccumIBits(); 11115 case BuiltinType::Accum: 11116 case BuiltinType::SatAccum: 11117 return Target.getAccumIBits(); 11118 case BuiltinType::LongAccum: 11119 case BuiltinType::SatLongAccum: 11120 return Target.getLongAccumIBits(); 11121 case BuiltinType::UShortAccum: 11122 case BuiltinType::SatUShortAccum: 11123 return Target.getUnsignedShortAccumIBits(); 11124 case BuiltinType::UAccum: 11125 case BuiltinType::SatUAccum: 11126 return Target.getUnsignedAccumIBits(); 11127 case BuiltinType::ULongAccum: 11128 case BuiltinType::SatULongAccum: 11129 return Target.getUnsignedLongAccumIBits(); 11130 case BuiltinType::ShortFract: 11131 case BuiltinType::SatShortFract: 11132 case BuiltinType::Fract: 11133 case BuiltinType::SatFract: 11134 case BuiltinType::LongFract: 11135 case BuiltinType::SatLongFract: 11136 case BuiltinType::UShortFract: 11137 case BuiltinType::SatUShortFract: 11138 case BuiltinType::UFract: 11139 case BuiltinType::SatUFract: 11140 case BuiltinType::ULongFract: 11141 case BuiltinType::SatULongFract: 11142 return 0; 11143 } 11144 } 11145 11146 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const { 11147 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 11148 "Can only get the fixed point semantics for a " 11149 "fixed point or integer type."); 11150 if (Ty->isIntegerType()) 11151 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty), 11152 Ty->isSignedIntegerType()); 11153 11154 bool isSigned = Ty->isSignedFixedPointType(); 11155 return FixedPointSemantics( 11156 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 11157 Ty->isSaturatedFixedPointType(), 11158 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 11159 } 11160 11161 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 11162 assert(Ty->isFixedPointType()); 11163 return APFixedPoint::getMax(getFixedPointSemantics(Ty)); 11164 } 11165 11166 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 11167 assert(Ty->isFixedPointType()); 11168 return APFixedPoint::getMin(getFixedPointSemantics(Ty)); 11169 } 11170 11171 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 11172 assert(Ty->isUnsignedFixedPointType() && 11173 "Expected unsigned fixed point type"); 11174 11175 switch (Ty->castAs<BuiltinType>()->getKind()) { 11176 case BuiltinType::UShortAccum: 11177 return ShortAccumTy; 11178 case BuiltinType::UAccum: 11179 return AccumTy; 11180 case BuiltinType::ULongAccum: 11181 return LongAccumTy; 11182 case BuiltinType::SatUShortAccum: 11183 return SatShortAccumTy; 11184 case BuiltinType::SatUAccum: 11185 return SatAccumTy; 11186 case BuiltinType::SatULongAccum: 11187 return SatLongAccumTy; 11188 case BuiltinType::UShortFract: 11189 return ShortFractTy; 11190 case BuiltinType::UFract: 11191 return FractTy; 11192 case BuiltinType::ULongFract: 11193 return LongFractTy; 11194 case BuiltinType::SatUShortFract: 11195 return SatShortFractTy; 11196 case BuiltinType::SatUFract: 11197 return SatFractTy; 11198 case BuiltinType::SatULongFract: 11199 return SatLongFractTy; 11200 default: 11201 llvm_unreachable("Unexpected unsigned fixed point type"); 11202 } 11203 } 11204 11205 ParsedTargetAttr 11206 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 11207 assert(TD != nullptr); 11208 ParsedTargetAttr ParsedAttr = TD->parse(); 11209 11210 ParsedAttr.Features.erase( 11211 llvm::remove_if(ParsedAttr.Features, 11212 [&](const std::string &Feat) { 11213 return !Target->isValidFeatureName( 11214 StringRef{Feat}.substr(1)); 11215 }), 11216 ParsedAttr.Features.end()); 11217 return ParsedAttr; 11218 } 11219 11220 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11221 const FunctionDecl *FD) const { 11222 if (FD) 11223 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 11224 else 11225 Target->initFeatureMap(FeatureMap, getDiagnostics(), 11226 Target->getTargetOpts().CPU, 11227 Target->getTargetOpts().Features); 11228 } 11229 11230 // Fills in the supplied string map with the set of target features for the 11231 // passed in function. 11232 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11233 GlobalDecl GD) const { 11234 StringRef TargetCPU = Target->getTargetOpts().CPU; 11235 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 11236 if (const auto *TD = FD->getAttr<TargetAttr>()) { 11237 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 11238 11239 // Make a copy of the features as passed on the command line into the 11240 // beginning of the additional features from the function to override. 11241 ParsedAttr.Features.insert( 11242 ParsedAttr.Features.begin(), 11243 Target->getTargetOpts().FeaturesAsWritten.begin(), 11244 Target->getTargetOpts().FeaturesAsWritten.end()); 11245 11246 if (ParsedAttr.Architecture != "" && 11247 Target->isValidCPUName(ParsedAttr.Architecture)) 11248 TargetCPU = ParsedAttr.Architecture; 11249 11250 // Now populate the feature map, first with the TargetCPU which is either 11251 // the default or a new one from the target attribute string. Then we'll use 11252 // the passed in features (FeaturesAsWritten) along with the new ones from 11253 // the attribute. 11254 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 11255 ParsedAttr.Features); 11256 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 11257 llvm::SmallVector<StringRef, 32> FeaturesTmp; 11258 Target->getCPUSpecificCPUDispatchFeatures( 11259 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 11260 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 11261 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 11262 } else { 11263 FeatureMap = Target->getTargetOpts().FeatureMap; 11264 } 11265 } 11266 11267 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 11268 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 11269 return *OMPTraitInfoVector.back(); 11270 } 11271 11272 const DiagnosticBuilder & 11273 clang::operator<<(const DiagnosticBuilder &DB, 11274 const ASTContext::SectionInfo &Section) { 11275 if (Section.Decl) 11276 return DB << Section.Decl; 11277 return DB << "a prior #pragma section"; 11278 } 11279