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/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Linkage.h" 58 #include "clang/Basic/Module.h" 59 #include "clang/Basic/NoSanitizeList.h" 60 #include "clang/Basic/ObjCRuntime.h" 61 #include "clang/Basic/SourceLocation.h" 62 #include "clang/Basic/SourceManager.h" 63 #include "clang/Basic/Specifiers.h" 64 #include "clang/Basic/TargetCXXABI.h" 65 #include "clang/Basic/TargetInfo.h" 66 #include "clang/Basic/XRayLists.h" 67 #include "llvm/ADT/APFixedPoint.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/MD5.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 103 enum FloatingRank { 104 BFloat16Rank, 105 Float16Rank, 106 HalfRank, 107 FloatRank, 108 DoubleRank, 109 LongDoubleRank, 110 Float128Rank, 111 Ibm128Rank 112 }; 113 114 /// \returns location that is relevant when searching for Doc comments related 115 /// to \p D. 116 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 117 SourceManager &SourceMgr) { 118 assert(D); 119 120 // User can not attach documentation to implicit declarations. 121 if (D->isImplicit()) 122 return {}; 123 124 // User can not attach documentation to implicit instantiations. 125 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 126 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 127 return {}; 128 } 129 130 if (const auto *VD = dyn_cast<VarDecl>(D)) { 131 if (VD->isStaticDataMember() && 132 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 133 return {}; 134 } 135 136 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 137 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 138 return {}; 139 } 140 141 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 142 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 143 if (TSK == TSK_ImplicitInstantiation || 144 TSK == TSK_Undeclared) 145 return {}; 146 } 147 148 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 149 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 150 return {}; 151 } 152 if (const auto *TD = dyn_cast<TagDecl>(D)) { 153 // When tag declaration (but not definition!) is part of the 154 // decl-specifier-seq of some other declaration, it doesn't get comment 155 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 156 return {}; 157 } 158 // TODO: handle comments for function parameters properly. 159 if (isa<ParmVarDecl>(D)) 160 return {}; 161 162 // TODO: we could look up template parameter documentation in the template 163 // documentation. 164 if (isa<TemplateTypeParmDecl>(D) || 165 isa<NonTypeTemplateParmDecl>(D) || 166 isa<TemplateTemplateParmDecl>(D)) 167 return {}; 168 169 // Find declaration location. 170 // For Objective-C declarations we generally don't expect to have multiple 171 // declarators, thus use declaration starting location as the "declaration 172 // location". 173 // For all other declarations multiple declarators are used quite frequently, 174 // so we use the location of the identifier as the "declaration location". 175 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 176 isa<ObjCPropertyDecl>(D) || 177 isa<RedeclarableTemplateDecl>(D) || 178 isa<ClassTemplateSpecializationDecl>(D) || 179 // Allow association with Y across {} in `typedef struct X {} Y`. 180 isa<TypedefDecl>(D)) 181 return D->getBeginLoc(); 182 183 const SourceLocation DeclLoc = D->getLocation(); 184 if (DeclLoc.isMacroID()) { 185 if (isa<TypedefDecl>(D)) { 186 // If location of the typedef name is in a macro, it is because being 187 // declared via a macro. Try using declaration's starting location as 188 // the "declaration location". 189 return D->getBeginLoc(); 190 } 191 192 if (const auto *TD = dyn_cast<TagDecl>(D)) { 193 // If location of the tag decl is inside a macro, but the spelling of 194 // the tag name comes from a macro argument, it looks like a special 195 // macro like NS_ENUM is being used to define the tag decl. In that 196 // case, adjust the source location to the expansion loc so that we can 197 // attach the comment to the tag decl. 198 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) 199 return SourceMgr.getExpansionLoc(DeclLoc); 200 } 201 } 202 203 return DeclLoc; 204 } 205 206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 207 const Decl *D, const SourceLocation RepresentativeLocForDecl, 208 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 209 // If the declaration doesn't map directly to a location in a file, we 210 // can't find the comment. 211 if (RepresentativeLocForDecl.isInvalid() || 212 !RepresentativeLocForDecl.isFileID()) 213 return nullptr; 214 215 // If there are no comments anywhere, we won't find anything. 216 if (CommentsInTheFile.empty()) 217 return nullptr; 218 219 // Decompose the location for the declaration and find the beginning of the 220 // file buffer. 221 const std::pair<FileID, unsigned> DeclLocDecomp = 222 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 223 224 // Slow path. 225 auto OffsetCommentBehindDecl = 226 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 227 228 // First check whether we have a trailing comment. 229 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 230 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 231 if ((CommentBehindDecl->isDocumentation() || 232 LangOpts.CommentOpts.ParseAllComments) && 233 CommentBehindDecl->isTrailingComment() && 234 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 235 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 236 237 // Check that Doxygen trailing comment comes after the declaration, starts 238 // on the same line and in the same file as the declaration. 239 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 240 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 241 OffsetCommentBehindDecl->first)) { 242 return CommentBehindDecl; 243 } 244 } 245 } 246 247 // The comment just after the declaration was not a trailing comment. 248 // Let's look at the previous comment. 249 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 250 return nullptr; 251 252 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 253 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 254 255 // Check that we actually have a non-member Doxygen comment. 256 if (!(CommentBeforeDecl->isDocumentation() || 257 LangOpts.CommentOpts.ParseAllComments) || 258 CommentBeforeDecl->isTrailingComment()) 259 return nullptr; 260 261 // Decompose the end of the comment. 262 const unsigned CommentEndOffset = 263 Comments.getCommentEndOffset(CommentBeforeDecl); 264 265 // Get the corresponding buffer. 266 bool Invalid = false; 267 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 268 &Invalid).data(); 269 if (Invalid) 270 return nullptr; 271 272 // Extract text between the comment and declaration. 273 StringRef Text(Buffer + CommentEndOffset, 274 DeclLocDecomp.second - CommentEndOffset); 275 276 // There should be no other declarations or preprocessor directives between 277 // comment and declaration. 278 if (Text.find_first_of(";{}#@") != StringRef::npos) 279 return nullptr; 280 281 return CommentBeforeDecl; 282 } 283 284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 285 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 286 287 // If the declaration doesn't map directly to a location in a file, we 288 // can't find the comment. 289 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 290 return nullptr; 291 292 if (ExternalSource && !CommentsLoaded) { 293 ExternalSource->ReadComments(); 294 CommentsLoaded = true; 295 } 296 297 if (Comments.empty()) 298 return nullptr; 299 300 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 301 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 302 if (!CommentsInThisFile || CommentsInThisFile->empty()) 303 return nullptr; 304 305 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 306 } 307 308 void ASTContext::addComment(const RawComment &RC) { 309 assert(LangOpts.RetainCommentsFromSystemHeaders || 310 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 311 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 312 } 313 314 /// If we have a 'templated' declaration for a template, adjust 'D' to 315 /// refer to the actual template. 316 /// If we have an implicit instantiation, adjust 'D' to refer to template. 317 static const Decl &adjustDeclToTemplate(const Decl &D) { 318 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 319 // Is this function declaration part of a function template? 320 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 321 return *FTD; 322 323 // Nothing to do if function is not an implicit instantiation. 324 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 325 return D; 326 327 // Function is an implicit instantiation of a function template? 328 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 329 return *FTD; 330 331 // Function is instantiated from a member definition of a class template? 332 if (const FunctionDecl *MemberDecl = 333 FD->getInstantiatedFromMemberFunction()) 334 return *MemberDecl; 335 336 return D; 337 } 338 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 339 // Static data member is instantiated from a member definition of a class 340 // template? 341 if (VD->isStaticDataMember()) 342 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 343 return *MemberDecl; 344 345 return D; 346 } 347 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 348 // Is this class declaration part of a class template? 349 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 350 return *CTD; 351 352 // Class is an implicit instantiation of a class template or partial 353 // specialization? 354 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 355 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 356 return D; 357 llvm::PointerUnion<ClassTemplateDecl *, 358 ClassTemplatePartialSpecializationDecl *> 359 PU = CTSD->getSpecializedTemplateOrPartial(); 360 return PU.is<ClassTemplateDecl *>() 361 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 362 : *static_cast<const Decl *>( 363 PU.get<ClassTemplatePartialSpecializationDecl *>()); 364 } 365 366 // Class is instantiated from a member definition of a class template? 367 if (const MemberSpecializationInfo *Info = 368 CRD->getMemberSpecializationInfo()) 369 return *Info->getInstantiatedFrom(); 370 371 return D; 372 } 373 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 374 // Enum is instantiated from a member definition of a class template? 375 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 376 return *MemberDecl; 377 378 return D; 379 } 380 // FIXME: Adjust alias templates? 381 return D; 382 } 383 384 const RawComment *ASTContext::getRawCommentForAnyRedecl( 385 const Decl *D, 386 const Decl **OriginalDecl) const { 387 if (!D) { 388 if (OriginalDecl) 389 OriginalDecl = nullptr; 390 return nullptr; 391 } 392 393 D = &adjustDeclToTemplate(*D); 394 395 // Any comment directly attached to D? 396 { 397 auto DeclComment = DeclRawComments.find(D); 398 if (DeclComment != DeclRawComments.end()) { 399 if (OriginalDecl) 400 *OriginalDecl = D; 401 return DeclComment->second; 402 } 403 } 404 405 // Any comment attached to any redeclaration of D? 406 const Decl *CanonicalD = D->getCanonicalDecl(); 407 if (!CanonicalD) 408 return nullptr; 409 410 { 411 auto RedeclComment = RedeclChainComments.find(CanonicalD); 412 if (RedeclComment != RedeclChainComments.end()) { 413 if (OriginalDecl) 414 *OriginalDecl = RedeclComment->second; 415 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 416 assert(CommentAtRedecl != DeclRawComments.end() && 417 "This decl is supposed to have comment attached."); 418 return CommentAtRedecl->second; 419 } 420 } 421 422 // Any redeclarations of D that we haven't checked for comments yet? 423 // We can't use DenseMap::iterator directly since it'd get invalid. 424 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 425 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 426 if (LookupRes != CommentlessRedeclChains.end()) 427 return LookupRes->second; 428 return nullptr; 429 }(); 430 431 for (const auto Redecl : D->redecls()) { 432 assert(Redecl); 433 // Skip all redeclarations that have been checked previously. 434 if (LastCheckedRedecl) { 435 if (LastCheckedRedecl == Redecl) { 436 LastCheckedRedecl = nullptr; 437 } 438 continue; 439 } 440 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 441 if (RedeclComment) { 442 cacheRawCommentForDecl(*Redecl, *RedeclComment); 443 if (OriginalDecl) 444 *OriginalDecl = Redecl; 445 return RedeclComment; 446 } 447 CommentlessRedeclChains[CanonicalD] = Redecl; 448 } 449 450 if (OriginalDecl) 451 *OriginalDecl = nullptr; 452 return nullptr; 453 } 454 455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 456 const RawComment &Comment) const { 457 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 458 DeclRawComments.try_emplace(&OriginalD, &Comment); 459 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 460 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 461 CommentlessRedeclChains.erase(CanonicalDecl); 462 } 463 464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 465 SmallVectorImpl<const NamedDecl *> &Redeclared) { 466 const DeclContext *DC = ObjCMethod->getDeclContext(); 467 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 468 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 469 if (!ID) 470 return; 471 // Add redeclared method here. 472 for (const auto *Ext : ID->known_extensions()) { 473 if (ObjCMethodDecl *RedeclaredMethod = 474 Ext->getMethod(ObjCMethod->getSelector(), 475 ObjCMethod->isInstanceMethod())) 476 Redeclared.push_back(RedeclaredMethod); 477 } 478 } 479 } 480 481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 482 const Preprocessor *PP) { 483 if (Comments.empty() || Decls.empty()) 484 return; 485 486 FileID File; 487 for (Decl *D : Decls) { 488 SourceLocation Loc = D->getLocation(); 489 if (Loc.isValid()) { 490 // See if there are any new comments that are not attached to a decl. 491 // The location doesn't have to be precise - we care only about the file. 492 File = SourceMgr.getDecomposedLoc(Loc).first; 493 break; 494 } 495 } 496 497 if (File.isInvalid()) 498 return; 499 500 auto CommentsInThisFile = Comments.getCommentsInFile(File); 501 if (!CommentsInThisFile || CommentsInThisFile->empty() || 502 CommentsInThisFile->rbegin()->second->isAttached()) 503 return; 504 505 // There is at least one comment not attached to a decl. 506 // Maybe it should be attached to one of Decls? 507 // 508 // Note that this way we pick up not only comments that precede the 509 // declaration, but also comments that *follow* the declaration -- thanks to 510 // the lookahead in the lexer: we've consumed the semicolon and looked 511 // ahead through comments. 512 513 for (const Decl *D : Decls) { 514 assert(D); 515 if (D->isInvalidDecl()) 516 continue; 517 518 D = &adjustDeclToTemplate(*D); 519 520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 521 522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 523 continue; 524 525 if (DeclRawComments.count(D) > 0) 526 continue; 527 528 if (RawComment *const DocComment = 529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 530 cacheRawCommentForDecl(*D, *DocComment); 531 comments::FullComment *FC = DocComment->parse(*this, PP, D); 532 ParsedComments[D->getCanonicalDecl()] = FC; 533 } 534 } 535 } 536 537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 538 const Decl *D) const { 539 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 540 ThisDeclInfo->CommentDecl = D; 541 ThisDeclInfo->IsFilled = false; 542 ThisDeclInfo->fill(); 543 ThisDeclInfo->CommentDecl = FC->getDecl(); 544 if (!ThisDeclInfo->TemplateParameters) 545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 546 comments::FullComment *CFC = 547 new (*this) comments::FullComment(FC->getBlocks(), 548 ThisDeclInfo); 549 return CFC; 550 } 551 552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 553 const RawComment *RC = getRawCommentForDeclNoCache(D); 554 return RC ? RC->parse(*this, nullptr, D) : nullptr; 555 } 556 557 comments::FullComment *ASTContext::getCommentForDecl( 558 const Decl *D, 559 const Preprocessor *PP) const { 560 if (!D || D->isInvalidDecl()) 561 return nullptr; 562 D = &adjustDeclToTemplate(*D); 563 564 const Decl *Canonical = D->getCanonicalDecl(); 565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 566 ParsedComments.find(Canonical); 567 568 if (Pos != ParsedComments.end()) { 569 if (Canonical != D) { 570 comments::FullComment *FC = Pos->second; 571 comments::FullComment *CFC = cloneFullComment(FC, D); 572 return CFC; 573 } 574 return Pos->second; 575 } 576 577 const Decl *OriginalDecl = nullptr; 578 579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 580 if (!RC) { 581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 582 SmallVector<const NamedDecl*, 8> Overridden; 583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 584 if (OMD && OMD->isPropertyAccessor()) 585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 587 return cloneFullComment(FC, D); 588 if (OMD) 589 addRedeclaredMethods(OMD, Overridden); 590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 591 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 593 return cloneFullComment(FC, D); 594 } 595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 596 // Attach any tag type's documentation to its typedef if latter 597 // does not have one of its own. 598 QualType QT = TD->getUnderlyingType(); 599 if (const auto *TT = QT->getAs<TagType>()) 600 if (const Decl *TD = TT->getDecl()) 601 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 602 return cloneFullComment(FC, D); 603 } 604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 605 while (IC->getSuperClass()) { 606 IC = IC->getSuperClass(); 607 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 608 return cloneFullComment(FC, D); 609 } 610 } 611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 613 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 614 return cloneFullComment(FC, D); 615 } 616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 617 if (!(RD = RD->getDefinition())) 618 return nullptr; 619 // Check non-virtual bases. 620 for (const auto &I : RD->bases()) { 621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 622 continue; 623 QualType Ty = I.getType(); 624 if (Ty.isNull()) 625 continue; 626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 627 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 628 continue; 629 630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 631 return cloneFullComment(FC, D); 632 } 633 } 634 // Check virtual bases. 635 for (const auto &I : RD->vbases()) { 636 if (I.getAccessSpecifier() != AS_public) 637 continue; 638 QualType Ty = I.getType(); 639 if (Ty.isNull()) 640 continue; 641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 642 if (!(VirtualBase= VirtualBase->getDefinition())) 643 continue; 644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 645 return cloneFullComment(FC, D); 646 } 647 } 648 } 649 return nullptr; 650 } 651 652 // If the RawComment was attached to other redeclaration of this Decl, we 653 // should parse the comment in context of that other Decl. This is important 654 // because comments can contain references to parameter names which can be 655 // different across redeclarations. 656 if (D != OriginalDecl && OriginalDecl) 657 return getCommentForDecl(OriginalDecl, PP); 658 659 comments::FullComment *FC = RC->parse(*this, PP, D); 660 ParsedComments[Canonical] = FC; 661 return FC; 662 } 663 664 void 665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 666 const ASTContext &C, 667 TemplateTemplateParmDecl *Parm) { 668 ID.AddInteger(Parm->getDepth()); 669 ID.AddInteger(Parm->getPosition()); 670 ID.AddBoolean(Parm->isParameterPack()); 671 672 TemplateParameterList *Params = Parm->getTemplateParameters(); 673 ID.AddInteger(Params->size()); 674 for (TemplateParameterList::const_iterator P = Params->begin(), 675 PEnd = Params->end(); 676 P != PEnd; ++P) { 677 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 678 ID.AddInteger(0); 679 ID.AddBoolean(TTP->isParameterPack()); 680 const TypeConstraint *TC = TTP->getTypeConstraint(); 681 ID.AddBoolean(TC != nullptr); 682 if (TC) 683 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 684 /*Canonical=*/true); 685 if (TTP->isExpandedParameterPack()) { 686 ID.AddBoolean(true); 687 ID.AddInteger(TTP->getNumExpansionParameters()); 688 } else 689 ID.AddBoolean(false); 690 continue; 691 } 692 693 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 694 ID.AddInteger(1); 695 ID.AddBoolean(NTTP->isParameterPack()); 696 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 697 if (NTTP->isExpandedParameterPack()) { 698 ID.AddBoolean(true); 699 ID.AddInteger(NTTP->getNumExpansionTypes()); 700 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 701 QualType T = NTTP->getExpansionType(I); 702 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 703 } 704 } else 705 ID.AddBoolean(false); 706 continue; 707 } 708 709 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 710 ID.AddInteger(2); 711 Profile(ID, C, TTP); 712 } 713 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 714 ID.AddBoolean(RequiresClause != nullptr); 715 if (RequiresClause) 716 RequiresClause->Profile(ID, C, /*Canonical=*/true); 717 } 718 719 static Expr * 720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 721 QualType ConstrainedType) { 722 // This is a bit ugly - we need to form a new immediately-declared 723 // constraint that references the new parameter; this would ideally 724 // require semantic analysis (e.g. template<C T> struct S {}; - the 725 // converted arguments of C<T> could be an argument pack if C is 726 // declared as template<typename... T> concept C = ...). 727 // We don't have semantic analysis here so we dig deep into the 728 // ready-made constraint expr and change the thing manually. 729 ConceptSpecializationExpr *CSE; 730 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 731 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 732 else 733 CSE = cast<ConceptSpecializationExpr>(IDC); 734 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 735 SmallVector<TemplateArgument, 3> NewConverted; 736 NewConverted.reserve(OldConverted.size()); 737 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 738 // The case: 739 // template<typename... T> concept C = true; 740 // template<C<int> T> struct S; -> constraint is C<{T, int}> 741 NewConverted.push_back(ConstrainedType); 742 llvm::append_range(NewConverted, 743 OldConverted.front().pack_elements().drop_front(1)); 744 TemplateArgument NewPack(NewConverted); 745 746 NewConverted.clear(); 747 NewConverted.push_back(NewPack); 748 assert(OldConverted.size() == 1 && 749 "Template parameter pack should be the last parameter"); 750 } else { 751 assert(OldConverted.front().getKind() == TemplateArgument::Type && 752 "Unexpected first argument kind for immediately-declared " 753 "constraint"); 754 NewConverted.push_back(ConstrainedType); 755 llvm::append_range(NewConverted, OldConverted.drop_front(1)); 756 } 757 Expr *NewIDC = ConceptSpecializationExpr::Create( 758 C, CSE->getNamedConcept(), NewConverted, nullptr, 759 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 760 761 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 762 NewIDC = new (C) CXXFoldExpr( 763 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 764 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 765 SourceLocation(), /*NumExpansions=*/None); 766 return NewIDC; 767 } 768 769 TemplateTemplateParmDecl * 770 ASTContext::getCanonicalTemplateTemplateParmDecl( 771 TemplateTemplateParmDecl *TTP) const { 772 // Check if we already have a canonical template template parameter. 773 llvm::FoldingSetNodeID ID; 774 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 775 void *InsertPos = nullptr; 776 CanonicalTemplateTemplateParm *Canonical 777 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 778 if (Canonical) 779 return Canonical->getParam(); 780 781 // Build a canonical template parameter list. 782 TemplateParameterList *Params = TTP->getTemplateParameters(); 783 SmallVector<NamedDecl *, 4> CanonParams; 784 CanonParams.reserve(Params->size()); 785 for (TemplateParameterList::const_iterator P = Params->begin(), 786 PEnd = Params->end(); 787 P != PEnd; ++P) { 788 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 789 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 790 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 791 TTP->getDepth(), TTP->getIndex(), nullptr, false, 792 TTP->isParameterPack(), TTP->hasTypeConstraint(), 793 TTP->isExpandedParameterPack() ? 794 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 795 if (const auto *TC = TTP->getTypeConstraint()) { 796 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 797 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 798 *this, TC->getImmediatelyDeclaredConstraint(), 799 ParamAsArgument); 800 TemplateArgumentListInfo CanonArgsAsWritten; 801 if (auto *Args = TC->getTemplateArgsAsWritten()) 802 for (const auto &ArgLoc : Args->arguments()) 803 CanonArgsAsWritten.addArgument( 804 TemplateArgumentLoc(ArgLoc.getArgument(), 805 TemplateArgumentLocInfo())); 806 NewTTP->setTypeConstraint( 807 NestedNameSpecifierLoc(), 808 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 809 SourceLocation()), /*FoundDecl=*/nullptr, 810 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 811 // simply omit the ArgsAsWritten 812 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 813 } 814 CanonParams.push_back(NewTTP); 815 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 816 QualType T = getCanonicalType(NTTP->getType()); 817 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 818 NonTypeTemplateParmDecl *Param; 819 if (NTTP->isExpandedParameterPack()) { 820 SmallVector<QualType, 2> ExpandedTypes; 821 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 822 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 823 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 824 ExpandedTInfos.push_back( 825 getTrivialTypeSourceInfo(ExpandedTypes.back())); 826 } 827 828 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 829 SourceLocation(), 830 SourceLocation(), 831 NTTP->getDepth(), 832 NTTP->getPosition(), nullptr, 833 T, 834 TInfo, 835 ExpandedTypes, 836 ExpandedTInfos); 837 } else { 838 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 839 SourceLocation(), 840 SourceLocation(), 841 NTTP->getDepth(), 842 NTTP->getPosition(), nullptr, 843 T, 844 NTTP->isParameterPack(), 845 TInfo); 846 } 847 if (AutoType *AT = T->getContainedAutoType()) { 848 if (AT->isConstrained()) { 849 Param->setPlaceholderTypeConstraint( 850 canonicalizeImmediatelyDeclaredConstraint( 851 *this, NTTP->getPlaceholderTypeConstraint(), T)); 852 } 853 } 854 CanonParams.push_back(Param); 855 856 } else 857 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 858 cast<TemplateTemplateParmDecl>(*P))); 859 } 860 861 Expr *CanonRequiresClause = nullptr; 862 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 863 CanonRequiresClause = RequiresClause; 864 865 TemplateTemplateParmDecl *CanonTTP 866 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 867 SourceLocation(), TTP->getDepth(), 868 TTP->getPosition(), 869 TTP->isParameterPack(), 870 nullptr, 871 TemplateParameterList::Create(*this, SourceLocation(), 872 SourceLocation(), 873 CanonParams, 874 SourceLocation(), 875 CanonRequiresClause)); 876 877 // Get the new insert position for the node we care about. 878 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 879 assert(!Canonical && "Shouldn't be in the map!"); 880 (void)Canonical; 881 882 // Create the canonical template template parameter entry. 883 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 884 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 885 return CanonTTP; 886 } 887 888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 889 auto Kind = getTargetInfo().getCXXABI().getKind(); 890 return getLangOpts().CXXABI.getValueOr(Kind); 891 } 892 893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 894 if (!LangOpts.CPlusPlus) return nullptr; 895 896 switch (getCXXABIKind()) { 897 case TargetCXXABI::AppleARM64: 898 case TargetCXXABI::Fuchsia: 899 case TargetCXXABI::GenericARM: // Same as Itanium at this level 900 case TargetCXXABI::iOS: 901 case TargetCXXABI::WatchOS: 902 case TargetCXXABI::GenericAArch64: 903 case TargetCXXABI::GenericMIPS: 904 case TargetCXXABI::GenericItanium: 905 case TargetCXXABI::WebAssembly: 906 case TargetCXXABI::XL: 907 return CreateItaniumCXXABI(*this); 908 case TargetCXXABI::Microsoft: 909 return CreateMicrosoftCXXABI(*this); 910 } 911 llvm_unreachable("Invalid CXXABI type!"); 912 } 913 914 interp::Context &ASTContext::getInterpContext() { 915 if (!InterpContext) { 916 InterpContext.reset(new interp::Context(*this)); 917 } 918 return *InterpContext.get(); 919 } 920 921 ParentMapContext &ASTContext::getParentMapContext() { 922 if (!ParentMapCtx) 923 ParentMapCtx.reset(new ParentMapContext(*this)); 924 return *ParentMapCtx.get(); 925 } 926 927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 928 const LangOptions &LOpts) { 929 if (LOpts.FakeAddressSpaceMap) { 930 // The fake address space map must have a distinct entry for each 931 // language-specific address space. 932 static const unsigned FakeAddrSpaceMap[] = { 933 0, // Default 934 1, // opencl_global 935 3, // opencl_local 936 2, // opencl_constant 937 0, // opencl_private 938 4, // opencl_generic 939 5, // opencl_global_device 940 6, // opencl_global_host 941 7, // cuda_device 942 8, // cuda_constant 943 9, // cuda_shared 944 1, // sycl_global 945 5, // sycl_global_device 946 6, // sycl_global_host 947 3, // sycl_local 948 0, // sycl_private 949 10, // ptr32_sptr 950 11, // ptr32_uptr 951 12 // ptr64 952 }; 953 return &FakeAddrSpaceMap; 954 } else { 955 return &T.getAddressSpaceMap(); 956 } 957 } 958 959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 960 const LangOptions &LangOpts) { 961 switch (LangOpts.getAddressSpaceMapMangling()) { 962 case LangOptions::ASMM_Target: 963 return TI.useAddressSpaceMapMangling(); 964 case LangOptions::ASMM_On: 965 return true; 966 case LangOptions::ASMM_Off: 967 return false; 968 } 969 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 970 } 971 972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 973 IdentifierTable &idents, SelectorTable &sels, 974 Builtin::Context &builtins, TranslationUnitKind TUKind) 975 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 976 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 977 TemplateSpecializationTypes(this_()), 978 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 979 SubstTemplateTemplateParmPacks(this_()), 980 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 981 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 982 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 983 LangOpts.XRayNeverInstrumentFiles, 984 LangOpts.XRayAttrListFiles, SM)), 985 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 986 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 987 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 988 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 989 CompCategories(this_()), LastSDM(nullptr, 0) { 990 addTranslationUnitDecl(); 991 } 992 993 void ASTContext::cleanup() { 994 // Release the DenseMaps associated with DeclContext objects. 995 // FIXME: Is this the ideal solution? 996 ReleaseDeclContextMaps(); 997 998 // Call all of the deallocation functions on all of their targets. 999 for (auto &Pair : Deallocations) 1000 (Pair.first)(Pair.second); 1001 Deallocations.clear(); 1002 1003 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1004 // because they can contain DenseMaps. 1005 for (llvm::DenseMap<const ObjCContainerDecl*, 1006 const ASTRecordLayout*>::iterator 1007 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1008 // Increment in loop to prevent using deallocated memory. 1009 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1010 R->Destroy(*this); 1011 ObjCLayouts.clear(); 1012 1013 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1014 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1015 // Increment in loop to prevent using deallocated memory. 1016 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1017 R->Destroy(*this); 1018 } 1019 ASTRecordLayouts.clear(); 1020 1021 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1022 AEnd = DeclAttrs.end(); 1023 A != AEnd; ++A) 1024 A->second->~AttrVec(); 1025 DeclAttrs.clear(); 1026 1027 for (const auto &Value : ModuleInitializers) 1028 Value.second->~PerModuleInitializers(); 1029 ModuleInitializers.clear(); 1030 } 1031 1032 ASTContext::~ASTContext() { cleanup(); } 1033 1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1035 TraversalScope = TopLevelDecls; 1036 getParentMapContext().clear(); 1037 } 1038 1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1040 Deallocations.push_back({Callback, Data}); 1041 } 1042 1043 void 1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1045 ExternalSource = std::move(Source); 1046 } 1047 1048 void ASTContext::PrintStats() const { 1049 llvm::errs() << "\n*** AST Context Stats:\n"; 1050 llvm::errs() << " " << Types.size() << " types total.\n"; 1051 1052 unsigned counts[] = { 1053 #define TYPE(Name, Parent) 0, 1054 #define ABSTRACT_TYPE(Name, Parent) 1055 #include "clang/AST/TypeNodes.inc" 1056 0 // Extra 1057 }; 1058 1059 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1060 Type *T = Types[i]; 1061 counts[(unsigned)T->getTypeClass()]++; 1062 } 1063 1064 unsigned Idx = 0; 1065 unsigned TotalBytes = 0; 1066 #define TYPE(Name, Parent) \ 1067 if (counts[Idx]) \ 1068 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1069 << " types, " << sizeof(Name##Type) << " each " \ 1070 << "(" << counts[Idx] * sizeof(Name##Type) \ 1071 << " bytes)\n"; \ 1072 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1073 ++Idx; 1074 #define ABSTRACT_TYPE(Name, Parent) 1075 #include "clang/AST/TypeNodes.inc" 1076 1077 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1078 1079 // Implicit special member functions. 1080 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1081 << NumImplicitDefaultConstructors 1082 << " implicit default constructors created\n"; 1083 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1084 << NumImplicitCopyConstructors 1085 << " implicit copy constructors created\n"; 1086 if (getLangOpts().CPlusPlus) 1087 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1088 << NumImplicitMoveConstructors 1089 << " implicit move constructors created\n"; 1090 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1091 << NumImplicitCopyAssignmentOperators 1092 << " implicit copy assignment operators created\n"; 1093 if (getLangOpts().CPlusPlus) 1094 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1095 << NumImplicitMoveAssignmentOperators 1096 << " implicit move assignment operators created\n"; 1097 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1098 << NumImplicitDestructors 1099 << " implicit destructors created\n"; 1100 1101 if (ExternalSource) { 1102 llvm::errs() << "\n"; 1103 ExternalSource->PrintStats(); 1104 } 1105 1106 BumpAlloc.PrintStats(); 1107 } 1108 1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1110 bool NotifyListeners) { 1111 if (NotifyListeners) 1112 if (auto *Listener = getASTMutationListener()) 1113 Listener->RedefinedHiddenDefinition(ND, M); 1114 1115 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1116 } 1117 1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1119 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1120 if (It == MergedDefModules.end()) 1121 return; 1122 1123 auto &Merged = It->second; 1124 llvm::DenseSet<Module*> Found; 1125 for (Module *&M : Merged) 1126 if (!Found.insert(M).second) 1127 M = nullptr; 1128 llvm::erase_value(Merged, nullptr); 1129 } 1130 1131 ArrayRef<Module *> 1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1133 auto MergedIt = 1134 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1135 if (MergedIt == MergedDefModules.end()) 1136 return None; 1137 return MergedIt->second; 1138 } 1139 1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1141 if (LazyInitializers.empty()) 1142 return; 1143 1144 auto *Source = Ctx.getExternalSource(); 1145 assert(Source && "lazy initializers but no external source"); 1146 1147 auto LazyInits = std::move(LazyInitializers); 1148 LazyInitializers.clear(); 1149 1150 for (auto ID : LazyInits) 1151 Initializers.push_back(Source->GetExternalDecl(ID)); 1152 1153 assert(LazyInitializers.empty() && 1154 "GetExternalDecl for lazy module initializer added more inits"); 1155 } 1156 1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1158 // One special case: if we add a module initializer that imports another 1159 // module, and that module's only initializer is an ImportDecl, simplify. 1160 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1161 auto It = ModuleInitializers.find(ID->getImportedModule()); 1162 1163 // Maybe the ImportDecl does nothing at all. (Common case.) 1164 if (It == ModuleInitializers.end()) 1165 return; 1166 1167 // Maybe the ImportDecl only imports another ImportDecl. 1168 auto &Imported = *It->second; 1169 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1170 Imported.resolve(*this); 1171 auto *OnlyDecl = Imported.Initializers.front(); 1172 if (isa<ImportDecl>(OnlyDecl)) 1173 D = OnlyDecl; 1174 } 1175 } 1176 1177 auto *&Inits = ModuleInitializers[M]; 1178 if (!Inits) 1179 Inits = new (*this) PerModuleInitializers; 1180 Inits->Initializers.push_back(D); 1181 } 1182 1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1184 auto *&Inits = ModuleInitializers[M]; 1185 if (!Inits) 1186 Inits = new (*this) PerModuleInitializers; 1187 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1188 IDs.begin(), IDs.end()); 1189 } 1190 1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1192 auto It = ModuleInitializers.find(M); 1193 if (It == ModuleInitializers.end()) 1194 return None; 1195 1196 auto *Inits = It->second; 1197 Inits->resolve(*this); 1198 return Inits->Initializers; 1199 } 1200 1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1202 if (!ExternCContext) 1203 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1204 1205 return ExternCContext; 1206 } 1207 1208 BuiltinTemplateDecl * 1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1210 const IdentifierInfo *II) const { 1211 auto *BuiltinTemplate = 1212 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1213 BuiltinTemplate->setImplicit(); 1214 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1215 1216 return BuiltinTemplate; 1217 } 1218 1219 BuiltinTemplateDecl * 1220 ASTContext::getMakeIntegerSeqDecl() const { 1221 if (!MakeIntegerSeqDecl) 1222 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1223 getMakeIntegerSeqName()); 1224 return MakeIntegerSeqDecl; 1225 } 1226 1227 BuiltinTemplateDecl * 1228 ASTContext::getTypePackElementDecl() const { 1229 if (!TypePackElementDecl) 1230 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1231 getTypePackElementName()); 1232 return TypePackElementDecl; 1233 } 1234 1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1236 RecordDecl::TagKind TK) const { 1237 SourceLocation Loc; 1238 RecordDecl *NewDecl; 1239 if (getLangOpts().CPlusPlus) 1240 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1241 Loc, &Idents.get(Name)); 1242 else 1243 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1244 &Idents.get(Name)); 1245 NewDecl->setImplicit(); 1246 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1247 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1248 return NewDecl; 1249 } 1250 1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1252 StringRef Name) const { 1253 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1254 TypedefDecl *NewDecl = TypedefDecl::Create( 1255 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1256 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1257 NewDecl->setImplicit(); 1258 return NewDecl; 1259 } 1260 1261 TypedefDecl *ASTContext::getInt128Decl() const { 1262 if (!Int128Decl) 1263 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1264 return Int128Decl; 1265 } 1266 1267 TypedefDecl *ASTContext::getUInt128Decl() const { 1268 if (!UInt128Decl) 1269 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1270 return UInt128Decl; 1271 } 1272 1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1274 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1275 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1276 Types.push_back(Ty); 1277 } 1278 1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1280 const TargetInfo *AuxTarget) { 1281 assert((!this->Target || this->Target == &Target) && 1282 "Incorrect target reinitialization"); 1283 assert(VoidTy.isNull() && "Context reinitialized?"); 1284 1285 this->Target = &Target; 1286 this->AuxTarget = AuxTarget; 1287 1288 ABI.reset(createCXXABI(Target)); 1289 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1291 1292 // C99 6.2.5p19. 1293 InitBuiltinType(VoidTy, BuiltinType::Void); 1294 1295 // C99 6.2.5p2. 1296 InitBuiltinType(BoolTy, BuiltinType::Bool); 1297 // C99 6.2.5p3. 1298 if (LangOpts.CharIsSigned) 1299 InitBuiltinType(CharTy, BuiltinType::Char_S); 1300 else 1301 InitBuiltinType(CharTy, BuiltinType::Char_U); 1302 // C99 6.2.5p4. 1303 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1304 InitBuiltinType(ShortTy, BuiltinType::Short); 1305 InitBuiltinType(IntTy, BuiltinType::Int); 1306 InitBuiltinType(LongTy, BuiltinType::Long); 1307 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1308 1309 // C99 6.2.5p6. 1310 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1311 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1312 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1313 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1314 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1315 1316 // C99 6.2.5p10. 1317 InitBuiltinType(FloatTy, BuiltinType::Float); 1318 InitBuiltinType(DoubleTy, BuiltinType::Double); 1319 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1320 1321 // GNU extension, __float128 for IEEE quadruple precision 1322 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1323 1324 // __ibm128 for IBM extended precision 1325 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1326 1327 // C11 extension ISO/IEC TS 18661-3 1328 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1329 1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1331 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1332 InitBuiltinType(AccumTy, BuiltinType::Accum); 1333 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1334 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1335 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1336 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1337 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1338 InitBuiltinType(FractTy, BuiltinType::Fract); 1339 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1340 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1341 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1342 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1343 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1344 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1345 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1346 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1347 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1348 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1349 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1350 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1351 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1352 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1353 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1354 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1355 1356 // GNU extension, 128-bit integers. 1357 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1359 1360 // C++ 3.9.1p5 1361 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1362 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1363 else // -fshort-wchar makes wchar_t be unsigned. 1364 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1365 if (LangOpts.CPlusPlus && LangOpts.WChar) 1366 WideCharTy = WCharTy; 1367 else { 1368 // C99 (or C++ using -fno-wchar). 1369 WideCharTy = getFromTargetType(Target.getWCharType()); 1370 } 1371 1372 WIntTy = getFromTargetType(Target.getWIntType()); 1373 1374 // C++20 (proposed) 1375 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1376 1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1378 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1379 else // C99 1380 Char16Ty = getFromTargetType(Target.getChar16Type()); 1381 1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1383 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1384 else // C99 1385 Char32Ty = getFromTargetType(Target.getChar32Type()); 1386 1387 // Placeholder type for type-dependent expressions whose type is 1388 // completely unknown. No code should ever check a type against 1389 // DependentTy and users should never see it; however, it is here to 1390 // help diagnose failures to properly check for type-dependent 1391 // expressions. 1392 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1393 1394 // Placeholder type for functions. 1395 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1396 1397 // Placeholder type for bound members. 1398 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1399 1400 // Placeholder type for pseudo-objects. 1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1402 1403 // "any" type; useful for debugger-like clients. 1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1405 1406 // Placeholder type for unbridged ARC casts. 1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1408 1409 // Placeholder type for builtin functions. 1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1411 1412 // Placeholder type for OMP array sections. 1413 if (LangOpts.OpenMP) { 1414 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1417 } 1418 if (LangOpts.MatrixTypes) 1419 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1420 1421 // Builtin types for 'id', 'Class', and 'SEL'. 1422 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1423 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1424 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1425 1426 if (LangOpts.OpenCL) { 1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1428 InitBuiltinType(SingletonId, BuiltinType::Id); 1429 #include "clang/Basic/OpenCLImageTypes.def" 1430 1431 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1432 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1433 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1434 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1435 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1436 1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1438 InitBuiltinType(Id##Ty, BuiltinType::Id); 1439 #include "clang/Basic/OpenCLExtensionTypes.def" 1440 } 1441 1442 if (Target.hasAArch64SVETypes()) { 1443 #define SVE_TYPE(Name, Id, SingletonId) \ 1444 InitBuiltinType(SingletonId, BuiltinType::Id); 1445 #include "clang/Basic/AArch64SVEACLETypes.def" 1446 } 1447 1448 if (Target.getTriple().isPPC64()) { 1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1450 InitBuiltinType(Id##Ty, BuiltinType::Id); 1451 #include "clang/Basic/PPCTypes.def" 1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1453 InitBuiltinType(Id##Ty, BuiltinType::Id); 1454 #include "clang/Basic/PPCTypes.def" 1455 } 1456 1457 if (Target.hasRISCVVTypes()) { 1458 #define RVV_TYPE(Name, Id, SingletonId) \ 1459 InitBuiltinType(SingletonId, BuiltinType::Id); 1460 #include "clang/Basic/RISCVVTypes.def" 1461 } 1462 1463 // Builtin type for __objc_yes and __objc_no 1464 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1465 SignedCharTy : BoolTy); 1466 1467 ObjCConstantStringType = QualType(); 1468 1469 ObjCSuperType = QualType(); 1470 1471 // void * type 1472 if (LangOpts.OpenCLGenericAddressSpace) { 1473 auto Q = VoidTy.getQualifiers(); 1474 Q.setAddressSpace(LangAS::opencl_generic); 1475 VoidPtrTy = getPointerType(getCanonicalType( 1476 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1477 } else { 1478 VoidPtrTy = getPointerType(VoidTy); 1479 } 1480 1481 // nullptr type (C++0x 2.14.7) 1482 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1483 1484 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1485 InitBuiltinType(HalfTy, BuiltinType::Half); 1486 1487 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1488 1489 // Builtin type used to help define __builtin_va_list. 1490 VaListTagDecl = nullptr; 1491 1492 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1493 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1494 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1495 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1496 } 1497 } 1498 1499 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1500 return SourceMgr.getDiagnostics(); 1501 } 1502 1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1504 AttrVec *&Result = DeclAttrs[D]; 1505 if (!Result) { 1506 void *Mem = Allocate(sizeof(AttrVec)); 1507 Result = new (Mem) AttrVec; 1508 } 1509 1510 return *Result; 1511 } 1512 1513 /// Erase the attributes corresponding to the given declaration. 1514 void ASTContext::eraseDeclAttrs(const Decl *D) { 1515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1516 if (Pos != DeclAttrs.end()) { 1517 Pos->second->~AttrVec(); 1518 DeclAttrs.erase(Pos); 1519 } 1520 } 1521 1522 // FIXME: Remove ? 1523 MemberSpecializationInfo * 1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1525 assert(Var->isStaticDataMember() && "Not a static data member"); 1526 return getTemplateOrSpecializationInfo(Var) 1527 .dyn_cast<MemberSpecializationInfo *>(); 1528 } 1529 1530 ASTContext::TemplateOrSpecializationInfo 1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1532 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1533 TemplateOrInstantiation.find(Var); 1534 if (Pos == TemplateOrInstantiation.end()) 1535 return {}; 1536 1537 return Pos->second; 1538 } 1539 1540 void 1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1542 TemplateSpecializationKind TSK, 1543 SourceLocation PointOfInstantiation) { 1544 assert(Inst->isStaticDataMember() && "Not a static data member"); 1545 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1546 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1547 Tmpl, TSK, PointOfInstantiation)); 1548 } 1549 1550 void 1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1552 TemplateOrSpecializationInfo TSI) { 1553 assert(!TemplateOrInstantiation[Inst] && 1554 "Already noted what the variable was instantiated from"); 1555 TemplateOrInstantiation[Inst] = TSI; 1556 } 1557 1558 NamedDecl * 1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1560 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1561 if (Pos == InstantiatedFromUsingDecl.end()) 1562 return nullptr; 1563 1564 return Pos->second; 1565 } 1566 1567 void 1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1569 assert((isa<UsingDecl>(Pattern) || 1570 isa<UnresolvedUsingValueDecl>(Pattern) || 1571 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1572 "pattern decl is not a using decl"); 1573 assert((isa<UsingDecl>(Inst) || 1574 isa<UnresolvedUsingValueDecl>(Inst) || 1575 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1576 "instantiation did not produce a using decl"); 1577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1578 InstantiatedFromUsingDecl[Inst] = Pattern; 1579 } 1580 1581 UsingEnumDecl * 1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1583 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1584 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1585 return nullptr; 1586 1587 return Pos->second; 1588 } 1589 1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1591 UsingEnumDecl *Pattern) { 1592 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1593 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1594 } 1595 1596 UsingShadowDecl * 1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1598 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1599 = InstantiatedFromUsingShadowDecl.find(Inst); 1600 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1601 return nullptr; 1602 1603 return Pos->second; 1604 } 1605 1606 void 1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1608 UsingShadowDecl *Pattern) { 1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1611 } 1612 1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1614 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1615 = InstantiatedFromUnnamedFieldDecl.find(Field); 1616 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1617 return nullptr; 1618 1619 return Pos->second; 1620 } 1621 1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1623 FieldDecl *Tmpl) { 1624 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1625 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1626 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1627 "Already noted what unnamed field was instantiated from"); 1628 1629 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1630 } 1631 1632 ASTContext::overridden_cxx_method_iterator 1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1634 return overridden_methods(Method).begin(); 1635 } 1636 1637 ASTContext::overridden_cxx_method_iterator 1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1639 return overridden_methods(Method).end(); 1640 } 1641 1642 unsigned 1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1644 auto Range = overridden_methods(Method); 1645 return Range.end() - Range.begin(); 1646 } 1647 1648 ASTContext::overridden_method_range 1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1650 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1651 OverriddenMethods.find(Method->getCanonicalDecl()); 1652 if (Pos == OverriddenMethods.end()) 1653 return overridden_method_range(nullptr, nullptr); 1654 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1655 } 1656 1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1658 const CXXMethodDecl *Overridden) { 1659 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1660 OverriddenMethods[Method].push_back(Overridden); 1661 } 1662 1663 void ASTContext::getOverriddenMethods( 1664 const NamedDecl *D, 1665 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1666 assert(D); 1667 1668 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1669 Overridden.append(overridden_methods_begin(CXXMethod), 1670 overridden_methods_end(CXXMethod)); 1671 return; 1672 } 1673 1674 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1675 if (!Method) 1676 return; 1677 1678 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1679 Method->getOverriddenMethods(OverDecls); 1680 Overridden.append(OverDecls.begin(), OverDecls.end()); 1681 } 1682 1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1684 assert(!Import->getNextLocalImport() && 1685 "Import declaration already in the chain"); 1686 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1687 if (!FirstLocalImport) { 1688 FirstLocalImport = Import; 1689 LastLocalImport = Import; 1690 return; 1691 } 1692 1693 LastLocalImport->setNextLocalImport(Import); 1694 LastLocalImport = Import; 1695 } 1696 1697 //===----------------------------------------------------------------------===// 1698 // Type Sizing and Analysis 1699 //===----------------------------------------------------------------------===// 1700 1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1702 /// scalar floating point type. 1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1704 switch (T->castAs<BuiltinType>()->getKind()) { 1705 default: 1706 llvm_unreachable("Not a floating point type!"); 1707 case BuiltinType::BFloat16: 1708 return Target->getBFloat16Format(); 1709 case BuiltinType::Float16: 1710 case BuiltinType::Half: 1711 return Target->getHalfFormat(); 1712 case BuiltinType::Float: return Target->getFloatFormat(); 1713 case BuiltinType::Double: return Target->getDoubleFormat(); 1714 case BuiltinType::Ibm128: 1715 return Target->getIbm128Format(); 1716 case BuiltinType::LongDouble: 1717 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1718 return AuxTarget->getLongDoubleFormat(); 1719 return Target->getLongDoubleFormat(); 1720 case BuiltinType::Float128: 1721 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1722 return AuxTarget->getFloat128Format(); 1723 return Target->getFloat128Format(); 1724 } 1725 } 1726 1727 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1728 unsigned Align = Target->getCharWidth(); 1729 1730 bool UseAlignAttrOnly = false; 1731 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1732 Align = AlignFromAttr; 1733 1734 // __attribute__((aligned)) can increase or decrease alignment 1735 // *except* on a struct or struct member, where it only increases 1736 // alignment unless 'packed' is also specified. 1737 // 1738 // It is an error for alignas to decrease alignment, so we can 1739 // ignore that possibility; Sema should diagnose it. 1740 if (isa<FieldDecl>(D)) { 1741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1743 } else { 1744 UseAlignAttrOnly = true; 1745 } 1746 } 1747 else if (isa<FieldDecl>(D)) 1748 UseAlignAttrOnly = 1749 D->hasAttr<PackedAttr>() || 1750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1751 1752 // If we're using the align attribute only, just ignore everything 1753 // else about the declaration and its type. 1754 if (UseAlignAttrOnly) { 1755 // do nothing 1756 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1757 QualType T = VD->getType(); 1758 if (const auto *RT = T->getAs<ReferenceType>()) { 1759 if (ForAlignof) 1760 T = RT->getPointeeType(); 1761 else 1762 T = getPointerType(RT->getPointeeType()); 1763 } 1764 QualType BaseT = getBaseElementType(T); 1765 if (T->isFunctionType()) 1766 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1767 else if (!BaseT->isIncompleteType()) { 1768 // Adjust alignments of declarations with array type by the 1769 // large-array alignment on the target. 1770 if (const ArrayType *arrayType = getAsArrayType(T)) { 1771 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1772 if (!ForAlignof && MinWidth) { 1773 if (isa<VariableArrayType>(arrayType)) 1774 Align = std::max(Align, Target->getLargeArrayAlign()); 1775 else if (isa<ConstantArrayType>(arrayType) && 1776 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1777 Align = std::max(Align, Target->getLargeArrayAlign()); 1778 } 1779 } 1780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1781 if (BaseT.getQualifiers().hasUnaligned()) 1782 Align = Target->getCharWidth(); 1783 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1784 if (VD->hasGlobalStorage() && !ForAlignof) { 1785 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1786 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1787 } 1788 } 1789 } 1790 1791 // Fields can be subject to extra alignment constraints, like if 1792 // the field is packed, the struct is packed, or the struct has a 1793 // a max-field-alignment constraint (#pragma pack). So calculate 1794 // the actual alignment of the field within the struct, and then 1795 // (as we're expected to) constrain that by the alignment of the type. 1796 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1797 const RecordDecl *Parent = Field->getParent(); 1798 // We can only produce a sensible answer if the record is valid. 1799 if (!Parent->isInvalidDecl()) { 1800 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1801 1802 // Start with the record's overall alignment. 1803 unsigned FieldAlign = toBits(Layout.getAlignment()); 1804 1805 // Use the GCD of that and the offset within the record. 1806 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1807 if (Offset > 0) { 1808 // Alignment is always a power of 2, so the GCD will be a power of 2, 1809 // which means we get to do this crazy thing instead of Euclid's. 1810 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1811 if (LowBitOfOffset < FieldAlign) 1812 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1813 } 1814 1815 Align = std::min(Align, FieldAlign); 1816 } 1817 } 1818 } 1819 1820 // Some targets have hard limitation on the maximum requestable alignment in 1821 // aligned attribute for static variables. 1822 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1823 const auto *VD = dyn_cast<VarDecl>(D); 1824 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1825 Align = std::min(Align, MaxAlignedAttr); 1826 1827 return toCharUnitsFromBits(Align); 1828 } 1829 1830 CharUnits ASTContext::getExnObjectAlignment() const { 1831 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1832 } 1833 1834 // getTypeInfoDataSizeInChars - Return the size of a type, in 1835 // chars. If the type is a record, its data size is returned. This is 1836 // the size of the memcpy that's performed when assigning this type 1837 // using a trivial copy/move assignment operator. 1838 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1839 TypeInfoChars Info = getTypeInfoInChars(T); 1840 1841 // In C++, objects can sometimes be allocated into the tail padding 1842 // of a base-class subobject. We decide whether that's possible 1843 // during class layout, so here we can just trust the layout results. 1844 if (getLangOpts().CPlusPlus) { 1845 if (const auto *RT = T->getAs<RecordType>()) { 1846 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1847 Info.Width = layout.getDataSize(); 1848 } 1849 } 1850 1851 return Info; 1852 } 1853 1854 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1855 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1856 TypeInfoChars 1857 static getConstantArrayInfoInChars(const ASTContext &Context, 1858 const ConstantArrayType *CAT) { 1859 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1860 uint64_t Size = CAT->getSize().getZExtValue(); 1861 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1862 (uint64_t)(-1)/Size) && 1863 "Overflow in array type char size evaluation"); 1864 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1865 unsigned Align = EltInfo.Align.getQuantity(); 1866 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1867 Context.getTargetInfo().getPointerWidth(0) == 64) 1868 Width = llvm::alignTo(Width, Align); 1869 return TypeInfoChars(CharUnits::fromQuantity(Width), 1870 CharUnits::fromQuantity(Align), 1871 EltInfo.AlignRequirement); 1872 } 1873 1874 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1875 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1876 return getConstantArrayInfoInChars(*this, CAT); 1877 TypeInfo Info = getTypeInfo(T); 1878 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1879 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1880 } 1881 1882 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1883 return getTypeInfoInChars(T.getTypePtr()); 1884 } 1885 1886 bool ASTContext::isAlignmentRequired(const Type *T) const { 1887 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1888 } 1889 1890 bool ASTContext::isAlignmentRequired(QualType T) const { 1891 return isAlignmentRequired(T.getTypePtr()); 1892 } 1893 1894 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1895 bool NeedsPreferredAlignment) const { 1896 // An alignment on a typedef overrides anything else. 1897 if (const auto *TT = T->getAs<TypedefType>()) 1898 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1899 return Align; 1900 1901 // If we have an (array of) complete type, we're done. 1902 T = getBaseElementType(T); 1903 if (!T->isIncompleteType()) 1904 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1905 1906 // If we had an array type, its element type might be a typedef 1907 // type with an alignment attribute. 1908 if (const auto *TT = T->getAs<TypedefType>()) 1909 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1910 return Align; 1911 1912 // Otherwise, see if the declaration of the type had an attribute. 1913 if (const auto *TT = T->getAs<TagType>()) 1914 return TT->getDecl()->getMaxAlignment(); 1915 1916 return 0; 1917 } 1918 1919 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1920 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1921 if (I != MemoizedTypeInfo.end()) 1922 return I->second; 1923 1924 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1925 TypeInfo TI = getTypeInfoImpl(T); 1926 MemoizedTypeInfo[T] = TI; 1927 return TI; 1928 } 1929 1930 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1931 /// method does not work on incomplete types. 1932 /// 1933 /// FIXME: Pointers into different addr spaces could have different sizes and 1934 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1935 /// should take a QualType, &c. 1936 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1937 uint64_t Width = 0; 1938 unsigned Align = 8; 1939 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1940 unsigned AS = 0; 1941 switch (T->getTypeClass()) { 1942 #define TYPE(Class, Base) 1943 #define ABSTRACT_TYPE(Class, Base) 1944 #define NON_CANONICAL_TYPE(Class, Base) 1945 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1947 case Type::Class: \ 1948 assert(!T->isDependentType() && "should not see dependent types here"); \ 1949 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1950 #include "clang/AST/TypeNodes.inc" 1951 llvm_unreachable("Should not see dependent types"); 1952 1953 case Type::FunctionNoProto: 1954 case Type::FunctionProto: 1955 // GCC extension: alignof(function) = 32 bits 1956 Width = 0; 1957 Align = 32; 1958 break; 1959 1960 case Type::IncompleteArray: 1961 case Type::VariableArray: 1962 case Type::ConstantArray: { 1963 // Model non-constant sized arrays as size zero, but track the alignment. 1964 uint64_t Size = 0; 1965 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1966 Size = CAT->getSize().getZExtValue(); 1967 1968 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1969 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1970 "Overflow in array type bit size evaluation"); 1971 Width = EltInfo.Width * Size; 1972 Align = EltInfo.Align; 1973 AlignRequirement = EltInfo.AlignRequirement; 1974 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1975 getTargetInfo().getPointerWidth(0) == 64) 1976 Width = llvm::alignTo(Width, Align); 1977 break; 1978 } 1979 1980 case Type::ExtVector: 1981 case Type::Vector: { 1982 const auto *VT = cast<VectorType>(T); 1983 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1984 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 1985 : EltInfo.Width * VT->getNumElements(); 1986 // Enforce at least byte alignment. 1987 Align = std::max<unsigned>(8, Width); 1988 1989 // If the alignment is not a power of 2, round up to the next power of 2. 1990 // This happens for non-power-of-2 length vectors. 1991 if (Align & (Align-1)) { 1992 Align = llvm::NextPowerOf2(Align); 1993 Width = llvm::alignTo(Width, Align); 1994 } 1995 // Adjust the alignment based on the target max. 1996 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1997 if (TargetVectorAlign && TargetVectorAlign < Align) 1998 Align = TargetVectorAlign; 1999 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 2000 // Adjust the alignment for fixed-length SVE vectors. This is important 2001 // for non-power-of-2 vector lengths. 2002 Align = 128; 2003 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2004 // Adjust the alignment for fixed-length SVE predicates. 2005 Align = 16; 2006 break; 2007 } 2008 2009 case Type::ConstantMatrix: { 2010 const auto *MT = cast<ConstantMatrixType>(T); 2011 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2012 // The internal layout of a matrix value is implementation defined. 2013 // Initially be ABI compatible with arrays with respect to alignment and 2014 // size. 2015 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2016 Align = ElementInfo.Align; 2017 break; 2018 } 2019 2020 case Type::Builtin: 2021 switch (cast<BuiltinType>(T)->getKind()) { 2022 default: llvm_unreachable("Unknown builtin type!"); 2023 case BuiltinType::Void: 2024 // GCC extension: alignof(void) = 8 bits. 2025 Width = 0; 2026 Align = 8; 2027 break; 2028 case BuiltinType::Bool: 2029 Width = Target->getBoolWidth(); 2030 Align = Target->getBoolAlign(); 2031 break; 2032 case BuiltinType::Char_S: 2033 case BuiltinType::Char_U: 2034 case BuiltinType::UChar: 2035 case BuiltinType::SChar: 2036 case BuiltinType::Char8: 2037 Width = Target->getCharWidth(); 2038 Align = Target->getCharAlign(); 2039 break; 2040 case BuiltinType::WChar_S: 2041 case BuiltinType::WChar_U: 2042 Width = Target->getWCharWidth(); 2043 Align = Target->getWCharAlign(); 2044 break; 2045 case BuiltinType::Char16: 2046 Width = Target->getChar16Width(); 2047 Align = Target->getChar16Align(); 2048 break; 2049 case BuiltinType::Char32: 2050 Width = Target->getChar32Width(); 2051 Align = Target->getChar32Align(); 2052 break; 2053 case BuiltinType::UShort: 2054 case BuiltinType::Short: 2055 Width = Target->getShortWidth(); 2056 Align = Target->getShortAlign(); 2057 break; 2058 case BuiltinType::UInt: 2059 case BuiltinType::Int: 2060 Width = Target->getIntWidth(); 2061 Align = Target->getIntAlign(); 2062 break; 2063 case BuiltinType::ULong: 2064 case BuiltinType::Long: 2065 Width = Target->getLongWidth(); 2066 Align = Target->getLongAlign(); 2067 break; 2068 case BuiltinType::ULongLong: 2069 case BuiltinType::LongLong: 2070 Width = Target->getLongLongWidth(); 2071 Align = Target->getLongLongAlign(); 2072 break; 2073 case BuiltinType::Int128: 2074 case BuiltinType::UInt128: 2075 Width = 128; 2076 Align = 128; // int128_t is 128-bit aligned on all targets. 2077 break; 2078 case BuiltinType::ShortAccum: 2079 case BuiltinType::UShortAccum: 2080 case BuiltinType::SatShortAccum: 2081 case BuiltinType::SatUShortAccum: 2082 Width = Target->getShortAccumWidth(); 2083 Align = Target->getShortAccumAlign(); 2084 break; 2085 case BuiltinType::Accum: 2086 case BuiltinType::UAccum: 2087 case BuiltinType::SatAccum: 2088 case BuiltinType::SatUAccum: 2089 Width = Target->getAccumWidth(); 2090 Align = Target->getAccumAlign(); 2091 break; 2092 case BuiltinType::LongAccum: 2093 case BuiltinType::ULongAccum: 2094 case BuiltinType::SatLongAccum: 2095 case BuiltinType::SatULongAccum: 2096 Width = Target->getLongAccumWidth(); 2097 Align = Target->getLongAccumAlign(); 2098 break; 2099 case BuiltinType::ShortFract: 2100 case BuiltinType::UShortFract: 2101 case BuiltinType::SatShortFract: 2102 case BuiltinType::SatUShortFract: 2103 Width = Target->getShortFractWidth(); 2104 Align = Target->getShortFractAlign(); 2105 break; 2106 case BuiltinType::Fract: 2107 case BuiltinType::UFract: 2108 case BuiltinType::SatFract: 2109 case BuiltinType::SatUFract: 2110 Width = Target->getFractWidth(); 2111 Align = Target->getFractAlign(); 2112 break; 2113 case BuiltinType::LongFract: 2114 case BuiltinType::ULongFract: 2115 case BuiltinType::SatLongFract: 2116 case BuiltinType::SatULongFract: 2117 Width = Target->getLongFractWidth(); 2118 Align = Target->getLongFractAlign(); 2119 break; 2120 case BuiltinType::BFloat16: 2121 Width = Target->getBFloat16Width(); 2122 Align = Target->getBFloat16Align(); 2123 break; 2124 case BuiltinType::Float16: 2125 case BuiltinType::Half: 2126 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2127 !getLangOpts().OpenMPIsDevice) { 2128 Width = Target->getHalfWidth(); 2129 Align = Target->getHalfAlign(); 2130 } else { 2131 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2132 "Expected OpenMP device compilation."); 2133 Width = AuxTarget->getHalfWidth(); 2134 Align = AuxTarget->getHalfAlign(); 2135 } 2136 break; 2137 case BuiltinType::Float: 2138 Width = Target->getFloatWidth(); 2139 Align = Target->getFloatAlign(); 2140 break; 2141 case BuiltinType::Double: 2142 Width = Target->getDoubleWidth(); 2143 Align = Target->getDoubleAlign(); 2144 break; 2145 case BuiltinType::Ibm128: 2146 Width = Target->getIbm128Width(); 2147 Align = Target->getIbm128Align(); 2148 break; 2149 case BuiltinType::LongDouble: 2150 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2151 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2152 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2153 Width = AuxTarget->getLongDoubleWidth(); 2154 Align = AuxTarget->getLongDoubleAlign(); 2155 } else { 2156 Width = Target->getLongDoubleWidth(); 2157 Align = Target->getLongDoubleAlign(); 2158 } 2159 break; 2160 case BuiltinType::Float128: 2161 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2162 !getLangOpts().OpenMPIsDevice) { 2163 Width = Target->getFloat128Width(); 2164 Align = Target->getFloat128Align(); 2165 } else { 2166 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2167 "Expected OpenMP device compilation."); 2168 Width = AuxTarget->getFloat128Width(); 2169 Align = AuxTarget->getFloat128Align(); 2170 } 2171 break; 2172 case BuiltinType::NullPtr: 2173 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2174 Align = Target->getPointerAlign(0); // == sizeof(void*) 2175 break; 2176 case BuiltinType::ObjCId: 2177 case BuiltinType::ObjCClass: 2178 case BuiltinType::ObjCSel: 2179 Width = Target->getPointerWidth(0); 2180 Align = Target->getPointerAlign(0); 2181 break; 2182 case BuiltinType::OCLSampler: 2183 case BuiltinType::OCLEvent: 2184 case BuiltinType::OCLClkEvent: 2185 case BuiltinType::OCLQueue: 2186 case BuiltinType::OCLReserveID: 2187 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2188 case BuiltinType::Id: 2189 #include "clang/Basic/OpenCLImageTypes.def" 2190 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2191 case BuiltinType::Id: 2192 #include "clang/Basic/OpenCLExtensionTypes.def" 2193 AS = getTargetAddressSpace( 2194 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2195 Width = Target->getPointerWidth(AS); 2196 Align = Target->getPointerAlign(AS); 2197 break; 2198 // The SVE types are effectively target-specific. The length of an 2199 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2200 // of 128 bits. There is one predicate bit for each vector byte, so the 2201 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2202 // 2203 // Because the length is only known at runtime, we use a dummy value 2204 // of 0 for the static length. The alignment values are those defined 2205 // by the Procedure Call Standard for the Arm Architecture. 2206 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2207 IsSigned, IsFP, IsBF) \ 2208 case BuiltinType::Id: \ 2209 Width = 0; \ 2210 Align = 128; \ 2211 break; 2212 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2213 case BuiltinType::Id: \ 2214 Width = 0; \ 2215 Align = 16; \ 2216 break; 2217 #include "clang/Basic/AArch64SVEACLETypes.def" 2218 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2219 case BuiltinType::Id: \ 2220 Width = Size; \ 2221 Align = Size; \ 2222 break; 2223 #include "clang/Basic/PPCTypes.def" 2224 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2225 IsFP) \ 2226 case BuiltinType::Id: \ 2227 Width = 0; \ 2228 Align = ElBits; \ 2229 break; 2230 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2231 case BuiltinType::Id: \ 2232 Width = 0; \ 2233 Align = 8; \ 2234 break; 2235 #include "clang/Basic/RISCVVTypes.def" 2236 } 2237 break; 2238 case Type::ObjCObjectPointer: 2239 Width = Target->getPointerWidth(0); 2240 Align = Target->getPointerAlign(0); 2241 break; 2242 case Type::BlockPointer: 2243 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2244 Width = Target->getPointerWidth(AS); 2245 Align = Target->getPointerAlign(AS); 2246 break; 2247 case Type::LValueReference: 2248 case Type::RValueReference: 2249 // alignof and sizeof should never enter this code path here, so we go 2250 // the pointer route. 2251 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2252 Width = Target->getPointerWidth(AS); 2253 Align = Target->getPointerAlign(AS); 2254 break; 2255 case Type::Pointer: 2256 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2257 Width = Target->getPointerWidth(AS); 2258 Align = Target->getPointerAlign(AS); 2259 break; 2260 case Type::MemberPointer: { 2261 const auto *MPT = cast<MemberPointerType>(T); 2262 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2263 Width = MPI.Width; 2264 Align = MPI.Align; 2265 break; 2266 } 2267 case Type::Complex: { 2268 // Complex types have the same alignment as their elements, but twice the 2269 // size. 2270 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2271 Width = EltInfo.Width * 2; 2272 Align = EltInfo.Align; 2273 break; 2274 } 2275 case Type::ObjCObject: 2276 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2277 case Type::Adjusted: 2278 case Type::Decayed: 2279 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2280 case Type::ObjCInterface: { 2281 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2282 if (ObjCI->getDecl()->isInvalidDecl()) { 2283 Width = 8; 2284 Align = 8; 2285 break; 2286 } 2287 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2288 Width = toBits(Layout.getSize()); 2289 Align = toBits(Layout.getAlignment()); 2290 break; 2291 } 2292 case Type::BitInt: { 2293 const auto *EIT = cast<BitIntType>(T); 2294 Align = 2295 std::min(static_cast<unsigned>(std::max( 2296 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2297 Target->getLongLongAlign()); 2298 Width = llvm::alignTo(EIT->getNumBits(), Align); 2299 break; 2300 } 2301 case Type::Record: 2302 case Type::Enum: { 2303 const auto *TT = cast<TagType>(T); 2304 2305 if (TT->getDecl()->isInvalidDecl()) { 2306 Width = 8; 2307 Align = 8; 2308 break; 2309 } 2310 2311 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2312 const EnumDecl *ED = ET->getDecl(); 2313 TypeInfo Info = 2314 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2315 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2316 Info.Align = AttrAlign; 2317 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2318 } 2319 return Info; 2320 } 2321 2322 const auto *RT = cast<RecordType>(TT); 2323 const RecordDecl *RD = RT->getDecl(); 2324 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2325 Width = toBits(Layout.getSize()); 2326 Align = toBits(Layout.getAlignment()); 2327 AlignRequirement = RD->hasAttr<AlignedAttr>() 2328 ? AlignRequirementKind::RequiredByRecord 2329 : AlignRequirementKind::None; 2330 break; 2331 } 2332 2333 case Type::SubstTemplateTypeParm: 2334 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2335 getReplacementType().getTypePtr()); 2336 2337 case Type::Auto: 2338 case Type::DeducedTemplateSpecialization: { 2339 const auto *A = cast<DeducedType>(T); 2340 assert(!A->getDeducedType().isNull() && 2341 "cannot request the size of an undeduced or dependent auto type"); 2342 return getTypeInfo(A->getDeducedType().getTypePtr()); 2343 } 2344 2345 case Type::Paren: 2346 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2347 2348 case Type::MacroQualified: 2349 return getTypeInfo( 2350 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2351 2352 case Type::ObjCTypeParam: 2353 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2354 2355 case Type::Using: 2356 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2357 2358 case Type::Typedef: { 2359 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2360 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2361 // If the typedef has an aligned attribute on it, it overrides any computed 2362 // alignment we have. This violates the GCC documentation (which says that 2363 // attribute(aligned) can only round up) but matches its implementation. 2364 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2365 Align = AttrAlign; 2366 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2367 } else { 2368 Align = Info.Align; 2369 AlignRequirement = Info.AlignRequirement; 2370 } 2371 Width = Info.Width; 2372 break; 2373 } 2374 2375 case Type::Elaborated: 2376 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2377 2378 case Type::Attributed: 2379 return getTypeInfo( 2380 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2381 2382 case Type::BTFTagAttributed: 2383 return getTypeInfo( 2384 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr()); 2385 2386 case Type::Atomic: { 2387 // Start with the base type information. 2388 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2389 Width = Info.Width; 2390 Align = Info.Align; 2391 2392 if (!Width) { 2393 // An otherwise zero-sized type should still generate an 2394 // atomic operation. 2395 Width = Target->getCharWidth(); 2396 assert(Align); 2397 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2398 // If the size of the type doesn't exceed the platform's max 2399 // atomic promotion width, make the size and alignment more 2400 // favorable to atomic operations: 2401 2402 // Round the size up to a power of 2. 2403 if (!llvm::isPowerOf2_64(Width)) 2404 Width = llvm::NextPowerOf2(Width); 2405 2406 // Set the alignment equal to the size. 2407 Align = static_cast<unsigned>(Width); 2408 } 2409 } 2410 break; 2411 2412 case Type::Pipe: 2413 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2414 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2415 break; 2416 } 2417 2418 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2419 return TypeInfo(Width, Align, AlignRequirement); 2420 } 2421 2422 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2423 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2424 if (I != MemoizedUnadjustedAlign.end()) 2425 return I->second; 2426 2427 unsigned UnadjustedAlign; 2428 if (const auto *RT = T->getAs<RecordType>()) { 2429 const RecordDecl *RD = RT->getDecl(); 2430 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2431 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2432 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2433 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2434 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2435 } else { 2436 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2437 } 2438 2439 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2440 return UnadjustedAlign; 2441 } 2442 2443 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2444 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2445 return SimdAlign; 2446 } 2447 2448 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2449 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2450 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2451 } 2452 2453 /// toBits - Convert a size in characters to a size in characters. 2454 int64_t ASTContext::toBits(CharUnits CharSize) const { 2455 return CharSize.getQuantity() * getCharWidth(); 2456 } 2457 2458 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2459 /// This method does not work on incomplete types. 2460 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2461 return getTypeInfoInChars(T).Width; 2462 } 2463 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2464 return getTypeInfoInChars(T).Width; 2465 } 2466 2467 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2468 /// characters. This method does not work on incomplete types. 2469 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2470 return toCharUnitsFromBits(getTypeAlign(T)); 2471 } 2472 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2473 return toCharUnitsFromBits(getTypeAlign(T)); 2474 } 2475 2476 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2477 /// type, in characters, before alignment adustments. This method does 2478 /// not work on incomplete types. 2479 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2480 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2481 } 2482 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2483 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2484 } 2485 2486 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2487 /// type for the current target in bits. This can be different than the ABI 2488 /// alignment in cases where it is beneficial for performance or backwards 2489 /// compatibility preserving to overalign a data type. (Note: despite the name, 2490 /// the preferred alignment is ABI-impacting, and not an optimization.) 2491 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2492 TypeInfo TI = getTypeInfo(T); 2493 unsigned ABIAlign = TI.Align; 2494 2495 T = T->getBaseElementTypeUnsafe(); 2496 2497 // The preferred alignment of member pointers is that of a pointer. 2498 if (T->isMemberPointerType()) 2499 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2500 2501 if (!Target->allowsLargerPreferedTypeAlignment()) 2502 return ABIAlign; 2503 2504 if (const auto *RT = T->getAs<RecordType>()) { 2505 const RecordDecl *RD = RT->getDecl(); 2506 2507 // When used as part of a typedef, or together with a 'packed' attribute, 2508 // the 'aligned' attribute can be used to decrease alignment. Note that the 2509 // 'packed' case is already taken into consideration when computing the 2510 // alignment, we only need to handle the typedef case here. 2511 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2512 RD->isInvalidDecl()) 2513 return ABIAlign; 2514 2515 unsigned PreferredAlign = static_cast<unsigned>( 2516 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2517 assert(PreferredAlign >= ABIAlign && 2518 "PreferredAlign should be at least as large as ABIAlign."); 2519 return PreferredAlign; 2520 } 2521 2522 // Double (and, for targets supporting AIX `power` alignment, long double) and 2523 // long long should be naturally aligned (despite requiring less alignment) if 2524 // possible. 2525 if (const auto *CT = T->getAs<ComplexType>()) 2526 T = CT->getElementType().getTypePtr(); 2527 if (const auto *ET = T->getAs<EnumType>()) 2528 T = ET->getDecl()->getIntegerType().getTypePtr(); 2529 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2530 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2531 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2532 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2533 Target->defaultsToAIXPowerAlignment())) 2534 // Don't increase the alignment if an alignment attribute was specified on a 2535 // typedef declaration. 2536 if (!TI.isAlignRequired()) 2537 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2538 2539 return ABIAlign; 2540 } 2541 2542 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2543 /// for __attribute__((aligned)) on this target, to be used if no alignment 2544 /// value is specified. 2545 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2546 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2547 } 2548 2549 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2550 /// to a global variable of the specified type. 2551 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2552 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2553 return std::max(getPreferredTypeAlign(T), 2554 getTargetInfo().getMinGlobalAlign(TypeSize)); 2555 } 2556 2557 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2558 /// should be given to a global variable of the specified type. 2559 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2560 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2561 } 2562 2563 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2564 CharUnits Offset = CharUnits::Zero(); 2565 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2566 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2567 Offset += Layout->getBaseClassOffset(Base); 2568 Layout = &getASTRecordLayout(Base); 2569 } 2570 return Offset; 2571 } 2572 2573 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2574 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2575 CharUnits ThisAdjustment = CharUnits::Zero(); 2576 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2577 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2578 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2579 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2580 const CXXRecordDecl *Base = RD; 2581 const CXXRecordDecl *Derived = Path[I]; 2582 if (DerivedMember) 2583 std::swap(Base, Derived); 2584 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2585 RD = Path[I]; 2586 } 2587 if (DerivedMember) 2588 ThisAdjustment = -ThisAdjustment; 2589 return ThisAdjustment; 2590 } 2591 2592 /// DeepCollectObjCIvars - 2593 /// This routine first collects all declared, but not synthesized, ivars in 2594 /// super class and then collects all ivars, including those synthesized for 2595 /// current class. This routine is used for implementation of current class 2596 /// when all ivars, declared and synthesized are known. 2597 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2598 bool leafClass, 2599 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2600 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2601 DeepCollectObjCIvars(SuperClass, false, Ivars); 2602 if (!leafClass) { 2603 llvm::append_range(Ivars, OI->ivars()); 2604 } else { 2605 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2606 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2607 Iv= Iv->getNextIvar()) 2608 Ivars.push_back(Iv); 2609 } 2610 } 2611 2612 /// CollectInheritedProtocols - Collect all protocols in current class and 2613 /// those inherited by it. 2614 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2615 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2616 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2617 // We can use protocol_iterator here instead of 2618 // all_referenced_protocol_iterator since we are walking all categories. 2619 for (auto *Proto : OI->all_referenced_protocols()) { 2620 CollectInheritedProtocols(Proto, Protocols); 2621 } 2622 2623 // Categories of this Interface. 2624 for (const auto *Cat : OI->visible_categories()) 2625 CollectInheritedProtocols(Cat, Protocols); 2626 2627 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2628 while (SD) { 2629 CollectInheritedProtocols(SD, Protocols); 2630 SD = SD->getSuperClass(); 2631 } 2632 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2633 for (auto *Proto : OC->protocols()) { 2634 CollectInheritedProtocols(Proto, Protocols); 2635 } 2636 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2637 // Insert the protocol. 2638 if (!Protocols.insert( 2639 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2640 return; 2641 2642 for (auto *Proto : OP->protocols()) 2643 CollectInheritedProtocols(Proto, Protocols); 2644 } 2645 } 2646 2647 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2648 const RecordDecl *RD) { 2649 assert(RD->isUnion() && "Must be union type"); 2650 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2651 2652 for (const auto *Field : RD->fields()) { 2653 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2654 return false; 2655 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2656 if (FieldSize != UnionSize) 2657 return false; 2658 } 2659 return !RD->field_empty(); 2660 } 2661 2662 static int64_t getSubobjectOffset(const FieldDecl *Field, 2663 const ASTContext &Context, 2664 const clang::ASTRecordLayout & /*Layout*/) { 2665 return Context.getFieldOffset(Field); 2666 } 2667 2668 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2669 const ASTContext &Context, 2670 const clang::ASTRecordLayout &Layout) { 2671 return Context.toBits(Layout.getBaseClassOffset(RD)); 2672 } 2673 2674 static llvm::Optional<int64_t> 2675 structHasUniqueObjectRepresentations(const ASTContext &Context, 2676 const RecordDecl *RD); 2677 2678 static llvm::Optional<int64_t> 2679 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2680 if (Field->getType()->isRecordType()) { 2681 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2682 if (!RD->isUnion()) 2683 return structHasUniqueObjectRepresentations(Context, RD); 2684 } 2685 if (!Field->getType()->isReferenceType() && 2686 !Context.hasUniqueObjectRepresentations(Field->getType())) 2687 return llvm::None; 2688 2689 int64_t FieldSizeInBits = 2690 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2691 if (Field->isBitField()) { 2692 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2693 if (BitfieldSize > FieldSizeInBits) 2694 return llvm::None; 2695 FieldSizeInBits = BitfieldSize; 2696 } 2697 return FieldSizeInBits; 2698 } 2699 2700 static llvm::Optional<int64_t> 2701 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2702 return structHasUniqueObjectRepresentations(Context, RD); 2703 } 2704 2705 template <typename RangeT> 2706 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2707 const RangeT &Subobjects, int64_t CurOffsetInBits, 2708 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2709 for (const auto *Subobject : Subobjects) { 2710 llvm::Optional<int64_t> SizeInBits = 2711 getSubobjectSizeInBits(Subobject, Context); 2712 if (!SizeInBits) 2713 return llvm::None; 2714 if (*SizeInBits != 0) { 2715 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2716 if (Offset != CurOffsetInBits) 2717 return llvm::None; 2718 CurOffsetInBits += *SizeInBits; 2719 } 2720 } 2721 return CurOffsetInBits; 2722 } 2723 2724 static llvm::Optional<int64_t> 2725 structHasUniqueObjectRepresentations(const ASTContext &Context, 2726 const RecordDecl *RD) { 2727 assert(!RD->isUnion() && "Must be struct/class type"); 2728 const auto &Layout = Context.getASTRecordLayout(RD); 2729 2730 int64_t CurOffsetInBits = 0; 2731 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2732 if (ClassDecl->isDynamicClass()) 2733 return llvm::None; 2734 2735 SmallVector<CXXRecordDecl *, 4> Bases; 2736 for (const auto &Base : ClassDecl->bases()) { 2737 // Empty types can be inherited from, and non-empty types can potentially 2738 // have tail padding, so just make sure there isn't an error. 2739 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2740 } 2741 2742 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2743 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2744 }); 2745 2746 llvm::Optional<int64_t> OffsetAfterBases = 2747 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2748 Context, Layout); 2749 if (!OffsetAfterBases) 2750 return llvm::None; 2751 CurOffsetInBits = *OffsetAfterBases; 2752 } 2753 2754 llvm::Optional<int64_t> OffsetAfterFields = 2755 structSubobjectsHaveUniqueObjectRepresentations( 2756 RD->fields(), CurOffsetInBits, Context, Layout); 2757 if (!OffsetAfterFields) 2758 return llvm::None; 2759 CurOffsetInBits = *OffsetAfterFields; 2760 2761 return CurOffsetInBits; 2762 } 2763 2764 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2765 // C++17 [meta.unary.prop]: 2766 // The predicate condition for a template specialization 2767 // has_unique_object_representations<T> shall be 2768 // satisfied if and only if: 2769 // (9.1) - T is trivially copyable, and 2770 // (9.2) - any two objects of type T with the same value have the same 2771 // object representation, where two objects 2772 // of array or non-union class type are considered to have the same value 2773 // if their respective sequences of 2774 // direct subobjects have the same values, and two objects of union type 2775 // are considered to have the same 2776 // value if they have the same active member and the corresponding members 2777 // have the same value. 2778 // The set of scalar types for which this condition holds is 2779 // implementation-defined. [ Note: If a type has padding 2780 // bits, the condition does not hold; otherwise, the condition holds true 2781 // for unsigned integral types. -- end note ] 2782 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2783 2784 // Arrays are unique only if their element type is unique. 2785 if (Ty->isArrayType()) 2786 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2787 2788 // (9.1) - T is trivially copyable... 2789 if (!Ty.isTriviallyCopyableType(*this)) 2790 return false; 2791 2792 // All integrals and enums are unique. 2793 if (Ty->isIntegralOrEnumerationType()) 2794 return true; 2795 2796 // All other pointers are unique. 2797 if (Ty->isPointerType()) 2798 return true; 2799 2800 if (Ty->isMemberPointerType()) { 2801 const auto *MPT = Ty->getAs<MemberPointerType>(); 2802 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2803 } 2804 2805 if (Ty->isRecordType()) { 2806 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2807 2808 if (Record->isInvalidDecl()) 2809 return false; 2810 2811 if (Record->isUnion()) 2812 return unionHasUniqueObjectRepresentations(*this, Record); 2813 2814 Optional<int64_t> StructSize = 2815 structHasUniqueObjectRepresentations(*this, Record); 2816 2817 return StructSize && 2818 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2819 } 2820 2821 // FIXME: More cases to handle here (list by rsmith): 2822 // vectors (careful about, eg, vector of 3 foo) 2823 // _Complex int and friends 2824 // _Atomic T 2825 // Obj-C block pointers 2826 // Obj-C object pointers 2827 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2828 // clk_event_t, queue_t, reserve_id_t) 2829 // There're also Obj-C class types and the Obj-C selector type, but I think it 2830 // makes sense for those to return false here. 2831 2832 return false; 2833 } 2834 2835 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2836 unsigned count = 0; 2837 // Count ivars declared in class extension. 2838 for (const auto *Ext : OI->known_extensions()) 2839 count += Ext->ivar_size(); 2840 2841 // Count ivar defined in this class's implementation. This 2842 // includes synthesized ivars. 2843 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2844 count += ImplDecl->ivar_size(); 2845 2846 return count; 2847 } 2848 2849 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2850 if (!E) 2851 return false; 2852 2853 // nullptr_t is always treated as null. 2854 if (E->getType()->isNullPtrType()) return true; 2855 2856 if (E->getType()->isAnyPointerType() && 2857 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2858 Expr::NPC_ValueDependentIsNull)) 2859 return true; 2860 2861 // Unfortunately, __null has type 'int'. 2862 if (isa<GNUNullExpr>(E)) return true; 2863 2864 return false; 2865 } 2866 2867 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2868 /// exists. 2869 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2870 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2871 I = ObjCImpls.find(D); 2872 if (I != ObjCImpls.end()) 2873 return cast<ObjCImplementationDecl>(I->second); 2874 return nullptr; 2875 } 2876 2877 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2878 /// exists. 2879 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2880 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2881 I = ObjCImpls.find(D); 2882 if (I != ObjCImpls.end()) 2883 return cast<ObjCCategoryImplDecl>(I->second); 2884 return nullptr; 2885 } 2886 2887 /// Set the implementation of ObjCInterfaceDecl. 2888 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2889 ObjCImplementationDecl *ImplD) { 2890 assert(IFaceD && ImplD && "Passed null params"); 2891 ObjCImpls[IFaceD] = ImplD; 2892 } 2893 2894 /// Set the implementation of ObjCCategoryDecl. 2895 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2896 ObjCCategoryImplDecl *ImplD) { 2897 assert(CatD && ImplD && "Passed null params"); 2898 ObjCImpls[CatD] = ImplD; 2899 } 2900 2901 const ObjCMethodDecl * 2902 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2903 return ObjCMethodRedecls.lookup(MD); 2904 } 2905 2906 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2907 const ObjCMethodDecl *Redecl) { 2908 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2909 ObjCMethodRedecls[MD] = Redecl; 2910 } 2911 2912 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2913 const NamedDecl *ND) const { 2914 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2915 return ID; 2916 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2917 return CD->getClassInterface(); 2918 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2919 return IMD->getClassInterface(); 2920 2921 return nullptr; 2922 } 2923 2924 /// Get the copy initialization expression of VarDecl, or nullptr if 2925 /// none exists. 2926 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2927 assert(VD && "Passed null params"); 2928 assert(VD->hasAttr<BlocksAttr>() && 2929 "getBlockVarCopyInits - not __block var"); 2930 auto I = BlockVarCopyInits.find(VD); 2931 if (I != BlockVarCopyInits.end()) 2932 return I->second; 2933 return {nullptr, false}; 2934 } 2935 2936 /// Set the copy initialization expression of a block var decl. 2937 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2938 bool CanThrow) { 2939 assert(VD && CopyExpr && "Passed null params"); 2940 assert(VD->hasAttr<BlocksAttr>() && 2941 "setBlockVarCopyInits - not __block var"); 2942 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2943 } 2944 2945 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2946 unsigned DataSize) const { 2947 if (!DataSize) 2948 DataSize = TypeLoc::getFullDataSizeForType(T); 2949 else 2950 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2951 "incorrect data size provided to CreateTypeSourceInfo!"); 2952 2953 auto *TInfo = 2954 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2955 new (TInfo) TypeSourceInfo(T); 2956 return TInfo; 2957 } 2958 2959 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2960 SourceLocation L) const { 2961 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2962 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2963 return DI; 2964 } 2965 2966 const ASTRecordLayout & 2967 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2968 return getObjCLayout(D, nullptr); 2969 } 2970 2971 const ASTRecordLayout & 2972 ASTContext::getASTObjCImplementationLayout( 2973 const ObjCImplementationDecl *D) const { 2974 return getObjCLayout(D->getClassInterface(), D); 2975 } 2976 2977 //===----------------------------------------------------------------------===// 2978 // Type creation/memoization methods 2979 //===----------------------------------------------------------------------===// 2980 2981 QualType 2982 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2983 unsigned fastQuals = quals.getFastQualifiers(); 2984 quals.removeFastQualifiers(); 2985 2986 // Check if we've already instantiated this type. 2987 llvm::FoldingSetNodeID ID; 2988 ExtQuals::Profile(ID, baseType, quals); 2989 void *insertPos = nullptr; 2990 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2991 assert(eq->getQualifiers() == quals); 2992 return QualType(eq, fastQuals); 2993 } 2994 2995 // If the base type is not canonical, make the appropriate canonical type. 2996 QualType canon; 2997 if (!baseType->isCanonicalUnqualified()) { 2998 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2999 canonSplit.Quals.addConsistentQualifiers(quals); 3000 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 3001 3002 // Re-find the insert position. 3003 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3004 } 3005 3006 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3007 ExtQualNodes.InsertNode(eq, insertPos); 3008 return QualType(eq, fastQuals); 3009 } 3010 3011 QualType ASTContext::getAddrSpaceQualType(QualType T, 3012 LangAS AddressSpace) const { 3013 QualType CanT = getCanonicalType(T); 3014 if (CanT.getAddressSpace() == AddressSpace) 3015 return T; 3016 3017 // If we are composing extended qualifiers together, merge together 3018 // into one ExtQuals node. 3019 QualifierCollector Quals; 3020 const Type *TypeNode = Quals.strip(T); 3021 3022 // If this type already has an address space specified, it cannot get 3023 // another one. 3024 assert(!Quals.hasAddressSpace() && 3025 "Type cannot be in multiple addr spaces!"); 3026 Quals.addAddressSpace(AddressSpace); 3027 3028 return getExtQualType(TypeNode, Quals); 3029 } 3030 3031 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3032 // If the type is not qualified with an address space, just return it 3033 // immediately. 3034 if (!T.hasAddressSpace()) 3035 return T; 3036 3037 // If we are composing extended qualifiers together, merge together 3038 // into one ExtQuals node. 3039 QualifierCollector Quals; 3040 const Type *TypeNode; 3041 3042 while (T.hasAddressSpace()) { 3043 TypeNode = Quals.strip(T); 3044 3045 // If the type no longer has an address space after stripping qualifiers, 3046 // jump out. 3047 if (!QualType(TypeNode, 0).hasAddressSpace()) 3048 break; 3049 3050 // There might be sugar in the way. Strip it and try again. 3051 T = T.getSingleStepDesugaredType(*this); 3052 } 3053 3054 Quals.removeAddressSpace(); 3055 3056 // Removal of the address space can mean there are no longer any 3057 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3058 // or required. 3059 if (Quals.hasNonFastQualifiers()) 3060 return getExtQualType(TypeNode, Quals); 3061 else 3062 return QualType(TypeNode, Quals.getFastQualifiers()); 3063 } 3064 3065 QualType ASTContext::getObjCGCQualType(QualType T, 3066 Qualifiers::GC GCAttr) const { 3067 QualType CanT = getCanonicalType(T); 3068 if (CanT.getObjCGCAttr() == GCAttr) 3069 return T; 3070 3071 if (const auto *ptr = T->getAs<PointerType>()) { 3072 QualType Pointee = ptr->getPointeeType(); 3073 if (Pointee->isAnyPointerType()) { 3074 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3075 return getPointerType(ResultType); 3076 } 3077 } 3078 3079 // If we are composing extended qualifiers together, merge together 3080 // into one ExtQuals node. 3081 QualifierCollector Quals; 3082 const Type *TypeNode = Quals.strip(T); 3083 3084 // If this type already has an ObjCGC specified, it cannot get 3085 // another one. 3086 assert(!Quals.hasObjCGCAttr() && 3087 "Type cannot have multiple ObjCGCs!"); 3088 Quals.addObjCGCAttr(GCAttr); 3089 3090 return getExtQualType(TypeNode, Quals); 3091 } 3092 3093 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3094 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3095 QualType Pointee = Ptr->getPointeeType(); 3096 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3097 return getPointerType(removeAddrSpaceQualType(Pointee)); 3098 } 3099 } 3100 return T; 3101 } 3102 3103 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3104 FunctionType::ExtInfo Info) { 3105 if (T->getExtInfo() == Info) 3106 return T; 3107 3108 QualType Result; 3109 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3110 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3111 } else { 3112 const auto *FPT = cast<FunctionProtoType>(T); 3113 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3114 EPI.ExtInfo = Info; 3115 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3116 } 3117 3118 return cast<FunctionType>(Result.getTypePtr()); 3119 } 3120 3121 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3122 QualType ResultType) { 3123 FD = FD->getMostRecentDecl(); 3124 while (true) { 3125 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3127 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3128 if (FunctionDecl *Next = FD->getPreviousDecl()) 3129 FD = Next; 3130 else 3131 break; 3132 } 3133 if (ASTMutationListener *L = getASTMutationListener()) 3134 L->DeducedReturnType(FD, ResultType); 3135 } 3136 3137 /// Get a function type and produce the equivalent function type with the 3138 /// specified exception specification. Type sugar that can be present on a 3139 /// declaration of a function with an exception specification is permitted 3140 /// and preserved. Other type sugar (for instance, typedefs) is not. 3141 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3142 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3143 // Might have some parens. 3144 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3145 return getParenType( 3146 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3147 3148 // Might be wrapped in a macro qualified type. 3149 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3150 return getMacroQualifiedType( 3151 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3152 MQT->getMacroIdentifier()); 3153 3154 // Might have a calling-convention attribute. 3155 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3156 return getAttributedType( 3157 AT->getAttrKind(), 3158 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3159 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3160 3161 // Anything else must be a function type. Rebuild it with the new exception 3162 // specification. 3163 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3164 return getFunctionType( 3165 Proto->getReturnType(), Proto->getParamTypes(), 3166 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3167 } 3168 3169 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3170 QualType U) { 3171 return hasSameType(T, U) || 3172 (getLangOpts().CPlusPlus17 && 3173 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3174 getFunctionTypeWithExceptionSpec(U, EST_None))); 3175 } 3176 3177 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3178 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3179 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3180 SmallVector<QualType, 16> Args(Proto->param_types()); 3181 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3182 Args[i] = removePtrSizeAddrSpace(Args[i]); 3183 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3184 } 3185 3186 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3187 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3188 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3189 } 3190 3191 return T; 3192 } 3193 3194 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3195 return hasSameType(T, U) || 3196 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3197 getFunctionTypeWithoutPtrSizes(U)); 3198 } 3199 3200 void ASTContext::adjustExceptionSpec( 3201 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3202 bool AsWritten) { 3203 // Update the type. 3204 QualType Updated = 3205 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3206 FD->setType(Updated); 3207 3208 if (!AsWritten) 3209 return; 3210 3211 // Update the type in the type source information too. 3212 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3213 // If the type and the type-as-written differ, we may need to update 3214 // the type-as-written too. 3215 if (TSInfo->getType() != FD->getType()) 3216 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3217 3218 // FIXME: When we get proper type location information for exceptions, 3219 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3220 // up the TypeSourceInfo; 3221 assert(TypeLoc::getFullDataSizeForType(Updated) == 3222 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3223 "TypeLoc size mismatch from updating exception specification"); 3224 TSInfo->overrideType(Updated); 3225 } 3226 } 3227 3228 /// getComplexType - Return the uniqued reference to the type for a complex 3229 /// number with the specified element type. 3230 QualType ASTContext::getComplexType(QualType T) const { 3231 // Unique pointers, to guarantee there is only one pointer of a particular 3232 // structure. 3233 llvm::FoldingSetNodeID ID; 3234 ComplexType::Profile(ID, T); 3235 3236 void *InsertPos = nullptr; 3237 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3238 return QualType(CT, 0); 3239 3240 // If the pointee type isn't canonical, this won't be a canonical type either, 3241 // so fill in the canonical type field. 3242 QualType Canonical; 3243 if (!T.isCanonical()) { 3244 Canonical = getComplexType(getCanonicalType(T)); 3245 3246 // Get the new insert position for the node we care about. 3247 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3248 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3249 } 3250 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3251 Types.push_back(New); 3252 ComplexTypes.InsertNode(New, InsertPos); 3253 return QualType(New, 0); 3254 } 3255 3256 /// getPointerType - Return the uniqued reference to the type for a pointer to 3257 /// the specified type. 3258 QualType ASTContext::getPointerType(QualType T) const { 3259 // Unique pointers, to guarantee there is only one pointer of a particular 3260 // structure. 3261 llvm::FoldingSetNodeID ID; 3262 PointerType::Profile(ID, T); 3263 3264 void *InsertPos = nullptr; 3265 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3266 return QualType(PT, 0); 3267 3268 // If the pointee type isn't canonical, this won't be a canonical type either, 3269 // so fill in the canonical type field. 3270 QualType Canonical; 3271 if (!T.isCanonical()) { 3272 Canonical = getPointerType(getCanonicalType(T)); 3273 3274 // Get the new insert position for the node we care about. 3275 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3276 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3277 } 3278 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3279 Types.push_back(New); 3280 PointerTypes.InsertNode(New, InsertPos); 3281 return QualType(New, 0); 3282 } 3283 3284 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3285 llvm::FoldingSetNodeID ID; 3286 AdjustedType::Profile(ID, Orig, New); 3287 void *InsertPos = nullptr; 3288 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3289 if (AT) 3290 return QualType(AT, 0); 3291 3292 QualType Canonical = getCanonicalType(New); 3293 3294 // Get the new insert position for the node we care about. 3295 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3296 assert(!AT && "Shouldn't be in the map!"); 3297 3298 AT = new (*this, TypeAlignment) 3299 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3300 Types.push_back(AT); 3301 AdjustedTypes.InsertNode(AT, InsertPos); 3302 return QualType(AT, 0); 3303 } 3304 3305 QualType ASTContext::getDecayedType(QualType T) const { 3306 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3307 3308 QualType Decayed; 3309 3310 // C99 6.7.5.3p7: 3311 // A declaration of a parameter as "array of type" shall be 3312 // adjusted to "qualified pointer to type", where the type 3313 // qualifiers (if any) are those specified within the [ and ] of 3314 // the array type derivation. 3315 if (T->isArrayType()) 3316 Decayed = getArrayDecayedType(T); 3317 3318 // C99 6.7.5.3p8: 3319 // A declaration of a parameter as "function returning type" 3320 // shall be adjusted to "pointer to function returning type", as 3321 // in 6.3.2.1. 3322 if (T->isFunctionType()) 3323 Decayed = getPointerType(T); 3324 3325 llvm::FoldingSetNodeID ID; 3326 AdjustedType::Profile(ID, T, Decayed); 3327 void *InsertPos = nullptr; 3328 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3329 if (AT) 3330 return QualType(AT, 0); 3331 3332 QualType Canonical = getCanonicalType(Decayed); 3333 3334 // Get the new insert position for the node we care about. 3335 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3336 assert(!AT && "Shouldn't be in the map!"); 3337 3338 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3339 Types.push_back(AT); 3340 AdjustedTypes.InsertNode(AT, InsertPos); 3341 return QualType(AT, 0); 3342 } 3343 3344 /// getBlockPointerType - Return the uniqued reference to the type for 3345 /// a pointer to the specified block. 3346 QualType ASTContext::getBlockPointerType(QualType T) const { 3347 assert(T->isFunctionType() && "block of function types only"); 3348 // Unique pointers, to guarantee there is only one block of a particular 3349 // structure. 3350 llvm::FoldingSetNodeID ID; 3351 BlockPointerType::Profile(ID, T); 3352 3353 void *InsertPos = nullptr; 3354 if (BlockPointerType *PT = 3355 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3356 return QualType(PT, 0); 3357 3358 // If the block pointee type isn't canonical, this won't be a canonical 3359 // type either so fill in the canonical type field. 3360 QualType Canonical; 3361 if (!T.isCanonical()) { 3362 Canonical = getBlockPointerType(getCanonicalType(T)); 3363 3364 // Get the new insert position for the node we care about. 3365 BlockPointerType *NewIP = 3366 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3367 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3368 } 3369 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3370 Types.push_back(New); 3371 BlockPointerTypes.InsertNode(New, InsertPos); 3372 return QualType(New, 0); 3373 } 3374 3375 /// getLValueReferenceType - Return the uniqued reference to the type for an 3376 /// lvalue reference to the specified type. 3377 QualType 3378 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3379 assert((!T->isPlaceholderType() || 3380 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3381 "Unresolved placeholder type"); 3382 3383 // Unique pointers, to guarantee there is only one pointer of a particular 3384 // structure. 3385 llvm::FoldingSetNodeID ID; 3386 ReferenceType::Profile(ID, T, SpelledAsLValue); 3387 3388 void *InsertPos = nullptr; 3389 if (LValueReferenceType *RT = 3390 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3391 return QualType(RT, 0); 3392 3393 const auto *InnerRef = T->getAs<ReferenceType>(); 3394 3395 // If the referencee type isn't canonical, this won't be a canonical type 3396 // either, so fill in the canonical type field. 3397 QualType Canonical; 3398 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3399 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3400 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3401 3402 // Get the new insert position for the node we care about. 3403 LValueReferenceType *NewIP = 3404 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3405 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3406 } 3407 3408 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3409 SpelledAsLValue); 3410 Types.push_back(New); 3411 LValueReferenceTypes.InsertNode(New, InsertPos); 3412 3413 return QualType(New, 0); 3414 } 3415 3416 /// getRValueReferenceType - Return the uniqued reference to the type for an 3417 /// rvalue reference to the specified type. 3418 QualType ASTContext::getRValueReferenceType(QualType T) const { 3419 assert((!T->isPlaceholderType() || 3420 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3421 "Unresolved placeholder type"); 3422 3423 // Unique pointers, to guarantee there is only one pointer of a particular 3424 // structure. 3425 llvm::FoldingSetNodeID ID; 3426 ReferenceType::Profile(ID, T, false); 3427 3428 void *InsertPos = nullptr; 3429 if (RValueReferenceType *RT = 3430 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3431 return QualType(RT, 0); 3432 3433 const auto *InnerRef = T->getAs<ReferenceType>(); 3434 3435 // If the referencee type isn't canonical, this won't be a canonical type 3436 // either, so fill in the canonical type field. 3437 QualType Canonical; 3438 if (InnerRef || !T.isCanonical()) { 3439 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3440 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3441 3442 // Get the new insert position for the node we care about. 3443 RValueReferenceType *NewIP = 3444 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3445 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3446 } 3447 3448 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3449 Types.push_back(New); 3450 RValueReferenceTypes.InsertNode(New, InsertPos); 3451 return QualType(New, 0); 3452 } 3453 3454 /// getMemberPointerType - Return the uniqued reference to the type for a 3455 /// member pointer to the specified type, in the specified class. 3456 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3457 // Unique pointers, to guarantee there is only one pointer of a particular 3458 // structure. 3459 llvm::FoldingSetNodeID ID; 3460 MemberPointerType::Profile(ID, T, Cls); 3461 3462 void *InsertPos = nullptr; 3463 if (MemberPointerType *PT = 3464 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3465 return QualType(PT, 0); 3466 3467 // If the pointee or class type isn't canonical, this won't be a canonical 3468 // type either, so fill in the canonical type field. 3469 QualType Canonical; 3470 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3471 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3472 3473 // Get the new insert position for the node we care about. 3474 MemberPointerType *NewIP = 3475 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3477 } 3478 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3479 Types.push_back(New); 3480 MemberPointerTypes.InsertNode(New, InsertPos); 3481 return QualType(New, 0); 3482 } 3483 3484 /// getConstantArrayType - Return the unique reference to the type for an 3485 /// array of the specified element type. 3486 QualType ASTContext::getConstantArrayType(QualType EltTy, 3487 const llvm::APInt &ArySizeIn, 3488 const Expr *SizeExpr, 3489 ArrayType::ArraySizeModifier ASM, 3490 unsigned IndexTypeQuals) const { 3491 assert((EltTy->isDependentType() || 3492 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3493 "Constant array of VLAs is illegal!"); 3494 3495 // We only need the size as part of the type if it's instantiation-dependent. 3496 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3497 SizeExpr = nullptr; 3498 3499 // Convert the array size into a canonical width matching the pointer size for 3500 // the target. 3501 llvm::APInt ArySize(ArySizeIn); 3502 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3503 3504 llvm::FoldingSetNodeID ID; 3505 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3506 IndexTypeQuals); 3507 3508 void *InsertPos = nullptr; 3509 if (ConstantArrayType *ATP = 3510 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3511 return QualType(ATP, 0); 3512 3513 // If the element type isn't canonical or has qualifiers, or the array bound 3514 // is instantiation-dependent, this won't be a canonical type either, so fill 3515 // in the canonical type field. 3516 QualType Canon; 3517 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3518 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3519 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3520 ASM, IndexTypeQuals); 3521 Canon = getQualifiedType(Canon, canonSplit.Quals); 3522 3523 // Get the new insert position for the node we care about. 3524 ConstantArrayType *NewIP = 3525 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3527 } 3528 3529 void *Mem = Allocate( 3530 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3531 TypeAlignment); 3532 auto *New = new (Mem) 3533 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3534 ConstantArrayTypes.InsertNode(New, InsertPos); 3535 Types.push_back(New); 3536 return QualType(New, 0); 3537 } 3538 3539 /// getVariableArrayDecayedType - Turns the given type, which may be 3540 /// variably-modified, into the corresponding type with all the known 3541 /// sizes replaced with [*]. 3542 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3543 // Vastly most common case. 3544 if (!type->isVariablyModifiedType()) return type; 3545 3546 QualType result; 3547 3548 SplitQualType split = type.getSplitDesugaredType(); 3549 const Type *ty = split.Ty; 3550 switch (ty->getTypeClass()) { 3551 #define TYPE(Class, Base) 3552 #define ABSTRACT_TYPE(Class, Base) 3553 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3554 #include "clang/AST/TypeNodes.inc" 3555 llvm_unreachable("didn't desugar past all non-canonical types?"); 3556 3557 // These types should never be variably-modified. 3558 case Type::Builtin: 3559 case Type::Complex: 3560 case Type::Vector: 3561 case Type::DependentVector: 3562 case Type::ExtVector: 3563 case Type::DependentSizedExtVector: 3564 case Type::ConstantMatrix: 3565 case Type::DependentSizedMatrix: 3566 case Type::DependentAddressSpace: 3567 case Type::ObjCObject: 3568 case Type::ObjCInterface: 3569 case Type::ObjCObjectPointer: 3570 case Type::Record: 3571 case Type::Enum: 3572 case Type::UnresolvedUsing: 3573 case Type::TypeOfExpr: 3574 case Type::TypeOf: 3575 case Type::Decltype: 3576 case Type::UnaryTransform: 3577 case Type::DependentName: 3578 case Type::InjectedClassName: 3579 case Type::TemplateSpecialization: 3580 case Type::DependentTemplateSpecialization: 3581 case Type::TemplateTypeParm: 3582 case Type::SubstTemplateTypeParmPack: 3583 case Type::Auto: 3584 case Type::DeducedTemplateSpecialization: 3585 case Type::PackExpansion: 3586 case Type::BitInt: 3587 case Type::DependentBitInt: 3588 llvm_unreachable("type should never be variably-modified"); 3589 3590 // These types can be variably-modified but should never need to 3591 // further decay. 3592 case Type::FunctionNoProto: 3593 case Type::FunctionProto: 3594 case Type::BlockPointer: 3595 case Type::MemberPointer: 3596 case Type::Pipe: 3597 return type; 3598 3599 // These types can be variably-modified. All these modifications 3600 // preserve structure except as noted by comments. 3601 // TODO: if we ever care about optimizing VLAs, there are no-op 3602 // optimizations available here. 3603 case Type::Pointer: 3604 result = getPointerType(getVariableArrayDecayedType( 3605 cast<PointerType>(ty)->getPointeeType())); 3606 break; 3607 3608 case Type::LValueReference: { 3609 const auto *lv = cast<LValueReferenceType>(ty); 3610 result = getLValueReferenceType( 3611 getVariableArrayDecayedType(lv->getPointeeType()), 3612 lv->isSpelledAsLValue()); 3613 break; 3614 } 3615 3616 case Type::RValueReference: { 3617 const auto *lv = cast<RValueReferenceType>(ty); 3618 result = getRValueReferenceType( 3619 getVariableArrayDecayedType(lv->getPointeeType())); 3620 break; 3621 } 3622 3623 case Type::Atomic: { 3624 const auto *at = cast<AtomicType>(ty); 3625 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3626 break; 3627 } 3628 3629 case Type::ConstantArray: { 3630 const auto *cat = cast<ConstantArrayType>(ty); 3631 result = getConstantArrayType( 3632 getVariableArrayDecayedType(cat->getElementType()), 3633 cat->getSize(), 3634 cat->getSizeExpr(), 3635 cat->getSizeModifier(), 3636 cat->getIndexTypeCVRQualifiers()); 3637 break; 3638 } 3639 3640 case Type::DependentSizedArray: { 3641 const auto *dat = cast<DependentSizedArrayType>(ty); 3642 result = getDependentSizedArrayType( 3643 getVariableArrayDecayedType(dat->getElementType()), 3644 dat->getSizeExpr(), 3645 dat->getSizeModifier(), 3646 dat->getIndexTypeCVRQualifiers(), 3647 dat->getBracketsRange()); 3648 break; 3649 } 3650 3651 // Turn incomplete types into [*] types. 3652 case Type::IncompleteArray: { 3653 const auto *iat = cast<IncompleteArrayType>(ty); 3654 result = getVariableArrayType( 3655 getVariableArrayDecayedType(iat->getElementType()), 3656 /*size*/ nullptr, 3657 ArrayType::Normal, 3658 iat->getIndexTypeCVRQualifiers(), 3659 SourceRange()); 3660 break; 3661 } 3662 3663 // Turn VLA types into [*] types. 3664 case Type::VariableArray: { 3665 const auto *vat = cast<VariableArrayType>(ty); 3666 result = getVariableArrayType( 3667 getVariableArrayDecayedType(vat->getElementType()), 3668 /*size*/ nullptr, 3669 ArrayType::Star, 3670 vat->getIndexTypeCVRQualifiers(), 3671 vat->getBracketsRange()); 3672 break; 3673 } 3674 } 3675 3676 // Apply the top-level qualifiers from the original. 3677 return getQualifiedType(result, split.Quals); 3678 } 3679 3680 /// getVariableArrayType - Returns a non-unique reference to the type for a 3681 /// variable array of the specified element type. 3682 QualType ASTContext::getVariableArrayType(QualType EltTy, 3683 Expr *NumElts, 3684 ArrayType::ArraySizeModifier ASM, 3685 unsigned IndexTypeQuals, 3686 SourceRange Brackets) const { 3687 // Since we don't unique expressions, it isn't possible to unique VLA's 3688 // that have an expression provided for their size. 3689 QualType Canon; 3690 3691 // Be sure to pull qualifiers off the element type. 3692 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3693 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3694 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3695 IndexTypeQuals, Brackets); 3696 Canon = getQualifiedType(Canon, canonSplit.Quals); 3697 } 3698 3699 auto *New = new (*this, TypeAlignment) 3700 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3701 3702 VariableArrayTypes.push_back(New); 3703 Types.push_back(New); 3704 return QualType(New, 0); 3705 } 3706 3707 /// getDependentSizedArrayType - Returns a non-unique reference to 3708 /// the type for a dependently-sized array of the specified element 3709 /// type. 3710 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3711 Expr *numElements, 3712 ArrayType::ArraySizeModifier ASM, 3713 unsigned elementTypeQuals, 3714 SourceRange brackets) const { 3715 assert((!numElements || numElements->isTypeDependent() || 3716 numElements->isValueDependent()) && 3717 "Size must be type- or value-dependent!"); 3718 3719 // Dependently-sized array types that do not have a specified number 3720 // of elements will have their sizes deduced from a dependent 3721 // initializer. We do no canonicalization here at all, which is okay 3722 // because they can't be used in most locations. 3723 if (!numElements) { 3724 auto *newType 3725 = new (*this, TypeAlignment) 3726 DependentSizedArrayType(*this, elementType, QualType(), 3727 numElements, ASM, elementTypeQuals, 3728 brackets); 3729 Types.push_back(newType); 3730 return QualType(newType, 0); 3731 } 3732 3733 // Otherwise, we actually build a new type every time, but we 3734 // also build a canonical type. 3735 3736 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3737 3738 void *insertPos = nullptr; 3739 llvm::FoldingSetNodeID ID; 3740 DependentSizedArrayType::Profile(ID, *this, 3741 QualType(canonElementType.Ty, 0), 3742 ASM, elementTypeQuals, numElements); 3743 3744 // Look for an existing type with these properties. 3745 DependentSizedArrayType *canonTy = 3746 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3747 3748 // If we don't have one, build one. 3749 if (!canonTy) { 3750 canonTy = new (*this, TypeAlignment) 3751 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3752 QualType(), numElements, ASM, elementTypeQuals, 3753 brackets); 3754 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3755 Types.push_back(canonTy); 3756 } 3757 3758 // Apply qualifiers from the element type to the array. 3759 QualType canon = getQualifiedType(QualType(canonTy,0), 3760 canonElementType.Quals); 3761 3762 // If we didn't need extra canonicalization for the element type or the size 3763 // expression, then just use that as our result. 3764 if (QualType(canonElementType.Ty, 0) == elementType && 3765 canonTy->getSizeExpr() == numElements) 3766 return canon; 3767 3768 // Otherwise, we need to build a type which follows the spelling 3769 // of the element type. 3770 auto *sugaredType 3771 = new (*this, TypeAlignment) 3772 DependentSizedArrayType(*this, elementType, canon, numElements, 3773 ASM, elementTypeQuals, brackets); 3774 Types.push_back(sugaredType); 3775 return QualType(sugaredType, 0); 3776 } 3777 3778 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3779 ArrayType::ArraySizeModifier ASM, 3780 unsigned elementTypeQuals) const { 3781 llvm::FoldingSetNodeID ID; 3782 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3783 3784 void *insertPos = nullptr; 3785 if (IncompleteArrayType *iat = 3786 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3787 return QualType(iat, 0); 3788 3789 // If the element type isn't canonical, this won't be a canonical type 3790 // either, so fill in the canonical type field. We also have to pull 3791 // qualifiers off the element type. 3792 QualType canon; 3793 3794 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3795 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3796 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3797 ASM, elementTypeQuals); 3798 canon = getQualifiedType(canon, canonSplit.Quals); 3799 3800 // Get the new insert position for the node we care about. 3801 IncompleteArrayType *existing = 3802 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3803 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3804 } 3805 3806 auto *newType = new (*this, TypeAlignment) 3807 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3808 3809 IncompleteArrayTypes.InsertNode(newType, insertPos); 3810 Types.push_back(newType); 3811 return QualType(newType, 0); 3812 } 3813 3814 ASTContext::BuiltinVectorTypeInfo 3815 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3816 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3817 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3818 NUMVECTORS}; 3819 3820 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3821 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3822 3823 switch (Ty->getKind()) { 3824 default: 3825 llvm_unreachable("Unsupported builtin vector type"); 3826 case BuiltinType::SveInt8: 3827 return SVE_INT_ELTTY(8, 16, true, 1); 3828 case BuiltinType::SveUint8: 3829 return SVE_INT_ELTTY(8, 16, false, 1); 3830 case BuiltinType::SveInt8x2: 3831 return SVE_INT_ELTTY(8, 16, true, 2); 3832 case BuiltinType::SveUint8x2: 3833 return SVE_INT_ELTTY(8, 16, false, 2); 3834 case BuiltinType::SveInt8x3: 3835 return SVE_INT_ELTTY(8, 16, true, 3); 3836 case BuiltinType::SveUint8x3: 3837 return SVE_INT_ELTTY(8, 16, false, 3); 3838 case BuiltinType::SveInt8x4: 3839 return SVE_INT_ELTTY(8, 16, true, 4); 3840 case BuiltinType::SveUint8x4: 3841 return SVE_INT_ELTTY(8, 16, false, 4); 3842 case BuiltinType::SveInt16: 3843 return SVE_INT_ELTTY(16, 8, true, 1); 3844 case BuiltinType::SveUint16: 3845 return SVE_INT_ELTTY(16, 8, false, 1); 3846 case BuiltinType::SveInt16x2: 3847 return SVE_INT_ELTTY(16, 8, true, 2); 3848 case BuiltinType::SveUint16x2: 3849 return SVE_INT_ELTTY(16, 8, false, 2); 3850 case BuiltinType::SveInt16x3: 3851 return SVE_INT_ELTTY(16, 8, true, 3); 3852 case BuiltinType::SveUint16x3: 3853 return SVE_INT_ELTTY(16, 8, false, 3); 3854 case BuiltinType::SveInt16x4: 3855 return SVE_INT_ELTTY(16, 8, true, 4); 3856 case BuiltinType::SveUint16x4: 3857 return SVE_INT_ELTTY(16, 8, false, 4); 3858 case BuiltinType::SveInt32: 3859 return SVE_INT_ELTTY(32, 4, true, 1); 3860 case BuiltinType::SveUint32: 3861 return SVE_INT_ELTTY(32, 4, false, 1); 3862 case BuiltinType::SveInt32x2: 3863 return SVE_INT_ELTTY(32, 4, true, 2); 3864 case BuiltinType::SveUint32x2: 3865 return SVE_INT_ELTTY(32, 4, false, 2); 3866 case BuiltinType::SveInt32x3: 3867 return SVE_INT_ELTTY(32, 4, true, 3); 3868 case BuiltinType::SveUint32x3: 3869 return SVE_INT_ELTTY(32, 4, false, 3); 3870 case BuiltinType::SveInt32x4: 3871 return SVE_INT_ELTTY(32, 4, true, 4); 3872 case BuiltinType::SveUint32x4: 3873 return SVE_INT_ELTTY(32, 4, false, 4); 3874 case BuiltinType::SveInt64: 3875 return SVE_INT_ELTTY(64, 2, true, 1); 3876 case BuiltinType::SveUint64: 3877 return SVE_INT_ELTTY(64, 2, false, 1); 3878 case BuiltinType::SveInt64x2: 3879 return SVE_INT_ELTTY(64, 2, true, 2); 3880 case BuiltinType::SveUint64x2: 3881 return SVE_INT_ELTTY(64, 2, false, 2); 3882 case BuiltinType::SveInt64x3: 3883 return SVE_INT_ELTTY(64, 2, true, 3); 3884 case BuiltinType::SveUint64x3: 3885 return SVE_INT_ELTTY(64, 2, false, 3); 3886 case BuiltinType::SveInt64x4: 3887 return SVE_INT_ELTTY(64, 2, true, 4); 3888 case BuiltinType::SveUint64x4: 3889 return SVE_INT_ELTTY(64, 2, false, 4); 3890 case BuiltinType::SveBool: 3891 return SVE_ELTTY(BoolTy, 16, 1); 3892 case BuiltinType::SveFloat16: 3893 return SVE_ELTTY(HalfTy, 8, 1); 3894 case BuiltinType::SveFloat16x2: 3895 return SVE_ELTTY(HalfTy, 8, 2); 3896 case BuiltinType::SveFloat16x3: 3897 return SVE_ELTTY(HalfTy, 8, 3); 3898 case BuiltinType::SveFloat16x4: 3899 return SVE_ELTTY(HalfTy, 8, 4); 3900 case BuiltinType::SveFloat32: 3901 return SVE_ELTTY(FloatTy, 4, 1); 3902 case BuiltinType::SveFloat32x2: 3903 return SVE_ELTTY(FloatTy, 4, 2); 3904 case BuiltinType::SveFloat32x3: 3905 return SVE_ELTTY(FloatTy, 4, 3); 3906 case BuiltinType::SveFloat32x4: 3907 return SVE_ELTTY(FloatTy, 4, 4); 3908 case BuiltinType::SveFloat64: 3909 return SVE_ELTTY(DoubleTy, 2, 1); 3910 case BuiltinType::SveFloat64x2: 3911 return SVE_ELTTY(DoubleTy, 2, 2); 3912 case BuiltinType::SveFloat64x3: 3913 return SVE_ELTTY(DoubleTy, 2, 3); 3914 case BuiltinType::SveFloat64x4: 3915 return SVE_ELTTY(DoubleTy, 2, 4); 3916 case BuiltinType::SveBFloat16: 3917 return SVE_ELTTY(BFloat16Ty, 8, 1); 3918 case BuiltinType::SveBFloat16x2: 3919 return SVE_ELTTY(BFloat16Ty, 8, 2); 3920 case BuiltinType::SveBFloat16x3: 3921 return SVE_ELTTY(BFloat16Ty, 8, 3); 3922 case BuiltinType::SveBFloat16x4: 3923 return SVE_ELTTY(BFloat16Ty, 8, 4); 3924 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3925 IsSigned) \ 3926 case BuiltinType::Id: \ 3927 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3928 llvm::ElementCount::getScalable(NumEls), NF}; 3929 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3930 case BuiltinType::Id: \ 3931 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3932 llvm::ElementCount::getScalable(NumEls), NF}; 3933 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3934 case BuiltinType::Id: \ 3935 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3936 #include "clang/Basic/RISCVVTypes.def" 3937 } 3938 } 3939 3940 /// getScalableVectorType - Return the unique reference to a scalable vector 3941 /// type of the specified element type and size. VectorType must be a built-in 3942 /// type. 3943 QualType ASTContext::getScalableVectorType(QualType EltTy, 3944 unsigned NumElts) const { 3945 if (Target->hasAArch64SVETypes()) { 3946 uint64_t EltTySize = getTypeSize(EltTy); 3947 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3948 IsSigned, IsFP, IsBF) \ 3949 if (!EltTy->isBooleanType() && \ 3950 ((EltTy->hasIntegerRepresentation() && \ 3951 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3952 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3953 IsFP && !IsBF) || \ 3954 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3955 IsBF && !IsFP)) && \ 3956 EltTySize == ElBits && NumElts == NumEls) { \ 3957 return SingletonId; \ 3958 } 3959 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3960 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3961 return SingletonId; 3962 #include "clang/Basic/AArch64SVEACLETypes.def" 3963 } else if (Target->hasRISCVVTypes()) { 3964 uint64_t EltTySize = getTypeSize(EltTy); 3965 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3966 IsFP) \ 3967 if (!EltTy->isBooleanType() && \ 3968 ((EltTy->hasIntegerRepresentation() && \ 3969 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3970 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3971 EltTySize == ElBits && NumElts == NumEls) \ 3972 return SingletonId; 3973 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3974 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3975 return SingletonId; 3976 #include "clang/Basic/RISCVVTypes.def" 3977 } 3978 return QualType(); 3979 } 3980 3981 /// getVectorType - Return the unique reference to a vector type of 3982 /// the specified element type and size. VectorType must be a built-in type. 3983 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3984 VectorType::VectorKind VecKind) const { 3985 assert(vecType->isBuiltinType()); 3986 3987 // Check if we've already instantiated a vector of this type. 3988 llvm::FoldingSetNodeID ID; 3989 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3990 3991 void *InsertPos = nullptr; 3992 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3993 return QualType(VTP, 0); 3994 3995 // If the element type isn't canonical, this won't be a canonical type either, 3996 // so fill in the canonical type field. 3997 QualType Canonical; 3998 if (!vecType.isCanonical()) { 3999 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 4000 4001 // Get the new insert position for the node we care about. 4002 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4003 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4004 } 4005 auto *New = new (*this, TypeAlignment) 4006 VectorType(vecType, NumElts, Canonical, VecKind); 4007 VectorTypes.InsertNode(New, InsertPos); 4008 Types.push_back(New); 4009 return QualType(New, 0); 4010 } 4011 4012 QualType 4013 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4014 SourceLocation AttrLoc, 4015 VectorType::VectorKind VecKind) const { 4016 llvm::FoldingSetNodeID ID; 4017 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4018 VecKind); 4019 void *InsertPos = nullptr; 4020 DependentVectorType *Canon = 4021 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4022 DependentVectorType *New; 4023 4024 if (Canon) { 4025 New = new (*this, TypeAlignment) DependentVectorType( 4026 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4027 } else { 4028 QualType CanonVecTy = getCanonicalType(VecType); 4029 if (CanonVecTy == VecType) { 4030 New = new (*this, TypeAlignment) DependentVectorType( 4031 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4032 4033 DependentVectorType *CanonCheck = 4034 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4035 assert(!CanonCheck && 4036 "Dependent-sized vector_size canonical type broken"); 4037 (void)CanonCheck; 4038 DependentVectorTypes.InsertNode(New, InsertPos); 4039 } else { 4040 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4041 SourceLocation(), VecKind); 4042 New = new (*this, TypeAlignment) DependentVectorType( 4043 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4044 } 4045 } 4046 4047 Types.push_back(New); 4048 return QualType(New, 0); 4049 } 4050 4051 /// getExtVectorType - Return the unique reference to an extended vector type of 4052 /// the specified element type and size. VectorType must be a built-in type. 4053 QualType 4054 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4055 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4056 4057 // Check if we've already instantiated a vector of this type. 4058 llvm::FoldingSetNodeID ID; 4059 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4060 VectorType::GenericVector); 4061 void *InsertPos = nullptr; 4062 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4063 return QualType(VTP, 0); 4064 4065 // If the element type isn't canonical, this won't be a canonical type either, 4066 // so fill in the canonical type field. 4067 QualType Canonical; 4068 if (!vecType.isCanonical()) { 4069 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4070 4071 // Get the new insert position for the node we care about. 4072 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4073 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4074 } 4075 auto *New = new (*this, TypeAlignment) 4076 ExtVectorType(vecType, NumElts, Canonical); 4077 VectorTypes.InsertNode(New, InsertPos); 4078 Types.push_back(New); 4079 return QualType(New, 0); 4080 } 4081 4082 QualType 4083 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4084 Expr *SizeExpr, 4085 SourceLocation AttrLoc) const { 4086 llvm::FoldingSetNodeID ID; 4087 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4088 SizeExpr); 4089 4090 void *InsertPos = nullptr; 4091 DependentSizedExtVectorType *Canon 4092 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4093 DependentSizedExtVectorType *New; 4094 if (Canon) { 4095 // We already have a canonical version of this array type; use it as 4096 // the canonical type for a newly-built type. 4097 New = new (*this, TypeAlignment) 4098 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4099 SizeExpr, AttrLoc); 4100 } else { 4101 QualType CanonVecTy = getCanonicalType(vecType); 4102 if (CanonVecTy == vecType) { 4103 New = new (*this, TypeAlignment) 4104 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4105 AttrLoc); 4106 4107 DependentSizedExtVectorType *CanonCheck 4108 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4109 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4110 (void)CanonCheck; 4111 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4112 } else { 4113 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4114 SourceLocation()); 4115 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4116 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4117 } 4118 } 4119 4120 Types.push_back(New); 4121 return QualType(New, 0); 4122 } 4123 4124 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4125 unsigned NumColumns) const { 4126 llvm::FoldingSetNodeID ID; 4127 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4128 Type::ConstantMatrix); 4129 4130 assert(MatrixType::isValidElementType(ElementTy) && 4131 "need a valid element type"); 4132 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4133 ConstantMatrixType::isDimensionValid(NumColumns) && 4134 "need valid matrix dimensions"); 4135 void *InsertPos = nullptr; 4136 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4137 return QualType(MTP, 0); 4138 4139 QualType Canonical; 4140 if (!ElementTy.isCanonical()) { 4141 Canonical = 4142 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4143 4144 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4145 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4146 (void)NewIP; 4147 } 4148 4149 auto *New = new (*this, TypeAlignment) 4150 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4151 MatrixTypes.InsertNode(New, InsertPos); 4152 Types.push_back(New); 4153 return QualType(New, 0); 4154 } 4155 4156 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4157 Expr *RowExpr, 4158 Expr *ColumnExpr, 4159 SourceLocation AttrLoc) const { 4160 QualType CanonElementTy = getCanonicalType(ElementTy); 4161 llvm::FoldingSetNodeID ID; 4162 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4163 ColumnExpr); 4164 4165 void *InsertPos = nullptr; 4166 DependentSizedMatrixType *Canon = 4167 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4168 4169 if (!Canon) { 4170 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4171 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4172 #ifndef NDEBUG 4173 DependentSizedMatrixType *CanonCheck = 4174 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4175 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4176 #endif 4177 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4178 Types.push_back(Canon); 4179 } 4180 4181 // Already have a canonical version of the matrix type 4182 // 4183 // If it exactly matches the requested type, use it directly. 4184 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4185 Canon->getRowExpr() == ColumnExpr) 4186 return QualType(Canon, 0); 4187 4188 // Use Canon as the canonical type for newly-built type. 4189 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4190 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4191 ColumnExpr, AttrLoc); 4192 Types.push_back(New); 4193 return QualType(New, 0); 4194 } 4195 4196 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4197 Expr *AddrSpaceExpr, 4198 SourceLocation AttrLoc) const { 4199 assert(AddrSpaceExpr->isInstantiationDependent()); 4200 4201 QualType canonPointeeType = getCanonicalType(PointeeType); 4202 4203 void *insertPos = nullptr; 4204 llvm::FoldingSetNodeID ID; 4205 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4206 AddrSpaceExpr); 4207 4208 DependentAddressSpaceType *canonTy = 4209 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4210 4211 if (!canonTy) { 4212 canonTy = new (*this, TypeAlignment) 4213 DependentAddressSpaceType(*this, canonPointeeType, 4214 QualType(), AddrSpaceExpr, AttrLoc); 4215 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4216 Types.push_back(canonTy); 4217 } 4218 4219 if (canonPointeeType == PointeeType && 4220 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4221 return QualType(canonTy, 0); 4222 4223 auto *sugaredType 4224 = new (*this, TypeAlignment) 4225 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4226 AddrSpaceExpr, AttrLoc); 4227 Types.push_back(sugaredType); 4228 return QualType(sugaredType, 0); 4229 } 4230 4231 /// Determine whether \p T is canonical as the result type of a function. 4232 static bool isCanonicalResultType(QualType T) { 4233 return T.isCanonical() && 4234 (T.getObjCLifetime() == Qualifiers::OCL_None || 4235 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4236 } 4237 4238 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4239 QualType 4240 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4241 const FunctionType::ExtInfo &Info) const { 4242 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter 4243 // functionality creates a function without a prototype regardless of 4244 // language mode (so it makes them even in C++). Once the rewriter has been 4245 // fixed, this assertion can be enabled again. 4246 //assert(!LangOpts.requiresStrictPrototypes() && 4247 // "strict prototypes are disabled"); 4248 4249 // Unique functions, to guarantee there is only one function of a particular 4250 // structure. 4251 llvm::FoldingSetNodeID ID; 4252 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4253 4254 void *InsertPos = nullptr; 4255 if (FunctionNoProtoType *FT = 4256 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4257 return QualType(FT, 0); 4258 4259 QualType Canonical; 4260 if (!isCanonicalResultType(ResultTy)) { 4261 Canonical = 4262 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4263 4264 // Get the new insert position for the node we care about. 4265 FunctionNoProtoType *NewIP = 4266 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4267 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4268 } 4269 4270 auto *New = new (*this, TypeAlignment) 4271 FunctionNoProtoType(ResultTy, Canonical, Info); 4272 Types.push_back(New); 4273 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4274 return QualType(New, 0); 4275 } 4276 4277 CanQualType 4278 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4279 CanQualType CanResultType = getCanonicalType(ResultType); 4280 4281 // Canonical result types do not have ARC lifetime qualifiers. 4282 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4283 Qualifiers Qs = CanResultType.getQualifiers(); 4284 Qs.removeObjCLifetime(); 4285 return CanQualType::CreateUnsafe( 4286 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4287 } 4288 4289 return CanResultType; 4290 } 4291 4292 static bool isCanonicalExceptionSpecification( 4293 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4294 if (ESI.Type == EST_None) 4295 return true; 4296 if (!NoexceptInType) 4297 return false; 4298 4299 // C++17 onwards: exception specification is part of the type, as a simple 4300 // boolean "can this function type throw". 4301 if (ESI.Type == EST_BasicNoexcept) 4302 return true; 4303 4304 // A noexcept(expr) specification is (possibly) canonical if expr is 4305 // value-dependent. 4306 if (ESI.Type == EST_DependentNoexcept) 4307 return true; 4308 4309 // A dynamic exception specification is canonical if it only contains pack 4310 // expansions (so we can't tell whether it's non-throwing) and all its 4311 // contained types are canonical. 4312 if (ESI.Type == EST_Dynamic) { 4313 bool AnyPackExpansions = false; 4314 for (QualType ET : ESI.Exceptions) { 4315 if (!ET.isCanonical()) 4316 return false; 4317 if (ET->getAs<PackExpansionType>()) 4318 AnyPackExpansions = true; 4319 } 4320 return AnyPackExpansions; 4321 } 4322 4323 return false; 4324 } 4325 4326 QualType ASTContext::getFunctionTypeInternal( 4327 QualType ResultTy, ArrayRef<QualType> ArgArray, 4328 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4329 size_t NumArgs = ArgArray.size(); 4330 4331 // Unique functions, to guarantee there is only one function of a particular 4332 // structure. 4333 llvm::FoldingSetNodeID ID; 4334 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4335 *this, true); 4336 4337 QualType Canonical; 4338 bool Unique = false; 4339 4340 void *InsertPos = nullptr; 4341 if (FunctionProtoType *FPT = 4342 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4343 QualType Existing = QualType(FPT, 0); 4344 4345 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4346 // it so long as our exception specification doesn't contain a dependent 4347 // noexcept expression, or we're just looking for a canonical type. 4348 // Otherwise, we're going to need to create a type 4349 // sugar node to hold the concrete expression. 4350 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4351 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4352 return Existing; 4353 4354 // We need a new type sugar node for this one, to hold the new noexcept 4355 // expression. We do no canonicalization here, but that's OK since we don't 4356 // expect to see the same noexcept expression much more than once. 4357 Canonical = getCanonicalType(Existing); 4358 Unique = true; 4359 } 4360 4361 bool NoexceptInType = getLangOpts().CPlusPlus17; 4362 bool IsCanonicalExceptionSpec = 4363 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4364 4365 // Determine whether the type being created is already canonical or not. 4366 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4367 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4368 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4369 if (!ArgArray[i].isCanonicalAsParam()) 4370 isCanonical = false; 4371 4372 if (OnlyWantCanonical) 4373 assert(isCanonical && 4374 "given non-canonical parameters constructing canonical type"); 4375 4376 // If this type isn't canonical, get the canonical version of it if we don't 4377 // already have it. The exception spec is only partially part of the 4378 // canonical type, and only in C++17 onwards. 4379 if (!isCanonical && Canonical.isNull()) { 4380 SmallVector<QualType, 16> CanonicalArgs; 4381 CanonicalArgs.reserve(NumArgs); 4382 for (unsigned i = 0; i != NumArgs; ++i) 4383 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4384 4385 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4386 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4387 CanonicalEPI.HasTrailingReturn = false; 4388 4389 if (IsCanonicalExceptionSpec) { 4390 // Exception spec is already OK. 4391 } else if (NoexceptInType) { 4392 switch (EPI.ExceptionSpec.Type) { 4393 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4394 // We don't know yet. It shouldn't matter what we pick here; no-one 4395 // should ever look at this. 4396 LLVM_FALLTHROUGH; 4397 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4398 CanonicalEPI.ExceptionSpec.Type = EST_None; 4399 break; 4400 4401 // A dynamic exception specification is almost always "not noexcept", 4402 // with the exception that a pack expansion might expand to no types. 4403 case EST_Dynamic: { 4404 bool AnyPacks = false; 4405 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4406 if (ET->getAs<PackExpansionType>()) 4407 AnyPacks = true; 4408 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4409 } 4410 if (!AnyPacks) 4411 CanonicalEPI.ExceptionSpec.Type = EST_None; 4412 else { 4413 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4414 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4415 } 4416 break; 4417 } 4418 4419 case EST_DynamicNone: 4420 case EST_BasicNoexcept: 4421 case EST_NoexceptTrue: 4422 case EST_NoThrow: 4423 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4424 break; 4425 4426 case EST_DependentNoexcept: 4427 llvm_unreachable("dependent noexcept is already canonical"); 4428 } 4429 } else { 4430 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4431 } 4432 4433 // Adjust the canonical function result type. 4434 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4435 Canonical = 4436 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4437 4438 // Get the new insert position for the node we care about. 4439 FunctionProtoType *NewIP = 4440 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4441 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4442 } 4443 4444 // Compute the needed size to hold this FunctionProtoType and the 4445 // various trailing objects. 4446 auto ESH = FunctionProtoType::getExceptionSpecSize( 4447 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4448 size_t Size = FunctionProtoType::totalSizeToAlloc< 4449 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4450 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4451 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4452 NumArgs, EPI.Variadic, 4453 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4454 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4455 EPI.ExtParameterInfos ? NumArgs : 0, 4456 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4457 4458 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4459 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4460 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4461 Types.push_back(FTP); 4462 if (!Unique) 4463 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4464 return QualType(FTP, 0); 4465 } 4466 4467 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4468 llvm::FoldingSetNodeID ID; 4469 PipeType::Profile(ID, T, ReadOnly); 4470 4471 void *InsertPos = nullptr; 4472 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4473 return QualType(PT, 0); 4474 4475 // If the pipe element type isn't canonical, this won't be a canonical type 4476 // either, so fill in the canonical type field. 4477 QualType Canonical; 4478 if (!T.isCanonical()) { 4479 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4480 4481 // Get the new insert position for the node we care about. 4482 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4483 assert(!NewIP && "Shouldn't be in the map!"); 4484 (void)NewIP; 4485 } 4486 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4487 Types.push_back(New); 4488 PipeTypes.InsertNode(New, InsertPos); 4489 return QualType(New, 0); 4490 } 4491 4492 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4493 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4494 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4495 : Ty; 4496 } 4497 4498 QualType ASTContext::getReadPipeType(QualType T) const { 4499 return getPipeType(T, true); 4500 } 4501 4502 QualType ASTContext::getWritePipeType(QualType T) const { 4503 return getPipeType(T, false); 4504 } 4505 4506 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4507 llvm::FoldingSetNodeID ID; 4508 BitIntType::Profile(ID, IsUnsigned, NumBits); 4509 4510 void *InsertPos = nullptr; 4511 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4512 return QualType(EIT, 0); 4513 4514 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4515 BitIntTypes.InsertNode(New, InsertPos); 4516 Types.push_back(New); 4517 return QualType(New, 0); 4518 } 4519 4520 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4521 Expr *NumBitsExpr) const { 4522 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4523 llvm::FoldingSetNodeID ID; 4524 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4525 4526 void *InsertPos = nullptr; 4527 if (DependentBitIntType *Existing = 4528 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4529 return QualType(Existing, 0); 4530 4531 auto *New = new (*this, TypeAlignment) 4532 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4533 DependentBitIntTypes.InsertNode(New, InsertPos); 4534 4535 Types.push_back(New); 4536 return QualType(New, 0); 4537 } 4538 4539 #ifndef NDEBUG 4540 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4541 if (!isa<CXXRecordDecl>(D)) return false; 4542 const auto *RD = cast<CXXRecordDecl>(D); 4543 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4544 return true; 4545 if (RD->getDescribedClassTemplate() && 4546 !isa<ClassTemplateSpecializationDecl>(RD)) 4547 return true; 4548 return false; 4549 } 4550 #endif 4551 4552 /// getInjectedClassNameType - Return the unique reference to the 4553 /// injected class name type for the specified templated declaration. 4554 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4555 QualType TST) const { 4556 assert(NeedsInjectedClassNameType(Decl)); 4557 if (Decl->TypeForDecl) { 4558 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4559 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4560 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4561 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4562 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4563 } else { 4564 Type *newType = 4565 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4566 Decl->TypeForDecl = newType; 4567 Types.push_back(newType); 4568 } 4569 return QualType(Decl->TypeForDecl, 0); 4570 } 4571 4572 /// getTypeDeclType - Return the unique reference to the type for the 4573 /// specified type declaration. 4574 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4575 assert(Decl && "Passed null for Decl param"); 4576 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4577 4578 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4579 return getTypedefType(Typedef); 4580 4581 assert(!isa<TemplateTypeParmDecl>(Decl) && 4582 "Template type parameter types are always available."); 4583 4584 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4585 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4586 assert(!NeedsInjectedClassNameType(Record)); 4587 return getRecordType(Record); 4588 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4589 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4590 return getEnumType(Enum); 4591 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4592 return getUnresolvedUsingType(Using); 4593 } else 4594 llvm_unreachable("TypeDecl without a type?"); 4595 4596 return QualType(Decl->TypeForDecl, 0); 4597 } 4598 4599 /// getTypedefType - Return the unique reference to the type for the 4600 /// specified typedef name decl. 4601 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4602 QualType Underlying) const { 4603 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4604 4605 if (Underlying.isNull()) 4606 Underlying = Decl->getUnderlyingType(); 4607 QualType Canonical = getCanonicalType(Underlying); 4608 auto *newType = new (*this, TypeAlignment) 4609 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4610 Decl->TypeForDecl = newType; 4611 Types.push_back(newType); 4612 return QualType(newType, 0); 4613 } 4614 4615 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4616 QualType Underlying) const { 4617 llvm::FoldingSetNodeID ID; 4618 UsingType::Profile(ID, Found); 4619 4620 void *InsertPos = nullptr; 4621 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4622 if (T) 4623 return QualType(T, 0); 4624 4625 assert(!Underlying.hasLocalQualifiers()); 4626 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4627 QualType Canon = Underlying.getCanonicalType(); 4628 4629 UsingType *NewType = 4630 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4631 Types.push_back(NewType); 4632 UsingTypes.InsertNode(NewType, InsertPos); 4633 return QualType(NewType, 0); 4634 } 4635 4636 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4637 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4638 4639 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4640 if (PrevDecl->TypeForDecl) 4641 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4642 4643 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4644 Decl->TypeForDecl = newType; 4645 Types.push_back(newType); 4646 return QualType(newType, 0); 4647 } 4648 4649 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4650 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4651 4652 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4653 if (PrevDecl->TypeForDecl) 4654 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4655 4656 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4657 Decl->TypeForDecl = newType; 4658 Types.push_back(newType); 4659 return QualType(newType, 0); 4660 } 4661 4662 QualType ASTContext::getUnresolvedUsingType( 4663 const UnresolvedUsingTypenameDecl *Decl) const { 4664 if (Decl->TypeForDecl) 4665 return QualType(Decl->TypeForDecl, 0); 4666 4667 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4668 Decl->getCanonicalDecl()) 4669 if (CanonicalDecl->TypeForDecl) 4670 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4671 4672 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4673 Decl->TypeForDecl = newType; 4674 Types.push_back(newType); 4675 return QualType(newType, 0); 4676 } 4677 4678 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4679 QualType modifiedType, 4680 QualType equivalentType) { 4681 llvm::FoldingSetNodeID id; 4682 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4683 4684 void *insertPos = nullptr; 4685 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4686 if (type) return QualType(type, 0); 4687 4688 QualType canon = getCanonicalType(equivalentType); 4689 type = new (*this, TypeAlignment) 4690 AttributedType(canon, attrKind, modifiedType, equivalentType); 4691 4692 Types.push_back(type); 4693 AttributedTypes.InsertNode(type, insertPos); 4694 4695 return QualType(type, 0); 4696 } 4697 4698 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 4699 QualType Wrapped) { 4700 llvm::FoldingSetNodeID ID; 4701 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr); 4702 4703 void *InsertPos = nullptr; 4704 BTFTagAttributedType *Ty = 4705 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 4706 if (Ty) 4707 return QualType(Ty, 0); 4708 4709 QualType Canon = getCanonicalType(Wrapped); 4710 Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr); 4711 4712 Types.push_back(Ty); 4713 BTFTagAttributedTypes.InsertNode(Ty, InsertPos); 4714 4715 return QualType(Ty, 0); 4716 } 4717 4718 /// Retrieve a substitution-result type. 4719 QualType 4720 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4721 QualType Replacement) const { 4722 assert(Replacement.isCanonical() 4723 && "replacement types must always be canonical"); 4724 4725 llvm::FoldingSetNodeID ID; 4726 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4727 void *InsertPos = nullptr; 4728 SubstTemplateTypeParmType *SubstParm 4729 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4730 4731 if (!SubstParm) { 4732 SubstParm = new (*this, TypeAlignment) 4733 SubstTemplateTypeParmType(Parm, Replacement); 4734 Types.push_back(SubstParm); 4735 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4736 } 4737 4738 return QualType(SubstParm, 0); 4739 } 4740 4741 /// Retrieve a 4742 QualType ASTContext::getSubstTemplateTypeParmPackType( 4743 const TemplateTypeParmType *Parm, 4744 const TemplateArgument &ArgPack) { 4745 #ifndef NDEBUG 4746 for (const auto &P : ArgPack.pack_elements()) { 4747 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4748 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4749 } 4750 #endif 4751 4752 llvm::FoldingSetNodeID ID; 4753 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4754 void *InsertPos = nullptr; 4755 if (SubstTemplateTypeParmPackType *SubstParm 4756 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4757 return QualType(SubstParm, 0); 4758 4759 QualType Canon; 4760 if (!Parm->isCanonicalUnqualified()) { 4761 Canon = getCanonicalType(QualType(Parm, 0)); 4762 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4763 ArgPack); 4764 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4765 } 4766 4767 auto *SubstParm 4768 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4769 ArgPack); 4770 Types.push_back(SubstParm); 4771 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4772 return QualType(SubstParm, 0); 4773 } 4774 4775 /// Retrieve the template type parameter type for a template 4776 /// parameter or parameter pack with the given depth, index, and (optionally) 4777 /// name. 4778 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4779 bool ParameterPack, 4780 TemplateTypeParmDecl *TTPDecl) const { 4781 llvm::FoldingSetNodeID ID; 4782 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4783 void *InsertPos = nullptr; 4784 TemplateTypeParmType *TypeParm 4785 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4786 4787 if (TypeParm) 4788 return QualType(TypeParm, 0); 4789 4790 if (TTPDecl) { 4791 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4792 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4793 4794 TemplateTypeParmType *TypeCheck 4795 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4796 assert(!TypeCheck && "Template type parameter canonical type broken"); 4797 (void)TypeCheck; 4798 } else 4799 TypeParm = new (*this, TypeAlignment) 4800 TemplateTypeParmType(Depth, Index, ParameterPack); 4801 4802 Types.push_back(TypeParm); 4803 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4804 4805 return QualType(TypeParm, 0); 4806 } 4807 4808 TypeSourceInfo * 4809 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4810 SourceLocation NameLoc, 4811 const TemplateArgumentListInfo &Args, 4812 QualType Underlying) const { 4813 assert(!Name.getAsDependentTemplateName() && 4814 "No dependent template names here!"); 4815 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4816 4817 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4818 TemplateSpecializationTypeLoc TL = 4819 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4820 TL.setTemplateKeywordLoc(SourceLocation()); 4821 TL.setTemplateNameLoc(NameLoc); 4822 TL.setLAngleLoc(Args.getLAngleLoc()); 4823 TL.setRAngleLoc(Args.getRAngleLoc()); 4824 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4825 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4826 return DI; 4827 } 4828 4829 QualType 4830 ASTContext::getTemplateSpecializationType(TemplateName Template, 4831 const TemplateArgumentListInfo &Args, 4832 QualType Underlying) const { 4833 assert(!Template.getAsDependentTemplateName() && 4834 "No dependent template names here!"); 4835 4836 SmallVector<TemplateArgument, 4> ArgVec; 4837 ArgVec.reserve(Args.size()); 4838 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4839 ArgVec.push_back(Arg.getArgument()); 4840 4841 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4842 } 4843 4844 #ifndef NDEBUG 4845 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4846 for (const TemplateArgument &Arg : Args) 4847 if (Arg.isPackExpansion()) 4848 return true; 4849 4850 return true; 4851 } 4852 #endif 4853 4854 QualType 4855 ASTContext::getTemplateSpecializationType(TemplateName Template, 4856 ArrayRef<TemplateArgument> Args, 4857 QualType Underlying) const { 4858 assert(!Template.getAsDependentTemplateName() && 4859 "No dependent template names here!"); 4860 // Look through qualified template names. 4861 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4862 Template = TemplateName(QTN->getTemplateDecl()); 4863 4864 bool IsTypeAlias = 4865 Template.getAsTemplateDecl() && 4866 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4867 QualType CanonType; 4868 if (!Underlying.isNull()) 4869 CanonType = getCanonicalType(Underlying); 4870 else { 4871 // We can get here with an alias template when the specialization contains 4872 // a pack expansion that does not match up with a parameter pack. 4873 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4874 "Caller must compute aliased type"); 4875 IsTypeAlias = false; 4876 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4877 } 4878 4879 // Allocate the (non-canonical) template specialization type, but don't 4880 // try to unique it: these types typically have location information that 4881 // we don't unique and don't want to lose. 4882 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4883 sizeof(TemplateArgument) * Args.size() + 4884 (IsTypeAlias? sizeof(QualType) : 0), 4885 TypeAlignment); 4886 auto *Spec 4887 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4888 IsTypeAlias ? Underlying : QualType()); 4889 4890 Types.push_back(Spec); 4891 return QualType(Spec, 0); 4892 } 4893 4894 static bool 4895 getCanonicalTemplateArguments(const ASTContext &C, 4896 ArrayRef<TemplateArgument> OrigArgs, 4897 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4898 bool AnyNonCanonArgs = false; 4899 unsigned NumArgs = OrigArgs.size(); 4900 CanonArgs.resize(NumArgs); 4901 for (unsigned I = 0; I != NumArgs; ++I) { 4902 const TemplateArgument &OrigArg = OrigArgs[I]; 4903 TemplateArgument &CanonArg = CanonArgs[I]; 4904 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4905 if (!CanonArg.structurallyEquals(OrigArg)) 4906 AnyNonCanonArgs = true; 4907 } 4908 return AnyNonCanonArgs; 4909 } 4910 4911 QualType ASTContext::getCanonicalTemplateSpecializationType( 4912 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4913 assert(!Template.getAsDependentTemplateName() && 4914 "No dependent template names here!"); 4915 4916 // Look through qualified template names. 4917 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4918 Template = TemplateName(QTN->getTemplateDecl()); 4919 4920 // Build the canonical template specialization type. 4921 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4922 SmallVector<TemplateArgument, 4> CanonArgs; 4923 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4924 4925 // Determine whether this canonical template specialization type already 4926 // exists. 4927 llvm::FoldingSetNodeID ID; 4928 TemplateSpecializationType::Profile(ID, CanonTemplate, 4929 CanonArgs, *this); 4930 4931 void *InsertPos = nullptr; 4932 TemplateSpecializationType *Spec 4933 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4934 4935 if (!Spec) { 4936 // Allocate a new canonical template specialization type. 4937 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4938 sizeof(TemplateArgument) * CanonArgs.size()), 4939 TypeAlignment); 4940 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4941 CanonArgs, 4942 QualType(), QualType()); 4943 Types.push_back(Spec); 4944 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4945 } 4946 4947 assert(Spec->isDependentType() && 4948 "Non-dependent template-id type must have a canonical type"); 4949 return QualType(Spec, 0); 4950 } 4951 4952 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4953 NestedNameSpecifier *NNS, 4954 QualType NamedType, 4955 TagDecl *OwnedTagDecl) const { 4956 llvm::FoldingSetNodeID ID; 4957 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4958 4959 void *InsertPos = nullptr; 4960 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4961 if (T) 4962 return QualType(T, 0); 4963 4964 QualType Canon = NamedType; 4965 if (!Canon.isCanonical()) { 4966 Canon = getCanonicalType(NamedType); 4967 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4968 assert(!CheckT && "Elaborated canonical type broken"); 4969 (void)CheckT; 4970 } 4971 4972 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4973 TypeAlignment); 4974 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4975 4976 Types.push_back(T); 4977 ElaboratedTypes.InsertNode(T, InsertPos); 4978 return QualType(T, 0); 4979 } 4980 4981 QualType 4982 ASTContext::getParenType(QualType InnerType) const { 4983 llvm::FoldingSetNodeID ID; 4984 ParenType::Profile(ID, InnerType); 4985 4986 void *InsertPos = nullptr; 4987 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4988 if (T) 4989 return QualType(T, 0); 4990 4991 QualType Canon = InnerType; 4992 if (!Canon.isCanonical()) { 4993 Canon = getCanonicalType(InnerType); 4994 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4995 assert(!CheckT && "Paren canonical type broken"); 4996 (void)CheckT; 4997 } 4998 4999 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 5000 Types.push_back(T); 5001 ParenTypes.InsertNode(T, InsertPos); 5002 return QualType(T, 0); 5003 } 5004 5005 QualType 5006 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 5007 const IdentifierInfo *MacroII) const { 5008 QualType Canon = UnderlyingTy; 5009 if (!Canon.isCanonical()) 5010 Canon = getCanonicalType(UnderlyingTy); 5011 5012 auto *newType = new (*this, TypeAlignment) 5013 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 5014 Types.push_back(newType); 5015 return QualType(newType, 0); 5016 } 5017 5018 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 5019 NestedNameSpecifier *NNS, 5020 const IdentifierInfo *Name, 5021 QualType Canon) const { 5022 if (Canon.isNull()) { 5023 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5024 if (CanonNNS != NNS) 5025 Canon = getDependentNameType(Keyword, CanonNNS, Name); 5026 } 5027 5028 llvm::FoldingSetNodeID ID; 5029 DependentNameType::Profile(ID, Keyword, NNS, Name); 5030 5031 void *InsertPos = nullptr; 5032 DependentNameType *T 5033 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5034 if (T) 5035 return QualType(T, 0); 5036 5037 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5038 Types.push_back(T); 5039 DependentNameTypes.InsertNode(T, InsertPos); 5040 return QualType(T, 0); 5041 } 5042 5043 QualType 5044 ASTContext::getDependentTemplateSpecializationType( 5045 ElaboratedTypeKeyword Keyword, 5046 NestedNameSpecifier *NNS, 5047 const IdentifierInfo *Name, 5048 const TemplateArgumentListInfo &Args) const { 5049 // TODO: avoid this copy 5050 SmallVector<TemplateArgument, 16> ArgCopy; 5051 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5052 ArgCopy.push_back(Args[I].getArgument()); 5053 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5054 } 5055 5056 QualType 5057 ASTContext::getDependentTemplateSpecializationType( 5058 ElaboratedTypeKeyword Keyword, 5059 NestedNameSpecifier *NNS, 5060 const IdentifierInfo *Name, 5061 ArrayRef<TemplateArgument> Args) const { 5062 assert((!NNS || NNS->isDependent()) && 5063 "nested-name-specifier must be dependent"); 5064 5065 llvm::FoldingSetNodeID ID; 5066 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5067 Name, Args); 5068 5069 void *InsertPos = nullptr; 5070 DependentTemplateSpecializationType *T 5071 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5072 if (T) 5073 return QualType(T, 0); 5074 5075 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5076 5077 ElaboratedTypeKeyword CanonKeyword = Keyword; 5078 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5079 5080 SmallVector<TemplateArgument, 16> CanonArgs; 5081 bool AnyNonCanonArgs = 5082 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5083 5084 QualType Canon; 5085 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5086 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5087 Name, 5088 CanonArgs); 5089 5090 // Find the insert position again. 5091 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5092 } 5093 5094 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5095 sizeof(TemplateArgument) * Args.size()), 5096 TypeAlignment); 5097 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5098 Name, Args, Canon); 5099 Types.push_back(T); 5100 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5101 return QualType(T, 0); 5102 } 5103 5104 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5105 TemplateArgument Arg; 5106 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5107 QualType ArgType = getTypeDeclType(TTP); 5108 if (TTP->isParameterPack()) 5109 ArgType = getPackExpansionType(ArgType, None); 5110 5111 Arg = TemplateArgument(ArgType); 5112 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5113 QualType T = 5114 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5115 // For class NTTPs, ensure we include the 'const' so the type matches that 5116 // of a real template argument. 5117 // FIXME: It would be more faithful to model this as something like an 5118 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5119 if (T->isRecordType()) 5120 T.addConst(); 5121 Expr *E = new (*this) DeclRefExpr( 5122 *this, NTTP, /*enclosing*/ false, T, 5123 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5124 5125 if (NTTP->isParameterPack()) 5126 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5127 None); 5128 Arg = TemplateArgument(E); 5129 } else { 5130 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5131 if (TTP->isParameterPack()) 5132 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5133 else 5134 Arg = TemplateArgument(TemplateName(TTP)); 5135 } 5136 5137 if (Param->isTemplateParameterPack()) 5138 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5139 5140 return Arg; 5141 } 5142 5143 void 5144 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5145 SmallVectorImpl<TemplateArgument> &Args) { 5146 Args.reserve(Args.size() + Params->size()); 5147 5148 for (NamedDecl *Param : *Params) 5149 Args.push_back(getInjectedTemplateArg(Param)); 5150 } 5151 5152 QualType ASTContext::getPackExpansionType(QualType Pattern, 5153 Optional<unsigned> NumExpansions, 5154 bool ExpectPackInType) { 5155 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5156 "Pack expansions must expand one or more parameter packs"); 5157 5158 llvm::FoldingSetNodeID ID; 5159 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5160 5161 void *InsertPos = nullptr; 5162 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5163 if (T) 5164 return QualType(T, 0); 5165 5166 QualType Canon; 5167 if (!Pattern.isCanonical()) { 5168 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5169 /*ExpectPackInType=*/false); 5170 5171 // Find the insert position again, in case we inserted an element into 5172 // PackExpansionTypes and invalidated our insert position. 5173 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5174 } 5175 5176 T = new (*this, TypeAlignment) 5177 PackExpansionType(Pattern, Canon, NumExpansions); 5178 Types.push_back(T); 5179 PackExpansionTypes.InsertNode(T, InsertPos); 5180 return QualType(T, 0); 5181 } 5182 5183 /// CmpProtocolNames - Comparison predicate for sorting protocols 5184 /// alphabetically. 5185 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5186 ObjCProtocolDecl *const *RHS) { 5187 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5188 } 5189 5190 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5191 if (Protocols.empty()) return true; 5192 5193 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5194 return false; 5195 5196 for (unsigned i = 1; i != Protocols.size(); ++i) 5197 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5198 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5199 return false; 5200 return true; 5201 } 5202 5203 static void 5204 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5205 // Sort protocols, keyed by name. 5206 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5207 5208 // Canonicalize. 5209 for (ObjCProtocolDecl *&P : Protocols) 5210 P = P->getCanonicalDecl(); 5211 5212 // Remove duplicates. 5213 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5214 Protocols.erase(ProtocolsEnd, Protocols.end()); 5215 } 5216 5217 QualType ASTContext::getObjCObjectType(QualType BaseType, 5218 ObjCProtocolDecl * const *Protocols, 5219 unsigned NumProtocols) const { 5220 return getObjCObjectType(BaseType, {}, 5221 llvm::makeArrayRef(Protocols, NumProtocols), 5222 /*isKindOf=*/false); 5223 } 5224 5225 QualType ASTContext::getObjCObjectType( 5226 QualType baseType, 5227 ArrayRef<QualType> typeArgs, 5228 ArrayRef<ObjCProtocolDecl *> protocols, 5229 bool isKindOf) const { 5230 // If the base type is an interface and there aren't any protocols or 5231 // type arguments to add, then the interface type will do just fine. 5232 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5233 isa<ObjCInterfaceType>(baseType)) 5234 return baseType; 5235 5236 // Look in the folding set for an existing type. 5237 llvm::FoldingSetNodeID ID; 5238 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5239 void *InsertPos = nullptr; 5240 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5241 return QualType(QT, 0); 5242 5243 // Determine the type arguments to be used for canonicalization, 5244 // which may be explicitly specified here or written on the base 5245 // type. 5246 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5247 if (effectiveTypeArgs.empty()) { 5248 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5249 effectiveTypeArgs = baseObject->getTypeArgs(); 5250 } 5251 5252 // Build the canonical type, which has the canonical base type and a 5253 // sorted-and-uniqued list of protocols and the type arguments 5254 // canonicalized. 5255 QualType canonical; 5256 bool typeArgsAreCanonical = llvm::all_of( 5257 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5258 bool protocolsSorted = areSortedAndUniqued(protocols); 5259 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5260 // Determine the canonical type arguments. 5261 ArrayRef<QualType> canonTypeArgs; 5262 SmallVector<QualType, 4> canonTypeArgsVec; 5263 if (!typeArgsAreCanonical) { 5264 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5265 for (auto typeArg : effectiveTypeArgs) 5266 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5267 canonTypeArgs = canonTypeArgsVec; 5268 } else { 5269 canonTypeArgs = effectiveTypeArgs; 5270 } 5271 5272 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5273 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5274 if (!protocolsSorted) { 5275 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5276 SortAndUniqueProtocols(canonProtocolsVec); 5277 canonProtocols = canonProtocolsVec; 5278 } else { 5279 canonProtocols = protocols; 5280 } 5281 5282 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5283 canonProtocols, isKindOf); 5284 5285 // Regenerate InsertPos. 5286 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5287 } 5288 5289 unsigned size = sizeof(ObjCObjectTypeImpl); 5290 size += typeArgs.size() * sizeof(QualType); 5291 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5292 void *mem = Allocate(size, TypeAlignment); 5293 auto *T = 5294 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5295 isKindOf); 5296 5297 Types.push_back(T); 5298 ObjCObjectTypes.InsertNode(T, InsertPos); 5299 return QualType(T, 0); 5300 } 5301 5302 /// Apply Objective-C protocol qualifiers to the given type. 5303 /// If this is for the canonical type of a type parameter, we can apply 5304 /// protocol qualifiers on the ObjCObjectPointerType. 5305 QualType 5306 ASTContext::applyObjCProtocolQualifiers(QualType type, 5307 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5308 bool allowOnPointerType) const { 5309 hasError = false; 5310 5311 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5312 return getObjCTypeParamType(objT->getDecl(), protocols); 5313 } 5314 5315 // Apply protocol qualifiers to ObjCObjectPointerType. 5316 if (allowOnPointerType) { 5317 if (const auto *objPtr = 5318 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5319 const ObjCObjectType *objT = objPtr->getObjectType(); 5320 // Merge protocol lists and construct ObjCObjectType. 5321 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5322 protocolsVec.append(objT->qual_begin(), 5323 objT->qual_end()); 5324 protocolsVec.append(protocols.begin(), protocols.end()); 5325 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5326 type = getObjCObjectType( 5327 objT->getBaseType(), 5328 objT->getTypeArgsAsWritten(), 5329 protocols, 5330 objT->isKindOfTypeAsWritten()); 5331 return getObjCObjectPointerType(type); 5332 } 5333 } 5334 5335 // Apply protocol qualifiers to ObjCObjectType. 5336 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5337 // FIXME: Check for protocols to which the class type is already 5338 // known to conform. 5339 5340 return getObjCObjectType(objT->getBaseType(), 5341 objT->getTypeArgsAsWritten(), 5342 protocols, 5343 objT->isKindOfTypeAsWritten()); 5344 } 5345 5346 // If the canonical type is ObjCObjectType, ... 5347 if (type->isObjCObjectType()) { 5348 // Silently overwrite any existing protocol qualifiers. 5349 // TODO: determine whether that's the right thing to do. 5350 5351 // FIXME: Check for protocols to which the class type is already 5352 // known to conform. 5353 return getObjCObjectType(type, {}, protocols, false); 5354 } 5355 5356 // id<protocol-list> 5357 if (type->isObjCIdType()) { 5358 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5359 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5360 objPtr->isKindOfType()); 5361 return getObjCObjectPointerType(type); 5362 } 5363 5364 // Class<protocol-list> 5365 if (type->isObjCClassType()) { 5366 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5367 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5368 objPtr->isKindOfType()); 5369 return getObjCObjectPointerType(type); 5370 } 5371 5372 hasError = true; 5373 return type; 5374 } 5375 5376 QualType 5377 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5378 ArrayRef<ObjCProtocolDecl *> protocols) const { 5379 // Look in the folding set for an existing type. 5380 llvm::FoldingSetNodeID ID; 5381 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5382 void *InsertPos = nullptr; 5383 if (ObjCTypeParamType *TypeParam = 5384 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5385 return QualType(TypeParam, 0); 5386 5387 // We canonicalize to the underlying type. 5388 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5389 if (!protocols.empty()) { 5390 // Apply the protocol qualifers. 5391 bool hasError; 5392 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5393 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5394 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5395 } 5396 5397 unsigned size = sizeof(ObjCTypeParamType); 5398 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5399 void *mem = Allocate(size, TypeAlignment); 5400 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5401 5402 Types.push_back(newType); 5403 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5404 return QualType(newType, 0); 5405 } 5406 5407 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5408 ObjCTypeParamDecl *New) const { 5409 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5410 // Update TypeForDecl after updating TypeSourceInfo. 5411 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5412 SmallVector<ObjCProtocolDecl *, 8> protocols; 5413 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5414 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5415 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5416 } 5417 5418 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5419 /// protocol list adopt all protocols in QT's qualified-id protocol 5420 /// list. 5421 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5422 ObjCInterfaceDecl *IC) { 5423 if (!QT->isObjCQualifiedIdType()) 5424 return false; 5425 5426 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5427 // If both the right and left sides have qualifiers. 5428 for (auto *Proto : OPT->quals()) { 5429 if (!IC->ClassImplementsProtocol(Proto, false)) 5430 return false; 5431 } 5432 return true; 5433 } 5434 return false; 5435 } 5436 5437 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5438 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5439 /// of protocols. 5440 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5441 ObjCInterfaceDecl *IDecl) { 5442 if (!QT->isObjCQualifiedIdType()) 5443 return false; 5444 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5445 if (!OPT) 5446 return false; 5447 if (!IDecl->hasDefinition()) 5448 return false; 5449 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5450 CollectInheritedProtocols(IDecl, InheritedProtocols); 5451 if (InheritedProtocols.empty()) 5452 return false; 5453 // Check that if every protocol in list of id<plist> conforms to a protocol 5454 // of IDecl's, then bridge casting is ok. 5455 bool Conforms = false; 5456 for (auto *Proto : OPT->quals()) { 5457 Conforms = false; 5458 for (auto *PI : InheritedProtocols) { 5459 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5460 Conforms = true; 5461 break; 5462 } 5463 } 5464 if (!Conforms) 5465 break; 5466 } 5467 if (Conforms) 5468 return true; 5469 5470 for (auto *PI : InheritedProtocols) { 5471 // If both the right and left sides have qualifiers. 5472 bool Adopts = false; 5473 for (auto *Proto : OPT->quals()) { 5474 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5475 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5476 break; 5477 } 5478 if (!Adopts) 5479 return false; 5480 } 5481 return true; 5482 } 5483 5484 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5485 /// the given object type. 5486 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5487 llvm::FoldingSetNodeID ID; 5488 ObjCObjectPointerType::Profile(ID, ObjectT); 5489 5490 void *InsertPos = nullptr; 5491 if (ObjCObjectPointerType *QT = 5492 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5493 return QualType(QT, 0); 5494 5495 // Find the canonical object type. 5496 QualType Canonical; 5497 if (!ObjectT.isCanonical()) { 5498 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5499 5500 // Regenerate InsertPos. 5501 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5502 } 5503 5504 // No match. 5505 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5506 auto *QType = 5507 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5508 5509 Types.push_back(QType); 5510 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5511 return QualType(QType, 0); 5512 } 5513 5514 /// getObjCInterfaceType - Return the unique reference to the type for the 5515 /// specified ObjC interface decl. The list of protocols is optional. 5516 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5517 ObjCInterfaceDecl *PrevDecl) const { 5518 if (Decl->TypeForDecl) 5519 return QualType(Decl->TypeForDecl, 0); 5520 5521 if (PrevDecl) { 5522 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5523 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5524 return QualType(PrevDecl->TypeForDecl, 0); 5525 } 5526 5527 // Prefer the definition, if there is one. 5528 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5529 Decl = Def; 5530 5531 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5532 auto *T = new (Mem) ObjCInterfaceType(Decl); 5533 Decl->TypeForDecl = T; 5534 Types.push_back(T); 5535 return QualType(T, 0); 5536 } 5537 5538 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5539 /// TypeOfExprType AST's (since expression's are never shared). For example, 5540 /// multiple declarations that refer to "typeof(x)" all contain different 5541 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5542 /// on canonical type's (which are always unique). 5543 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5544 TypeOfExprType *toe; 5545 if (tofExpr->isTypeDependent()) { 5546 llvm::FoldingSetNodeID ID; 5547 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5548 5549 void *InsertPos = nullptr; 5550 DependentTypeOfExprType *Canon 5551 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5552 if (Canon) { 5553 // We already have a "canonical" version of an identical, dependent 5554 // typeof(expr) type. Use that as our canonical type. 5555 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5556 QualType((TypeOfExprType*)Canon, 0)); 5557 } else { 5558 // Build a new, canonical typeof(expr) type. 5559 Canon 5560 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5561 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5562 toe = Canon; 5563 } 5564 } else { 5565 QualType Canonical = getCanonicalType(tofExpr->getType()); 5566 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5567 } 5568 Types.push_back(toe); 5569 return QualType(toe, 0); 5570 } 5571 5572 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5573 /// TypeOfType nodes. The only motivation to unique these nodes would be 5574 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5575 /// an issue. This doesn't affect the type checker, since it operates 5576 /// on canonical types (which are always unique). 5577 QualType ASTContext::getTypeOfType(QualType tofType) const { 5578 QualType Canonical = getCanonicalType(tofType); 5579 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5580 Types.push_back(tot); 5581 return QualType(tot, 0); 5582 } 5583 5584 /// getReferenceQualifiedType - Given an expr, will return the type for 5585 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5586 /// and class member access into account. 5587 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5588 // C++11 [dcl.type.simple]p4: 5589 // [...] 5590 QualType T = E->getType(); 5591 switch (E->getValueKind()) { 5592 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5593 // type of e; 5594 case VK_XValue: 5595 return getRValueReferenceType(T); 5596 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5597 // type of e; 5598 case VK_LValue: 5599 return getLValueReferenceType(T); 5600 // - otherwise, decltype(e) is the type of e. 5601 case VK_PRValue: 5602 return T; 5603 } 5604 llvm_unreachable("Unknown value kind"); 5605 } 5606 5607 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5608 /// nodes. This would never be helpful, since each such type has its own 5609 /// expression, and would not give a significant memory saving, since there 5610 /// is an Expr tree under each such type. 5611 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5612 DecltypeType *dt; 5613 5614 // C++11 [temp.type]p2: 5615 // If an expression e involves a template parameter, decltype(e) denotes a 5616 // unique dependent type. Two such decltype-specifiers refer to the same 5617 // type only if their expressions are equivalent (14.5.6.1). 5618 if (e->isInstantiationDependent()) { 5619 llvm::FoldingSetNodeID ID; 5620 DependentDecltypeType::Profile(ID, *this, e); 5621 5622 void *InsertPos = nullptr; 5623 DependentDecltypeType *Canon 5624 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5625 if (!Canon) { 5626 // Build a new, canonical decltype(expr) type. 5627 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5628 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5629 } 5630 dt = new (*this, TypeAlignment) 5631 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5632 } else { 5633 dt = new (*this, TypeAlignment) 5634 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5635 } 5636 Types.push_back(dt); 5637 return QualType(dt, 0); 5638 } 5639 5640 /// getUnaryTransformationType - We don't unique these, since the memory 5641 /// savings are minimal and these are rare. 5642 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5643 QualType UnderlyingType, 5644 UnaryTransformType::UTTKind Kind) 5645 const { 5646 UnaryTransformType *ut = nullptr; 5647 5648 if (BaseType->isDependentType()) { 5649 // Look in the folding set for an existing type. 5650 llvm::FoldingSetNodeID ID; 5651 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5652 5653 void *InsertPos = nullptr; 5654 DependentUnaryTransformType *Canon 5655 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5656 5657 if (!Canon) { 5658 // Build a new, canonical __underlying_type(type) type. 5659 Canon = new (*this, TypeAlignment) 5660 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5661 Kind); 5662 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5663 } 5664 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5665 QualType(), Kind, 5666 QualType(Canon, 0)); 5667 } else { 5668 QualType CanonType = getCanonicalType(UnderlyingType); 5669 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5670 UnderlyingType, Kind, 5671 CanonType); 5672 } 5673 Types.push_back(ut); 5674 return QualType(ut, 0); 5675 } 5676 5677 QualType ASTContext::getAutoTypeInternal( 5678 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5679 bool IsPack, ConceptDecl *TypeConstraintConcept, 5680 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5681 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5682 !TypeConstraintConcept && !IsDependent) 5683 return getAutoDeductType(); 5684 5685 // Look in the folding set for an existing type. 5686 void *InsertPos = nullptr; 5687 llvm::FoldingSetNodeID ID; 5688 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5689 TypeConstraintConcept, TypeConstraintArgs); 5690 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5691 return QualType(AT, 0); 5692 5693 QualType Canon; 5694 if (!IsCanon) { 5695 if (DeducedType.isNull()) { 5696 SmallVector<TemplateArgument, 4> CanonArgs; 5697 bool AnyNonCanonArgs = 5698 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5699 if (AnyNonCanonArgs) { 5700 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5701 TypeConstraintConcept, CanonArgs, true); 5702 // Find the insert position again. 5703 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5704 } 5705 } else { 5706 Canon = DeducedType.getCanonicalType(); 5707 } 5708 } 5709 5710 void *Mem = Allocate(sizeof(AutoType) + 5711 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5712 TypeAlignment); 5713 auto *AT = new (Mem) AutoType( 5714 DeducedType, Keyword, 5715 (IsDependent ? TypeDependence::DependentInstantiation 5716 : TypeDependence::None) | 5717 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5718 Canon, TypeConstraintConcept, TypeConstraintArgs); 5719 Types.push_back(AT); 5720 AutoTypes.InsertNode(AT, InsertPos); 5721 return QualType(AT, 0); 5722 } 5723 5724 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5725 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5726 /// canonical deduced-but-dependent 'auto' type. 5727 QualType 5728 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5729 bool IsDependent, bool IsPack, 5730 ConceptDecl *TypeConstraintConcept, 5731 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5732 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5733 assert((!IsDependent || DeducedType.isNull()) && 5734 "A dependent auto should be undeduced"); 5735 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5736 TypeConstraintConcept, TypeConstraintArgs); 5737 } 5738 5739 /// Return the uniqued reference to the deduced template specialization type 5740 /// which has been deduced to the given type, or to the canonical undeduced 5741 /// such type, or the canonical deduced-but-dependent such type. 5742 QualType ASTContext::getDeducedTemplateSpecializationType( 5743 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5744 // Look in the folding set for an existing type. 5745 void *InsertPos = nullptr; 5746 llvm::FoldingSetNodeID ID; 5747 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5748 IsDependent); 5749 if (DeducedTemplateSpecializationType *DTST = 5750 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5751 return QualType(DTST, 0); 5752 5753 auto *DTST = new (*this, TypeAlignment) 5754 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5755 llvm::FoldingSetNodeID TempID; 5756 DTST->Profile(TempID); 5757 assert(ID == TempID && "ID does not match"); 5758 Types.push_back(DTST); 5759 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5760 return QualType(DTST, 0); 5761 } 5762 5763 /// getAtomicType - Return the uniqued reference to the atomic type for 5764 /// the given value type. 5765 QualType ASTContext::getAtomicType(QualType T) const { 5766 // Unique pointers, to guarantee there is only one pointer of a particular 5767 // structure. 5768 llvm::FoldingSetNodeID ID; 5769 AtomicType::Profile(ID, T); 5770 5771 void *InsertPos = nullptr; 5772 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5773 return QualType(AT, 0); 5774 5775 // If the atomic value type isn't canonical, this won't be a canonical type 5776 // either, so fill in the canonical type field. 5777 QualType Canonical; 5778 if (!T.isCanonical()) { 5779 Canonical = getAtomicType(getCanonicalType(T)); 5780 5781 // Get the new insert position for the node we care about. 5782 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5783 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5784 } 5785 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5786 Types.push_back(New); 5787 AtomicTypes.InsertNode(New, InsertPos); 5788 return QualType(New, 0); 5789 } 5790 5791 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5792 QualType ASTContext::getAutoDeductType() const { 5793 if (AutoDeductTy.isNull()) 5794 AutoDeductTy = QualType(new (*this, TypeAlignment) 5795 AutoType(QualType(), AutoTypeKeyword::Auto, 5796 TypeDependence::None, QualType(), 5797 /*concept*/ nullptr, /*args*/ {}), 5798 0); 5799 return AutoDeductTy; 5800 } 5801 5802 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5803 QualType ASTContext::getAutoRRefDeductType() const { 5804 if (AutoRRefDeductTy.isNull()) 5805 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5806 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5807 return AutoRRefDeductTy; 5808 } 5809 5810 /// getTagDeclType - Return the unique reference to the type for the 5811 /// specified TagDecl (struct/union/class/enum) decl. 5812 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5813 assert(Decl); 5814 // FIXME: What is the design on getTagDeclType when it requires casting 5815 // away const? mutable? 5816 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5817 } 5818 5819 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5820 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5821 /// needs to agree with the definition in <stddef.h>. 5822 CanQualType ASTContext::getSizeType() const { 5823 return getFromTargetType(Target->getSizeType()); 5824 } 5825 5826 /// Return the unique signed counterpart of the integer type 5827 /// corresponding to size_t. 5828 CanQualType ASTContext::getSignedSizeType() const { 5829 return getFromTargetType(Target->getSignedSizeType()); 5830 } 5831 5832 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5833 CanQualType ASTContext::getIntMaxType() const { 5834 return getFromTargetType(Target->getIntMaxType()); 5835 } 5836 5837 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5838 CanQualType ASTContext::getUIntMaxType() const { 5839 return getFromTargetType(Target->getUIntMaxType()); 5840 } 5841 5842 /// getSignedWCharType - Return the type of "signed wchar_t". 5843 /// Used when in C++, as a GCC extension. 5844 QualType ASTContext::getSignedWCharType() const { 5845 // FIXME: derive from "Target" ? 5846 return WCharTy; 5847 } 5848 5849 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5850 /// Used when in C++, as a GCC extension. 5851 QualType ASTContext::getUnsignedWCharType() const { 5852 // FIXME: derive from "Target" ? 5853 return UnsignedIntTy; 5854 } 5855 5856 QualType ASTContext::getIntPtrType() const { 5857 return getFromTargetType(Target->getIntPtrType()); 5858 } 5859 5860 QualType ASTContext::getUIntPtrType() const { 5861 return getCorrespondingUnsignedType(getIntPtrType()); 5862 } 5863 5864 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5865 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5866 QualType ASTContext::getPointerDiffType() const { 5867 return getFromTargetType(Target->getPtrDiffType(0)); 5868 } 5869 5870 /// Return the unique unsigned counterpart of "ptrdiff_t" 5871 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5872 /// in the definition of %tu format specifier. 5873 QualType ASTContext::getUnsignedPointerDiffType() const { 5874 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5875 } 5876 5877 /// Return the unique type for "pid_t" defined in 5878 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5879 QualType ASTContext::getProcessIDType() const { 5880 return getFromTargetType(Target->getProcessIDType()); 5881 } 5882 5883 //===----------------------------------------------------------------------===// 5884 // Type Operators 5885 //===----------------------------------------------------------------------===// 5886 5887 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5888 // Push qualifiers into arrays, and then discard any remaining 5889 // qualifiers. 5890 T = getCanonicalType(T); 5891 T = getVariableArrayDecayedType(T); 5892 const Type *Ty = T.getTypePtr(); 5893 QualType Result; 5894 if (isa<ArrayType>(Ty)) { 5895 Result = getArrayDecayedType(QualType(Ty,0)); 5896 } else if (isa<FunctionType>(Ty)) { 5897 Result = getPointerType(QualType(Ty, 0)); 5898 } else { 5899 Result = QualType(Ty, 0); 5900 } 5901 5902 return CanQualType::CreateUnsafe(Result); 5903 } 5904 5905 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5906 Qualifiers &quals) { 5907 SplitQualType splitType = type.getSplitUnqualifiedType(); 5908 5909 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5910 // the unqualified desugared type and then drops it on the floor. 5911 // We then have to strip that sugar back off with 5912 // getUnqualifiedDesugaredType(), which is silly. 5913 const auto *AT = 5914 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5915 5916 // If we don't have an array, just use the results in splitType. 5917 if (!AT) { 5918 quals = splitType.Quals; 5919 return QualType(splitType.Ty, 0); 5920 } 5921 5922 // Otherwise, recurse on the array's element type. 5923 QualType elementType = AT->getElementType(); 5924 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5925 5926 // If that didn't change the element type, AT has no qualifiers, so we 5927 // can just use the results in splitType. 5928 if (elementType == unqualElementType) { 5929 assert(quals.empty()); // from the recursive call 5930 quals = splitType.Quals; 5931 return QualType(splitType.Ty, 0); 5932 } 5933 5934 // Otherwise, add in the qualifiers from the outermost type, then 5935 // build the type back up. 5936 quals.addConsistentQualifiers(splitType.Quals); 5937 5938 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5939 return getConstantArrayType(unqualElementType, CAT->getSize(), 5940 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5941 } 5942 5943 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5944 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5945 } 5946 5947 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5948 return getVariableArrayType(unqualElementType, 5949 VAT->getSizeExpr(), 5950 VAT->getSizeModifier(), 5951 VAT->getIndexTypeCVRQualifiers(), 5952 VAT->getBracketsRange()); 5953 } 5954 5955 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5956 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5957 DSAT->getSizeModifier(), 0, 5958 SourceRange()); 5959 } 5960 5961 /// Attempt to unwrap two types that may both be array types with the same bound 5962 /// (or both be array types of unknown bound) for the purpose of comparing the 5963 /// cv-decomposition of two types per C++ [conv.qual]. 5964 /// 5965 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5966 /// C++20 [conv.qual], if permitted by the current language mode. 5967 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5968 bool AllowPiMismatch) { 5969 while (true) { 5970 auto *AT1 = getAsArrayType(T1); 5971 if (!AT1) 5972 return; 5973 5974 auto *AT2 = getAsArrayType(T2); 5975 if (!AT2) 5976 return; 5977 5978 // If we don't have two array types with the same constant bound nor two 5979 // incomplete array types, we've unwrapped everything we can. 5980 // C++20 also permits one type to be a constant array type and the other 5981 // to be an incomplete array type. 5982 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5983 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5984 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5985 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 5986 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5987 isa<IncompleteArrayType>(AT2)))) 5988 return; 5989 } else if (isa<IncompleteArrayType>(AT1)) { 5990 if (!(isa<IncompleteArrayType>(AT2) || 5991 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5992 isa<ConstantArrayType>(AT2)))) 5993 return; 5994 } else { 5995 return; 5996 } 5997 5998 T1 = AT1->getElementType(); 5999 T2 = AT2->getElementType(); 6000 } 6001 } 6002 6003 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 6004 /// 6005 /// If T1 and T2 are both pointer types of the same kind, or both array types 6006 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 6007 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 6008 /// 6009 /// This function will typically be called in a loop that successively 6010 /// "unwraps" pointer and pointer-to-member types to compare them at each 6011 /// level. 6012 /// 6013 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6014 /// C++20 [conv.qual], if permitted by the current language mode. 6015 /// 6016 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 6017 /// pair of types that can't be unwrapped further. 6018 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 6019 bool AllowPiMismatch) { 6020 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 6021 6022 const auto *T1PtrType = T1->getAs<PointerType>(); 6023 const auto *T2PtrType = T2->getAs<PointerType>(); 6024 if (T1PtrType && T2PtrType) { 6025 T1 = T1PtrType->getPointeeType(); 6026 T2 = T2PtrType->getPointeeType(); 6027 return true; 6028 } 6029 6030 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6031 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6032 if (T1MPType && T2MPType && 6033 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6034 QualType(T2MPType->getClass(), 0))) { 6035 T1 = T1MPType->getPointeeType(); 6036 T2 = T2MPType->getPointeeType(); 6037 return true; 6038 } 6039 6040 if (getLangOpts().ObjC) { 6041 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6042 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6043 if (T1OPType && T2OPType) { 6044 T1 = T1OPType->getPointeeType(); 6045 T2 = T2OPType->getPointeeType(); 6046 return true; 6047 } 6048 } 6049 6050 // FIXME: Block pointers, too? 6051 6052 return false; 6053 } 6054 6055 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6056 while (true) { 6057 Qualifiers Quals; 6058 T1 = getUnqualifiedArrayType(T1, Quals); 6059 T2 = getUnqualifiedArrayType(T2, Quals); 6060 if (hasSameType(T1, T2)) 6061 return true; 6062 if (!UnwrapSimilarTypes(T1, T2)) 6063 return false; 6064 } 6065 } 6066 6067 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6068 while (true) { 6069 Qualifiers Quals1, Quals2; 6070 T1 = getUnqualifiedArrayType(T1, Quals1); 6071 T2 = getUnqualifiedArrayType(T2, Quals2); 6072 6073 Quals1.removeCVRQualifiers(); 6074 Quals2.removeCVRQualifiers(); 6075 if (Quals1 != Quals2) 6076 return false; 6077 6078 if (hasSameType(T1, T2)) 6079 return true; 6080 6081 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6082 return false; 6083 } 6084 } 6085 6086 DeclarationNameInfo 6087 ASTContext::getNameForTemplate(TemplateName Name, 6088 SourceLocation NameLoc) const { 6089 switch (Name.getKind()) { 6090 case TemplateName::QualifiedTemplate: 6091 case TemplateName::Template: 6092 // DNInfo work in progress: CHECKME: what about DNLoc? 6093 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6094 NameLoc); 6095 6096 case TemplateName::OverloadedTemplate: { 6097 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6098 // DNInfo work in progress: CHECKME: what about DNLoc? 6099 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6100 } 6101 6102 case TemplateName::AssumedTemplate: { 6103 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6104 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6105 } 6106 6107 case TemplateName::DependentTemplate: { 6108 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6109 DeclarationName DName; 6110 if (DTN->isIdentifier()) { 6111 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6112 return DeclarationNameInfo(DName, NameLoc); 6113 } else { 6114 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6115 // DNInfo work in progress: FIXME: source locations? 6116 DeclarationNameLoc DNLoc = 6117 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6118 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6119 } 6120 } 6121 6122 case TemplateName::SubstTemplateTemplateParm: { 6123 SubstTemplateTemplateParmStorage *subst 6124 = Name.getAsSubstTemplateTemplateParm(); 6125 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6126 NameLoc); 6127 } 6128 6129 case TemplateName::SubstTemplateTemplateParmPack: { 6130 SubstTemplateTemplateParmPackStorage *subst 6131 = Name.getAsSubstTemplateTemplateParmPack(); 6132 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6133 NameLoc); 6134 } 6135 case TemplateName::UsingTemplate: 6136 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(), 6137 NameLoc); 6138 } 6139 6140 llvm_unreachable("bad template name kind!"); 6141 } 6142 6143 TemplateName 6144 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6145 switch (Name.getKind()) { 6146 case TemplateName::UsingTemplate: 6147 case TemplateName::QualifiedTemplate: 6148 case TemplateName::Template: { 6149 TemplateDecl *Template = Name.getAsTemplateDecl(); 6150 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6151 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6152 6153 // The canonical template name is the canonical template declaration. 6154 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6155 } 6156 6157 case TemplateName::OverloadedTemplate: 6158 case TemplateName::AssumedTemplate: 6159 llvm_unreachable("cannot canonicalize unresolved template"); 6160 6161 case TemplateName::DependentTemplate: { 6162 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6163 assert(DTN && "Non-dependent template names must refer to template decls."); 6164 return DTN->CanonicalTemplateName; 6165 } 6166 6167 case TemplateName::SubstTemplateTemplateParm: { 6168 SubstTemplateTemplateParmStorage *subst 6169 = Name.getAsSubstTemplateTemplateParm(); 6170 return getCanonicalTemplateName(subst->getReplacement()); 6171 } 6172 6173 case TemplateName::SubstTemplateTemplateParmPack: { 6174 SubstTemplateTemplateParmPackStorage *subst 6175 = Name.getAsSubstTemplateTemplateParmPack(); 6176 TemplateTemplateParmDecl *canonParameter 6177 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6178 TemplateArgument canonArgPack 6179 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6180 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6181 } 6182 } 6183 6184 llvm_unreachable("bad template name!"); 6185 } 6186 6187 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6188 const TemplateName &Y) const { 6189 return getCanonicalTemplateName(X).getAsVoidPointer() == 6190 getCanonicalTemplateName(Y).getAsVoidPointer(); 6191 } 6192 6193 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6194 const NamedDecl *Y) { 6195 if (X->getKind() != Y->getKind()) 6196 return false; 6197 6198 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6199 auto *TY = cast<TemplateTypeParmDecl>(Y); 6200 if (TX->isParameterPack() != TY->isParameterPack()) 6201 return false; 6202 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6203 return false; 6204 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6205 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6206 if (!TXTC != !TYTC) 6207 return false; 6208 if (TXTC && TYTC) { 6209 auto *NCX = TXTC->getNamedConcept(); 6210 auto *NCY = TYTC->getNamedConcept(); 6211 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6212 return false; 6213 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6214 return false; 6215 if (TXTC->hasExplicitTemplateArgs()) { 6216 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6217 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6218 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6219 return false; 6220 llvm::FoldingSetNodeID XID, YID; 6221 for (auto &ArgLoc : TXTCArgs->arguments()) 6222 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6223 for (auto &ArgLoc : TYTCArgs->arguments()) 6224 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6225 if (XID != YID) 6226 return false; 6227 } 6228 } 6229 return true; 6230 } 6231 6232 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6233 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6234 return TX->isParameterPack() == TY->isParameterPack() && 6235 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6236 } 6237 6238 auto *TX = cast<TemplateTemplateParmDecl>(X); 6239 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6240 return TX->isParameterPack() == TY->isParameterPack() && 6241 isSameTemplateParameterList(TX->getTemplateParameters(), 6242 TY->getTemplateParameters()); 6243 } 6244 6245 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6246 const TemplateParameterList *Y) { 6247 if (X->size() != Y->size()) 6248 return false; 6249 6250 for (unsigned I = 0, N = X->size(); I != N; ++I) 6251 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6252 return false; 6253 6254 const Expr *XRC = X->getRequiresClause(); 6255 const Expr *YRC = Y->getRequiresClause(); 6256 if (!XRC != !YRC) 6257 return false; 6258 if (XRC) { 6259 llvm::FoldingSetNodeID XRCID, YRCID; 6260 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6261 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6262 if (XRCID != YRCID) 6263 return false; 6264 } 6265 6266 return true; 6267 } 6268 6269 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6270 if (auto *NS = X->getAsNamespace()) 6271 return NS; 6272 if (auto *NAS = X->getAsNamespaceAlias()) 6273 return NAS->getNamespace(); 6274 return nullptr; 6275 } 6276 6277 static bool isSameQualifier(const NestedNameSpecifier *X, 6278 const NestedNameSpecifier *Y) { 6279 if (auto *NSX = getNamespace(X)) { 6280 auto *NSY = getNamespace(Y); 6281 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6282 return false; 6283 } else if (X->getKind() != Y->getKind()) 6284 return false; 6285 6286 // FIXME: For namespaces and types, we're permitted to check that the entity 6287 // is named via the same tokens. We should probably do so. 6288 switch (X->getKind()) { 6289 case NestedNameSpecifier::Identifier: 6290 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6291 return false; 6292 break; 6293 case NestedNameSpecifier::Namespace: 6294 case NestedNameSpecifier::NamespaceAlias: 6295 // We've already checked that we named the same namespace. 6296 break; 6297 case NestedNameSpecifier::TypeSpec: 6298 case NestedNameSpecifier::TypeSpecWithTemplate: 6299 if (X->getAsType()->getCanonicalTypeInternal() != 6300 Y->getAsType()->getCanonicalTypeInternal()) 6301 return false; 6302 break; 6303 case NestedNameSpecifier::Global: 6304 case NestedNameSpecifier::Super: 6305 return true; 6306 } 6307 6308 // Recurse into earlier portion of NNS, if any. 6309 auto *PX = X->getPrefix(); 6310 auto *PY = Y->getPrefix(); 6311 if (PX && PY) 6312 return isSameQualifier(PX, PY); 6313 return !PX && !PY; 6314 } 6315 6316 /// Determine whether the attributes we can overload on are identical for A and 6317 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6318 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6319 const FunctionDecl *B) { 6320 // Note that pass_object_size attributes are represented in the function's 6321 // ExtParameterInfo, so we don't need to check them here. 6322 6323 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6324 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6325 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6326 6327 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6328 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6329 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6330 6331 // Return false if the number of enable_if attributes is different. 6332 if (!Cand1A || !Cand2A) 6333 return false; 6334 6335 Cand1ID.clear(); 6336 Cand2ID.clear(); 6337 6338 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6339 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6340 6341 // Return false if any of the enable_if expressions of A and B are 6342 // different. 6343 if (Cand1ID != Cand2ID) 6344 return false; 6345 } 6346 return true; 6347 } 6348 6349 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6350 if (X == Y) 6351 return true; 6352 6353 if (X->getDeclName() != Y->getDeclName()) 6354 return false; 6355 6356 // Must be in the same context. 6357 // 6358 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6359 // could be two different declarations of the same function. (We will fix the 6360 // semantic DC to refer to the primary definition after merging.) 6361 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6362 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6363 return false; 6364 6365 // Two typedefs refer to the same entity if they have the same underlying 6366 // type. 6367 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6368 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6369 return hasSameType(TypedefX->getUnderlyingType(), 6370 TypedefY->getUnderlyingType()); 6371 6372 // Must have the same kind. 6373 if (X->getKind() != Y->getKind()) 6374 return false; 6375 6376 // Objective-C classes and protocols with the same name always match. 6377 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6378 return true; 6379 6380 if (isa<ClassTemplateSpecializationDecl>(X)) { 6381 // No need to handle these here: we merge them when adding them to the 6382 // template. 6383 return false; 6384 } 6385 6386 // Compatible tags match. 6387 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6388 const auto *TagY = cast<TagDecl>(Y); 6389 return (TagX->getTagKind() == TagY->getTagKind()) || 6390 ((TagX->getTagKind() == TTK_Struct || 6391 TagX->getTagKind() == TTK_Class || 6392 TagX->getTagKind() == TTK_Interface) && 6393 (TagY->getTagKind() == TTK_Struct || 6394 TagY->getTagKind() == TTK_Class || 6395 TagY->getTagKind() == TTK_Interface)); 6396 } 6397 6398 // Functions with the same type and linkage match. 6399 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6400 // functions, etc. 6401 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6402 const auto *FuncY = cast<FunctionDecl>(Y); 6403 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6404 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6405 if (CtorX->getInheritedConstructor() && 6406 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6407 CtorY->getInheritedConstructor().getConstructor())) 6408 return false; 6409 } 6410 6411 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6412 return false; 6413 6414 // Multiversioned functions with different feature strings are represented 6415 // as separate declarations. 6416 if (FuncX->isMultiVersion()) { 6417 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6418 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6419 assert(TAX && TAY && "Multiversion Function without target attribute"); 6420 6421 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6422 return false; 6423 } 6424 6425 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6426 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6427 if (!XRC != !YRC) 6428 return false; 6429 if (XRC) { 6430 llvm::FoldingSetNodeID XRCID, YRCID; 6431 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6432 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6433 if (XRCID != YRCID) 6434 return false; 6435 } 6436 6437 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6438 // Map to the first declaration that we've already merged into this one. 6439 // The TSI of redeclarations might not match (due to calling conventions 6440 // being inherited onto the type but not the TSI), but the TSI type of 6441 // the first declaration of the function should match across modules. 6442 FD = FD->getCanonicalDecl(); 6443 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6444 : FD->getType(); 6445 }; 6446 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6447 if (!hasSameType(XT, YT)) { 6448 // We can get functions with different types on the redecl chain in C++17 6449 // if they have differing exception specifications and at least one of 6450 // the excpetion specs is unresolved. 6451 auto *XFPT = XT->getAs<FunctionProtoType>(); 6452 auto *YFPT = YT->getAs<FunctionProtoType>(); 6453 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6454 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6455 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6456 // FIXME: We could make isSameEntity const after we make 6457 // hasSameFunctionTypeIgnoringExceptionSpec const. 6458 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6459 return true; 6460 return false; 6461 } 6462 6463 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6464 hasSameOverloadableAttrs(FuncX, FuncY); 6465 } 6466 6467 // Variables with the same type and linkage match. 6468 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6469 const auto *VarY = cast<VarDecl>(Y); 6470 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6471 if (hasSameType(VarX->getType(), VarY->getType())) 6472 return true; 6473 6474 // We can get decls with different types on the redecl chain. Eg. 6475 // template <typename T> struct S { static T Var[]; }; // #1 6476 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6477 // Only? happens when completing an incomplete array type. In this case 6478 // when comparing #1 and #2 we should go through their element type. 6479 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6480 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6481 if (!VarXTy || !VarYTy) 6482 return false; 6483 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6484 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6485 } 6486 return false; 6487 } 6488 6489 // Namespaces with the same name and inlinedness match. 6490 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6491 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6492 return NamespaceX->isInline() == NamespaceY->isInline(); 6493 } 6494 6495 // Identical template names and kinds match if their template parameter lists 6496 // and patterns match. 6497 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6498 const auto *TemplateY = cast<TemplateDecl>(Y); 6499 return isSameEntity(TemplateX->getTemplatedDecl(), 6500 TemplateY->getTemplatedDecl()) && 6501 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6502 TemplateY->getTemplateParameters()); 6503 } 6504 6505 // Fields with the same name and the same type match. 6506 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6507 const auto *FDY = cast<FieldDecl>(Y); 6508 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6509 return hasSameType(FDX->getType(), FDY->getType()); 6510 } 6511 6512 // Indirect fields with the same target field match. 6513 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6514 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6515 return IFDX->getAnonField()->getCanonicalDecl() == 6516 IFDY->getAnonField()->getCanonicalDecl(); 6517 } 6518 6519 // Enumerators with the same name match. 6520 if (isa<EnumConstantDecl>(X)) 6521 // FIXME: Also check the value is odr-equivalent. 6522 return true; 6523 6524 // Using shadow declarations with the same target match. 6525 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6526 const auto *USY = cast<UsingShadowDecl>(Y); 6527 return USX->getTargetDecl() == USY->getTargetDecl(); 6528 } 6529 6530 // Using declarations with the same qualifier match. (We already know that 6531 // the name matches.) 6532 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6533 const auto *UY = cast<UsingDecl>(Y); 6534 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6535 UX->hasTypename() == UY->hasTypename() && 6536 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6537 } 6538 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6539 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6540 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6541 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6542 } 6543 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6544 return isSameQualifier( 6545 UX->getQualifier(), 6546 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6547 } 6548 6549 // Using-pack declarations are only created by instantiation, and match if 6550 // they're instantiated from matching UnresolvedUsing...Decls. 6551 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6552 return declaresSameEntity( 6553 UX->getInstantiatedFromUsingDecl(), 6554 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6555 } 6556 6557 // Namespace alias definitions with the same target match. 6558 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6559 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6560 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6561 } 6562 6563 return false; 6564 } 6565 6566 TemplateArgument 6567 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6568 switch (Arg.getKind()) { 6569 case TemplateArgument::Null: 6570 return Arg; 6571 6572 case TemplateArgument::Expression: 6573 return Arg; 6574 6575 case TemplateArgument::Declaration: { 6576 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6577 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6578 } 6579 6580 case TemplateArgument::NullPtr: 6581 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6582 /*isNullPtr*/true); 6583 6584 case TemplateArgument::Template: 6585 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6586 6587 case TemplateArgument::TemplateExpansion: 6588 return TemplateArgument(getCanonicalTemplateName( 6589 Arg.getAsTemplateOrTemplatePattern()), 6590 Arg.getNumTemplateExpansions()); 6591 6592 case TemplateArgument::Integral: 6593 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6594 6595 case TemplateArgument::Type: 6596 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6597 6598 case TemplateArgument::Pack: { 6599 if (Arg.pack_size() == 0) 6600 return Arg; 6601 6602 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6603 unsigned Idx = 0; 6604 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6605 AEnd = Arg.pack_end(); 6606 A != AEnd; (void)++A, ++Idx) 6607 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6608 6609 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6610 } 6611 } 6612 6613 // Silence GCC warning 6614 llvm_unreachable("Unhandled template argument kind"); 6615 } 6616 6617 NestedNameSpecifier * 6618 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6619 if (!NNS) 6620 return nullptr; 6621 6622 switch (NNS->getKind()) { 6623 case NestedNameSpecifier::Identifier: 6624 // Canonicalize the prefix but keep the identifier the same. 6625 return NestedNameSpecifier::Create(*this, 6626 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6627 NNS->getAsIdentifier()); 6628 6629 case NestedNameSpecifier::Namespace: 6630 // A namespace is canonical; build a nested-name-specifier with 6631 // this namespace and no prefix. 6632 return NestedNameSpecifier::Create(*this, nullptr, 6633 NNS->getAsNamespace()->getOriginalNamespace()); 6634 6635 case NestedNameSpecifier::NamespaceAlias: 6636 // A namespace is canonical; build a nested-name-specifier with 6637 // this namespace and no prefix. 6638 return NestedNameSpecifier::Create(*this, nullptr, 6639 NNS->getAsNamespaceAlias()->getNamespace() 6640 ->getOriginalNamespace()); 6641 6642 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6643 // latter will have the 'template' keyword when printed. 6644 case NestedNameSpecifier::TypeSpec: 6645 case NestedNameSpecifier::TypeSpecWithTemplate: { 6646 const Type *T = getCanonicalType(NNS->getAsType()); 6647 6648 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6649 // break it apart into its prefix and identifier, then reconsititute those 6650 // as the canonical nested-name-specifier. This is required to canonicalize 6651 // a dependent nested-name-specifier involving typedefs of dependent-name 6652 // types, e.g., 6653 // typedef typename T::type T1; 6654 // typedef typename T1::type T2; 6655 if (const auto *DNT = T->getAs<DependentNameType>()) 6656 return NestedNameSpecifier::Create( 6657 *this, DNT->getQualifier(), 6658 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6659 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6660 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6661 const_cast<Type *>(T)); 6662 6663 // TODO: Set 'Template' parameter to true for other template types. 6664 return NestedNameSpecifier::Create(*this, nullptr, false, 6665 const_cast<Type *>(T)); 6666 } 6667 6668 case NestedNameSpecifier::Global: 6669 case NestedNameSpecifier::Super: 6670 // The global specifier and __super specifer are canonical and unique. 6671 return NNS; 6672 } 6673 6674 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6675 } 6676 6677 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6678 // Handle the non-qualified case efficiently. 6679 if (!T.hasLocalQualifiers()) { 6680 // Handle the common positive case fast. 6681 if (const auto *AT = dyn_cast<ArrayType>(T)) 6682 return AT; 6683 } 6684 6685 // Handle the common negative case fast. 6686 if (!isa<ArrayType>(T.getCanonicalType())) 6687 return nullptr; 6688 6689 // Apply any qualifiers from the array type to the element type. This 6690 // implements C99 6.7.3p8: "If the specification of an array type includes 6691 // any type qualifiers, the element type is so qualified, not the array type." 6692 6693 // If we get here, we either have type qualifiers on the type, or we have 6694 // sugar such as a typedef in the way. If we have type qualifiers on the type 6695 // we must propagate them down into the element type. 6696 6697 SplitQualType split = T.getSplitDesugaredType(); 6698 Qualifiers qs = split.Quals; 6699 6700 // If we have a simple case, just return now. 6701 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6702 if (!ATy || qs.empty()) 6703 return ATy; 6704 6705 // Otherwise, we have an array and we have qualifiers on it. Push the 6706 // qualifiers into the array element type and return a new array type. 6707 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6708 6709 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6710 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6711 CAT->getSizeExpr(), 6712 CAT->getSizeModifier(), 6713 CAT->getIndexTypeCVRQualifiers())); 6714 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6715 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6716 IAT->getSizeModifier(), 6717 IAT->getIndexTypeCVRQualifiers())); 6718 6719 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6720 return cast<ArrayType>( 6721 getDependentSizedArrayType(NewEltTy, 6722 DSAT->getSizeExpr(), 6723 DSAT->getSizeModifier(), 6724 DSAT->getIndexTypeCVRQualifiers(), 6725 DSAT->getBracketsRange())); 6726 6727 const auto *VAT = cast<VariableArrayType>(ATy); 6728 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6729 VAT->getSizeExpr(), 6730 VAT->getSizeModifier(), 6731 VAT->getIndexTypeCVRQualifiers(), 6732 VAT->getBracketsRange())); 6733 } 6734 6735 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6736 if (T->isArrayType() || T->isFunctionType()) 6737 return getDecayedType(T); 6738 return T; 6739 } 6740 6741 QualType ASTContext::getSignatureParameterType(QualType T) const { 6742 T = getVariableArrayDecayedType(T); 6743 T = getAdjustedParameterType(T); 6744 return T.getUnqualifiedType(); 6745 } 6746 6747 QualType ASTContext::getExceptionObjectType(QualType T) const { 6748 // C++ [except.throw]p3: 6749 // A throw-expression initializes a temporary object, called the exception 6750 // object, the type of which is determined by removing any top-level 6751 // cv-qualifiers from the static type of the operand of throw and adjusting 6752 // the type from "array of T" or "function returning T" to "pointer to T" 6753 // or "pointer to function returning T", [...] 6754 T = getVariableArrayDecayedType(T); 6755 if (T->isArrayType() || T->isFunctionType()) 6756 T = getDecayedType(T); 6757 return T.getUnqualifiedType(); 6758 } 6759 6760 /// getArrayDecayedType - Return the properly qualified result of decaying the 6761 /// specified array type to a pointer. This operation is non-trivial when 6762 /// handling typedefs etc. The canonical type of "T" must be an array type, 6763 /// this returns a pointer to a properly qualified element of the array. 6764 /// 6765 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6766 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6767 // Get the element type with 'getAsArrayType' so that we don't lose any 6768 // typedefs in the element type of the array. This also handles propagation 6769 // of type qualifiers from the array type into the element type if present 6770 // (C99 6.7.3p8). 6771 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6772 assert(PrettyArrayType && "Not an array type!"); 6773 6774 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6775 6776 // int x[restrict 4] -> int *restrict 6777 QualType Result = getQualifiedType(PtrTy, 6778 PrettyArrayType->getIndexTypeQualifiers()); 6779 6780 // int x[_Nullable] -> int * _Nullable 6781 if (auto Nullability = Ty->getNullability(*this)) { 6782 Result = const_cast<ASTContext *>(this)->getAttributedType( 6783 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6784 } 6785 return Result; 6786 } 6787 6788 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6789 return getBaseElementType(array->getElementType()); 6790 } 6791 6792 QualType ASTContext::getBaseElementType(QualType type) const { 6793 Qualifiers qs; 6794 while (true) { 6795 SplitQualType split = type.getSplitDesugaredType(); 6796 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6797 if (!array) break; 6798 6799 type = array->getElementType(); 6800 qs.addConsistentQualifiers(split.Quals); 6801 } 6802 6803 return getQualifiedType(type, qs); 6804 } 6805 6806 /// getConstantArrayElementCount - Returns number of constant array elements. 6807 uint64_t 6808 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6809 uint64_t ElementCount = 1; 6810 do { 6811 ElementCount *= CA->getSize().getZExtValue(); 6812 CA = dyn_cast_or_null<ConstantArrayType>( 6813 CA->getElementType()->getAsArrayTypeUnsafe()); 6814 } while (CA); 6815 return ElementCount; 6816 } 6817 6818 /// getFloatingRank - Return a relative rank for floating point types. 6819 /// This routine will assert if passed a built-in type that isn't a float. 6820 static FloatingRank getFloatingRank(QualType T) { 6821 if (const auto *CT = T->getAs<ComplexType>()) 6822 return getFloatingRank(CT->getElementType()); 6823 6824 switch (T->castAs<BuiltinType>()->getKind()) { 6825 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6826 case BuiltinType::Float16: return Float16Rank; 6827 case BuiltinType::Half: return HalfRank; 6828 case BuiltinType::Float: return FloatRank; 6829 case BuiltinType::Double: return DoubleRank; 6830 case BuiltinType::LongDouble: return LongDoubleRank; 6831 case BuiltinType::Float128: return Float128Rank; 6832 case BuiltinType::BFloat16: return BFloat16Rank; 6833 case BuiltinType::Ibm128: return Ibm128Rank; 6834 } 6835 } 6836 6837 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6838 /// point types, ignoring the domain of the type (i.e. 'double' == 6839 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6840 /// LHS < RHS, return -1. 6841 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6842 FloatingRank LHSR = getFloatingRank(LHS); 6843 FloatingRank RHSR = getFloatingRank(RHS); 6844 6845 if (LHSR == RHSR) 6846 return 0; 6847 if (LHSR > RHSR) 6848 return 1; 6849 return -1; 6850 } 6851 6852 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6853 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6854 return 0; 6855 return getFloatingTypeOrder(LHS, RHS); 6856 } 6857 6858 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6859 /// routine will assert if passed a built-in type that isn't an integer or enum, 6860 /// or if it is not canonicalized. 6861 unsigned ASTContext::getIntegerRank(const Type *T) const { 6862 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6863 6864 // Results in this 'losing' to any type of the same size, but winning if 6865 // larger. 6866 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6867 return 0 + (EIT->getNumBits() << 3); 6868 6869 switch (cast<BuiltinType>(T)->getKind()) { 6870 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6871 case BuiltinType::Bool: 6872 return 1 + (getIntWidth(BoolTy) << 3); 6873 case BuiltinType::Char_S: 6874 case BuiltinType::Char_U: 6875 case BuiltinType::SChar: 6876 case BuiltinType::UChar: 6877 return 2 + (getIntWidth(CharTy) << 3); 6878 case BuiltinType::Short: 6879 case BuiltinType::UShort: 6880 return 3 + (getIntWidth(ShortTy) << 3); 6881 case BuiltinType::Int: 6882 case BuiltinType::UInt: 6883 return 4 + (getIntWidth(IntTy) << 3); 6884 case BuiltinType::Long: 6885 case BuiltinType::ULong: 6886 return 5 + (getIntWidth(LongTy) << 3); 6887 case BuiltinType::LongLong: 6888 case BuiltinType::ULongLong: 6889 return 6 + (getIntWidth(LongLongTy) << 3); 6890 case BuiltinType::Int128: 6891 case BuiltinType::UInt128: 6892 return 7 + (getIntWidth(Int128Ty) << 3); 6893 } 6894 } 6895 6896 /// Whether this is a promotable bitfield reference according 6897 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6898 /// 6899 /// \returns the type this bit-field will promote to, or NULL if no 6900 /// promotion occurs. 6901 QualType ASTContext::isPromotableBitField(Expr *E) const { 6902 if (E->isTypeDependent() || E->isValueDependent()) 6903 return {}; 6904 6905 // C++ [conv.prom]p5: 6906 // If the bit-field has an enumerated type, it is treated as any other 6907 // value of that type for promotion purposes. 6908 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6909 return {}; 6910 6911 // FIXME: We should not do this unless E->refersToBitField() is true. This 6912 // matters in C where getSourceBitField() will find bit-fields for various 6913 // cases where the source expression is not a bit-field designator. 6914 6915 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6916 if (!Field) 6917 return {}; 6918 6919 QualType FT = Field->getType(); 6920 6921 uint64_t BitWidth = Field->getBitWidthValue(*this); 6922 uint64_t IntSize = getTypeSize(IntTy); 6923 // C++ [conv.prom]p5: 6924 // A prvalue for an integral bit-field can be converted to a prvalue of type 6925 // int if int can represent all the values of the bit-field; otherwise, it 6926 // can be converted to unsigned int if unsigned int can represent all the 6927 // values of the bit-field. If the bit-field is larger yet, no integral 6928 // promotion applies to it. 6929 // C11 6.3.1.1/2: 6930 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6931 // If an int can represent all values of the original type (as restricted by 6932 // the width, for a bit-field), the value is converted to an int; otherwise, 6933 // it is converted to an unsigned int. 6934 // 6935 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6936 // We perform that promotion here to match GCC and C++. 6937 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6938 // greater than that of 'int'. We perform that promotion to match GCC. 6939 if (BitWidth < IntSize) 6940 return IntTy; 6941 6942 if (BitWidth == IntSize) 6943 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6944 6945 // Bit-fields wider than int are not subject to promotions, and therefore act 6946 // like the base type. GCC has some weird bugs in this area that we 6947 // deliberately do not follow (GCC follows a pre-standard resolution to 6948 // C's DR315 which treats bit-width as being part of the type, and this leaks 6949 // into their semantics in some cases). 6950 return {}; 6951 } 6952 6953 /// getPromotedIntegerType - Returns the type that Promotable will 6954 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6955 /// integer type. 6956 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6957 assert(!Promotable.isNull()); 6958 assert(Promotable->isPromotableIntegerType()); 6959 if (const auto *ET = Promotable->getAs<EnumType>()) 6960 return ET->getDecl()->getPromotionType(); 6961 6962 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6963 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6964 // (3.9.1) can be converted to a prvalue of the first of the following 6965 // types that can represent all the values of its underlying type: 6966 // int, unsigned int, long int, unsigned long int, long long int, or 6967 // unsigned long long int [...] 6968 // FIXME: Is there some better way to compute this? 6969 if (BT->getKind() == BuiltinType::WChar_S || 6970 BT->getKind() == BuiltinType::WChar_U || 6971 BT->getKind() == BuiltinType::Char8 || 6972 BT->getKind() == BuiltinType::Char16 || 6973 BT->getKind() == BuiltinType::Char32) { 6974 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6975 uint64_t FromSize = getTypeSize(BT); 6976 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6977 LongLongTy, UnsignedLongLongTy }; 6978 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6979 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6980 if (FromSize < ToSize || 6981 (FromSize == ToSize && 6982 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6983 return PromoteTypes[Idx]; 6984 } 6985 llvm_unreachable("char type should fit into long long"); 6986 } 6987 } 6988 6989 // At this point, we should have a signed or unsigned integer type. 6990 if (Promotable->isSignedIntegerType()) 6991 return IntTy; 6992 uint64_t PromotableSize = getIntWidth(Promotable); 6993 uint64_t IntSize = getIntWidth(IntTy); 6994 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6995 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6996 } 6997 6998 /// Recurses in pointer/array types until it finds an objc retainable 6999 /// type and returns its ownership. 7000 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 7001 while (!T.isNull()) { 7002 if (T.getObjCLifetime() != Qualifiers::OCL_None) 7003 return T.getObjCLifetime(); 7004 if (T->isArrayType()) 7005 T = getBaseElementType(T); 7006 else if (const auto *PT = T->getAs<PointerType>()) 7007 T = PT->getPointeeType(); 7008 else if (const auto *RT = T->getAs<ReferenceType>()) 7009 T = RT->getPointeeType(); 7010 else 7011 break; 7012 } 7013 7014 return Qualifiers::OCL_None; 7015 } 7016 7017 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 7018 // Incomplete enum types are not treated as integer types. 7019 // FIXME: In C++, enum types are never integer types. 7020 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 7021 return ET->getDecl()->getIntegerType().getTypePtr(); 7022 return nullptr; 7023 } 7024 7025 /// getIntegerTypeOrder - Returns the highest ranked integer type: 7026 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 7027 /// LHS < RHS, return -1. 7028 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 7029 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 7030 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 7031 7032 // Unwrap enums to their underlying type. 7033 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 7034 LHSC = getIntegerTypeForEnum(ET); 7035 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7036 RHSC = getIntegerTypeForEnum(ET); 7037 7038 if (LHSC == RHSC) return 0; 7039 7040 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7041 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7042 7043 unsigned LHSRank = getIntegerRank(LHSC); 7044 unsigned RHSRank = getIntegerRank(RHSC); 7045 7046 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7047 if (LHSRank == RHSRank) return 0; 7048 return LHSRank > RHSRank ? 1 : -1; 7049 } 7050 7051 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7052 if (LHSUnsigned) { 7053 // If the unsigned [LHS] type is larger, return it. 7054 if (LHSRank >= RHSRank) 7055 return 1; 7056 7057 // If the signed type can represent all values of the unsigned type, it 7058 // wins. Because we are dealing with 2's complement and types that are 7059 // powers of two larger than each other, this is always safe. 7060 return -1; 7061 } 7062 7063 // If the unsigned [RHS] type is larger, return it. 7064 if (RHSRank >= LHSRank) 7065 return -1; 7066 7067 // If the signed type can represent all values of the unsigned type, it 7068 // wins. Because we are dealing with 2's complement and types that are 7069 // powers of two larger than each other, this is always safe. 7070 return 1; 7071 } 7072 7073 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7074 if (CFConstantStringTypeDecl) 7075 return CFConstantStringTypeDecl; 7076 7077 assert(!CFConstantStringTagDecl && 7078 "tag and typedef should be initialized together"); 7079 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7080 CFConstantStringTagDecl->startDefinition(); 7081 7082 struct { 7083 QualType Type; 7084 const char *Name; 7085 } Fields[5]; 7086 unsigned Count = 0; 7087 7088 /// Objective-C ABI 7089 /// 7090 /// typedef struct __NSConstantString_tag { 7091 /// const int *isa; 7092 /// int flags; 7093 /// const char *str; 7094 /// long length; 7095 /// } __NSConstantString; 7096 /// 7097 /// Swift ABI (4.1, 4.2) 7098 /// 7099 /// typedef struct __NSConstantString_tag { 7100 /// uintptr_t _cfisa; 7101 /// uintptr_t _swift_rc; 7102 /// _Atomic(uint64_t) _cfinfoa; 7103 /// const char *_ptr; 7104 /// uint32_t _length; 7105 /// } __NSConstantString; 7106 /// 7107 /// Swift ABI (5.0) 7108 /// 7109 /// typedef struct __NSConstantString_tag { 7110 /// uintptr_t _cfisa; 7111 /// uintptr_t _swift_rc; 7112 /// _Atomic(uint64_t) _cfinfoa; 7113 /// const char *_ptr; 7114 /// uintptr_t _length; 7115 /// } __NSConstantString; 7116 7117 const auto CFRuntime = getLangOpts().CFRuntime; 7118 if (static_cast<unsigned>(CFRuntime) < 7119 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7120 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7121 Fields[Count++] = { IntTy, "flags" }; 7122 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7123 Fields[Count++] = { LongTy, "length" }; 7124 } else { 7125 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7126 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7127 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7128 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7129 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7130 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7131 Fields[Count++] = { IntTy, "_ptr" }; 7132 else 7133 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7134 } 7135 7136 // Create fields 7137 for (unsigned i = 0; i < Count; ++i) { 7138 FieldDecl *Field = 7139 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7140 SourceLocation(), &Idents.get(Fields[i].Name), 7141 Fields[i].Type, /*TInfo=*/nullptr, 7142 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7143 Field->setAccess(AS_public); 7144 CFConstantStringTagDecl->addDecl(Field); 7145 } 7146 7147 CFConstantStringTagDecl->completeDefinition(); 7148 // This type is designed to be compatible with NSConstantString, but cannot 7149 // use the same name, since NSConstantString is an interface. 7150 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7151 CFConstantStringTypeDecl = 7152 buildImplicitTypedef(tagType, "__NSConstantString"); 7153 7154 return CFConstantStringTypeDecl; 7155 } 7156 7157 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7158 if (!CFConstantStringTagDecl) 7159 getCFConstantStringDecl(); // Build the tag and the typedef. 7160 return CFConstantStringTagDecl; 7161 } 7162 7163 // getCFConstantStringType - Return the type used for constant CFStrings. 7164 QualType ASTContext::getCFConstantStringType() const { 7165 return getTypedefType(getCFConstantStringDecl()); 7166 } 7167 7168 QualType ASTContext::getObjCSuperType() const { 7169 if (ObjCSuperType.isNull()) { 7170 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7171 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7172 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7173 } 7174 return ObjCSuperType; 7175 } 7176 7177 void ASTContext::setCFConstantStringType(QualType T) { 7178 const auto *TD = T->castAs<TypedefType>(); 7179 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7180 const auto *TagType = 7181 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7182 CFConstantStringTagDecl = TagType->getDecl(); 7183 } 7184 7185 QualType ASTContext::getBlockDescriptorType() const { 7186 if (BlockDescriptorType) 7187 return getTagDeclType(BlockDescriptorType); 7188 7189 RecordDecl *RD; 7190 // FIXME: Needs the FlagAppleBlock bit. 7191 RD = buildImplicitRecord("__block_descriptor"); 7192 RD->startDefinition(); 7193 7194 QualType FieldTypes[] = { 7195 UnsignedLongTy, 7196 UnsignedLongTy, 7197 }; 7198 7199 static const char *const FieldNames[] = { 7200 "reserved", 7201 "Size" 7202 }; 7203 7204 for (size_t i = 0; i < 2; ++i) { 7205 FieldDecl *Field = FieldDecl::Create( 7206 *this, RD, SourceLocation(), SourceLocation(), 7207 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7208 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7209 Field->setAccess(AS_public); 7210 RD->addDecl(Field); 7211 } 7212 7213 RD->completeDefinition(); 7214 7215 BlockDescriptorType = RD; 7216 7217 return getTagDeclType(BlockDescriptorType); 7218 } 7219 7220 QualType ASTContext::getBlockDescriptorExtendedType() const { 7221 if (BlockDescriptorExtendedType) 7222 return getTagDeclType(BlockDescriptorExtendedType); 7223 7224 RecordDecl *RD; 7225 // FIXME: Needs the FlagAppleBlock bit. 7226 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7227 RD->startDefinition(); 7228 7229 QualType FieldTypes[] = { 7230 UnsignedLongTy, 7231 UnsignedLongTy, 7232 getPointerType(VoidPtrTy), 7233 getPointerType(VoidPtrTy) 7234 }; 7235 7236 static const char *const FieldNames[] = { 7237 "reserved", 7238 "Size", 7239 "CopyFuncPtr", 7240 "DestroyFuncPtr" 7241 }; 7242 7243 for (size_t i = 0; i < 4; ++i) { 7244 FieldDecl *Field = FieldDecl::Create( 7245 *this, RD, SourceLocation(), SourceLocation(), 7246 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7247 /*BitWidth=*/nullptr, 7248 /*Mutable=*/false, ICIS_NoInit); 7249 Field->setAccess(AS_public); 7250 RD->addDecl(Field); 7251 } 7252 7253 RD->completeDefinition(); 7254 7255 BlockDescriptorExtendedType = RD; 7256 return getTagDeclType(BlockDescriptorExtendedType); 7257 } 7258 7259 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7260 const auto *BT = dyn_cast<BuiltinType>(T); 7261 7262 if (!BT) { 7263 if (isa<PipeType>(T)) 7264 return OCLTK_Pipe; 7265 7266 return OCLTK_Default; 7267 } 7268 7269 switch (BT->getKind()) { 7270 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7271 case BuiltinType::Id: \ 7272 return OCLTK_Image; 7273 #include "clang/Basic/OpenCLImageTypes.def" 7274 7275 case BuiltinType::OCLClkEvent: 7276 return OCLTK_ClkEvent; 7277 7278 case BuiltinType::OCLEvent: 7279 return OCLTK_Event; 7280 7281 case BuiltinType::OCLQueue: 7282 return OCLTK_Queue; 7283 7284 case BuiltinType::OCLReserveID: 7285 return OCLTK_ReserveID; 7286 7287 case BuiltinType::OCLSampler: 7288 return OCLTK_Sampler; 7289 7290 default: 7291 return OCLTK_Default; 7292 } 7293 } 7294 7295 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7296 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7297 } 7298 7299 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7300 /// requires copy/dispose. Note that this must match the logic 7301 /// in buildByrefHelpers. 7302 bool ASTContext::BlockRequiresCopying(QualType Ty, 7303 const VarDecl *D) { 7304 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7305 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7306 if (!copyExpr && record->hasTrivialDestructor()) return false; 7307 7308 return true; 7309 } 7310 7311 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7312 // move or destroy. 7313 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7314 return true; 7315 7316 if (!Ty->isObjCRetainableType()) return false; 7317 7318 Qualifiers qs = Ty.getQualifiers(); 7319 7320 // If we have lifetime, that dominates. 7321 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7322 switch (lifetime) { 7323 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7324 7325 // These are just bits as far as the runtime is concerned. 7326 case Qualifiers::OCL_ExplicitNone: 7327 case Qualifiers::OCL_Autoreleasing: 7328 return false; 7329 7330 // These cases should have been taken care of when checking the type's 7331 // non-triviality. 7332 case Qualifiers::OCL_Weak: 7333 case Qualifiers::OCL_Strong: 7334 llvm_unreachable("impossible"); 7335 } 7336 llvm_unreachable("fell out of lifetime switch!"); 7337 } 7338 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7339 Ty->isObjCObjectPointerType()); 7340 } 7341 7342 bool ASTContext::getByrefLifetime(QualType Ty, 7343 Qualifiers::ObjCLifetime &LifeTime, 7344 bool &HasByrefExtendedLayout) const { 7345 if (!getLangOpts().ObjC || 7346 getLangOpts().getGC() != LangOptions::NonGC) 7347 return false; 7348 7349 HasByrefExtendedLayout = false; 7350 if (Ty->isRecordType()) { 7351 HasByrefExtendedLayout = true; 7352 LifeTime = Qualifiers::OCL_None; 7353 } else if ((LifeTime = Ty.getObjCLifetime())) { 7354 // Honor the ARC qualifiers. 7355 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7356 // The MRR rule. 7357 LifeTime = Qualifiers::OCL_ExplicitNone; 7358 } else { 7359 LifeTime = Qualifiers::OCL_None; 7360 } 7361 return true; 7362 } 7363 7364 CanQualType ASTContext::getNSUIntegerType() const { 7365 assert(Target && "Expected target to be initialized"); 7366 const llvm::Triple &T = Target->getTriple(); 7367 // Windows is LLP64 rather than LP64 7368 if (T.isOSWindows() && T.isArch64Bit()) 7369 return UnsignedLongLongTy; 7370 return UnsignedLongTy; 7371 } 7372 7373 CanQualType ASTContext::getNSIntegerType() const { 7374 assert(Target && "Expected target to be initialized"); 7375 const llvm::Triple &T = Target->getTriple(); 7376 // Windows is LLP64 rather than LP64 7377 if (T.isOSWindows() && T.isArch64Bit()) 7378 return LongLongTy; 7379 return LongTy; 7380 } 7381 7382 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7383 if (!ObjCInstanceTypeDecl) 7384 ObjCInstanceTypeDecl = 7385 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7386 return ObjCInstanceTypeDecl; 7387 } 7388 7389 // This returns true if a type has been typedefed to BOOL: 7390 // typedef <type> BOOL; 7391 static bool isTypeTypedefedAsBOOL(QualType T) { 7392 if (const auto *TT = dyn_cast<TypedefType>(T)) 7393 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7394 return II->isStr("BOOL"); 7395 7396 return false; 7397 } 7398 7399 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7400 /// purpose. 7401 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7402 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7403 return CharUnits::Zero(); 7404 7405 CharUnits sz = getTypeSizeInChars(type); 7406 7407 // Make all integer and enum types at least as large as an int 7408 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7409 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7410 // Treat arrays as pointers, since that's how they're passed in. 7411 else if (type->isArrayType()) 7412 sz = getTypeSizeInChars(VoidPtrTy); 7413 return sz; 7414 } 7415 7416 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7417 return getTargetInfo().getCXXABI().isMicrosoft() && 7418 VD->isStaticDataMember() && 7419 VD->getType()->isIntegralOrEnumerationType() && 7420 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7421 } 7422 7423 ASTContext::InlineVariableDefinitionKind 7424 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7425 if (!VD->isInline()) 7426 return InlineVariableDefinitionKind::None; 7427 7428 // In almost all cases, it's a weak definition. 7429 auto *First = VD->getFirstDecl(); 7430 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7431 return InlineVariableDefinitionKind::Weak; 7432 7433 // If there's a file-context declaration in this translation unit, it's a 7434 // non-discardable definition. 7435 for (auto *D : VD->redecls()) 7436 if (D->getLexicalDeclContext()->isFileContext() && 7437 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7438 return InlineVariableDefinitionKind::Strong; 7439 7440 // If we've not seen one yet, we don't know. 7441 return InlineVariableDefinitionKind::WeakUnknown; 7442 } 7443 7444 static std::string charUnitsToString(const CharUnits &CU) { 7445 return llvm::itostr(CU.getQuantity()); 7446 } 7447 7448 /// getObjCEncodingForBlock - Return the encoded type for this block 7449 /// declaration. 7450 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7451 std::string S; 7452 7453 const BlockDecl *Decl = Expr->getBlockDecl(); 7454 QualType BlockTy = 7455 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7456 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7457 // Encode result type. 7458 if (getLangOpts().EncodeExtendedBlockSig) 7459 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7460 true /*Extended*/); 7461 else 7462 getObjCEncodingForType(BlockReturnTy, S); 7463 // Compute size of all parameters. 7464 // Start with computing size of a pointer in number of bytes. 7465 // FIXME: There might(should) be a better way of doing this computation! 7466 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7467 CharUnits ParmOffset = PtrSize; 7468 for (auto PI : Decl->parameters()) { 7469 QualType PType = PI->getType(); 7470 CharUnits sz = getObjCEncodingTypeSize(PType); 7471 if (sz.isZero()) 7472 continue; 7473 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7474 ParmOffset += sz; 7475 } 7476 // Size of the argument frame 7477 S += charUnitsToString(ParmOffset); 7478 // Block pointer and offset. 7479 S += "@?0"; 7480 7481 // Argument types. 7482 ParmOffset = PtrSize; 7483 for (auto PVDecl : Decl->parameters()) { 7484 QualType PType = PVDecl->getOriginalType(); 7485 if (const auto *AT = 7486 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7487 // Use array's original type only if it has known number of 7488 // elements. 7489 if (!isa<ConstantArrayType>(AT)) 7490 PType = PVDecl->getType(); 7491 } else if (PType->isFunctionType()) 7492 PType = PVDecl->getType(); 7493 if (getLangOpts().EncodeExtendedBlockSig) 7494 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7495 S, true /*Extended*/); 7496 else 7497 getObjCEncodingForType(PType, S); 7498 S += charUnitsToString(ParmOffset); 7499 ParmOffset += getObjCEncodingTypeSize(PType); 7500 } 7501 7502 return S; 7503 } 7504 7505 std::string 7506 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7507 std::string S; 7508 // Encode result type. 7509 getObjCEncodingForType(Decl->getReturnType(), S); 7510 CharUnits ParmOffset; 7511 // Compute size of all parameters. 7512 for (auto PI : Decl->parameters()) { 7513 QualType PType = PI->getType(); 7514 CharUnits sz = getObjCEncodingTypeSize(PType); 7515 if (sz.isZero()) 7516 continue; 7517 7518 assert(sz.isPositive() && 7519 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7520 ParmOffset += sz; 7521 } 7522 S += charUnitsToString(ParmOffset); 7523 ParmOffset = CharUnits::Zero(); 7524 7525 // Argument types. 7526 for (auto PVDecl : Decl->parameters()) { 7527 QualType PType = PVDecl->getOriginalType(); 7528 if (const auto *AT = 7529 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7530 // Use array's original type only if it has known number of 7531 // elements. 7532 if (!isa<ConstantArrayType>(AT)) 7533 PType = PVDecl->getType(); 7534 } else if (PType->isFunctionType()) 7535 PType = PVDecl->getType(); 7536 getObjCEncodingForType(PType, S); 7537 S += charUnitsToString(ParmOffset); 7538 ParmOffset += getObjCEncodingTypeSize(PType); 7539 } 7540 7541 return S; 7542 } 7543 7544 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7545 /// method parameter or return type. If Extended, include class names and 7546 /// block object types. 7547 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7548 QualType T, std::string& S, 7549 bool Extended) const { 7550 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7551 getObjCEncodingForTypeQualifier(QT, S); 7552 // Encode parameter type. 7553 ObjCEncOptions Options = ObjCEncOptions() 7554 .setExpandPointedToStructures() 7555 .setExpandStructures() 7556 .setIsOutermostType(); 7557 if (Extended) 7558 Options.setEncodeBlockParameters().setEncodeClassNames(); 7559 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7560 } 7561 7562 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7563 /// declaration. 7564 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7565 bool Extended) const { 7566 // FIXME: This is not very efficient. 7567 // Encode return type. 7568 std::string S; 7569 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7570 Decl->getReturnType(), S, Extended); 7571 // Compute size of all parameters. 7572 // Start with computing size of a pointer in number of bytes. 7573 // FIXME: There might(should) be a better way of doing this computation! 7574 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7575 // The first two arguments (self and _cmd) are pointers; account for 7576 // their size. 7577 CharUnits ParmOffset = 2 * PtrSize; 7578 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7579 E = Decl->sel_param_end(); PI != E; ++PI) { 7580 QualType PType = (*PI)->getType(); 7581 CharUnits sz = getObjCEncodingTypeSize(PType); 7582 if (sz.isZero()) 7583 continue; 7584 7585 assert(sz.isPositive() && 7586 "getObjCEncodingForMethodDecl - Incomplete param type"); 7587 ParmOffset += sz; 7588 } 7589 S += charUnitsToString(ParmOffset); 7590 S += "@0:"; 7591 S += charUnitsToString(PtrSize); 7592 7593 // Argument types. 7594 ParmOffset = 2 * PtrSize; 7595 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7596 E = Decl->sel_param_end(); PI != E; ++PI) { 7597 const ParmVarDecl *PVDecl = *PI; 7598 QualType PType = PVDecl->getOriginalType(); 7599 if (const auto *AT = 7600 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7601 // Use array's original type only if it has known number of 7602 // elements. 7603 if (!isa<ConstantArrayType>(AT)) 7604 PType = PVDecl->getType(); 7605 } else if (PType->isFunctionType()) 7606 PType = PVDecl->getType(); 7607 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7608 PType, S, Extended); 7609 S += charUnitsToString(ParmOffset); 7610 ParmOffset += getObjCEncodingTypeSize(PType); 7611 } 7612 7613 return S; 7614 } 7615 7616 ObjCPropertyImplDecl * 7617 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7618 const ObjCPropertyDecl *PD, 7619 const Decl *Container) const { 7620 if (!Container) 7621 return nullptr; 7622 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7623 for (auto *PID : CID->property_impls()) 7624 if (PID->getPropertyDecl() == PD) 7625 return PID; 7626 } else { 7627 const auto *OID = cast<ObjCImplementationDecl>(Container); 7628 for (auto *PID : OID->property_impls()) 7629 if (PID->getPropertyDecl() == PD) 7630 return PID; 7631 } 7632 return nullptr; 7633 } 7634 7635 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7636 /// property declaration. If non-NULL, Container must be either an 7637 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7638 /// NULL when getting encodings for protocol properties. 7639 /// Property attributes are stored as a comma-delimited C string. The simple 7640 /// attributes readonly and bycopy are encoded as single characters. The 7641 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7642 /// encoded as single characters, followed by an identifier. Property types 7643 /// are also encoded as a parametrized attribute. The characters used to encode 7644 /// these attributes are defined by the following enumeration: 7645 /// @code 7646 /// enum PropertyAttributes { 7647 /// kPropertyReadOnly = 'R', // property is read-only. 7648 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7649 /// kPropertyByref = '&', // property is a reference to the value last assigned 7650 /// kPropertyDynamic = 'D', // property is dynamic 7651 /// kPropertyGetter = 'G', // followed by getter selector name 7652 /// kPropertySetter = 'S', // followed by setter selector name 7653 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7654 /// kPropertyType = 'T' // followed by old-style type encoding. 7655 /// kPropertyWeak = 'W' // 'weak' property 7656 /// kPropertyStrong = 'P' // property GC'able 7657 /// kPropertyNonAtomic = 'N' // property non-atomic 7658 /// }; 7659 /// @endcode 7660 std::string 7661 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7662 const Decl *Container) const { 7663 // Collect information from the property implementation decl(s). 7664 bool Dynamic = false; 7665 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7666 7667 if (ObjCPropertyImplDecl *PropertyImpDecl = 7668 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7669 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7670 Dynamic = true; 7671 else 7672 SynthesizePID = PropertyImpDecl; 7673 } 7674 7675 // FIXME: This is not very efficient. 7676 std::string S = "T"; 7677 7678 // Encode result type. 7679 // GCC has some special rules regarding encoding of properties which 7680 // closely resembles encoding of ivars. 7681 getObjCEncodingForPropertyType(PD->getType(), S); 7682 7683 if (PD->isReadOnly()) { 7684 S += ",R"; 7685 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7686 S += ",C"; 7687 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7688 S += ",&"; 7689 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7690 S += ",W"; 7691 } else { 7692 switch (PD->getSetterKind()) { 7693 case ObjCPropertyDecl::Assign: break; 7694 case ObjCPropertyDecl::Copy: S += ",C"; break; 7695 case ObjCPropertyDecl::Retain: S += ",&"; break; 7696 case ObjCPropertyDecl::Weak: S += ",W"; break; 7697 } 7698 } 7699 7700 // It really isn't clear at all what this means, since properties 7701 // are "dynamic by default". 7702 if (Dynamic) 7703 S += ",D"; 7704 7705 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7706 S += ",N"; 7707 7708 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7709 S += ",G"; 7710 S += PD->getGetterName().getAsString(); 7711 } 7712 7713 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7714 S += ",S"; 7715 S += PD->getSetterName().getAsString(); 7716 } 7717 7718 if (SynthesizePID) { 7719 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7720 S += ",V"; 7721 S += OID->getNameAsString(); 7722 } 7723 7724 // FIXME: OBJCGC: weak & strong 7725 return S; 7726 } 7727 7728 /// getLegacyIntegralTypeEncoding - 7729 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7730 /// 'l' or 'L' , but not always. For typedefs, we need to use 7731 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7732 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7733 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7734 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7735 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7736 PointeeTy = UnsignedIntTy; 7737 else 7738 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7739 PointeeTy = IntTy; 7740 } 7741 } 7742 } 7743 7744 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7745 const FieldDecl *Field, 7746 QualType *NotEncodedT) const { 7747 // We follow the behavior of gcc, expanding structures which are 7748 // directly pointed to, and expanding embedded structures. Note that 7749 // these rules are sufficient to prevent recursive encoding of the 7750 // same type. 7751 getObjCEncodingForTypeImpl(T, S, 7752 ObjCEncOptions() 7753 .setExpandPointedToStructures() 7754 .setExpandStructures() 7755 .setIsOutermostType(), 7756 Field, NotEncodedT); 7757 } 7758 7759 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7760 std::string& S) const { 7761 // Encode result type. 7762 // GCC has some special rules regarding encoding of properties which 7763 // closely resembles encoding of ivars. 7764 getObjCEncodingForTypeImpl(T, S, 7765 ObjCEncOptions() 7766 .setExpandPointedToStructures() 7767 .setExpandStructures() 7768 .setIsOutermostType() 7769 .setEncodingProperty(), 7770 /*Field=*/nullptr); 7771 } 7772 7773 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7774 const BuiltinType *BT) { 7775 BuiltinType::Kind kind = BT->getKind(); 7776 switch (kind) { 7777 case BuiltinType::Void: return 'v'; 7778 case BuiltinType::Bool: return 'B'; 7779 case BuiltinType::Char8: 7780 case BuiltinType::Char_U: 7781 case BuiltinType::UChar: return 'C'; 7782 case BuiltinType::Char16: 7783 case BuiltinType::UShort: return 'S'; 7784 case BuiltinType::Char32: 7785 case BuiltinType::UInt: return 'I'; 7786 case BuiltinType::ULong: 7787 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7788 case BuiltinType::UInt128: return 'T'; 7789 case BuiltinType::ULongLong: return 'Q'; 7790 case BuiltinType::Char_S: 7791 case BuiltinType::SChar: return 'c'; 7792 case BuiltinType::Short: return 's'; 7793 case BuiltinType::WChar_S: 7794 case BuiltinType::WChar_U: 7795 case BuiltinType::Int: return 'i'; 7796 case BuiltinType::Long: 7797 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7798 case BuiltinType::LongLong: return 'q'; 7799 case BuiltinType::Int128: return 't'; 7800 case BuiltinType::Float: return 'f'; 7801 case BuiltinType::Double: return 'd'; 7802 case BuiltinType::LongDouble: return 'D'; 7803 case BuiltinType::NullPtr: return '*'; // like char* 7804 7805 case BuiltinType::BFloat16: 7806 case BuiltinType::Float16: 7807 case BuiltinType::Float128: 7808 case BuiltinType::Ibm128: 7809 case BuiltinType::Half: 7810 case BuiltinType::ShortAccum: 7811 case BuiltinType::Accum: 7812 case BuiltinType::LongAccum: 7813 case BuiltinType::UShortAccum: 7814 case BuiltinType::UAccum: 7815 case BuiltinType::ULongAccum: 7816 case BuiltinType::ShortFract: 7817 case BuiltinType::Fract: 7818 case BuiltinType::LongFract: 7819 case BuiltinType::UShortFract: 7820 case BuiltinType::UFract: 7821 case BuiltinType::ULongFract: 7822 case BuiltinType::SatShortAccum: 7823 case BuiltinType::SatAccum: 7824 case BuiltinType::SatLongAccum: 7825 case BuiltinType::SatUShortAccum: 7826 case BuiltinType::SatUAccum: 7827 case BuiltinType::SatULongAccum: 7828 case BuiltinType::SatShortFract: 7829 case BuiltinType::SatFract: 7830 case BuiltinType::SatLongFract: 7831 case BuiltinType::SatUShortFract: 7832 case BuiltinType::SatUFract: 7833 case BuiltinType::SatULongFract: 7834 // FIXME: potentially need @encodes for these! 7835 return ' '; 7836 7837 #define SVE_TYPE(Name, Id, SingletonId) \ 7838 case BuiltinType::Id: 7839 #include "clang/Basic/AArch64SVEACLETypes.def" 7840 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7841 #include "clang/Basic/RISCVVTypes.def" 7842 { 7843 DiagnosticsEngine &Diags = C->getDiagnostics(); 7844 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7845 "cannot yet @encode type %0"); 7846 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7847 return ' '; 7848 } 7849 7850 case BuiltinType::ObjCId: 7851 case BuiltinType::ObjCClass: 7852 case BuiltinType::ObjCSel: 7853 llvm_unreachable("@encoding ObjC primitive type"); 7854 7855 // OpenCL and placeholder types don't need @encodings. 7856 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7857 case BuiltinType::Id: 7858 #include "clang/Basic/OpenCLImageTypes.def" 7859 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7860 case BuiltinType::Id: 7861 #include "clang/Basic/OpenCLExtensionTypes.def" 7862 case BuiltinType::OCLEvent: 7863 case BuiltinType::OCLClkEvent: 7864 case BuiltinType::OCLQueue: 7865 case BuiltinType::OCLReserveID: 7866 case BuiltinType::OCLSampler: 7867 case BuiltinType::Dependent: 7868 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7869 case BuiltinType::Id: 7870 #include "clang/Basic/PPCTypes.def" 7871 #define BUILTIN_TYPE(KIND, ID) 7872 #define PLACEHOLDER_TYPE(KIND, ID) \ 7873 case BuiltinType::KIND: 7874 #include "clang/AST/BuiltinTypes.def" 7875 llvm_unreachable("invalid builtin type for @encode"); 7876 } 7877 llvm_unreachable("invalid BuiltinType::Kind value"); 7878 } 7879 7880 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7881 EnumDecl *Enum = ET->getDecl(); 7882 7883 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7884 if (!Enum->isFixed()) 7885 return 'i'; 7886 7887 // The encoding of a fixed enum type matches its fixed underlying type. 7888 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7889 return getObjCEncodingForPrimitiveType(C, BT); 7890 } 7891 7892 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7893 QualType T, const FieldDecl *FD) { 7894 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7895 S += 'b'; 7896 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7897 // The GNU runtime requires more information; bitfields are encoded as b, 7898 // then the offset (in bits) of the first element, then the type of the 7899 // bitfield, then the size in bits. For example, in this structure: 7900 // 7901 // struct 7902 // { 7903 // int integer; 7904 // int flags:2; 7905 // }; 7906 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7907 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7908 // information is not especially sensible, but we're stuck with it for 7909 // compatibility with GCC, although providing it breaks anything that 7910 // actually uses runtime introspection and wants to work on both runtimes... 7911 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7912 uint64_t Offset; 7913 7914 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7915 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7916 IVD); 7917 } else { 7918 const RecordDecl *RD = FD->getParent(); 7919 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7920 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7921 } 7922 7923 S += llvm::utostr(Offset); 7924 7925 if (const auto *ET = T->getAs<EnumType>()) 7926 S += ObjCEncodingForEnumType(Ctx, ET); 7927 else { 7928 const auto *BT = T->castAs<BuiltinType>(); 7929 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7930 } 7931 } 7932 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7933 } 7934 7935 // Helper function for determining whether the encoded type string would include 7936 // a template specialization type. 7937 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7938 bool VisitBasesAndFields) { 7939 T = T->getBaseElementTypeUnsafe(); 7940 7941 if (auto *PT = T->getAs<PointerType>()) 7942 return hasTemplateSpecializationInEncodedString( 7943 PT->getPointeeType().getTypePtr(), false); 7944 7945 auto *CXXRD = T->getAsCXXRecordDecl(); 7946 7947 if (!CXXRD) 7948 return false; 7949 7950 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7951 return true; 7952 7953 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7954 return false; 7955 7956 for (auto B : CXXRD->bases()) 7957 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7958 true)) 7959 return true; 7960 7961 for (auto *FD : CXXRD->fields()) 7962 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7963 true)) 7964 return true; 7965 7966 return false; 7967 } 7968 7969 // FIXME: Use SmallString for accumulating string. 7970 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7971 const ObjCEncOptions Options, 7972 const FieldDecl *FD, 7973 QualType *NotEncodedT) const { 7974 CanQualType CT = getCanonicalType(T); 7975 switch (CT->getTypeClass()) { 7976 case Type::Builtin: 7977 case Type::Enum: 7978 if (FD && FD->isBitField()) 7979 return EncodeBitField(this, S, T, FD); 7980 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7981 S += getObjCEncodingForPrimitiveType(this, BT); 7982 else 7983 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7984 return; 7985 7986 case Type::Complex: 7987 S += 'j'; 7988 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7989 ObjCEncOptions(), 7990 /*Field=*/nullptr); 7991 return; 7992 7993 case Type::Atomic: 7994 S += 'A'; 7995 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7996 ObjCEncOptions(), 7997 /*Field=*/nullptr); 7998 return; 7999 8000 // encoding for pointer or reference types. 8001 case Type::Pointer: 8002 case Type::LValueReference: 8003 case Type::RValueReference: { 8004 QualType PointeeTy; 8005 if (isa<PointerType>(CT)) { 8006 const auto *PT = T->castAs<PointerType>(); 8007 if (PT->isObjCSelType()) { 8008 S += ':'; 8009 return; 8010 } 8011 PointeeTy = PT->getPointeeType(); 8012 } else { 8013 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 8014 } 8015 8016 bool isReadOnly = false; 8017 // For historical/compatibility reasons, the read-only qualifier of the 8018 // pointee gets emitted _before_ the '^'. The read-only qualifier of 8019 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 8020 // Also, do not emit the 'r' for anything but the outermost type! 8021 if (isa<TypedefType>(T.getTypePtr())) { 8022 if (Options.IsOutermostType() && T.isConstQualified()) { 8023 isReadOnly = true; 8024 S += 'r'; 8025 } 8026 } else if (Options.IsOutermostType()) { 8027 QualType P = PointeeTy; 8028 while (auto PT = P->getAs<PointerType>()) 8029 P = PT->getPointeeType(); 8030 if (P.isConstQualified()) { 8031 isReadOnly = true; 8032 S += 'r'; 8033 } 8034 } 8035 if (isReadOnly) { 8036 // Another legacy compatibility encoding. Some ObjC qualifier and type 8037 // combinations need to be rearranged. 8038 // Rewrite "in const" from "nr" to "rn" 8039 if (StringRef(S).endswith("nr")) 8040 S.replace(S.end()-2, S.end(), "rn"); 8041 } 8042 8043 if (PointeeTy->isCharType()) { 8044 // char pointer types should be encoded as '*' unless it is a 8045 // type that has been typedef'd to 'BOOL'. 8046 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8047 S += '*'; 8048 return; 8049 } 8050 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8051 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8052 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8053 S += '#'; 8054 return; 8055 } 8056 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8057 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8058 S += '@'; 8059 return; 8060 } 8061 // If the encoded string for the class includes template names, just emit 8062 // "^v" for pointers to the class. 8063 if (getLangOpts().CPlusPlus && 8064 (!getLangOpts().EncodeCXXClassTemplateSpec && 8065 hasTemplateSpecializationInEncodedString( 8066 RTy, Options.ExpandPointedToStructures()))) { 8067 S += "^v"; 8068 return; 8069 } 8070 // fall through... 8071 } 8072 S += '^'; 8073 getLegacyIntegralTypeEncoding(PointeeTy); 8074 8075 ObjCEncOptions NewOptions; 8076 if (Options.ExpandPointedToStructures()) 8077 NewOptions.setExpandStructures(); 8078 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8079 /*Field=*/nullptr, NotEncodedT); 8080 return; 8081 } 8082 8083 case Type::ConstantArray: 8084 case Type::IncompleteArray: 8085 case Type::VariableArray: { 8086 const auto *AT = cast<ArrayType>(CT); 8087 8088 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8089 // Incomplete arrays are encoded as a pointer to the array element. 8090 S += '^'; 8091 8092 getObjCEncodingForTypeImpl( 8093 AT->getElementType(), S, 8094 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8095 } else { 8096 S += '['; 8097 8098 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8099 S += llvm::utostr(CAT->getSize().getZExtValue()); 8100 else { 8101 //Variable length arrays are encoded as a regular array with 0 elements. 8102 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8103 "Unknown array type!"); 8104 S += '0'; 8105 } 8106 8107 getObjCEncodingForTypeImpl( 8108 AT->getElementType(), S, 8109 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8110 NotEncodedT); 8111 S += ']'; 8112 } 8113 return; 8114 } 8115 8116 case Type::FunctionNoProto: 8117 case Type::FunctionProto: 8118 S += '?'; 8119 return; 8120 8121 case Type::Record: { 8122 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8123 S += RDecl->isUnion() ? '(' : '{'; 8124 // Anonymous structures print as '?' 8125 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8126 S += II->getName(); 8127 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8128 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8129 llvm::raw_string_ostream OS(S); 8130 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8131 getPrintingPolicy()); 8132 } 8133 } else { 8134 S += '?'; 8135 } 8136 if (Options.ExpandStructures()) { 8137 S += '='; 8138 if (!RDecl->isUnion()) { 8139 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8140 } else { 8141 for (const auto *Field : RDecl->fields()) { 8142 if (FD) { 8143 S += '"'; 8144 S += Field->getNameAsString(); 8145 S += '"'; 8146 } 8147 8148 // Special case bit-fields. 8149 if (Field->isBitField()) { 8150 getObjCEncodingForTypeImpl(Field->getType(), S, 8151 ObjCEncOptions().setExpandStructures(), 8152 Field); 8153 } else { 8154 QualType qt = Field->getType(); 8155 getLegacyIntegralTypeEncoding(qt); 8156 getObjCEncodingForTypeImpl( 8157 qt, S, 8158 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8159 NotEncodedT); 8160 } 8161 } 8162 } 8163 } 8164 S += RDecl->isUnion() ? ')' : '}'; 8165 return; 8166 } 8167 8168 case Type::BlockPointer: { 8169 const auto *BT = T->castAs<BlockPointerType>(); 8170 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8171 if (Options.EncodeBlockParameters()) { 8172 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8173 8174 S += '<'; 8175 // Block return type 8176 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8177 Options.forComponentType(), FD, NotEncodedT); 8178 // Block self 8179 S += "@?"; 8180 // Block parameters 8181 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8182 for (const auto &I : FPT->param_types()) 8183 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8184 NotEncodedT); 8185 } 8186 S += '>'; 8187 } 8188 return; 8189 } 8190 8191 case Type::ObjCObject: { 8192 // hack to match legacy encoding of *id and *Class 8193 QualType Ty = getObjCObjectPointerType(CT); 8194 if (Ty->isObjCIdType()) { 8195 S += "{objc_object=}"; 8196 return; 8197 } 8198 else if (Ty->isObjCClassType()) { 8199 S += "{objc_class=}"; 8200 return; 8201 } 8202 // TODO: Double check to make sure this intentionally falls through. 8203 LLVM_FALLTHROUGH; 8204 } 8205 8206 case Type::ObjCInterface: { 8207 // Ignore protocol qualifiers when mangling at this level. 8208 // @encode(class_name) 8209 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8210 S += '{'; 8211 S += OI->getObjCRuntimeNameAsString(); 8212 if (Options.ExpandStructures()) { 8213 S += '='; 8214 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8215 DeepCollectObjCIvars(OI, true, Ivars); 8216 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8217 const FieldDecl *Field = Ivars[i]; 8218 if (Field->isBitField()) 8219 getObjCEncodingForTypeImpl(Field->getType(), S, 8220 ObjCEncOptions().setExpandStructures(), 8221 Field); 8222 else 8223 getObjCEncodingForTypeImpl(Field->getType(), S, 8224 ObjCEncOptions().setExpandStructures(), FD, 8225 NotEncodedT); 8226 } 8227 } 8228 S += '}'; 8229 return; 8230 } 8231 8232 case Type::ObjCObjectPointer: { 8233 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8234 if (OPT->isObjCIdType()) { 8235 S += '@'; 8236 return; 8237 } 8238 8239 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8240 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8241 // Since this is a binary compatibility issue, need to consult with 8242 // runtime folks. Fortunately, this is a *very* obscure construct. 8243 S += '#'; 8244 return; 8245 } 8246 8247 if (OPT->isObjCQualifiedIdType()) { 8248 getObjCEncodingForTypeImpl( 8249 getObjCIdType(), S, 8250 Options.keepingOnly(ObjCEncOptions() 8251 .setExpandPointedToStructures() 8252 .setExpandStructures()), 8253 FD); 8254 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8255 // Note that we do extended encoding of protocol qualifier list 8256 // Only when doing ivar or property encoding. 8257 S += '"'; 8258 for (const auto *I : OPT->quals()) { 8259 S += '<'; 8260 S += I->getObjCRuntimeNameAsString(); 8261 S += '>'; 8262 } 8263 S += '"'; 8264 } 8265 return; 8266 } 8267 8268 S += '@'; 8269 if (OPT->getInterfaceDecl() && 8270 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8271 S += '"'; 8272 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8273 for (const auto *I : OPT->quals()) { 8274 S += '<'; 8275 S += I->getObjCRuntimeNameAsString(); 8276 S += '>'; 8277 } 8278 S += '"'; 8279 } 8280 return; 8281 } 8282 8283 // gcc just blithely ignores member pointers. 8284 // FIXME: we should do better than that. 'M' is available. 8285 case Type::MemberPointer: 8286 // This matches gcc's encoding, even though technically it is insufficient. 8287 //FIXME. We should do a better job than gcc. 8288 case Type::Vector: 8289 case Type::ExtVector: 8290 // Until we have a coherent encoding of these three types, issue warning. 8291 if (NotEncodedT) 8292 *NotEncodedT = T; 8293 return; 8294 8295 case Type::ConstantMatrix: 8296 if (NotEncodedT) 8297 *NotEncodedT = T; 8298 return; 8299 8300 case Type::BitInt: 8301 if (NotEncodedT) 8302 *NotEncodedT = T; 8303 return; 8304 8305 // We could see an undeduced auto type here during error recovery. 8306 // Just ignore it. 8307 case Type::Auto: 8308 case Type::DeducedTemplateSpecialization: 8309 return; 8310 8311 case Type::Pipe: 8312 #define ABSTRACT_TYPE(KIND, BASE) 8313 #define TYPE(KIND, BASE) 8314 #define DEPENDENT_TYPE(KIND, BASE) \ 8315 case Type::KIND: 8316 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8317 case Type::KIND: 8318 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8319 case Type::KIND: 8320 #include "clang/AST/TypeNodes.inc" 8321 llvm_unreachable("@encode for dependent type!"); 8322 } 8323 llvm_unreachable("bad type kind!"); 8324 } 8325 8326 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8327 std::string &S, 8328 const FieldDecl *FD, 8329 bool includeVBases, 8330 QualType *NotEncodedT) const { 8331 assert(RDecl && "Expected non-null RecordDecl"); 8332 assert(!RDecl->isUnion() && "Should not be called for unions"); 8333 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8334 return; 8335 8336 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8337 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8338 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8339 8340 if (CXXRec) { 8341 for (const auto &BI : CXXRec->bases()) { 8342 if (!BI.isVirtual()) { 8343 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8344 if (base->isEmpty()) 8345 continue; 8346 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8347 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8348 std::make_pair(offs, base)); 8349 } 8350 } 8351 } 8352 8353 unsigned i = 0; 8354 for (FieldDecl *Field : RDecl->fields()) { 8355 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8356 continue; 8357 uint64_t offs = layout.getFieldOffset(i); 8358 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8359 std::make_pair(offs, Field)); 8360 ++i; 8361 } 8362 8363 if (CXXRec && includeVBases) { 8364 for (const auto &BI : CXXRec->vbases()) { 8365 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8366 if (base->isEmpty()) 8367 continue; 8368 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8369 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8370 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8371 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8372 std::make_pair(offs, base)); 8373 } 8374 } 8375 8376 CharUnits size; 8377 if (CXXRec) { 8378 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8379 } else { 8380 size = layout.getSize(); 8381 } 8382 8383 #ifndef NDEBUG 8384 uint64_t CurOffs = 0; 8385 #endif 8386 std::multimap<uint64_t, NamedDecl *>::iterator 8387 CurLayObj = FieldOrBaseOffsets.begin(); 8388 8389 if (CXXRec && CXXRec->isDynamicClass() && 8390 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8391 if (FD) { 8392 S += "\"_vptr$"; 8393 std::string recname = CXXRec->getNameAsString(); 8394 if (recname.empty()) recname = "?"; 8395 S += recname; 8396 S += '"'; 8397 } 8398 S += "^^?"; 8399 #ifndef NDEBUG 8400 CurOffs += getTypeSize(VoidPtrTy); 8401 #endif 8402 } 8403 8404 if (!RDecl->hasFlexibleArrayMember()) { 8405 // Mark the end of the structure. 8406 uint64_t offs = toBits(size); 8407 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8408 std::make_pair(offs, nullptr)); 8409 } 8410 8411 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8412 #ifndef NDEBUG 8413 assert(CurOffs <= CurLayObj->first); 8414 if (CurOffs < CurLayObj->first) { 8415 uint64_t padding = CurLayObj->first - CurOffs; 8416 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8417 // packing/alignment of members is different that normal, in which case 8418 // the encoding will be out-of-sync with the real layout. 8419 // If the runtime switches to just consider the size of types without 8420 // taking into account alignment, we could make padding explicit in the 8421 // encoding (e.g. using arrays of chars). The encoding strings would be 8422 // longer then though. 8423 CurOffs += padding; 8424 } 8425 #endif 8426 8427 NamedDecl *dcl = CurLayObj->second; 8428 if (!dcl) 8429 break; // reached end of structure. 8430 8431 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8432 // We expand the bases without their virtual bases since those are going 8433 // in the initial structure. Note that this differs from gcc which 8434 // expands virtual bases each time one is encountered in the hierarchy, 8435 // making the encoding type bigger than it really is. 8436 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8437 NotEncodedT); 8438 assert(!base->isEmpty()); 8439 #ifndef NDEBUG 8440 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8441 #endif 8442 } else { 8443 const auto *field = cast<FieldDecl>(dcl); 8444 if (FD) { 8445 S += '"'; 8446 S += field->getNameAsString(); 8447 S += '"'; 8448 } 8449 8450 if (field->isBitField()) { 8451 EncodeBitField(this, S, field->getType(), field); 8452 #ifndef NDEBUG 8453 CurOffs += field->getBitWidthValue(*this); 8454 #endif 8455 } else { 8456 QualType qt = field->getType(); 8457 getLegacyIntegralTypeEncoding(qt); 8458 getObjCEncodingForTypeImpl( 8459 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8460 FD, NotEncodedT); 8461 #ifndef NDEBUG 8462 CurOffs += getTypeSize(field->getType()); 8463 #endif 8464 } 8465 } 8466 } 8467 } 8468 8469 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8470 std::string& S) const { 8471 if (QT & Decl::OBJC_TQ_In) 8472 S += 'n'; 8473 if (QT & Decl::OBJC_TQ_Inout) 8474 S += 'N'; 8475 if (QT & Decl::OBJC_TQ_Out) 8476 S += 'o'; 8477 if (QT & Decl::OBJC_TQ_Bycopy) 8478 S += 'O'; 8479 if (QT & Decl::OBJC_TQ_Byref) 8480 S += 'R'; 8481 if (QT & Decl::OBJC_TQ_Oneway) 8482 S += 'V'; 8483 } 8484 8485 TypedefDecl *ASTContext::getObjCIdDecl() const { 8486 if (!ObjCIdDecl) { 8487 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8488 T = getObjCObjectPointerType(T); 8489 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8490 } 8491 return ObjCIdDecl; 8492 } 8493 8494 TypedefDecl *ASTContext::getObjCSelDecl() const { 8495 if (!ObjCSelDecl) { 8496 QualType T = getPointerType(ObjCBuiltinSelTy); 8497 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8498 } 8499 return ObjCSelDecl; 8500 } 8501 8502 TypedefDecl *ASTContext::getObjCClassDecl() const { 8503 if (!ObjCClassDecl) { 8504 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8505 T = getObjCObjectPointerType(T); 8506 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8507 } 8508 return ObjCClassDecl; 8509 } 8510 8511 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8512 if (!ObjCProtocolClassDecl) { 8513 ObjCProtocolClassDecl 8514 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8515 SourceLocation(), 8516 &Idents.get("Protocol"), 8517 /*typeParamList=*/nullptr, 8518 /*PrevDecl=*/nullptr, 8519 SourceLocation(), true); 8520 } 8521 8522 return ObjCProtocolClassDecl; 8523 } 8524 8525 //===----------------------------------------------------------------------===// 8526 // __builtin_va_list Construction Functions 8527 //===----------------------------------------------------------------------===// 8528 8529 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8530 StringRef Name) { 8531 // typedef char* __builtin[_ms]_va_list; 8532 QualType T = Context->getPointerType(Context->CharTy); 8533 return Context->buildImplicitTypedef(T, Name); 8534 } 8535 8536 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8537 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8538 } 8539 8540 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8541 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8542 } 8543 8544 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8545 // typedef void* __builtin_va_list; 8546 QualType T = Context->getPointerType(Context->VoidTy); 8547 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8548 } 8549 8550 static TypedefDecl * 8551 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8552 // struct __va_list 8553 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8554 if (Context->getLangOpts().CPlusPlus) { 8555 // namespace std { struct __va_list { 8556 auto *NS = NamespaceDecl::Create( 8557 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8558 /*Inline*/ false, SourceLocation(), SourceLocation(), 8559 &Context->Idents.get("std"), 8560 /*PrevDecl*/ nullptr); 8561 NS->setImplicit(); 8562 VaListTagDecl->setDeclContext(NS); 8563 } 8564 8565 VaListTagDecl->startDefinition(); 8566 8567 const size_t NumFields = 5; 8568 QualType FieldTypes[NumFields]; 8569 const char *FieldNames[NumFields]; 8570 8571 // void *__stack; 8572 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8573 FieldNames[0] = "__stack"; 8574 8575 // void *__gr_top; 8576 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8577 FieldNames[1] = "__gr_top"; 8578 8579 // void *__vr_top; 8580 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8581 FieldNames[2] = "__vr_top"; 8582 8583 // int __gr_offs; 8584 FieldTypes[3] = Context->IntTy; 8585 FieldNames[3] = "__gr_offs"; 8586 8587 // int __vr_offs; 8588 FieldTypes[4] = Context->IntTy; 8589 FieldNames[4] = "__vr_offs"; 8590 8591 // Create fields 8592 for (unsigned i = 0; i < NumFields; ++i) { 8593 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8594 VaListTagDecl, 8595 SourceLocation(), 8596 SourceLocation(), 8597 &Context->Idents.get(FieldNames[i]), 8598 FieldTypes[i], /*TInfo=*/nullptr, 8599 /*BitWidth=*/nullptr, 8600 /*Mutable=*/false, 8601 ICIS_NoInit); 8602 Field->setAccess(AS_public); 8603 VaListTagDecl->addDecl(Field); 8604 } 8605 VaListTagDecl->completeDefinition(); 8606 Context->VaListTagDecl = VaListTagDecl; 8607 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8608 8609 // } __builtin_va_list; 8610 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8611 } 8612 8613 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8614 // typedef struct __va_list_tag { 8615 RecordDecl *VaListTagDecl; 8616 8617 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8618 VaListTagDecl->startDefinition(); 8619 8620 const size_t NumFields = 5; 8621 QualType FieldTypes[NumFields]; 8622 const char *FieldNames[NumFields]; 8623 8624 // unsigned char gpr; 8625 FieldTypes[0] = Context->UnsignedCharTy; 8626 FieldNames[0] = "gpr"; 8627 8628 // unsigned char fpr; 8629 FieldTypes[1] = Context->UnsignedCharTy; 8630 FieldNames[1] = "fpr"; 8631 8632 // unsigned short reserved; 8633 FieldTypes[2] = Context->UnsignedShortTy; 8634 FieldNames[2] = "reserved"; 8635 8636 // void* overflow_arg_area; 8637 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8638 FieldNames[3] = "overflow_arg_area"; 8639 8640 // void* reg_save_area; 8641 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8642 FieldNames[4] = "reg_save_area"; 8643 8644 // Create fields 8645 for (unsigned i = 0; i < NumFields; ++i) { 8646 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8647 SourceLocation(), 8648 SourceLocation(), 8649 &Context->Idents.get(FieldNames[i]), 8650 FieldTypes[i], /*TInfo=*/nullptr, 8651 /*BitWidth=*/nullptr, 8652 /*Mutable=*/false, 8653 ICIS_NoInit); 8654 Field->setAccess(AS_public); 8655 VaListTagDecl->addDecl(Field); 8656 } 8657 VaListTagDecl->completeDefinition(); 8658 Context->VaListTagDecl = VaListTagDecl; 8659 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8660 8661 // } __va_list_tag; 8662 TypedefDecl *VaListTagTypedefDecl = 8663 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8664 8665 QualType VaListTagTypedefType = 8666 Context->getTypedefType(VaListTagTypedefDecl); 8667 8668 // typedef __va_list_tag __builtin_va_list[1]; 8669 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8670 QualType VaListTagArrayType 8671 = Context->getConstantArrayType(VaListTagTypedefType, 8672 Size, nullptr, ArrayType::Normal, 0); 8673 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8674 } 8675 8676 static TypedefDecl * 8677 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8678 // struct __va_list_tag { 8679 RecordDecl *VaListTagDecl; 8680 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8681 VaListTagDecl->startDefinition(); 8682 8683 const size_t NumFields = 4; 8684 QualType FieldTypes[NumFields]; 8685 const char *FieldNames[NumFields]; 8686 8687 // unsigned gp_offset; 8688 FieldTypes[0] = Context->UnsignedIntTy; 8689 FieldNames[0] = "gp_offset"; 8690 8691 // unsigned fp_offset; 8692 FieldTypes[1] = Context->UnsignedIntTy; 8693 FieldNames[1] = "fp_offset"; 8694 8695 // void* overflow_arg_area; 8696 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8697 FieldNames[2] = "overflow_arg_area"; 8698 8699 // void* reg_save_area; 8700 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8701 FieldNames[3] = "reg_save_area"; 8702 8703 // Create fields 8704 for (unsigned i = 0; i < NumFields; ++i) { 8705 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8706 VaListTagDecl, 8707 SourceLocation(), 8708 SourceLocation(), 8709 &Context->Idents.get(FieldNames[i]), 8710 FieldTypes[i], /*TInfo=*/nullptr, 8711 /*BitWidth=*/nullptr, 8712 /*Mutable=*/false, 8713 ICIS_NoInit); 8714 Field->setAccess(AS_public); 8715 VaListTagDecl->addDecl(Field); 8716 } 8717 VaListTagDecl->completeDefinition(); 8718 Context->VaListTagDecl = VaListTagDecl; 8719 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8720 8721 // }; 8722 8723 // typedef struct __va_list_tag __builtin_va_list[1]; 8724 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8725 QualType VaListTagArrayType = Context->getConstantArrayType( 8726 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8727 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8728 } 8729 8730 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8731 // typedef int __builtin_va_list[4]; 8732 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8733 QualType IntArrayType = Context->getConstantArrayType( 8734 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8735 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8736 } 8737 8738 static TypedefDecl * 8739 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8740 // struct __va_list 8741 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8742 if (Context->getLangOpts().CPlusPlus) { 8743 // namespace std { struct __va_list { 8744 NamespaceDecl *NS; 8745 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8746 Context->getTranslationUnitDecl(), 8747 /*Inline*/false, SourceLocation(), 8748 SourceLocation(), &Context->Idents.get("std"), 8749 /*PrevDecl*/ nullptr); 8750 NS->setImplicit(); 8751 VaListDecl->setDeclContext(NS); 8752 } 8753 8754 VaListDecl->startDefinition(); 8755 8756 // void * __ap; 8757 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8758 VaListDecl, 8759 SourceLocation(), 8760 SourceLocation(), 8761 &Context->Idents.get("__ap"), 8762 Context->getPointerType(Context->VoidTy), 8763 /*TInfo=*/nullptr, 8764 /*BitWidth=*/nullptr, 8765 /*Mutable=*/false, 8766 ICIS_NoInit); 8767 Field->setAccess(AS_public); 8768 VaListDecl->addDecl(Field); 8769 8770 // }; 8771 VaListDecl->completeDefinition(); 8772 Context->VaListTagDecl = VaListDecl; 8773 8774 // typedef struct __va_list __builtin_va_list; 8775 QualType T = Context->getRecordType(VaListDecl); 8776 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8777 } 8778 8779 static TypedefDecl * 8780 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8781 // struct __va_list_tag { 8782 RecordDecl *VaListTagDecl; 8783 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8784 VaListTagDecl->startDefinition(); 8785 8786 const size_t NumFields = 4; 8787 QualType FieldTypes[NumFields]; 8788 const char *FieldNames[NumFields]; 8789 8790 // long __gpr; 8791 FieldTypes[0] = Context->LongTy; 8792 FieldNames[0] = "__gpr"; 8793 8794 // long __fpr; 8795 FieldTypes[1] = Context->LongTy; 8796 FieldNames[1] = "__fpr"; 8797 8798 // void *__overflow_arg_area; 8799 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8800 FieldNames[2] = "__overflow_arg_area"; 8801 8802 // void *__reg_save_area; 8803 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8804 FieldNames[3] = "__reg_save_area"; 8805 8806 // Create fields 8807 for (unsigned i = 0; i < NumFields; ++i) { 8808 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8809 VaListTagDecl, 8810 SourceLocation(), 8811 SourceLocation(), 8812 &Context->Idents.get(FieldNames[i]), 8813 FieldTypes[i], /*TInfo=*/nullptr, 8814 /*BitWidth=*/nullptr, 8815 /*Mutable=*/false, 8816 ICIS_NoInit); 8817 Field->setAccess(AS_public); 8818 VaListTagDecl->addDecl(Field); 8819 } 8820 VaListTagDecl->completeDefinition(); 8821 Context->VaListTagDecl = VaListTagDecl; 8822 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8823 8824 // }; 8825 8826 // typedef __va_list_tag __builtin_va_list[1]; 8827 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8828 QualType VaListTagArrayType = Context->getConstantArrayType( 8829 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8830 8831 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8832 } 8833 8834 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8835 // typedef struct __va_list_tag { 8836 RecordDecl *VaListTagDecl; 8837 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8838 VaListTagDecl->startDefinition(); 8839 8840 const size_t NumFields = 3; 8841 QualType FieldTypes[NumFields]; 8842 const char *FieldNames[NumFields]; 8843 8844 // void *CurrentSavedRegisterArea; 8845 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8846 FieldNames[0] = "__current_saved_reg_area_pointer"; 8847 8848 // void *SavedRegAreaEnd; 8849 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8850 FieldNames[1] = "__saved_reg_area_end_pointer"; 8851 8852 // void *OverflowArea; 8853 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8854 FieldNames[2] = "__overflow_area_pointer"; 8855 8856 // Create fields 8857 for (unsigned i = 0; i < NumFields; ++i) { 8858 FieldDecl *Field = FieldDecl::Create( 8859 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8860 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8861 /*TInfo=*/nullptr, 8862 /*BitWidth=*/nullptr, 8863 /*Mutable=*/false, ICIS_NoInit); 8864 Field->setAccess(AS_public); 8865 VaListTagDecl->addDecl(Field); 8866 } 8867 VaListTagDecl->completeDefinition(); 8868 Context->VaListTagDecl = VaListTagDecl; 8869 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8870 8871 // } __va_list_tag; 8872 TypedefDecl *VaListTagTypedefDecl = 8873 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8874 8875 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8876 8877 // typedef __va_list_tag __builtin_va_list[1]; 8878 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8879 QualType VaListTagArrayType = Context->getConstantArrayType( 8880 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8881 8882 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8883 } 8884 8885 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8886 TargetInfo::BuiltinVaListKind Kind) { 8887 switch (Kind) { 8888 case TargetInfo::CharPtrBuiltinVaList: 8889 return CreateCharPtrBuiltinVaListDecl(Context); 8890 case TargetInfo::VoidPtrBuiltinVaList: 8891 return CreateVoidPtrBuiltinVaListDecl(Context); 8892 case TargetInfo::AArch64ABIBuiltinVaList: 8893 return CreateAArch64ABIBuiltinVaListDecl(Context); 8894 case TargetInfo::PowerABIBuiltinVaList: 8895 return CreatePowerABIBuiltinVaListDecl(Context); 8896 case TargetInfo::X86_64ABIBuiltinVaList: 8897 return CreateX86_64ABIBuiltinVaListDecl(Context); 8898 case TargetInfo::PNaClABIBuiltinVaList: 8899 return CreatePNaClABIBuiltinVaListDecl(Context); 8900 case TargetInfo::AAPCSABIBuiltinVaList: 8901 return CreateAAPCSABIBuiltinVaListDecl(Context); 8902 case TargetInfo::SystemZBuiltinVaList: 8903 return CreateSystemZBuiltinVaListDecl(Context); 8904 case TargetInfo::HexagonBuiltinVaList: 8905 return CreateHexagonBuiltinVaListDecl(Context); 8906 } 8907 8908 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8909 } 8910 8911 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8912 if (!BuiltinVaListDecl) { 8913 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8914 assert(BuiltinVaListDecl->isImplicit()); 8915 } 8916 8917 return BuiltinVaListDecl; 8918 } 8919 8920 Decl *ASTContext::getVaListTagDecl() const { 8921 // Force the creation of VaListTagDecl by building the __builtin_va_list 8922 // declaration. 8923 if (!VaListTagDecl) 8924 (void)getBuiltinVaListDecl(); 8925 8926 return VaListTagDecl; 8927 } 8928 8929 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8930 if (!BuiltinMSVaListDecl) 8931 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8932 8933 return BuiltinMSVaListDecl; 8934 } 8935 8936 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8937 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8938 } 8939 8940 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8941 assert(ObjCConstantStringType.isNull() && 8942 "'NSConstantString' type already set!"); 8943 8944 ObjCConstantStringType = getObjCInterfaceType(Decl); 8945 } 8946 8947 /// Retrieve the template name that corresponds to a non-empty 8948 /// lookup. 8949 TemplateName 8950 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8951 UnresolvedSetIterator End) const { 8952 unsigned size = End - Begin; 8953 assert(size > 1 && "set is not overloaded!"); 8954 8955 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8956 size * sizeof(FunctionTemplateDecl*)); 8957 auto *OT = new (memory) OverloadedTemplateStorage(size); 8958 8959 NamedDecl **Storage = OT->getStorage(); 8960 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8961 NamedDecl *D = *I; 8962 assert(isa<FunctionTemplateDecl>(D) || 8963 isa<UnresolvedUsingValueDecl>(D) || 8964 (isa<UsingShadowDecl>(D) && 8965 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8966 *Storage++ = D; 8967 } 8968 8969 return TemplateName(OT); 8970 } 8971 8972 /// Retrieve a template name representing an unqualified-id that has been 8973 /// assumed to name a template for ADL purposes. 8974 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8975 auto *OT = new (*this) AssumedTemplateStorage(Name); 8976 return TemplateName(OT); 8977 } 8978 8979 /// Retrieve the template name that represents a qualified 8980 /// template name such as \c std::vector. 8981 TemplateName 8982 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8983 bool TemplateKeyword, 8984 TemplateDecl *Template) const { 8985 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8986 8987 // FIXME: Canonicalization? 8988 llvm::FoldingSetNodeID ID; 8989 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8990 8991 void *InsertPos = nullptr; 8992 QualifiedTemplateName *QTN = 8993 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8994 if (!QTN) { 8995 QTN = new (*this, alignof(QualifiedTemplateName)) 8996 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8997 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8998 } 8999 9000 return TemplateName(QTN); 9001 } 9002 9003 /// Retrieve the template name that represents a dependent 9004 /// template name such as \c MetaFun::template apply. 9005 TemplateName 9006 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9007 const IdentifierInfo *Name) const { 9008 assert((!NNS || NNS->isDependent()) && 9009 "Nested name specifier must be dependent"); 9010 9011 llvm::FoldingSetNodeID ID; 9012 DependentTemplateName::Profile(ID, NNS, Name); 9013 9014 void *InsertPos = nullptr; 9015 DependentTemplateName *QTN = 9016 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9017 9018 if (QTN) 9019 return TemplateName(QTN); 9020 9021 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9022 if (CanonNNS == NNS) { 9023 QTN = new (*this, alignof(DependentTemplateName)) 9024 DependentTemplateName(NNS, Name); 9025 } else { 9026 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9027 QTN = new (*this, alignof(DependentTemplateName)) 9028 DependentTemplateName(NNS, Name, Canon); 9029 DependentTemplateName *CheckQTN = 9030 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9031 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9032 (void)CheckQTN; 9033 } 9034 9035 DependentTemplateNames.InsertNode(QTN, InsertPos); 9036 return TemplateName(QTN); 9037 } 9038 9039 /// Retrieve the template name that represents a dependent 9040 /// template name such as \c MetaFun::template operator+. 9041 TemplateName 9042 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9043 OverloadedOperatorKind Operator) const { 9044 assert((!NNS || NNS->isDependent()) && 9045 "Nested name specifier must be dependent"); 9046 9047 llvm::FoldingSetNodeID ID; 9048 DependentTemplateName::Profile(ID, NNS, Operator); 9049 9050 void *InsertPos = nullptr; 9051 DependentTemplateName *QTN 9052 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9053 9054 if (QTN) 9055 return TemplateName(QTN); 9056 9057 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9058 if (CanonNNS == NNS) { 9059 QTN = new (*this, alignof(DependentTemplateName)) 9060 DependentTemplateName(NNS, Operator); 9061 } else { 9062 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9063 QTN = new (*this, alignof(DependentTemplateName)) 9064 DependentTemplateName(NNS, Operator, Canon); 9065 9066 DependentTemplateName *CheckQTN 9067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9068 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9069 (void)CheckQTN; 9070 } 9071 9072 DependentTemplateNames.InsertNode(QTN, InsertPos); 9073 return TemplateName(QTN); 9074 } 9075 9076 TemplateName 9077 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9078 TemplateName replacement) const { 9079 llvm::FoldingSetNodeID ID; 9080 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9081 9082 void *insertPos = nullptr; 9083 SubstTemplateTemplateParmStorage *subst 9084 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9085 9086 if (!subst) { 9087 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9088 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9089 } 9090 9091 return TemplateName(subst); 9092 } 9093 9094 TemplateName 9095 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9096 const TemplateArgument &ArgPack) const { 9097 auto &Self = const_cast<ASTContext &>(*this); 9098 llvm::FoldingSetNodeID ID; 9099 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9100 9101 void *InsertPos = nullptr; 9102 SubstTemplateTemplateParmPackStorage *Subst 9103 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9104 9105 if (!Subst) { 9106 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9107 ArgPack.pack_size(), 9108 ArgPack.pack_begin()); 9109 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9110 } 9111 9112 return TemplateName(Subst); 9113 } 9114 9115 /// getFromTargetType - Given one of the integer types provided by 9116 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9117 /// is actually a value of type @c TargetInfo::IntType. 9118 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9119 switch (Type) { 9120 case TargetInfo::NoInt: return {}; 9121 case TargetInfo::SignedChar: return SignedCharTy; 9122 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9123 case TargetInfo::SignedShort: return ShortTy; 9124 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9125 case TargetInfo::SignedInt: return IntTy; 9126 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9127 case TargetInfo::SignedLong: return LongTy; 9128 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9129 case TargetInfo::SignedLongLong: return LongLongTy; 9130 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9131 } 9132 9133 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9134 } 9135 9136 //===----------------------------------------------------------------------===// 9137 // Type Predicates. 9138 //===----------------------------------------------------------------------===// 9139 9140 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9141 /// garbage collection attribute. 9142 /// 9143 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9144 if (getLangOpts().getGC() == LangOptions::NonGC) 9145 return Qualifiers::GCNone; 9146 9147 assert(getLangOpts().ObjC); 9148 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9149 9150 // Default behaviour under objective-C's gc is for ObjC pointers 9151 // (or pointers to them) be treated as though they were declared 9152 // as __strong. 9153 if (GCAttrs == Qualifiers::GCNone) { 9154 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9155 return Qualifiers::Strong; 9156 else if (Ty->isPointerType()) 9157 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9158 } else { 9159 // It's not valid to set GC attributes on anything that isn't a 9160 // pointer. 9161 #ifndef NDEBUG 9162 QualType CT = Ty->getCanonicalTypeInternal(); 9163 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9164 CT = AT->getElementType(); 9165 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9166 #endif 9167 } 9168 return GCAttrs; 9169 } 9170 9171 //===----------------------------------------------------------------------===// 9172 // Type Compatibility Testing 9173 //===----------------------------------------------------------------------===// 9174 9175 /// areCompatVectorTypes - Return true if the two specified vector types are 9176 /// compatible. 9177 static bool areCompatVectorTypes(const VectorType *LHS, 9178 const VectorType *RHS) { 9179 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9180 return LHS->getElementType() == RHS->getElementType() && 9181 LHS->getNumElements() == RHS->getNumElements(); 9182 } 9183 9184 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9185 /// compatible. 9186 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9187 const ConstantMatrixType *RHS) { 9188 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9189 return LHS->getElementType() == RHS->getElementType() && 9190 LHS->getNumRows() == RHS->getNumRows() && 9191 LHS->getNumColumns() == RHS->getNumColumns(); 9192 } 9193 9194 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9195 QualType SecondVec) { 9196 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9197 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9198 9199 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9200 return true; 9201 9202 // Treat Neon vector types and most AltiVec vector types as if they are the 9203 // equivalent GCC vector types. 9204 const auto *First = FirstVec->castAs<VectorType>(); 9205 const auto *Second = SecondVec->castAs<VectorType>(); 9206 if (First->getNumElements() == Second->getNumElements() && 9207 hasSameType(First->getElementType(), Second->getElementType()) && 9208 First->getVectorKind() != VectorType::AltiVecPixel && 9209 First->getVectorKind() != VectorType::AltiVecBool && 9210 Second->getVectorKind() != VectorType::AltiVecPixel && 9211 Second->getVectorKind() != VectorType::AltiVecBool && 9212 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9213 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9214 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9215 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9216 return true; 9217 9218 return false; 9219 } 9220 9221 /// getSVETypeSize - Return SVE vector or predicate register size. 9222 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9223 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9224 return Ty->getKind() == BuiltinType::SveBool 9225 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9226 : Context.getLangOpts().VScaleMin * 128; 9227 } 9228 9229 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9230 QualType SecondType) { 9231 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9232 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9233 "Expected SVE builtin type and vector type!"); 9234 9235 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9236 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9237 if (const auto *VT = SecondType->getAs<VectorType>()) { 9238 // Predicates have the same representation as uint8 so we also have to 9239 // check the kind to make these types incompatible. 9240 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9241 return BT->getKind() == BuiltinType::SveBool; 9242 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9243 return VT->getElementType().getCanonicalType() == 9244 FirstType->getSveEltType(*this); 9245 else if (VT->getVectorKind() == VectorType::GenericVector) 9246 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9247 hasSameType(VT->getElementType(), 9248 getBuiltinVectorTypeInfo(BT).ElementType); 9249 } 9250 } 9251 return false; 9252 }; 9253 9254 return IsValidCast(FirstType, SecondType) || 9255 IsValidCast(SecondType, FirstType); 9256 } 9257 9258 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9259 QualType SecondType) { 9260 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9261 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9262 "Expected SVE builtin type and vector type!"); 9263 9264 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9265 const auto *BT = FirstType->getAs<BuiltinType>(); 9266 if (!BT) 9267 return false; 9268 9269 const auto *VecTy = SecondType->getAs<VectorType>(); 9270 if (VecTy && 9271 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9272 VecTy->getVectorKind() == VectorType::GenericVector)) { 9273 const LangOptions::LaxVectorConversionKind LVCKind = 9274 getLangOpts().getLaxVectorConversions(); 9275 9276 // Can not convert between sve predicates and sve vectors because of 9277 // different size. 9278 if (BT->getKind() == BuiltinType::SveBool && 9279 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9280 return false; 9281 9282 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9283 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9284 // converts to VLAT and VLAT implicitly converts to GNUT." 9285 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9286 // predicates. 9287 if (VecTy->getVectorKind() == VectorType::GenericVector && 9288 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9289 return false; 9290 9291 // If -flax-vector-conversions=all is specified, the types are 9292 // certainly compatible. 9293 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9294 return true; 9295 9296 // If -flax-vector-conversions=integer is specified, the types are 9297 // compatible if the elements are integer types. 9298 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9299 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9300 FirstType->getSveEltType(*this)->isIntegerType(); 9301 } 9302 9303 return false; 9304 }; 9305 9306 return IsLaxCompatible(FirstType, SecondType) || 9307 IsLaxCompatible(SecondType, FirstType); 9308 } 9309 9310 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9311 while (true) { 9312 // __strong id 9313 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9314 if (Attr->getAttrKind() == attr::ObjCOwnership) 9315 return true; 9316 9317 Ty = Attr->getModifiedType(); 9318 9319 // X *__strong (...) 9320 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9321 Ty = Paren->getInnerType(); 9322 9323 // We do not want to look through typedefs, typeof(expr), 9324 // typeof(type), or any other way that the type is somehow 9325 // abstracted. 9326 } else { 9327 return false; 9328 } 9329 } 9330 } 9331 9332 //===----------------------------------------------------------------------===// 9333 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9334 //===----------------------------------------------------------------------===// 9335 9336 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9337 /// inheritance hierarchy of 'rProto'. 9338 bool 9339 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9340 ObjCProtocolDecl *rProto) const { 9341 if (declaresSameEntity(lProto, rProto)) 9342 return true; 9343 for (auto *PI : rProto->protocols()) 9344 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9345 return true; 9346 return false; 9347 } 9348 9349 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9350 /// Class<pr1, ...>. 9351 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9352 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9353 for (auto *lhsProto : lhs->quals()) { 9354 bool match = false; 9355 for (auto *rhsProto : rhs->quals()) { 9356 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9357 match = true; 9358 break; 9359 } 9360 } 9361 if (!match) 9362 return false; 9363 } 9364 return true; 9365 } 9366 9367 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9368 /// ObjCQualifiedIDType. 9369 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9370 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9371 bool compare) { 9372 // Allow id<P..> and an 'id' in all cases. 9373 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9374 return true; 9375 9376 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9377 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9378 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9379 return false; 9380 9381 if (lhs->isObjCQualifiedIdType()) { 9382 if (rhs->qual_empty()) { 9383 // If the RHS is a unqualified interface pointer "NSString*", 9384 // make sure we check the class hierarchy. 9385 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9386 for (auto *I : lhs->quals()) { 9387 // when comparing an id<P> on lhs with a static type on rhs, 9388 // see if static class implements all of id's protocols, directly or 9389 // through its super class and categories. 9390 if (!rhsID->ClassImplementsProtocol(I, true)) 9391 return false; 9392 } 9393 } 9394 // If there are no qualifiers and no interface, we have an 'id'. 9395 return true; 9396 } 9397 // Both the right and left sides have qualifiers. 9398 for (auto *lhsProto : lhs->quals()) { 9399 bool match = false; 9400 9401 // when comparing an id<P> on lhs with a static type on rhs, 9402 // see if static class implements all of id's protocols, directly or 9403 // through its super class and categories. 9404 for (auto *rhsProto : rhs->quals()) { 9405 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9406 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9407 match = true; 9408 break; 9409 } 9410 } 9411 // If the RHS is a qualified interface pointer "NSString<P>*", 9412 // make sure we check the class hierarchy. 9413 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9414 for (auto *I : lhs->quals()) { 9415 // when comparing an id<P> on lhs with a static type on rhs, 9416 // see if static class implements all of id's protocols, directly or 9417 // through its super class and categories. 9418 if (rhsID->ClassImplementsProtocol(I, true)) { 9419 match = true; 9420 break; 9421 } 9422 } 9423 } 9424 if (!match) 9425 return false; 9426 } 9427 9428 return true; 9429 } 9430 9431 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9432 9433 if (lhs->getInterfaceType()) { 9434 // If both the right and left sides have qualifiers. 9435 for (auto *lhsProto : lhs->quals()) { 9436 bool match = false; 9437 9438 // when comparing an id<P> on rhs with a static type on lhs, 9439 // see if static class implements all of id's protocols, directly or 9440 // through its super class and categories. 9441 // First, lhs protocols in the qualifier list must be found, direct 9442 // or indirect in rhs's qualifier list or it is a mismatch. 9443 for (auto *rhsProto : rhs->quals()) { 9444 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9445 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9446 match = true; 9447 break; 9448 } 9449 } 9450 if (!match) 9451 return false; 9452 } 9453 9454 // Static class's protocols, or its super class or category protocols 9455 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9456 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9458 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9459 // This is rather dubious but matches gcc's behavior. If lhs has 9460 // no type qualifier and its class has no static protocol(s) 9461 // assume that it is mismatch. 9462 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9463 return false; 9464 for (auto *lhsProto : LHSInheritedProtocols) { 9465 bool match = false; 9466 for (auto *rhsProto : rhs->quals()) { 9467 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9468 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9469 match = true; 9470 break; 9471 } 9472 } 9473 if (!match) 9474 return false; 9475 } 9476 } 9477 return true; 9478 } 9479 return false; 9480 } 9481 9482 /// canAssignObjCInterfaces - Return true if the two interface types are 9483 /// compatible for assignment from RHS to LHS. This handles validation of any 9484 /// protocol qualifiers on the LHS or RHS. 9485 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9486 const ObjCObjectPointerType *RHSOPT) { 9487 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9488 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9489 9490 // If either type represents the built-in 'id' type, return true. 9491 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9492 return true; 9493 9494 // Function object that propagates a successful result or handles 9495 // __kindof types. 9496 auto finish = [&](bool succeeded) -> bool { 9497 if (succeeded) 9498 return true; 9499 9500 if (!RHS->isKindOfType()) 9501 return false; 9502 9503 // Strip off __kindof and protocol qualifiers, then check whether 9504 // we can assign the other way. 9505 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9506 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9507 }; 9508 9509 // Casts from or to id<P> are allowed when the other side has compatible 9510 // protocols. 9511 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9512 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9513 } 9514 9515 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9516 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9517 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9518 } 9519 9520 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9521 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9522 return true; 9523 } 9524 9525 // If we have 2 user-defined types, fall into that path. 9526 if (LHS->getInterface() && RHS->getInterface()) { 9527 return finish(canAssignObjCInterfaces(LHS, RHS)); 9528 } 9529 9530 return false; 9531 } 9532 9533 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9534 /// for providing type-safety for objective-c pointers used to pass/return 9535 /// arguments in block literals. When passed as arguments, passing 'A*' where 9536 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9537 /// not OK. For the return type, the opposite is not OK. 9538 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9539 const ObjCObjectPointerType *LHSOPT, 9540 const ObjCObjectPointerType *RHSOPT, 9541 bool BlockReturnType) { 9542 9543 // Function object that propagates a successful result or handles 9544 // __kindof types. 9545 auto finish = [&](bool succeeded) -> bool { 9546 if (succeeded) 9547 return true; 9548 9549 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9550 if (!Expected->isKindOfType()) 9551 return false; 9552 9553 // Strip off __kindof and protocol qualifiers, then check whether 9554 // we can assign the other way. 9555 return canAssignObjCInterfacesInBlockPointer( 9556 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9557 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9558 BlockReturnType); 9559 }; 9560 9561 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9562 return true; 9563 9564 if (LHSOPT->isObjCBuiltinType()) { 9565 return finish(RHSOPT->isObjCBuiltinType() || 9566 RHSOPT->isObjCQualifiedIdType()); 9567 } 9568 9569 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9570 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9571 // Use for block parameters previous type checking for compatibility. 9572 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9573 // Or corrected type checking as in non-compat mode. 9574 (!BlockReturnType && 9575 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9576 else 9577 return finish(ObjCQualifiedIdTypesAreCompatible( 9578 (BlockReturnType ? LHSOPT : RHSOPT), 9579 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9580 } 9581 9582 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9583 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9584 if (LHS && RHS) { // We have 2 user-defined types. 9585 if (LHS != RHS) { 9586 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9587 return finish(BlockReturnType); 9588 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9589 return finish(!BlockReturnType); 9590 } 9591 else 9592 return true; 9593 } 9594 return false; 9595 } 9596 9597 /// Comparison routine for Objective-C protocols to be used with 9598 /// llvm::array_pod_sort. 9599 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9600 ObjCProtocolDecl * const *rhs) { 9601 return (*lhs)->getName().compare((*rhs)->getName()); 9602 } 9603 9604 /// getIntersectionOfProtocols - This routine finds the intersection of set 9605 /// of protocols inherited from two distinct objective-c pointer objects with 9606 /// the given common base. 9607 /// It is used to build composite qualifier list of the composite type of 9608 /// the conditional expression involving two objective-c pointer objects. 9609 static 9610 void getIntersectionOfProtocols(ASTContext &Context, 9611 const ObjCInterfaceDecl *CommonBase, 9612 const ObjCObjectPointerType *LHSOPT, 9613 const ObjCObjectPointerType *RHSOPT, 9614 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9615 9616 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9617 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9618 assert(LHS->getInterface() && "LHS must have an interface base"); 9619 assert(RHS->getInterface() && "RHS must have an interface base"); 9620 9621 // Add all of the protocols for the LHS. 9622 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9623 9624 // Start with the protocol qualifiers. 9625 for (auto proto : LHS->quals()) { 9626 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9627 } 9628 9629 // Also add the protocols associated with the LHS interface. 9630 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9631 9632 // Add all of the protocols for the RHS. 9633 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9634 9635 // Start with the protocol qualifiers. 9636 for (auto proto : RHS->quals()) { 9637 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9638 } 9639 9640 // Also add the protocols associated with the RHS interface. 9641 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9642 9643 // Compute the intersection of the collected protocol sets. 9644 for (auto proto : LHSProtocolSet) { 9645 if (RHSProtocolSet.count(proto)) 9646 IntersectionSet.push_back(proto); 9647 } 9648 9649 // Compute the set of protocols that is implied by either the common type or 9650 // the protocols within the intersection. 9651 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9652 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9653 9654 // Remove any implied protocols from the list of inherited protocols. 9655 if (!ImpliedProtocols.empty()) { 9656 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9657 return ImpliedProtocols.contains(proto); 9658 }); 9659 } 9660 9661 // Sort the remaining protocols by name. 9662 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9663 compareObjCProtocolsByName); 9664 } 9665 9666 /// Determine whether the first type is a subtype of the second. 9667 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9668 QualType rhs) { 9669 // Common case: two object pointers. 9670 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9671 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9672 if (lhsOPT && rhsOPT) 9673 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9674 9675 // Two block pointers. 9676 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9677 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9678 if (lhsBlock && rhsBlock) 9679 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9680 9681 // If either is an unqualified 'id' and the other is a block, it's 9682 // acceptable. 9683 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9684 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9685 return true; 9686 9687 return false; 9688 } 9689 9690 // Check that the given Objective-C type argument lists are equivalent. 9691 static bool sameObjCTypeArgs(ASTContext &ctx, 9692 const ObjCInterfaceDecl *iface, 9693 ArrayRef<QualType> lhsArgs, 9694 ArrayRef<QualType> rhsArgs, 9695 bool stripKindOf) { 9696 if (lhsArgs.size() != rhsArgs.size()) 9697 return false; 9698 9699 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9700 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9701 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9702 continue; 9703 9704 switch (typeParams->begin()[i]->getVariance()) { 9705 case ObjCTypeParamVariance::Invariant: 9706 if (!stripKindOf || 9707 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9708 rhsArgs[i].stripObjCKindOfType(ctx))) { 9709 return false; 9710 } 9711 break; 9712 9713 case ObjCTypeParamVariance::Covariant: 9714 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9715 return false; 9716 break; 9717 9718 case ObjCTypeParamVariance::Contravariant: 9719 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9720 return false; 9721 break; 9722 } 9723 } 9724 9725 return true; 9726 } 9727 9728 QualType ASTContext::areCommonBaseCompatible( 9729 const ObjCObjectPointerType *Lptr, 9730 const ObjCObjectPointerType *Rptr) { 9731 const ObjCObjectType *LHS = Lptr->getObjectType(); 9732 const ObjCObjectType *RHS = Rptr->getObjectType(); 9733 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9734 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9735 9736 if (!LDecl || !RDecl) 9737 return {}; 9738 9739 // When either LHS or RHS is a kindof type, we should return a kindof type. 9740 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9741 // kindof(A). 9742 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9743 9744 // Follow the left-hand side up the class hierarchy until we either hit a 9745 // root or find the RHS. Record the ancestors in case we don't find it. 9746 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9747 LHSAncestors; 9748 while (true) { 9749 // Record this ancestor. We'll need this if the common type isn't in the 9750 // path from the LHS to the root. 9751 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9752 9753 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9754 // Get the type arguments. 9755 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9756 bool anyChanges = false; 9757 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9758 // Both have type arguments, compare them. 9759 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9760 LHS->getTypeArgs(), RHS->getTypeArgs(), 9761 /*stripKindOf=*/true)) 9762 return {}; 9763 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9764 // If only one has type arguments, the result will not have type 9765 // arguments. 9766 LHSTypeArgs = {}; 9767 anyChanges = true; 9768 } 9769 9770 // Compute the intersection of protocols. 9771 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9772 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9773 Protocols); 9774 if (!Protocols.empty()) 9775 anyChanges = true; 9776 9777 // If anything in the LHS will have changed, build a new result type. 9778 // If we need to return a kindof type but LHS is not a kindof type, we 9779 // build a new result type. 9780 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9781 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9782 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9783 anyKindOf || LHS->isKindOfType()); 9784 return getObjCObjectPointerType(Result); 9785 } 9786 9787 return getObjCObjectPointerType(QualType(LHS, 0)); 9788 } 9789 9790 // Find the superclass. 9791 QualType LHSSuperType = LHS->getSuperClassType(); 9792 if (LHSSuperType.isNull()) 9793 break; 9794 9795 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9796 } 9797 9798 // We didn't find anything by following the LHS to its root; now check 9799 // the RHS against the cached set of ancestors. 9800 while (true) { 9801 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9802 if (KnownLHS != LHSAncestors.end()) { 9803 LHS = KnownLHS->second; 9804 9805 // Get the type arguments. 9806 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9807 bool anyChanges = false; 9808 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9809 // Both have type arguments, compare them. 9810 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9811 LHS->getTypeArgs(), RHS->getTypeArgs(), 9812 /*stripKindOf=*/true)) 9813 return {}; 9814 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9815 // If only one has type arguments, the result will not have type 9816 // arguments. 9817 RHSTypeArgs = {}; 9818 anyChanges = true; 9819 } 9820 9821 // Compute the intersection of protocols. 9822 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9823 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9824 Protocols); 9825 if (!Protocols.empty()) 9826 anyChanges = true; 9827 9828 // If we need to return a kindof type but RHS is not a kindof type, we 9829 // build a new result type. 9830 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9831 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9832 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9833 anyKindOf || RHS->isKindOfType()); 9834 return getObjCObjectPointerType(Result); 9835 } 9836 9837 return getObjCObjectPointerType(QualType(RHS, 0)); 9838 } 9839 9840 // Find the superclass of the RHS. 9841 QualType RHSSuperType = RHS->getSuperClassType(); 9842 if (RHSSuperType.isNull()) 9843 break; 9844 9845 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9846 } 9847 9848 return {}; 9849 } 9850 9851 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9852 const ObjCObjectType *RHS) { 9853 assert(LHS->getInterface() && "LHS is not an interface type"); 9854 assert(RHS->getInterface() && "RHS is not an interface type"); 9855 9856 // Verify that the base decls are compatible: the RHS must be a subclass of 9857 // the LHS. 9858 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9859 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9860 if (!IsSuperClass) 9861 return false; 9862 9863 // If the LHS has protocol qualifiers, determine whether all of them are 9864 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9865 // LHS). 9866 if (LHS->getNumProtocols() > 0) { 9867 // OK if conversion of LHS to SuperClass results in narrowing of types 9868 // ; i.e., SuperClass may implement at least one of the protocols 9869 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9870 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9871 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9872 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9873 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9874 // qualifiers. 9875 for (auto *RHSPI : RHS->quals()) 9876 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9877 // If there is no protocols associated with RHS, it is not a match. 9878 if (SuperClassInheritedProtocols.empty()) 9879 return false; 9880 9881 for (const auto *LHSProto : LHS->quals()) { 9882 bool SuperImplementsProtocol = false; 9883 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9884 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9885 SuperImplementsProtocol = true; 9886 break; 9887 } 9888 if (!SuperImplementsProtocol) 9889 return false; 9890 } 9891 } 9892 9893 // If the LHS is specialized, we may need to check type arguments. 9894 if (LHS->isSpecialized()) { 9895 // Follow the superclass chain until we've matched the LHS class in the 9896 // hierarchy. This substitutes type arguments through. 9897 const ObjCObjectType *RHSSuper = RHS; 9898 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9899 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9900 9901 // If the RHS is specializd, compare type arguments. 9902 if (RHSSuper->isSpecialized() && 9903 !sameObjCTypeArgs(*this, LHS->getInterface(), 9904 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9905 /*stripKindOf=*/true)) { 9906 return false; 9907 } 9908 } 9909 9910 return true; 9911 } 9912 9913 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9914 // get the "pointed to" types 9915 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9916 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9917 9918 if (!LHSOPT || !RHSOPT) 9919 return false; 9920 9921 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9922 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9923 } 9924 9925 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9926 return canAssignObjCInterfaces( 9927 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9928 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9929 } 9930 9931 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9932 /// both shall have the identically qualified version of a compatible type. 9933 /// C99 6.2.7p1: Two types have compatible types if their types are the 9934 /// same. See 6.7.[2,3,5] for additional rules. 9935 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9936 bool CompareUnqualified) { 9937 if (getLangOpts().CPlusPlus) 9938 return hasSameType(LHS, RHS); 9939 9940 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9941 } 9942 9943 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9944 return typesAreCompatible(LHS, RHS); 9945 } 9946 9947 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9948 return !mergeTypes(LHS, RHS, true).isNull(); 9949 } 9950 9951 /// mergeTransparentUnionType - if T is a transparent union type and a member 9952 /// of T is compatible with SubType, return the merged type, else return 9953 /// QualType() 9954 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9955 bool OfBlockPointer, 9956 bool Unqualified) { 9957 if (const RecordType *UT = T->getAsUnionType()) { 9958 RecordDecl *UD = UT->getDecl(); 9959 if (UD->hasAttr<TransparentUnionAttr>()) { 9960 for (const auto *I : UD->fields()) { 9961 QualType ET = I->getType().getUnqualifiedType(); 9962 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9963 if (!MT.isNull()) 9964 return MT; 9965 } 9966 } 9967 } 9968 9969 return {}; 9970 } 9971 9972 /// mergeFunctionParameterTypes - merge two types which appear as function 9973 /// parameter types 9974 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9975 bool OfBlockPointer, 9976 bool Unqualified) { 9977 // GNU extension: two types are compatible if they appear as a function 9978 // argument, one of the types is a transparent union type and the other 9979 // type is compatible with a union member 9980 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9981 Unqualified); 9982 if (!lmerge.isNull()) 9983 return lmerge; 9984 9985 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9986 Unqualified); 9987 if (!rmerge.isNull()) 9988 return rmerge; 9989 9990 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9991 } 9992 9993 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9994 bool OfBlockPointer, bool Unqualified, 9995 bool AllowCXX) { 9996 const auto *lbase = lhs->castAs<FunctionType>(); 9997 const auto *rbase = rhs->castAs<FunctionType>(); 9998 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9999 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 10000 bool allLTypes = true; 10001 bool allRTypes = true; 10002 10003 // Check return type 10004 QualType retType; 10005 if (OfBlockPointer) { 10006 QualType RHS = rbase->getReturnType(); 10007 QualType LHS = lbase->getReturnType(); 10008 bool UnqualifiedResult = Unqualified; 10009 if (!UnqualifiedResult) 10010 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10011 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10012 } 10013 else 10014 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10015 Unqualified); 10016 if (retType.isNull()) 10017 return {}; 10018 10019 if (Unqualified) 10020 retType = retType.getUnqualifiedType(); 10021 10022 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10023 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10024 if (Unqualified) { 10025 LRetType = LRetType.getUnqualifiedType(); 10026 RRetType = RRetType.getUnqualifiedType(); 10027 } 10028 10029 if (getCanonicalType(retType) != LRetType) 10030 allLTypes = false; 10031 if (getCanonicalType(retType) != RRetType) 10032 allRTypes = false; 10033 10034 // FIXME: double check this 10035 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10036 // rbase->getRegParmAttr() != 0 && 10037 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10038 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10039 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10040 10041 // Compatible functions must have compatible calling conventions 10042 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10043 return {}; 10044 10045 // Regparm is part of the calling convention. 10046 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10047 return {}; 10048 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10049 return {}; 10050 10051 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10052 return {}; 10053 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10054 return {}; 10055 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10056 return {}; 10057 10058 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10059 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10060 10061 if (lbaseInfo.getNoReturn() != NoReturn) 10062 allLTypes = false; 10063 if (rbaseInfo.getNoReturn() != NoReturn) 10064 allRTypes = false; 10065 10066 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10067 10068 if (lproto && rproto) { // two C99 style function prototypes 10069 assert((AllowCXX || 10070 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10071 "C++ shouldn't be here"); 10072 // Compatible functions must have the same number of parameters 10073 if (lproto->getNumParams() != rproto->getNumParams()) 10074 return {}; 10075 10076 // Variadic and non-variadic functions aren't compatible 10077 if (lproto->isVariadic() != rproto->isVariadic()) 10078 return {}; 10079 10080 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10081 return {}; 10082 10083 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10084 bool canUseLeft, canUseRight; 10085 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10086 newParamInfos)) 10087 return {}; 10088 10089 if (!canUseLeft) 10090 allLTypes = false; 10091 if (!canUseRight) 10092 allRTypes = false; 10093 10094 // Check parameter type compatibility 10095 SmallVector<QualType, 10> types; 10096 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10097 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10098 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10099 QualType paramType = mergeFunctionParameterTypes( 10100 lParamType, rParamType, OfBlockPointer, Unqualified); 10101 if (paramType.isNull()) 10102 return {}; 10103 10104 if (Unqualified) 10105 paramType = paramType.getUnqualifiedType(); 10106 10107 types.push_back(paramType); 10108 if (Unqualified) { 10109 lParamType = lParamType.getUnqualifiedType(); 10110 rParamType = rParamType.getUnqualifiedType(); 10111 } 10112 10113 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10114 allLTypes = false; 10115 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10116 allRTypes = false; 10117 } 10118 10119 if (allLTypes) return lhs; 10120 if (allRTypes) return rhs; 10121 10122 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10123 EPI.ExtInfo = einfo; 10124 EPI.ExtParameterInfos = 10125 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10126 return getFunctionType(retType, types, EPI); 10127 } 10128 10129 if (lproto) allRTypes = false; 10130 if (rproto) allLTypes = false; 10131 10132 const FunctionProtoType *proto = lproto ? lproto : rproto; 10133 if (proto) { 10134 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10135 if (proto->isVariadic()) 10136 return {}; 10137 // Check that the types are compatible with the types that 10138 // would result from default argument promotions (C99 6.7.5.3p15). 10139 // The only types actually affected are promotable integer 10140 // types and floats, which would be passed as a different 10141 // type depending on whether the prototype is visible. 10142 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10143 QualType paramTy = proto->getParamType(i); 10144 10145 // Look at the converted type of enum types, since that is the type used 10146 // to pass enum values. 10147 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10148 paramTy = Enum->getDecl()->getIntegerType(); 10149 if (paramTy.isNull()) 10150 return {}; 10151 } 10152 10153 if (paramTy->isPromotableIntegerType() || 10154 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10155 return {}; 10156 } 10157 10158 if (allLTypes) return lhs; 10159 if (allRTypes) return rhs; 10160 10161 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10162 EPI.ExtInfo = einfo; 10163 return getFunctionType(retType, proto->getParamTypes(), EPI); 10164 } 10165 10166 if (allLTypes) return lhs; 10167 if (allRTypes) return rhs; 10168 return getFunctionNoProtoType(retType, einfo); 10169 } 10170 10171 /// Given that we have an enum type and a non-enum type, try to merge them. 10172 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10173 QualType other, bool isBlockReturnType) { 10174 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10175 // a signed integer type, or an unsigned integer type. 10176 // Compatibility is based on the underlying type, not the promotion 10177 // type. 10178 QualType underlyingType = ET->getDecl()->getIntegerType(); 10179 if (underlyingType.isNull()) 10180 return {}; 10181 if (Context.hasSameType(underlyingType, other)) 10182 return other; 10183 10184 // In block return types, we're more permissive and accept any 10185 // integral type of the same size. 10186 if (isBlockReturnType && other->isIntegerType() && 10187 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10188 return other; 10189 10190 return {}; 10191 } 10192 10193 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10194 bool OfBlockPointer, 10195 bool Unqualified, bool BlockReturnType) { 10196 // For C++ we will not reach this code with reference types (see below), 10197 // for OpenMP variant call overloading we might. 10198 // 10199 // C++ [expr]: If an expression initially has the type "reference to T", the 10200 // type is adjusted to "T" prior to any further analysis, the expression 10201 // designates the object or function denoted by the reference, and the 10202 // expression is an lvalue unless the reference is an rvalue reference and 10203 // the expression is a function call (possibly inside parentheses). 10204 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10205 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10206 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10207 LHS->getTypeClass() == RHS->getTypeClass()) 10208 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10209 OfBlockPointer, Unqualified, BlockReturnType); 10210 if (LHSRefTy || RHSRefTy) 10211 return {}; 10212 10213 if (Unqualified) { 10214 LHS = LHS.getUnqualifiedType(); 10215 RHS = RHS.getUnqualifiedType(); 10216 } 10217 10218 QualType LHSCan = getCanonicalType(LHS), 10219 RHSCan = getCanonicalType(RHS); 10220 10221 // If two types are identical, they are compatible. 10222 if (LHSCan == RHSCan) 10223 return LHS; 10224 10225 // If the qualifiers are different, the types aren't compatible... mostly. 10226 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10227 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10228 if (LQuals != RQuals) { 10229 // If any of these qualifiers are different, we have a type 10230 // mismatch. 10231 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10232 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10233 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10234 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10235 return {}; 10236 10237 // Exactly one GC qualifier difference is allowed: __strong is 10238 // okay if the other type has no GC qualifier but is an Objective 10239 // C object pointer (i.e. implicitly strong by default). We fix 10240 // this by pretending that the unqualified type was actually 10241 // qualified __strong. 10242 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10243 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10244 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10245 10246 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10247 return {}; 10248 10249 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10250 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10251 } 10252 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10253 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10254 } 10255 return {}; 10256 } 10257 10258 // Okay, qualifiers are equal. 10259 10260 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10261 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10262 10263 // We want to consider the two function types to be the same for these 10264 // comparisons, just force one to the other. 10265 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10266 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10267 10268 // Same as above for arrays 10269 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10270 LHSClass = Type::ConstantArray; 10271 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10272 RHSClass = Type::ConstantArray; 10273 10274 // ObjCInterfaces are just specialized ObjCObjects. 10275 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10276 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10277 10278 // Canonicalize ExtVector -> Vector. 10279 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10280 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10281 10282 // If the canonical type classes don't match. 10283 if (LHSClass != RHSClass) { 10284 // Note that we only have special rules for turning block enum 10285 // returns into block int returns, not vice-versa. 10286 if (const auto *ETy = LHS->getAs<EnumType>()) { 10287 return mergeEnumWithInteger(*this, ETy, RHS, false); 10288 } 10289 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10290 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10291 } 10292 // allow block pointer type to match an 'id' type. 10293 if (OfBlockPointer && !BlockReturnType) { 10294 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10295 return LHS; 10296 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10297 return RHS; 10298 } 10299 // Allow __auto_type to match anything; it merges to the type with more 10300 // information. 10301 if (const auto *AT = LHS->getAs<AutoType>()) { 10302 if (AT->isGNUAutoType()) 10303 return RHS; 10304 } 10305 if (const auto *AT = RHS->getAs<AutoType>()) { 10306 if (AT->isGNUAutoType()) 10307 return LHS; 10308 } 10309 return {}; 10310 } 10311 10312 // The canonical type classes match. 10313 switch (LHSClass) { 10314 #define TYPE(Class, Base) 10315 #define ABSTRACT_TYPE(Class, Base) 10316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10317 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10318 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10319 #include "clang/AST/TypeNodes.inc" 10320 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10321 10322 case Type::Auto: 10323 case Type::DeducedTemplateSpecialization: 10324 case Type::LValueReference: 10325 case Type::RValueReference: 10326 case Type::MemberPointer: 10327 llvm_unreachable("C++ should never be in mergeTypes"); 10328 10329 case Type::ObjCInterface: 10330 case Type::IncompleteArray: 10331 case Type::VariableArray: 10332 case Type::FunctionProto: 10333 case Type::ExtVector: 10334 llvm_unreachable("Types are eliminated above"); 10335 10336 case Type::Pointer: 10337 { 10338 // Merge two pointer types, while trying to preserve typedef info 10339 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10340 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10341 if (Unqualified) { 10342 LHSPointee = LHSPointee.getUnqualifiedType(); 10343 RHSPointee = RHSPointee.getUnqualifiedType(); 10344 } 10345 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10346 Unqualified); 10347 if (ResultType.isNull()) 10348 return {}; 10349 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10350 return LHS; 10351 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10352 return RHS; 10353 return getPointerType(ResultType); 10354 } 10355 case Type::BlockPointer: 10356 { 10357 // Merge two block pointer types, while trying to preserve typedef info 10358 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10359 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10360 if (Unqualified) { 10361 LHSPointee = LHSPointee.getUnqualifiedType(); 10362 RHSPointee = RHSPointee.getUnqualifiedType(); 10363 } 10364 if (getLangOpts().OpenCL) { 10365 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10366 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10367 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10368 // 6.12.5) thus the following check is asymmetric. 10369 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10370 return {}; 10371 LHSPteeQual.removeAddressSpace(); 10372 RHSPteeQual.removeAddressSpace(); 10373 LHSPointee = 10374 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10375 RHSPointee = 10376 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10377 } 10378 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10379 Unqualified); 10380 if (ResultType.isNull()) 10381 return {}; 10382 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10383 return LHS; 10384 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10385 return RHS; 10386 return getBlockPointerType(ResultType); 10387 } 10388 case Type::Atomic: 10389 { 10390 // Merge two pointer types, while trying to preserve typedef info 10391 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10392 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10393 if (Unqualified) { 10394 LHSValue = LHSValue.getUnqualifiedType(); 10395 RHSValue = RHSValue.getUnqualifiedType(); 10396 } 10397 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10398 Unqualified); 10399 if (ResultType.isNull()) 10400 return {}; 10401 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10402 return LHS; 10403 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10404 return RHS; 10405 return getAtomicType(ResultType); 10406 } 10407 case Type::ConstantArray: 10408 { 10409 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10410 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10411 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10412 return {}; 10413 10414 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10415 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10416 if (Unqualified) { 10417 LHSElem = LHSElem.getUnqualifiedType(); 10418 RHSElem = RHSElem.getUnqualifiedType(); 10419 } 10420 10421 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10422 if (ResultType.isNull()) 10423 return {}; 10424 10425 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10426 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10427 10428 // If either side is a variable array, and both are complete, check whether 10429 // the current dimension is definite. 10430 if (LVAT || RVAT) { 10431 auto SizeFetch = [this](const VariableArrayType* VAT, 10432 const ConstantArrayType* CAT) 10433 -> std::pair<bool,llvm::APInt> { 10434 if (VAT) { 10435 Optional<llvm::APSInt> TheInt; 10436 Expr *E = VAT->getSizeExpr(); 10437 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10438 return std::make_pair(true, *TheInt); 10439 return std::make_pair(false, llvm::APSInt()); 10440 } 10441 if (CAT) 10442 return std::make_pair(true, CAT->getSize()); 10443 return std::make_pair(false, llvm::APInt()); 10444 }; 10445 10446 bool HaveLSize, HaveRSize; 10447 llvm::APInt LSize, RSize; 10448 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10449 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10450 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10451 return {}; // Definite, but unequal, array dimension 10452 } 10453 10454 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10455 return LHS; 10456 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10457 return RHS; 10458 if (LCAT) 10459 return getConstantArrayType(ResultType, LCAT->getSize(), 10460 LCAT->getSizeExpr(), 10461 ArrayType::ArraySizeModifier(), 0); 10462 if (RCAT) 10463 return getConstantArrayType(ResultType, RCAT->getSize(), 10464 RCAT->getSizeExpr(), 10465 ArrayType::ArraySizeModifier(), 0); 10466 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10467 return LHS; 10468 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10469 return RHS; 10470 if (LVAT) { 10471 // FIXME: This isn't correct! But tricky to implement because 10472 // the array's size has to be the size of LHS, but the type 10473 // has to be different. 10474 return LHS; 10475 } 10476 if (RVAT) { 10477 // FIXME: This isn't correct! But tricky to implement because 10478 // the array's size has to be the size of RHS, but the type 10479 // has to be different. 10480 return RHS; 10481 } 10482 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10483 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10484 return getIncompleteArrayType(ResultType, 10485 ArrayType::ArraySizeModifier(), 0); 10486 } 10487 case Type::FunctionNoProto: 10488 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10489 case Type::Record: 10490 case Type::Enum: 10491 return {}; 10492 case Type::Builtin: 10493 // Only exactly equal builtin types are compatible, which is tested above. 10494 return {}; 10495 case Type::Complex: 10496 // Distinct complex types are incompatible. 10497 return {}; 10498 case Type::Vector: 10499 // FIXME: The merged type should be an ExtVector! 10500 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10501 RHSCan->castAs<VectorType>())) 10502 return LHS; 10503 return {}; 10504 case Type::ConstantMatrix: 10505 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10506 RHSCan->castAs<ConstantMatrixType>())) 10507 return LHS; 10508 return {}; 10509 case Type::ObjCObject: { 10510 // Check if the types are assignment compatible. 10511 // FIXME: This should be type compatibility, e.g. whether 10512 // "LHS x; RHS x;" at global scope is legal. 10513 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10514 RHS->castAs<ObjCObjectType>())) 10515 return LHS; 10516 return {}; 10517 } 10518 case Type::ObjCObjectPointer: 10519 if (OfBlockPointer) { 10520 if (canAssignObjCInterfacesInBlockPointer( 10521 LHS->castAs<ObjCObjectPointerType>(), 10522 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10523 return LHS; 10524 return {}; 10525 } 10526 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10527 RHS->castAs<ObjCObjectPointerType>())) 10528 return LHS; 10529 return {}; 10530 case Type::Pipe: 10531 assert(LHS != RHS && 10532 "Equivalent pipe types should have already been handled!"); 10533 return {}; 10534 case Type::BitInt: { 10535 // Merge two bit-precise int types, while trying to preserve typedef info. 10536 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10537 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10538 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10539 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10540 10541 // Like unsigned/int, shouldn't have a type if they don't match. 10542 if (LHSUnsigned != RHSUnsigned) 10543 return {}; 10544 10545 if (LHSBits != RHSBits) 10546 return {}; 10547 return LHS; 10548 } 10549 } 10550 10551 llvm_unreachable("Invalid Type::Class!"); 10552 } 10553 10554 bool ASTContext::mergeExtParameterInfo( 10555 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10556 bool &CanUseFirst, bool &CanUseSecond, 10557 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10558 assert(NewParamInfos.empty() && "param info list not empty"); 10559 CanUseFirst = CanUseSecond = true; 10560 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10561 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10562 10563 // Fast path: if the first type doesn't have ext parameter infos, 10564 // we match if and only if the second type also doesn't have them. 10565 if (!FirstHasInfo && !SecondHasInfo) 10566 return true; 10567 10568 bool NeedParamInfo = false; 10569 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10570 : SecondFnType->getExtParameterInfos().size(); 10571 10572 for (size_t I = 0; I < E; ++I) { 10573 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10574 if (FirstHasInfo) 10575 FirstParam = FirstFnType->getExtParameterInfo(I); 10576 if (SecondHasInfo) 10577 SecondParam = SecondFnType->getExtParameterInfo(I); 10578 10579 // Cannot merge unless everything except the noescape flag matches. 10580 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10581 return false; 10582 10583 bool FirstNoEscape = FirstParam.isNoEscape(); 10584 bool SecondNoEscape = SecondParam.isNoEscape(); 10585 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10586 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10587 if (NewParamInfos.back().getOpaqueValue()) 10588 NeedParamInfo = true; 10589 if (FirstNoEscape != IsNoEscape) 10590 CanUseFirst = false; 10591 if (SecondNoEscape != IsNoEscape) 10592 CanUseSecond = false; 10593 } 10594 10595 if (!NeedParamInfo) 10596 NewParamInfos.clear(); 10597 10598 return true; 10599 } 10600 10601 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10602 ObjCLayouts[CD] = nullptr; 10603 } 10604 10605 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10606 /// 'RHS' attributes and returns the merged version; including for function 10607 /// return types. 10608 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10609 QualType LHSCan = getCanonicalType(LHS), 10610 RHSCan = getCanonicalType(RHS); 10611 // If two types are identical, they are compatible. 10612 if (LHSCan == RHSCan) 10613 return LHS; 10614 if (RHSCan->isFunctionType()) { 10615 if (!LHSCan->isFunctionType()) 10616 return {}; 10617 QualType OldReturnType = 10618 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10619 QualType NewReturnType = 10620 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10621 QualType ResReturnType = 10622 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10623 if (ResReturnType.isNull()) 10624 return {}; 10625 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10626 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10627 // In either case, use OldReturnType to build the new function type. 10628 const auto *F = LHS->castAs<FunctionType>(); 10629 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10630 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10631 EPI.ExtInfo = getFunctionExtInfo(LHS); 10632 QualType ResultType = 10633 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10634 return ResultType; 10635 } 10636 } 10637 return {}; 10638 } 10639 10640 // If the qualifiers are different, the types can still be merged. 10641 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10642 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10643 if (LQuals != RQuals) { 10644 // If any of these qualifiers are different, we have a type mismatch. 10645 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10646 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10647 return {}; 10648 10649 // Exactly one GC qualifier difference is allowed: __strong is 10650 // okay if the other type has no GC qualifier but is an Objective 10651 // C object pointer (i.e. implicitly strong by default). We fix 10652 // this by pretending that the unqualified type was actually 10653 // qualified __strong. 10654 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10655 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10656 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10657 10658 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10659 return {}; 10660 10661 if (GC_L == Qualifiers::Strong) 10662 return LHS; 10663 if (GC_R == Qualifiers::Strong) 10664 return RHS; 10665 return {}; 10666 } 10667 10668 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10669 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10670 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10671 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10672 if (ResQT == LHSBaseQT) 10673 return LHS; 10674 if (ResQT == RHSBaseQT) 10675 return RHS; 10676 } 10677 return {}; 10678 } 10679 10680 //===----------------------------------------------------------------------===// 10681 // Integer Predicates 10682 //===----------------------------------------------------------------------===// 10683 10684 unsigned ASTContext::getIntWidth(QualType T) const { 10685 if (const auto *ET = T->getAs<EnumType>()) 10686 T = ET->getDecl()->getIntegerType(); 10687 if (T->isBooleanType()) 10688 return 1; 10689 if (const auto *EIT = T->getAs<BitIntType>()) 10690 return EIT->getNumBits(); 10691 // For builtin types, just use the standard type sizing method 10692 return (unsigned)getTypeSize(T); 10693 } 10694 10695 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10696 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10697 "Unexpected type"); 10698 10699 // Turn <4 x signed int> -> <4 x unsigned int> 10700 if (const auto *VTy = T->getAs<VectorType>()) 10701 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10702 VTy->getNumElements(), VTy->getVectorKind()); 10703 10704 // For _BitInt, return an unsigned _BitInt with same width. 10705 if (const auto *EITy = T->getAs<BitIntType>()) 10706 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10707 10708 // For enums, get the underlying integer type of the enum, and let the general 10709 // integer type signchanging code handle it. 10710 if (const auto *ETy = T->getAs<EnumType>()) 10711 T = ETy->getDecl()->getIntegerType(); 10712 10713 switch (T->castAs<BuiltinType>()->getKind()) { 10714 case BuiltinType::Char_S: 10715 case BuiltinType::SChar: 10716 return UnsignedCharTy; 10717 case BuiltinType::Short: 10718 return UnsignedShortTy; 10719 case BuiltinType::Int: 10720 return UnsignedIntTy; 10721 case BuiltinType::Long: 10722 return UnsignedLongTy; 10723 case BuiltinType::LongLong: 10724 return UnsignedLongLongTy; 10725 case BuiltinType::Int128: 10726 return UnsignedInt128Ty; 10727 // wchar_t is special. It is either signed or not, but when it's signed, 10728 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10729 // version of it's underlying type instead. 10730 case BuiltinType::WChar_S: 10731 return getUnsignedWCharType(); 10732 10733 case BuiltinType::ShortAccum: 10734 return UnsignedShortAccumTy; 10735 case BuiltinType::Accum: 10736 return UnsignedAccumTy; 10737 case BuiltinType::LongAccum: 10738 return UnsignedLongAccumTy; 10739 case BuiltinType::SatShortAccum: 10740 return SatUnsignedShortAccumTy; 10741 case BuiltinType::SatAccum: 10742 return SatUnsignedAccumTy; 10743 case BuiltinType::SatLongAccum: 10744 return SatUnsignedLongAccumTy; 10745 case BuiltinType::ShortFract: 10746 return UnsignedShortFractTy; 10747 case BuiltinType::Fract: 10748 return UnsignedFractTy; 10749 case BuiltinType::LongFract: 10750 return UnsignedLongFractTy; 10751 case BuiltinType::SatShortFract: 10752 return SatUnsignedShortFractTy; 10753 case BuiltinType::SatFract: 10754 return SatUnsignedFractTy; 10755 case BuiltinType::SatLongFract: 10756 return SatUnsignedLongFractTy; 10757 default: 10758 llvm_unreachable("Unexpected signed integer or fixed point type"); 10759 } 10760 } 10761 10762 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10763 assert((T->hasUnsignedIntegerRepresentation() || 10764 T->isUnsignedFixedPointType()) && 10765 "Unexpected type"); 10766 10767 // Turn <4 x unsigned int> -> <4 x signed int> 10768 if (const auto *VTy = T->getAs<VectorType>()) 10769 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10770 VTy->getNumElements(), VTy->getVectorKind()); 10771 10772 // For _BitInt, return a signed _BitInt with same width. 10773 if (const auto *EITy = T->getAs<BitIntType>()) 10774 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10775 10776 // For enums, get the underlying integer type of the enum, and let the general 10777 // integer type signchanging code handle it. 10778 if (const auto *ETy = T->getAs<EnumType>()) 10779 T = ETy->getDecl()->getIntegerType(); 10780 10781 switch (T->castAs<BuiltinType>()->getKind()) { 10782 case BuiltinType::Char_U: 10783 case BuiltinType::UChar: 10784 return SignedCharTy; 10785 case BuiltinType::UShort: 10786 return ShortTy; 10787 case BuiltinType::UInt: 10788 return IntTy; 10789 case BuiltinType::ULong: 10790 return LongTy; 10791 case BuiltinType::ULongLong: 10792 return LongLongTy; 10793 case BuiltinType::UInt128: 10794 return Int128Ty; 10795 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10796 // there's no matching "signed wchar_t". Therefore we return the signed 10797 // version of it's underlying type instead. 10798 case BuiltinType::WChar_U: 10799 return getSignedWCharType(); 10800 10801 case BuiltinType::UShortAccum: 10802 return ShortAccumTy; 10803 case BuiltinType::UAccum: 10804 return AccumTy; 10805 case BuiltinType::ULongAccum: 10806 return LongAccumTy; 10807 case BuiltinType::SatUShortAccum: 10808 return SatShortAccumTy; 10809 case BuiltinType::SatUAccum: 10810 return SatAccumTy; 10811 case BuiltinType::SatULongAccum: 10812 return SatLongAccumTy; 10813 case BuiltinType::UShortFract: 10814 return ShortFractTy; 10815 case BuiltinType::UFract: 10816 return FractTy; 10817 case BuiltinType::ULongFract: 10818 return LongFractTy; 10819 case BuiltinType::SatUShortFract: 10820 return SatShortFractTy; 10821 case BuiltinType::SatUFract: 10822 return SatFractTy; 10823 case BuiltinType::SatULongFract: 10824 return SatLongFractTy; 10825 default: 10826 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10827 } 10828 } 10829 10830 ASTMutationListener::~ASTMutationListener() = default; 10831 10832 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10833 QualType ReturnType) {} 10834 10835 //===----------------------------------------------------------------------===// 10836 // Builtin Type Computation 10837 //===----------------------------------------------------------------------===// 10838 10839 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10840 /// pointer over the consumed characters. This returns the resultant type. If 10841 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10842 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10843 /// a vector of "i*". 10844 /// 10845 /// RequiresICE is filled in on return to indicate whether the value is required 10846 /// to be an Integer Constant Expression. 10847 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10848 ASTContext::GetBuiltinTypeError &Error, 10849 bool &RequiresICE, 10850 bool AllowTypeModifiers) { 10851 // Modifiers. 10852 int HowLong = 0; 10853 bool Signed = false, Unsigned = false; 10854 RequiresICE = false; 10855 10856 // Read the prefixed modifiers first. 10857 bool Done = false; 10858 #ifndef NDEBUG 10859 bool IsSpecial = false; 10860 #endif 10861 while (!Done) { 10862 switch (*Str++) { 10863 default: Done = true; --Str; break; 10864 case 'I': 10865 RequiresICE = true; 10866 break; 10867 case 'S': 10868 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10869 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10870 Signed = true; 10871 break; 10872 case 'U': 10873 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10874 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10875 Unsigned = true; 10876 break; 10877 case 'L': 10878 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10879 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10880 ++HowLong; 10881 break; 10882 case 'N': 10883 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10884 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10885 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10886 #ifndef NDEBUG 10887 IsSpecial = true; 10888 #endif 10889 if (Context.getTargetInfo().getLongWidth() == 32) 10890 ++HowLong; 10891 break; 10892 case 'W': 10893 // This modifier represents int64 type. 10894 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10895 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10896 #ifndef NDEBUG 10897 IsSpecial = true; 10898 #endif 10899 switch (Context.getTargetInfo().getInt64Type()) { 10900 default: 10901 llvm_unreachable("Unexpected integer type"); 10902 case TargetInfo::SignedLong: 10903 HowLong = 1; 10904 break; 10905 case TargetInfo::SignedLongLong: 10906 HowLong = 2; 10907 break; 10908 } 10909 break; 10910 case 'Z': 10911 // This modifier represents int32 type. 10912 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10913 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10914 #ifndef NDEBUG 10915 IsSpecial = true; 10916 #endif 10917 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10918 default: 10919 llvm_unreachable("Unexpected integer type"); 10920 case TargetInfo::SignedInt: 10921 HowLong = 0; 10922 break; 10923 case TargetInfo::SignedLong: 10924 HowLong = 1; 10925 break; 10926 case TargetInfo::SignedLongLong: 10927 HowLong = 2; 10928 break; 10929 } 10930 break; 10931 case 'O': 10932 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10933 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10934 #ifndef NDEBUG 10935 IsSpecial = true; 10936 #endif 10937 if (Context.getLangOpts().OpenCL) 10938 HowLong = 1; 10939 else 10940 HowLong = 2; 10941 break; 10942 } 10943 } 10944 10945 QualType Type; 10946 10947 // Read the base type. 10948 switch (*Str++) { 10949 default: llvm_unreachable("Unknown builtin type letter!"); 10950 case 'x': 10951 assert(HowLong == 0 && !Signed && !Unsigned && 10952 "Bad modifiers used with 'x'!"); 10953 Type = Context.Float16Ty; 10954 break; 10955 case 'y': 10956 assert(HowLong == 0 && !Signed && !Unsigned && 10957 "Bad modifiers used with 'y'!"); 10958 Type = Context.BFloat16Ty; 10959 break; 10960 case 'v': 10961 assert(HowLong == 0 && !Signed && !Unsigned && 10962 "Bad modifiers used with 'v'!"); 10963 Type = Context.VoidTy; 10964 break; 10965 case 'h': 10966 assert(HowLong == 0 && !Signed && !Unsigned && 10967 "Bad modifiers used with 'h'!"); 10968 Type = Context.HalfTy; 10969 break; 10970 case 'f': 10971 assert(HowLong == 0 && !Signed && !Unsigned && 10972 "Bad modifiers used with 'f'!"); 10973 Type = Context.FloatTy; 10974 break; 10975 case 'd': 10976 assert(HowLong < 3 && !Signed && !Unsigned && 10977 "Bad modifiers used with 'd'!"); 10978 if (HowLong == 1) 10979 Type = Context.LongDoubleTy; 10980 else if (HowLong == 2) 10981 Type = Context.Float128Ty; 10982 else 10983 Type = Context.DoubleTy; 10984 break; 10985 case 's': 10986 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10987 if (Unsigned) 10988 Type = Context.UnsignedShortTy; 10989 else 10990 Type = Context.ShortTy; 10991 break; 10992 case 'i': 10993 if (HowLong == 3) 10994 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10995 else if (HowLong == 2) 10996 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10997 else if (HowLong == 1) 10998 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10999 else 11000 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 11001 break; 11002 case 'c': 11003 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 11004 if (Signed) 11005 Type = Context.SignedCharTy; 11006 else if (Unsigned) 11007 Type = Context.UnsignedCharTy; 11008 else 11009 Type = Context.CharTy; 11010 break; 11011 case 'b': // boolean 11012 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11013 Type = Context.BoolTy; 11014 break; 11015 case 'z': // size_t. 11016 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11017 Type = Context.getSizeType(); 11018 break; 11019 case 'w': // wchar_t. 11020 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11021 Type = Context.getWideCharType(); 11022 break; 11023 case 'F': 11024 Type = Context.getCFConstantStringType(); 11025 break; 11026 case 'G': 11027 Type = Context.getObjCIdType(); 11028 break; 11029 case 'H': 11030 Type = Context.getObjCSelType(); 11031 break; 11032 case 'M': 11033 Type = Context.getObjCSuperType(); 11034 break; 11035 case 'a': 11036 Type = Context.getBuiltinVaListType(); 11037 assert(!Type.isNull() && "builtin va list type not initialized!"); 11038 break; 11039 case 'A': 11040 // This is a "reference" to a va_list; however, what exactly 11041 // this means depends on how va_list is defined. There are two 11042 // different kinds of va_list: ones passed by value, and ones 11043 // passed by reference. An example of a by-value va_list is 11044 // x86, where va_list is a char*. An example of by-ref va_list 11045 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11046 // we want this argument to be a char*&; for x86-64, we want 11047 // it to be a __va_list_tag*. 11048 Type = Context.getBuiltinVaListType(); 11049 assert(!Type.isNull() && "builtin va list type not initialized!"); 11050 if (Type->isArrayType()) 11051 Type = Context.getArrayDecayedType(Type); 11052 else 11053 Type = Context.getLValueReferenceType(Type); 11054 break; 11055 case 'q': { 11056 char *End; 11057 unsigned NumElements = strtoul(Str, &End, 10); 11058 assert(End != Str && "Missing vector size"); 11059 Str = End; 11060 11061 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11062 RequiresICE, false); 11063 assert(!RequiresICE && "Can't require vector ICE"); 11064 11065 Type = Context.getScalableVectorType(ElementType, NumElements); 11066 break; 11067 } 11068 case 'V': { 11069 char *End; 11070 unsigned NumElements = strtoul(Str, &End, 10); 11071 assert(End != Str && "Missing vector size"); 11072 Str = End; 11073 11074 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11075 RequiresICE, false); 11076 assert(!RequiresICE && "Can't require vector ICE"); 11077 11078 // TODO: No way to make AltiVec vectors in builtins yet. 11079 Type = Context.getVectorType(ElementType, NumElements, 11080 VectorType::GenericVector); 11081 break; 11082 } 11083 case 'E': { 11084 char *End; 11085 11086 unsigned NumElements = strtoul(Str, &End, 10); 11087 assert(End != Str && "Missing vector size"); 11088 11089 Str = End; 11090 11091 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11092 false); 11093 Type = Context.getExtVectorType(ElementType, NumElements); 11094 break; 11095 } 11096 case 'X': { 11097 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11098 false); 11099 assert(!RequiresICE && "Can't require complex ICE"); 11100 Type = Context.getComplexType(ElementType); 11101 break; 11102 } 11103 case 'Y': 11104 Type = Context.getPointerDiffType(); 11105 break; 11106 case 'P': 11107 Type = Context.getFILEType(); 11108 if (Type.isNull()) { 11109 Error = ASTContext::GE_Missing_stdio; 11110 return {}; 11111 } 11112 break; 11113 case 'J': 11114 if (Signed) 11115 Type = Context.getsigjmp_bufType(); 11116 else 11117 Type = Context.getjmp_bufType(); 11118 11119 if (Type.isNull()) { 11120 Error = ASTContext::GE_Missing_setjmp; 11121 return {}; 11122 } 11123 break; 11124 case 'K': 11125 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11126 Type = Context.getucontext_tType(); 11127 11128 if (Type.isNull()) { 11129 Error = ASTContext::GE_Missing_ucontext; 11130 return {}; 11131 } 11132 break; 11133 case 'p': 11134 Type = Context.getProcessIDType(); 11135 break; 11136 } 11137 11138 // If there are modifiers and if we're allowed to parse them, go for it. 11139 Done = !AllowTypeModifiers; 11140 while (!Done) { 11141 switch (char c = *Str++) { 11142 default: Done = true; --Str; break; 11143 case '*': 11144 case '&': { 11145 // Both pointers and references can have their pointee types 11146 // qualified with an address space. 11147 char *End; 11148 unsigned AddrSpace = strtoul(Str, &End, 10); 11149 if (End != Str) { 11150 // Note AddrSpace == 0 is not the same as an unspecified address space. 11151 Type = Context.getAddrSpaceQualType( 11152 Type, 11153 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11154 Str = End; 11155 } 11156 if (c == '*') 11157 Type = Context.getPointerType(Type); 11158 else 11159 Type = Context.getLValueReferenceType(Type); 11160 break; 11161 } 11162 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11163 case 'C': 11164 Type = Type.withConst(); 11165 break; 11166 case 'D': 11167 Type = Context.getVolatileType(Type); 11168 break; 11169 case 'R': 11170 Type = Type.withRestrict(); 11171 break; 11172 } 11173 } 11174 11175 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11176 "Integer constant 'I' type must be an integer"); 11177 11178 return Type; 11179 } 11180 11181 // On some targets such as PowerPC, some of the builtins are defined with custom 11182 // type descriptors for target-dependent types. These descriptors are decoded in 11183 // other functions, but it may be useful to be able to fall back to default 11184 // descriptor decoding to define builtins mixing target-dependent and target- 11185 // independent types. This function allows decoding one type descriptor with 11186 // default decoding. 11187 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11188 GetBuiltinTypeError &Error, bool &RequireICE, 11189 bool AllowTypeModifiers) const { 11190 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11191 } 11192 11193 /// GetBuiltinType - Return the type for the specified builtin. 11194 QualType ASTContext::GetBuiltinType(unsigned Id, 11195 GetBuiltinTypeError &Error, 11196 unsigned *IntegerConstantArgs) const { 11197 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11198 if (TypeStr[0] == '\0') { 11199 Error = GE_Missing_type; 11200 return {}; 11201 } 11202 11203 SmallVector<QualType, 8> ArgTypes; 11204 11205 bool RequiresICE = false; 11206 Error = GE_None; 11207 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11208 RequiresICE, true); 11209 if (Error != GE_None) 11210 return {}; 11211 11212 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11213 11214 while (TypeStr[0] && TypeStr[0] != '.') { 11215 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11216 if (Error != GE_None) 11217 return {}; 11218 11219 // If this argument is required to be an IntegerConstantExpression and the 11220 // caller cares, fill in the bitmask we return. 11221 if (RequiresICE && IntegerConstantArgs) 11222 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11223 11224 // Do array -> pointer decay. The builtin should use the decayed type. 11225 if (Ty->isArrayType()) 11226 Ty = getArrayDecayedType(Ty); 11227 11228 ArgTypes.push_back(Ty); 11229 } 11230 11231 if (Id == Builtin::BI__GetExceptionInfo) 11232 return {}; 11233 11234 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11235 "'.' should only occur at end of builtin type list!"); 11236 11237 bool Variadic = (TypeStr[0] == '.'); 11238 11239 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11240 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11241 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11242 11243 11244 // We really shouldn't be making a no-proto type here. 11245 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes()) 11246 return getFunctionNoProtoType(ResType, EI); 11247 11248 FunctionProtoType::ExtProtoInfo EPI; 11249 EPI.ExtInfo = EI; 11250 EPI.Variadic = Variadic; 11251 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11252 EPI.ExceptionSpec.Type = 11253 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11254 11255 return getFunctionType(ResType, ArgTypes, EPI); 11256 } 11257 11258 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11259 const FunctionDecl *FD) { 11260 if (!FD->isExternallyVisible()) 11261 return GVA_Internal; 11262 11263 // Non-user-provided functions get emitted as weak definitions with every 11264 // use, no matter whether they've been explicitly instantiated etc. 11265 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11266 if (!MD->isUserProvided()) 11267 return GVA_DiscardableODR; 11268 11269 GVALinkage External; 11270 switch (FD->getTemplateSpecializationKind()) { 11271 case TSK_Undeclared: 11272 case TSK_ExplicitSpecialization: 11273 External = GVA_StrongExternal; 11274 break; 11275 11276 case TSK_ExplicitInstantiationDefinition: 11277 return GVA_StrongODR; 11278 11279 // C++11 [temp.explicit]p10: 11280 // [ Note: The intent is that an inline function that is the subject of 11281 // an explicit instantiation declaration will still be implicitly 11282 // instantiated when used so that the body can be considered for 11283 // inlining, but that no out-of-line copy of the inline function would be 11284 // generated in the translation unit. -- end note ] 11285 case TSK_ExplicitInstantiationDeclaration: 11286 return GVA_AvailableExternally; 11287 11288 case TSK_ImplicitInstantiation: 11289 External = GVA_DiscardableODR; 11290 break; 11291 } 11292 11293 if (!FD->isInlined()) 11294 return External; 11295 11296 if ((!Context.getLangOpts().CPlusPlus && 11297 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11298 !FD->hasAttr<DLLExportAttr>()) || 11299 FD->hasAttr<GNUInlineAttr>()) { 11300 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11301 11302 // GNU or C99 inline semantics. Determine whether this symbol should be 11303 // externally visible. 11304 if (FD->isInlineDefinitionExternallyVisible()) 11305 return External; 11306 11307 // C99 inline semantics, where the symbol is not externally visible. 11308 return GVA_AvailableExternally; 11309 } 11310 11311 // Functions specified with extern and inline in -fms-compatibility mode 11312 // forcibly get emitted. While the body of the function cannot be later 11313 // replaced, the function definition cannot be discarded. 11314 if (FD->isMSExternInline()) 11315 return GVA_StrongODR; 11316 11317 return GVA_DiscardableODR; 11318 } 11319 11320 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11321 const Decl *D, GVALinkage L) { 11322 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11323 // dllexport/dllimport on inline functions. 11324 if (D->hasAttr<DLLImportAttr>()) { 11325 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11326 return GVA_AvailableExternally; 11327 } else if (D->hasAttr<DLLExportAttr>()) { 11328 if (L == GVA_DiscardableODR) 11329 return GVA_StrongODR; 11330 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11331 // Device-side functions with __global__ attribute must always be 11332 // visible externally so they can be launched from host. 11333 if (D->hasAttr<CUDAGlobalAttr>() && 11334 (L == GVA_DiscardableODR || L == GVA_Internal)) 11335 return GVA_StrongODR; 11336 // Single source offloading languages like CUDA/HIP need to be able to 11337 // access static device variables from host code of the same compilation 11338 // unit. This is done by externalizing the static variable with a shared 11339 // name between the host and device compilation which is the same for the 11340 // same compilation unit whereas different among different compilation 11341 // units. 11342 if (Context.shouldExternalize(D)) 11343 return GVA_StrongExternal; 11344 } 11345 return L; 11346 } 11347 11348 /// Adjust the GVALinkage for a declaration based on what an external AST source 11349 /// knows about whether there can be other definitions of this declaration. 11350 static GVALinkage 11351 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11352 GVALinkage L) { 11353 ExternalASTSource *Source = Ctx.getExternalSource(); 11354 if (!Source) 11355 return L; 11356 11357 switch (Source->hasExternalDefinitions(D)) { 11358 case ExternalASTSource::EK_Never: 11359 // Other translation units rely on us to provide the definition. 11360 if (L == GVA_DiscardableODR) 11361 return GVA_StrongODR; 11362 break; 11363 11364 case ExternalASTSource::EK_Always: 11365 return GVA_AvailableExternally; 11366 11367 case ExternalASTSource::EK_ReplyHazy: 11368 break; 11369 } 11370 return L; 11371 } 11372 11373 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11374 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11375 adjustGVALinkageForAttributes(*this, FD, 11376 basicGVALinkageForFunction(*this, FD))); 11377 } 11378 11379 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11380 const VarDecl *VD) { 11381 if (!VD->isExternallyVisible()) 11382 return GVA_Internal; 11383 11384 if (VD->isStaticLocal()) { 11385 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11386 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11387 LexicalContext = LexicalContext->getLexicalParent(); 11388 11389 // ObjC Blocks can create local variables that don't have a FunctionDecl 11390 // LexicalContext. 11391 if (!LexicalContext) 11392 return GVA_DiscardableODR; 11393 11394 // Otherwise, let the static local variable inherit its linkage from the 11395 // nearest enclosing function. 11396 auto StaticLocalLinkage = 11397 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11398 11399 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11400 // be emitted in any object with references to the symbol for the object it 11401 // contains, whether inline or out-of-line." 11402 // Similar behavior is observed with MSVC. An alternative ABI could use 11403 // StrongODR/AvailableExternally to match the function, but none are 11404 // known/supported currently. 11405 if (StaticLocalLinkage == GVA_StrongODR || 11406 StaticLocalLinkage == GVA_AvailableExternally) 11407 return GVA_DiscardableODR; 11408 return StaticLocalLinkage; 11409 } 11410 11411 // MSVC treats in-class initialized static data members as definitions. 11412 // By giving them non-strong linkage, out-of-line definitions won't 11413 // cause link errors. 11414 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11415 return GVA_DiscardableODR; 11416 11417 // Most non-template variables have strong linkage; inline variables are 11418 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11419 GVALinkage StrongLinkage; 11420 switch (Context.getInlineVariableDefinitionKind(VD)) { 11421 case ASTContext::InlineVariableDefinitionKind::None: 11422 StrongLinkage = GVA_StrongExternal; 11423 break; 11424 case ASTContext::InlineVariableDefinitionKind::Weak: 11425 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11426 StrongLinkage = GVA_DiscardableODR; 11427 break; 11428 case ASTContext::InlineVariableDefinitionKind::Strong: 11429 StrongLinkage = GVA_StrongODR; 11430 break; 11431 } 11432 11433 switch (VD->getTemplateSpecializationKind()) { 11434 case TSK_Undeclared: 11435 return StrongLinkage; 11436 11437 case TSK_ExplicitSpecialization: 11438 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11439 VD->isStaticDataMember() 11440 ? GVA_StrongODR 11441 : StrongLinkage; 11442 11443 case TSK_ExplicitInstantiationDefinition: 11444 return GVA_StrongODR; 11445 11446 case TSK_ExplicitInstantiationDeclaration: 11447 return GVA_AvailableExternally; 11448 11449 case TSK_ImplicitInstantiation: 11450 return GVA_DiscardableODR; 11451 } 11452 11453 llvm_unreachable("Invalid Linkage!"); 11454 } 11455 11456 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11457 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11458 adjustGVALinkageForAttributes(*this, VD, 11459 basicGVALinkageForVariable(*this, VD))); 11460 } 11461 11462 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11463 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11464 if (!VD->isFileVarDecl()) 11465 return false; 11466 // Global named register variables (GNU extension) are never emitted. 11467 if (VD->getStorageClass() == SC_Register) 11468 return false; 11469 if (VD->getDescribedVarTemplate() || 11470 isa<VarTemplatePartialSpecializationDecl>(VD)) 11471 return false; 11472 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11473 // We never need to emit an uninstantiated function template. 11474 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11475 return false; 11476 } else if (isa<PragmaCommentDecl>(D)) 11477 return true; 11478 else if (isa<PragmaDetectMismatchDecl>(D)) 11479 return true; 11480 else if (isa<OMPRequiresDecl>(D)) 11481 return true; 11482 else if (isa<OMPThreadPrivateDecl>(D)) 11483 return !D->getDeclContext()->isDependentContext(); 11484 else if (isa<OMPAllocateDecl>(D)) 11485 return !D->getDeclContext()->isDependentContext(); 11486 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11487 return !D->getDeclContext()->isDependentContext(); 11488 else if (isa<ImportDecl>(D)) 11489 return true; 11490 else 11491 return false; 11492 11493 // If this is a member of a class template, we do not need to emit it. 11494 if (D->getDeclContext()->isDependentContext()) 11495 return false; 11496 11497 // Weak references don't produce any output by themselves. 11498 if (D->hasAttr<WeakRefAttr>()) 11499 return false; 11500 11501 // Aliases and used decls are required. 11502 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11503 return true; 11504 11505 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11506 // Forward declarations aren't required. 11507 if (!FD->doesThisDeclarationHaveABody()) 11508 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11509 11510 // Constructors and destructors are required. 11511 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11512 return true; 11513 11514 // The key function for a class is required. This rule only comes 11515 // into play when inline functions can be key functions, though. 11516 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11517 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11518 const CXXRecordDecl *RD = MD->getParent(); 11519 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11520 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11521 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11522 return true; 11523 } 11524 } 11525 } 11526 11527 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11528 11529 // static, static inline, always_inline, and extern inline functions can 11530 // always be deferred. Normal inline functions can be deferred in C99/C++. 11531 // Implicit template instantiations can also be deferred in C++. 11532 return !isDiscardableGVALinkage(Linkage); 11533 } 11534 11535 const auto *VD = cast<VarDecl>(D); 11536 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11537 11538 // If the decl is marked as `declare target to`, it should be emitted for the 11539 // host and for the device. 11540 if (LangOpts.OpenMP && 11541 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11542 return true; 11543 11544 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11545 !isMSStaticDataMemberInlineDefinition(VD)) 11546 return false; 11547 11548 // Variables that can be needed in other TUs are required. 11549 auto Linkage = GetGVALinkageForVariable(VD); 11550 if (!isDiscardableGVALinkage(Linkage)) 11551 return true; 11552 11553 // We never need to emit a variable that is available in another TU. 11554 if (Linkage == GVA_AvailableExternally) 11555 return false; 11556 11557 // Variables that have destruction with side-effects are required. 11558 if (VD->needsDestruction(*this)) 11559 return true; 11560 11561 // Variables that have initialization with side-effects are required. 11562 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11563 // We can get a value-dependent initializer during error recovery. 11564 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11565 return true; 11566 11567 // Likewise, variables with tuple-like bindings are required if their 11568 // bindings have side-effects. 11569 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11570 for (const auto *BD : DD->bindings()) 11571 if (const auto *BindingVD = BD->getHoldingVar()) 11572 if (DeclMustBeEmitted(BindingVD)) 11573 return true; 11574 11575 return false; 11576 } 11577 11578 void ASTContext::forEachMultiversionedFunctionVersion( 11579 const FunctionDecl *FD, 11580 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11581 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11582 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11583 FD = FD->getMostRecentDecl(); 11584 // FIXME: The order of traversal here matters and depends on the order of 11585 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11586 // shouldn't rely on that. 11587 for (auto *CurDecl : 11588 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11589 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11590 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11591 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11592 SeenDecls.insert(CurFD); 11593 Pred(CurFD); 11594 } 11595 } 11596 } 11597 11598 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11599 bool IsCXXMethod, 11600 bool IsBuiltin) const { 11601 // Pass through to the C++ ABI object 11602 if (IsCXXMethod) 11603 return ABI->getDefaultMethodCallConv(IsVariadic); 11604 11605 // Builtins ignore user-specified default calling convention and remain the 11606 // Target's default calling convention. 11607 if (!IsBuiltin) { 11608 switch (LangOpts.getDefaultCallingConv()) { 11609 case LangOptions::DCC_None: 11610 break; 11611 case LangOptions::DCC_CDecl: 11612 return CC_C; 11613 case LangOptions::DCC_FastCall: 11614 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11615 return CC_X86FastCall; 11616 break; 11617 case LangOptions::DCC_StdCall: 11618 if (!IsVariadic) 11619 return CC_X86StdCall; 11620 break; 11621 case LangOptions::DCC_VectorCall: 11622 // __vectorcall cannot be applied to variadic functions. 11623 if (!IsVariadic) 11624 return CC_X86VectorCall; 11625 break; 11626 case LangOptions::DCC_RegCall: 11627 // __regcall cannot be applied to variadic functions. 11628 if (!IsVariadic) 11629 return CC_X86RegCall; 11630 break; 11631 } 11632 } 11633 return Target->getDefaultCallingConv(); 11634 } 11635 11636 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11637 // Pass through to the C++ ABI object 11638 return ABI->isNearlyEmpty(RD); 11639 } 11640 11641 VTableContextBase *ASTContext::getVTableContext() { 11642 if (!VTContext.get()) { 11643 auto ABI = Target->getCXXABI(); 11644 if (ABI.isMicrosoft()) 11645 VTContext.reset(new MicrosoftVTableContext(*this)); 11646 else { 11647 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11648 ? ItaniumVTableContext::Relative 11649 : ItaniumVTableContext::Pointer; 11650 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11651 } 11652 } 11653 return VTContext.get(); 11654 } 11655 11656 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11657 if (!T) 11658 T = Target; 11659 switch (T->getCXXABI().getKind()) { 11660 case TargetCXXABI::AppleARM64: 11661 case TargetCXXABI::Fuchsia: 11662 case TargetCXXABI::GenericAArch64: 11663 case TargetCXXABI::GenericItanium: 11664 case TargetCXXABI::GenericARM: 11665 case TargetCXXABI::GenericMIPS: 11666 case TargetCXXABI::iOS: 11667 case TargetCXXABI::WebAssembly: 11668 case TargetCXXABI::WatchOS: 11669 case TargetCXXABI::XL: 11670 return ItaniumMangleContext::create(*this, getDiagnostics()); 11671 case TargetCXXABI::Microsoft: 11672 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11673 } 11674 llvm_unreachable("Unsupported ABI"); 11675 } 11676 11677 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11678 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11679 "Device mangle context does not support Microsoft mangling."); 11680 switch (T.getCXXABI().getKind()) { 11681 case TargetCXXABI::AppleARM64: 11682 case TargetCXXABI::Fuchsia: 11683 case TargetCXXABI::GenericAArch64: 11684 case TargetCXXABI::GenericItanium: 11685 case TargetCXXABI::GenericARM: 11686 case TargetCXXABI::GenericMIPS: 11687 case TargetCXXABI::iOS: 11688 case TargetCXXABI::WebAssembly: 11689 case TargetCXXABI::WatchOS: 11690 case TargetCXXABI::XL: 11691 return ItaniumMangleContext::create( 11692 *this, getDiagnostics(), 11693 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11694 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11695 return RD->getDeviceLambdaManglingNumber(); 11696 return llvm::None; 11697 }); 11698 case TargetCXXABI::Microsoft: 11699 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11700 } 11701 llvm_unreachable("Unsupported ABI"); 11702 } 11703 11704 CXXABI::~CXXABI() = default; 11705 11706 size_t ASTContext::getSideTableAllocatedMemory() const { 11707 return ASTRecordLayouts.getMemorySize() + 11708 llvm::capacity_in_bytes(ObjCLayouts) + 11709 llvm::capacity_in_bytes(KeyFunctions) + 11710 llvm::capacity_in_bytes(ObjCImpls) + 11711 llvm::capacity_in_bytes(BlockVarCopyInits) + 11712 llvm::capacity_in_bytes(DeclAttrs) + 11713 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11714 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11715 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11716 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11717 llvm::capacity_in_bytes(OverriddenMethods) + 11718 llvm::capacity_in_bytes(Types) + 11719 llvm::capacity_in_bytes(VariableArrayTypes); 11720 } 11721 11722 /// getIntTypeForBitwidth - 11723 /// sets integer QualTy according to specified details: 11724 /// bitwidth, signed/unsigned. 11725 /// Returns empty type if there is no appropriate target types. 11726 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11727 unsigned Signed) const { 11728 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11729 CanQualType QualTy = getFromTargetType(Ty); 11730 if (!QualTy && DestWidth == 128) 11731 return Signed ? Int128Ty : UnsignedInt128Ty; 11732 return QualTy; 11733 } 11734 11735 /// getRealTypeForBitwidth - 11736 /// sets floating point QualTy according to specified bitwidth. 11737 /// Returns empty type if there is no appropriate target types. 11738 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11739 FloatModeKind ExplicitType) const { 11740 FloatModeKind Ty = 11741 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11742 switch (Ty) { 11743 case FloatModeKind::Float: 11744 return FloatTy; 11745 case FloatModeKind::Double: 11746 return DoubleTy; 11747 case FloatModeKind::LongDouble: 11748 return LongDoubleTy; 11749 case FloatModeKind::Float128: 11750 return Float128Ty; 11751 case FloatModeKind::Ibm128: 11752 return Ibm128Ty; 11753 case FloatModeKind::NoFloat: 11754 return {}; 11755 } 11756 11757 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11758 } 11759 11760 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11761 if (Number > 1) 11762 MangleNumbers[ND] = Number; 11763 } 11764 11765 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11766 auto I = MangleNumbers.find(ND); 11767 return I != MangleNumbers.end() ? I->second : 1; 11768 } 11769 11770 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11771 if (Number > 1) 11772 StaticLocalNumbers[VD] = Number; 11773 } 11774 11775 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11776 auto I = StaticLocalNumbers.find(VD); 11777 return I != StaticLocalNumbers.end() ? I->second : 1; 11778 } 11779 11780 MangleNumberingContext & 11781 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11782 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11783 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11784 if (!MCtx) 11785 MCtx = createMangleNumberingContext(); 11786 return *MCtx; 11787 } 11788 11789 MangleNumberingContext & 11790 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11791 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11792 std::unique_ptr<MangleNumberingContext> &MCtx = 11793 ExtraMangleNumberingContexts[D]; 11794 if (!MCtx) 11795 MCtx = createMangleNumberingContext(); 11796 return *MCtx; 11797 } 11798 11799 std::unique_ptr<MangleNumberingContext> 11800 ASTContext::createMangleNumberingContext() const { 11801 return ABI->createMangleNumberingContext(); 11802 } 11803 11804 const CXXConstructorDecl * 11805 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11806 return ABI->getCopyConstructorForExceptionObject( 11807 cast<CXXRecordDecl>(RD->getFirstDecl())); 11808 } 11809 11810 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11811 CXXConstructorDecl *CD) { 11812 return ABI->addCopyConstructorForExceptionObject( 11813 cast<CXXRecordDecl>(RD->getFirstDecl()), 11814 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11815 } 11816 11817 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11818 TypedefNameDecl *DD) { 11819 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11820 } 11821 11822 TypedefNameDecl * 11823 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11824 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11825 } 11826 11827 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11828 DeclaratorDecl *DD) { 11829 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11830 } 11831 11832 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11833 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11834 } 11835 11836 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11837 ParamIndices[D] = index; 11838 } 11839 11840 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11841 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11842 assert(I != ParamIndices.end() && 11843 "ParmIndices lacks entry set by ParmVarDecl"); 11844 return I->second; 11845 } 11846 11847 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11848 unsigned Length) const { 11849 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11850 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11851 EltTy = EltTy.withConst(); 11852 11853 EltTy = adjustStringLiteralBaseType(EltTy); 11854 11855 // Get an array type for the string, according to C99 6.4.5. This includes 11856 // the null terminator character. 11857 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11858 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11859 } 11860 11861 StringLiteral * 11862 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11863 StringLiteral *&Result = StringLiteralCache[Key]; 11864 if (!Result) 11865 Result = StringLiteral::Create( 11866 *this, Key, StringLiteral::Ascii, 11867 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11868 SourceLocation()); 11869 return Result; 11870 } 11871 11872 MSGuidDecl * 11873 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11874 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11875 11876 llvm::FoldingSetNodeID ID; 11877 MSGuidDecl::Profile(ID, Parts); 11878 11879 void *InsertPos; 11880 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11881 return Existing; 11882 11883 QualType GUIDType = getMSGuidType().withConst(); 11884 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11885 MSGuidDecls.InsertNode(New, InsertPos); 11886 return New; 11887 } 11888 11889 UnnamedGlobalConstantDecl * 11890 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty, 11891 const APValue &APVal) const { 11892 llvm::FoldingSetNodeID ID; 11893 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal); 11894 11895 void *InsertPos; 11896 if (UnnamedGlobalConstantDecl *Existing = 11897 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos)) 11898 return Existing; 11899 11900 UnnamedGlobalConstantDecl *New = 11901 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal); 11902 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos); 11903 return New; 11904 } 11905 11906 TemplateParamObjectDecl * 11907 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11908 assert(T->isRecordType() && "template param object of unexpected type"); 11909 11910 // C++ [temp.param]p8: 11911 // [...] a static storage duration object of type 'const T' [...] 11912 T.addConst(); 11913 11914 llvm::FoldingSetNodeID ID; 11915 TemplateParamObjectDecl::Profile(ID, T, V); 11916 11917 void *InsertPos; 11918 if (TemplateParamObjectDecl *Existing = 11919 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11920 return Existing; 11921 11922 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11923 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11924 return New; 11925 } 11926 11927 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11928 const llvm::Triple &T = getTargetInfo().getTriple(); 11929 if (!T.isOSDarwin()) 11930 return false; 11931 11932 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11933 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11934 return false; 11935 11936 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11937 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11938 uint64_t Size = sizeChars.getQuantity(); 11939 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11940 unsigned Align = alignChars.getQuantity(); 11941 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11942 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11943 } 11944 11945 bool 11946 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11947 const ObjCMethodDecl *MethodImpl) { 11948 // No point trying to match an unavailable/deprecated mothod. 11949 if (MethodDecl->hasAttr<UnavailableAttr>() 11950 || MethodDecl->hasAttr<DeprecatedAttr>()) 11951 return false; 11952 if (MethodDecl->getObjCDeclQualifier() != 11953 MethodImpl->getObjCDeclQualifier()) 11954 return false; 11955 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11956 return false; 11957 11958 if (MethodDecl->param_size() != MethodImpl->param_size()) 11959 return false; 11960 11961 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11962 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11963 EF = MethodDecl->param_end(); 11964 IM != EM && IF != EF; ++IM, ++IF) { 11965 const ParmVarDecl *DeclVar = (*IF); 11966 const ParmVarDecl *ImplVar = (*IM); 11967 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11968 return false; 11969 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11970 return false; 11971 } 11972 11973 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11974 } 11975 11976 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11977 LangAS AS; 11978 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11979 AS = LangAS::Default; 11980 else 11981 AS = QT->getPointeeType().getAddressSpace(); 11982 11983 return getTargetInfo().getNullPointerValue(AS); 11984 } 11985 11986 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11987 // Return the address space for the type. If the type is a 11988 // function type without an address space qualifier, the 11989 // program address space is used. Otherwise, the target picks 11990 // the best address space based on the type information 11991 return T->isFunctionType() && !T.hasAddressSpace() 11992 ? getTargetInfo().getProgramAddressSpace() 11993 : getTargetAddressSpace(T.getQualifiers()); 11994 } 11995 11996 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 11997 return getTargetAddressSpace(Q.getAddressSpace()); 11998 } 11999 12000 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 12001 if (isTargetAddressSpace(AS)) 12002 return toTargetAddressSpace(AS); 12003 else 12004 return (*AddrSpaceMap)[(unsigned)AS]; 12005 } 12006 12007 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 12008 assert(Ty->isFixedPointType()); 12009 12010 if (Ty->isSaturatedFixedPointType()) return Ty; 12011 12012 switch (Ty->castAs<BuiltinType>()->getKind()) { 12013 default: 12014 llvm_unreachable("Not a fixed point type!"); 12015 case BuiltinType::ShortAccum: 12016 return SatShortAccumTy; 12017 case BuiltinType::Accum: 12018 return SatAccumTy; 12019 case BuiltinType::LongAccum: 12020 return SatLongAccumTy; 12021 case BuiltinType::UShortAccum: 12022 return SatUnsignedShortAccumTy; 12023 case BuiltinType::UAccum: 12024 return SatUnsignedAccumTy; 12025 case BuiltinType::ULongAccum: 12026 return SatUnsignedLongAccumTy; 12027 case BuiltinType::ShortFract: 12028 return SatShortFractTy; 12029 case BuiltinType::Fract: 12030 return SatFractTy; 12031 case BuiltinType::LongFract: 12032 return SatLongFractTy; 12033 case BuiltinType::UShortFract: 12034 return SatUnsignedShortFractTy; 12035 case BuiltinType::UFract: 12036 return SatUnsignedFractTy; 12037 case BuiltinType::ULongFract: 12038 return SatUnsignedLongFractTy; 12039 } 12040 } 12041 12042 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12043 if (LangOpts.OpenCL) 12044 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12045 12046 if (LangOpts.CUDA) 12047 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12048 12049 return getLangASFromTargetAS(AS); 12050 } 12051 12052 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12053 // doesn't include ASTContext.h 12054 template 12055 clang::LazyGenerationalUpdatePtr< 12056 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12057 clang::LazyGenerationalUpdatePtr< 12058 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12059 const clang::ASTContext &Ctx, Decl *Value); 12060 12061 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12062 assert(Ty->isFixedPointType()); 12063 12064 const TargetInfo &Target = getTargetInfo(); 12065 switch (Ty->castAs<BuiltinType>()->getKind()) { 12066 default: 12067 llvm_unreachable("Not a fixed point type!"); 12068 case BuiltinType::ShortAccum: 12069 case BuiltinType::SatShortAccum: 12070 return Target.getShortAccumScale(); 12071 case BuiltinType::Accum: 12072 case BuiltinType::SatAccum: 12073 return Target.getAccumScale(); 12074 case BuiltinType::LongAccum: 12075 case BuiltinType::SatLongAccum: 12076 return Target.getLongAccumScale(); 12077 case BuiltinType::UShortAccum: 12078 case BuiltinType::SatUShortAccum: 12079 return Target.getUnsignedShortAccumScale(); 12080 case BuiltinType::UAccum: 12081 case BuiltinType::SatUAccum: 12082 return Target.getUnsignedAccumScale(); 12083 case BuiltinType::ULongAccum: 12084 case BuiltinType::SatULongAccum: 12085 return Target.getUnsignedLongAccumScale(); 12086 case BuiltinType::ShortFract: 12087 case BuiltinType::SatShortFract: 12088 return Target.getShortFractScale(); 12089 case BuiltinType::Fract: 12090 case BuiltinType::SatFract: 12091 return Target.getFractScale(); 12092 case BuiltinType::LongFract: 12093 case BuiltinType::SatLongFract: 12094 return Target.getLongFractScale(); 12095 case BuiltinType::UShortFract: 12096 case BuiltinType::SatUShortFract: 12097 return Target.getUnsignedShortFractScale(); 12098 case BuiltinType::UFract: 12099 case BuiltinType::SatUFract: 12100 return Target.getUnsignedFractScale(); 12101 case BuiltinType::ULongFract: 12102 case BuiltinType::SatULongFract: 12103 return Target.getUnsignedLongFractScale(); 12104 } 12105 } 12106 12107 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12108 assert(Ty->isFixedPointType()); 12109 12110 const TargetInfo &Target = getTargetInfo(); 12111 switch (Ty->castAs<BuiltinType>()->getKind()) { 12112 default: 12113 llvm_unreachable("Not a fixed point type!"); 12114 case BuiltinType::ShortAccum: 12115 case BuiltinType::SatShortAccum: 12116 return Target.getShortAccumIBits(); 12117 case BuiltinType::Accum: 12118 case BuiltinType::SatAccum: 12119 return Target.getAccumIBits(); 12120 case BuiltinType::LongAccum: 12121 case BuiltinType::SatLongAccum: 12122 return Target.getLongAccumIBits(); 12123 case BuiltinType::UShortAccum: 12124 case BuiltinType::SatUShortAccum: 12125 return Target.getUnsignedShortAccumIBits(); 12126 case BuiltinType::UAccum: 12127 case BuiltinType::SatUAccum: 12128 return Target.getUnsignedAccumIBits(); 12129 case BuiltinType::ULongAccum: 12130 case BuiltinType::SatULongAccum: 12131 return Target.getUnsignedLongAccumIBits(); 12132 case BuiltinType::ShortFract: 12133 case BuiltinType::SatShortFract: 12134 case BuiltinType::Fract: 12135 case BuiltinType::SatFract: 12136 case BuiltinType::LongFract: 12137 case BuiltinType::SatLongFract: 12138 case BuiltinType::UShortFract: 12139 case BuiltinType::SatUShortFract: 12140 case BuiltinType::UFract: 12141 case BuiltinType::SatUFract: 12142 case BuiltinType::ULongFract: 12143 case BuiltinType::SatULongFract: 12144 return 0; 12145 } 12146 } 12147 12148 llvm::FixedPointSemantics 12149 ASTContext::getFixedPointSemantics(QualType Ty) const { 12150 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12151 "Can only get the fixed point semantics for a " 12152 "fixed point or integer type."); 12153 if (Ty->isIntegerType()) 12154 return llvm::FixedPointSemantics::GetIntegerSemantics( 12155 getIntWidth(Ty), Ty->isSignedIntegerType()); 12156 12157 bool isSigned = Ty->isSignedFixedPointType(); 12158 return llvm::FixedPointSemantics( 12159 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12160 Ty->isSaturatedFixedPointType(), 12161 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12162 } 12163 12164 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12165 assert(Ty->isFixedPointType()); 12166 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12167 } 12168 12169 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12170 assert(Ty->isFixedPointType()); 12171 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12172 } 12173 12174 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12175 assert(Ty->isUnsignedFixedPointType() && 12176 "Expected unsigned fixed point type"); 12177 12178 switch (Ty->castAs<BuiltinType>()->getKind()) { 12179 case BuiltinType::UShortAccum: 12180 return ShortAccumTy; 12181 case BuiltinType::UAccum: 12182 return AccumTy; 12183 case BuiltinType::ULongAccum: 12184 return LongAccumTy; 12185 case BuiltinType::SatUShortAccum: 12186 return SatShortAccumTy; 12187 case BuiltinType::SatUAccum: 12188 return SatAccumTy; 12189 case BuiltinType::SatULongAccum: 12190 return SatLongAccumTy; 12191 case BuiltinType::UShortFract: 12192 return ShortFractTy; 12193 case BuiltinType::UFract: 12194 return FractTy; 12195 case BuiltinType::ULongFract: 12196 return LongFractTy; 12197 case BuiltinType::SatUShortFract: 12198 return SatShortFractTy; 12199 case BuiltinType::SatUFract: 12200 return SatFractTy; 12201 case BuiltinType::SatULongFract: 12202 return SatLongFractTy; 12203 default: 12204 llvm_unreachable("Unexpected unsigned fixed point type"); 12205 } 12206 } 12207 12208 ParsedTargetAttr 12209 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12210 assert(TD != nullptr); 12211 ParsedTargetAttr ParsedAttr = TD->parse(); 12212 12213 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12214 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12215 }); 12216 return ParsedAttr; 12217 } 12218 12219 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12220 const FunctionDecl *FD) const { 12221 if (FD) 12222 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12223 else 12224 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12225 Target->getTargetOpts().CPU, 12226 Target->getTargetOpts().Features); 12227 } 12228 12229 // Fills in the supplied string map with the set of target features for the 12230 // passed in function. 12231 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12232 GlobalDecl GD) const { 12233 StringRef TargetCPU = Target->getTargetOpts().CPU; 12234 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12235 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12236 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12237 12238 // Make a copy of the features as passed on the command line into the 12239 // beginning of the additional features from the function to override. 12240 ParsedAttr.Features.insert( 12241 ParsedAttr.Features.begin(), 12242 Target->getTargetOpts().FeaturesAsWritten.begin(), 12243 Target->getTargetOpts().FeaturesAsWritten.end()); 12244 12245 if (ParsedAttr.Architecture != "" && 12246 Target->isValidCPUName(ParsedAttr.Architecture)) 12247 TargetCPU = ParsedAttr.Architecture; 12248 12249 // Now populate the feature map, first with the TargetCPU which is either 12250 // the default or a new one from the target attribute string. Then we'll use 12251 // the passed in features (FeaturesAsWritten) along with the new ones from 12252 // the attribute. 12253 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12254 ParsedAttr.Features); 12255 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12256 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12257 Target->getCPUSpecificCPUDispatchFeatures( 12258 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12259 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12260 Features.insert(Features.begin(), 12261 Target->getTargetOpts().FeaturesAsWritten.begin(), 12262 Target->getTargetOpts().FeaturesAsWritten.end()); 12263 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12264 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12265 std::vector<std::string> Features; 12266 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12267 if (VersionStr.startswith("arch=")) 12268 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12269 else if (VersionStr != "default") 12270 Features.push_back((StringRef{"+"} + VersionStr).str()); 12271 12272 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12273 } else { 12274 FeatureMap = Target->getTargetOpts().FeatureMap; 12275 } 12276 } 12277 12278 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12279 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12280 return *OMPTraitInfoVector.back(); 12281 } 12282 12283 const StreamingDiagnostic &clang:: 12284 operator<<(const StreamingDiagnostic &DB, 12285 const ASTContext::SectionInfo &Section) { 12286 if (Section.Decl) 12287 return DB << Section.Decl; 12288 return DB << "a prior #pragma section"; 12289 } 12290 12291 bool ASTContext::mayExternalize(const Decl *D) const { 12292 bool IsStaticVar = 12293 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12294 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12295 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12296 (D->hasAttr<CUDAConstantAttr>() && 12297 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12298 // CUDA/HIP: static managed variables need to be externalized since it is 12299 // a declaration in IR, therefore cannot have internal linkage. Kernels in 12300 // anonymous name space needs to be externalized to avoid duplicate symbols. 12301 return (IsStaticVar && 12302 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) || 12303 (D->hasAttr<CUDAGlobalAttr>() && D->isInAnonymousNamespace()); 12304 } 12305 12306 bool ASTContext::shouldExternalize(const Decl *D) const { 12307 return mayExternalize(D) && 12308 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() || 12309 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12310 } 12311 12312 StringRef ASTContext::getCUIDHash() const { 12313 if (!CUIDHash.empty()) 12314 return CUIDHash; 12315 if (LangOpts.CUID.empty()) 12316 return StringRef(); 12317 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12318 return CUIDHash; 12319 } 12320