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 "ByteCode/Context.h" 15 #include "CXXABI.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/ExternalASTSource.h" 36 #include "clang/AST/Mangle.h" 37 #include "clang/AST/MangleNumberingContext.h" 38 #include "clang/AST/NestedNameSpecifier.h" 39 #include "clang/AST/ParentMapContext.h" 40 #include "clang/AST/RawCommentList.h" 41 #include "clang/AST/RecordLayout.h" 42 #include "clang/AST/Stmt.h" 43 #include "clang/AST/TemplateBase.h" 44 #include "clang/AST/TemplateName.h" 45 #include "clang/AST/Type.h" 46 #include "clang/AST/TypeLoc.h" 47 #include "clang/AST/UnresolvedSet.h" 48 #include "clang/AST/VTableBuilder.h" 49 #include "clang/Basic/AddressSpaces.h" 50 #include "clang/Basic/Builtins.h" 51 #include "clang/Basic/CommentOptions.h" 52 #include "clang/Basic/ExceptionSpecificationType.h" 53 #include "clang/Basic/IdentifierTable.h" 54 #include "clang/Basic/LLVM.h" 55 #include "clang/Basic/LangOptions.h" 56 #include "clang/Basic/Linkage.h" 57 #include "clang/Basic/Module.h" 58 #include "clang/Basic/NoSanitizeList.h" 59 #include "clang/Basic/ObjCRuntime.h" 60 #include "clang/Basic/ProfileList.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/PointerUnion.h" 75 #include "llvm/ADT/STLExtras.h" 76 #include "llvm/ADT/SmallPtrSet.h" 77 #include "llvm/ADT/SmallVector.h" 78 #include "llvm/ADT/StringExtras.h" 79 #include "llvm/ADT/StringRef.h" 80 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 81 #include "llvm/Support/Capacity.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/MD5.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/SipHash.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/TargetParser/AArch64TargetParser.h" 89 #include "llvm/TargetParser/Triple.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <optional> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 102 using namespace clang; 103 104 enum FloatingRank { 105 BFloat16Rank, 106 Float16Rank, 107 HalfRank, 108 FloatRank, 109 DoubleRank, 110 LongDoubleRank, 111 Float128Rank, 112 Ibm128Rank 113 }; 114 115 template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> { 116 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; } 117 118 static FoldingSetNodeID getTombstoneKey() { 119 FoldingSetNodeID id; 120 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) { 121 id.AddInteger(std::numeric_limits<unsigned>::max()); 122 } 123 return id; 124 } 125 126 static unsigned getHashValue(const FoldingSetNodeID &Val) { 127 return Val.ComputeHash(); 128 } 129 130 static bool isEqual(const FoldingSetNodeID &LHS, 131 const FoldingSetNodeID &RHS) { 132 return LHS == RHS; 133 } 134 }; 135 136 /// \returns The locations that are relevant when searching for Doc comments 137 /// related to \p D. 138 static SmallVector<SourceLocation, 2> 139 getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) { 140 assert(D); 141 142 // User can not attach documentation to implicit declarations. 143 if (D->isImplicit()) 144 return {}; 145 146 // User can not attach documentation to implicit instantiations. 147 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 148 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 149 return {}; 150 } 151 152 if (const auto *VD = dyn_cast<VarDecl>(D)) { 153 if (VD->isStaticDataMember() && 154 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 155 return {}; 156 } 157 158 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 159 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 160 return {}; 161 } 162 163 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 164 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 165 if (TSK == TSK_ImplicitInstantiation || 166 TSK == TSK_Undeclared) 167 return {}; 168 } 169 170 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 171 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 172 return {}; 173 } 174 if (const auto *TD = dyn_cast<TagDecl>(D)) { 175 // When tag declaration (but not definition!) is part of the 176 // decl-specifier-seq of some other declaration, it doesn't get comment 177 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 178 return {}; 179 } 180 // TODO: handle comments for function parameters properly. 181 if (isa<ParmVarDecl>(D)) 182 return {}; 183 184 // TODO: we could look up template parameter documentation in the template 185 // documentation. 186 if (isa<TemplateTypeParmDecl>(D) || 187 isa<NonTypeTemplateParmDecl>(D) || 188 isa<TemplateTemplateParmDecl>(D)) 189 return {}; 190 191 SmallVector<SourceLocation, 2> Locations; 192 // Find declaration location. 193 // For Objective-C declarations we generally don't expect to have multiple 194 // declarators, thus use declaration starting location as the "declaration 195 // location". 196 // For all other declarations multiple declarators are used quite frequently, 197 // so we use the location of the identifier as the "declaration location". 198 SourceLocation BaseLocation; 199 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 200 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) || 201 isa<ClassTemplateSpecializationDecl>(D) || 202 // Allow association with Y across {} in `typedef struct X {} Y`. 203 isa<TypedefDecl>(D)) 204 BaseLocation = D->getBeginLoc(); 205 else 206 BaseLocation = D->getLocation(); 207 208 if (!D->getLocation().isMacroID()) { 209 Locations.emplace_back(BaseLocation); 210 } else { 211 const auto *DeclCtx = D->getDeclContext(); 212 213 // When encountering definitions generated from a macro (that are not 214 // contained by another declaration in the macro) we need to try and find 215 // the comment at the location of the expansion but if there is no comment 216 // there we should retry to see if there is a comment inside the macro as 217 // well. To this end we return first BaseLocation to first look at the 218 // expansion site, the second value is the spelling location of the 219 // beginning of the declaration defined inside the macro. 220 if (!(DeclCtx && 221 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) { 222 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation)); 223 } 224 225 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that 226 // we don't refer to the macro argument location at the expansion site (this 227 // can happen if the name's spelling is provided via macro argument), and 228 // always to the declaration itself. 229 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc())); 230 } 231 232 return Locations; 233 } 234 235 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 236 const Decl *D, const SourceLocation RepresentativeLocForDecl, 237 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 238 // If the declaration doesn't map directly to a location in a file, we 239 // can't find the comment. 240 if (RepresentativeLocForDecl.isInvalid() || 241 !RepresentativeLocForDecl.isFileID()) 242 return nullptr; 243 244 // If there are no comments anywhere, we won't find anything. 245 if (CommentsInTheFile.empty()) 246 return nullptr; 247 248 // Decompose the location for the declaration and find the beginning of the 249 // file buffer. 250 const std::pair<FileID, unsigned> DeclLocDecomp = 251 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 252 253 // Slow path. 254 auto OffsetCommentBehindDecl = 255 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 256 257 // First check whether we have a trailing comment. 258 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 259 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 260 if ((CommentBehindDecl->isDocumentation() || 261 LangOpts.CommentOpts.ParseAllComments) && 262 CommentBehindDecl->isTrailingComment() && 263 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 264 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 265 266 // Check that Doxygen trailing comment comes after the declaration, starts 267 // on the same line and in the same file as the declaration. 268 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 269 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 270 OffsetCommentBehindDecl->first)) { 271 return CommentBehindDecl; 272 } 273 } 274 } 275 276 // The comment just after the declaration was not a trailing comment. 277 // Let's look at the previous comment. 278 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 279 return nullptr; 280 281 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 282 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 283 284 // Check that we actually have a non-member Doxygen comment. 285 if (!(CommentBeforeDecl->isDocumentation() || 286 LangOpts.CommentOpts.ParseAllComments) || 287 CommentBeforeDecl->isTrailingComment()) 288 return nullptr; 289 290 // Decompose the end of the comment. 291 const unsigned CommentEndOffset = 292 Comments.getCommentEndOffset(CommentBeforeDecl); 293 294 // Get the corresponding buffer. 295 bool Invalid = false; 296 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 297 &Invalid).data(); 298 if (Invalid) 299 return nullptr; 300 301 // Extract text between the comment and declaration. 302 StringRef Text(Buffer + CommentEndOffset, 303 DeclLocDecomp.second - CommentEndOffset); 304 305 // There should be no other declarations or preprocessor directives between 306 // comment and declaration. 307 if (Text.find_last_of(";{}#@") != StringRef::npos) 308 return nullptr; 309 310 return CommentBeforeDecl; 311 } 312 313 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 314 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr); 315 316 for (const auto DeclLoc : DeclLocs) { 317 // If the declaration doesn't map directly to a location in a file, we 318 // can't find the comment. 319 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 320 continue; 321 322 if (ExternalSource && !CommentsLoaded) { 323 ExternalSource->ReadComments(); 324 CommentsLoaded = true; 325 } 326 327 if (Comments.empty()) 328 continue; 329 330 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 331 if (!File.isValid()) 332 continue; 333 334 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 335 if (!CommentsInThisFile || CommentsInThisFile->empty()) 336 continue; 337 338 if (RawComment *Comment = 339 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) 340 return Comment; 341 } 342 343 return nullptr; 344 } 345 346 void ASTContext::addComment(const RawComment &RC) { 347 assert(LangOpts.RetainCommentsFromSystemHeaders || 348 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 349 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 350 } 351 352 /// If we have a 'templated' declaration for a template, adjust 'D' to 353 /// refer to the actual template. 354 /// If we have an implicit instantiation, adjust 'D' to refer to template. 355 static const Decl &adjustDeclToTemplate(const Decl &D) { 356 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 357 // Is this function declaration part of a function template? 358 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 359 return *FTD; 360 361 // Nothing to do if function is not an implicit instantiation. 362 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 363 return D; 364 365 // Function is an implicit instantiation of a function template? 366 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 367 return *FTD; 368 369 // Function is instantiated from a member definition of a class template? 370 if (const FunctionDecl *MemberDecl = 371 FD->getInstantiatedFromMemberFunction()) 372 return *MemberDecl; 373 374 return D; 375 } 376 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 377 // Static data member is instantiated from a member definition of a class 378 // template? 379 if (VD->isStaticDataMember()) 380 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 381 return *MemberDecl; 382 383 return D; 384 } 385 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 386 // Is this class declaration part of a class template? 387 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 388 return *CTD; 389 390 // Class is an implicit instantiation of a class template or partial 391 // specialization? 392 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 393 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 394 return D; 395 llvm::PointerUnion<ClassTemplateDecl *, 396 ClassTemplatePartialSpecializationDecl *> 397 PU = CTSD->getSpecializedTemplateOrPartial(); 398 return isa<ClassTemplateDecl *>(PU) 399 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU)) 400 : *static_cast<const Decl *>( 401 cast<ClassTemplatePartialSpecializationDecl *>(PU)); 402 } 403 404 // Class is instantiated from a member definition of a class template? 405 if (const MemberSpecializationInfo *Info = 406 CRD->getMemberSpecializationInfo()) 407 return *Info->getInstantiatedFrom(); 408 409 return D; 410 } 411 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 412 // Enum is instantiated from a member definition of a class template? 413 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 414 return *MemberDecl; 415 416 return D; 417 } 418 // FIXME: Adjust alias templates? 419 return D; 420 } 421 422 const RawComment *ASTContext::getRawCommentForAnyRedecl( 423 const Decl *D, 424 const Decl **OriginalDecl) const { 425 if (!D) { 426 if (OriginalDecl) 427 OriginalDecl = nullptr; 428 return nullptr; 429 } 430 431 D = &adjustDeclToTemplate(*D); 432 433 // Any comment directly attached to D? 434 { 435 auto DeclComment = DeclRawComments.find(D); 436 if (DeclComment != DeclRawComments.end()) { 437 if (OriginalDecl) 438 *OriginalDecl = D; 439 return DeclComment->second; 440 } 441 } 442 443 // Any comment attached to any redeclaration of D? 444 const Decl *CanonicalD = D->getCanonicalDecl(); 445 if (!CanonicalD) 446 return nullptr; 447 448 { 449 auto RedeclComment = RedeclChainComments.find(CanonicalD); 450 if (RedeclComment != RedeclChainComments.end()) { 451 if (OriginalDecl) 452 *OriginalDecl = RedeclComment->second; 453 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 454 assert(CommentAtRedecl != DeclRawComments.end() && 455 "This decl is supposed to have comment attached."); 456 return CommentAtRedecl->second; 457 } 458 } 459 460 // Any redeclarations of D that we haven't checked for comments yet? 461 const Decl *LastCheckedRedecl = [&]() { 462 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD); 463 bool CanUseCommentlessCache = false; 464 if (LastChecked) { 465 for (auto *Redecl : CanonicalD->redecls()) { 466 if (Redecl == D) { 467 CanUseCommentlessCache = true; 468 break; 469 } 470 if (Redecl == LastChecked) 471 break; 472 } 473 } 474 // FIXME: This could be improved so that even if CanUseCommentlessCache 475 // is false, once we've traversed past CanonicalD we still skip ahead 476 // LastChecked. 477 return CanUseCommentlessCache ? LastChecked : nullptr; 478 }(); 479 480 for (const Decl *Redecl : D->redecls()) { 481 assert(Redecl); 482 // Skip all redeclarations that have been checked previously. 483 if (LastCheckedRedecl) { 484 if (LastCheckedRedecl == Redecl) { 485 LastCheckedRedecl = nullptr; 486 } 487 continue; 488 } 489 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 490 if (RedeclComment) { 491 cacheRawCommentForDecl(*Redecl, *RedeclComment); 492 if (OriginalDecl) 493 *OriginalDecl = Redecl; 494 return RedeclComment; 495 } 496 CommentlessRedeclChains[CanonicalD] = Redecl; 497 } 498 499 if (OriginalDecl) 500 *OriginalDecl = nullptr; 501 return nullptr; 502 } 503 504 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 505 const RawComment &Comment) const { 506 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 507 DeclRawComments.try_emplace(&OriginalD, &Comment); 508 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 509 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 510 CommentlessRedeclChains.erase(CanonicalDecl); 511 } 512 513 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 514 SmallVectorImpl<const NamedDecl *> &Redeclared) { 515 const DeclContext *DC = ObjCMethod->getDeclContext(); 516 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 517 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 518 if (!ID) 519 return; 520 // Add redeclared method here. 521 for (const auto *Ext : ID->known_extensions()) { 522 if (ObjCMethodDecl *RedeclaredMethod = 523 Ext->getMethod(ObjCMethod->getSelector(), 524 ObjCMethod->isInstanceMethod())) 525 Redeclared.push_back(RedeclaredMethod); 526 } 527 } 528 } 529 530 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 531 const Preprocessor *PP) { 532 if (Comments.empty() || Decls.empty()) 533 return; 534 535 FileID File; 536 for (const Decl *D : Decls) { 537 if (D->isInvalidDecl()) 538 continue; 539 540 D = &adjustDeclToTemplate(*D); 541 SourceLocation Loc = D->getLocation(); 542 if (Loc.isValid()) { 543 // See if there are any new comments that are not attached to a decl. 544 // The location doesn't have to be precise - we care only about the file. 545 File = SourceMgr.getDecomposedLoc(Loc).first; 546 break; 547 } 548 } 549 550 if (File.isInvalid()) 551 return; 552 553 auto CommentsInThisFile = Comments.getCommentsInFile(File); 554 if (!CommentsInThisFile || CommentsInThisFile->empty() || 555 CommentsInThisFile->rbegin()->second->isAttached()) 556 return; 557 558 // There is at least one comment not attached to a decl. 559 // Maybe it should be attached to one of Decls? 560 // 561 // Note that this way we pick up not only comments that precede the 562 // declaration, but also comments that *follow* the declaration -- thanks to 563 // the lookahead in the lexer: we've consumed the semicolon and looked 564 // ahead through comments. 565 for (const Decl *D : Decls) { 566 assert(D); 567 if (D->isInvalidDecl()) 568 continue; 569 570 D = &adjustDeclToTemplate(*D); 571 572 if (DeclRawComments.count(D) > 0) 573 continue; 574 575 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr); 576 577 for (const auto DeclLoc : DeclLocs) { 578 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 579 continue; 580 581 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl( 582 D, DeclLoc, *CommentsInThisFile)) { 583 cacheRawCommentForDecl(*D, *DocComment); 584 comments::FullComment *FC = DocComment->parse(*this, PP, D); 585 ParsedComments[D->getCanonicalDecl()] = FC; 586 break; 587 } 588 } 589 } 590 } 591 592 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 593 const Decl *D) const { 594 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 595 ThisDeclInfo->CommentDecl = D; 596 ThisDeclInfo->IsFilled = false; 597 ThisDeclInfo->fill(); 598 ThisDeclInfo->CommentDecl = FC->getDecl(); 599 if (!ThisDeclInfo->TemplateParameters) 600 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 601 comments::FullComment *CFC = 602 new (*this) comments::FullComment(FC->getBlocks(), 603 ThisDeclInfo); 604 return CFC; 605 } 606 607 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 608 const RawComment *RC = getRawCommentForDeclNoCache(D); 609 return RC ? RC->parse(*this, nullptr, D) : nullptr; 610 } 611 612 comments::FullComment *ASTContext::getCommentForDecl( 613 const Decl *D, 614 const Preprocessor *PP) const { 615 if (!D || D->isInvalidDecl()) 616 return nullptr; 617 D = &adjustDeclToTemplate(*D); 618 619 const Decl *Canonical = D->getCanonicalDecl(); 620 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 621 ParsedComments.find(Canonical); 622 623 if (Pos != ParsedComments.end()) { 624 if (Canonical != D) { 625 comments::FullComment *FC = Pos->second; 626 comments::FullComment *CFC = cloneFullComment(FC, D); 627 return CFC; 628 } 629 return Pos->second; 630 } 631 632 const Decl *OriginalDecl = nullptr; 633 634 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 635 if (!RC) { 636 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 637 SmallVector<const NamedDecl*, 8> Overridden; 638 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 639 if (OMD && OMD->isPropertyAccessor()) 640 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 641 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 642 return cloneFullComment(FC, D); 643 if (OMD) 644 addRedeclaredMethods(OMD, Overridden); 645 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 646 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 647 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 648 return cloneFullComment(FC, D); 649 } 650 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 651 // Attach any tag type's documentation to its typedef if latter 652 // does not have one of its own. 653 QualType QT = TD->getUnderlyingType(); 654 if (const auto *TT = QT->getAs<TagType>()) 655 if (const Decl *TD = TT->getDecl()) 656 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 657 return cloneFullComment(FC, D); 658 } 659 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 660 while (IC->getSuperClass()) { 661 IC = IC->getSuperClass(); 662 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 663 return cloneFullComment(FC, D); 664 } 665 } 666 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 667 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 668 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 669 return cloneFullComment(FC, D); 670 } 671 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 672 if (!(RD = RD->getDefinition())) 673 return nullptr; 674 // Check non-virtual bases. 675 for (const auto &I : RD->bases()) { 676 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 677 continue; 678 QualType Ty = I.getType(); 679 if (Ty.isNull()) 680 continue; 681 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 682 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 683 continue; 684 685 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 686 return cloneFullComment(FC, D); 687 } 688 } 689 // Check virtual bases. 690 for (const auto &I : RD->vbases()) { 691 if (I.getAccessSpecifier() != AS_public) 692 continue; 693 QualType Ty = I.getType(); 694 if (Ty.isNull()) 695 continue; 696 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 697 if (!(VirtualBase= VirtualBase->getDefinition())) 698 continue; 699 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 700 return cloneFullComment(FC, D); 701 } 702 } 703 } 704 return nullptr; 705 } 706 707 // If the RawComment was attached to other redeclaration of this Decl, we 708 // should parse the comment in context of that other Decl. This is important 709 // because comments can contain references to parameter names which can be 710 // different across redeclarations. 711 if (D != OriginalDecl && OriginalDecl) 712 return getCommentForDecl(OriginalDecl, PP); 713 714 comments::FullComment *FC = RC->parse(*this, PP, D); 715 ParsedComments[Canonical] = FC; 716 return FC; 717 } 718 719 void 720 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 721 const ASTContext &C, 722 TemplateTemplateParmDecl *Parm) { 723 ID.AddInteger(Parm->getDepth()); 724 ID.AddInteger(Parm->getPosition()); 725 ID.AddBoolean(Parm->isParameterPack()); 726 727 TemplateParameterList *Params = Parm->getTemplateParameters(); 728 ID.AddInteger(Params->size()); 729 for (TemplateParameterList::const_iterator P = Params->begin(), 730 PEnd = Params->end(); 731 P != PEnd; ++P) { 732 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 733 ID.AddInteger(0); 734 ID.AddBoolean(TTP->isParameterPack()); 735 if (TTP->isExpandedParameterPack()) { 736 ID.AddBoolean(true); 737 ID.AddInteger(TTP->getNumExpansionParameters()); 738 } else 739 ID.AddBoolean(false); 740 continue; 741 } 742 743 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 744 ID.AddInteger(1); 745 ID.AddBoolean(NTTP->isParameterPack()); 746 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType())) 747 .getAsOpaquePtr()); 748 if (NTTP->isExpandedParameterPack()) { 749 ID.AddBoolean(true); 750 ID.AddInteger(NTTP->getNumExpansionTypes()); 751 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 752 QualType T = NTTP->getExpansionType(I); 753 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 754 } 755 } else 756 ID.AddBoolean(false); 757 continue; 758 } 759 760 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 761 ID.AddInteger(2); 762 Profile(ID, C, TTP); 763 } 764 } 765 766 TemplateTemplateParmDecl * 767 ASTContext::getCanonicalTemplateTemplateParmDecl( 768 TemplateTemplateParmDecl *TTP) const { 769 // Check if we already have a canonical template template parameter. 770 llvm::FoldingSetNodeID ID; 771 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 772 void *InsertPos = nullptr; 773 CanonicalTemplateTemplateParm *Canonical 774 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 775 if (Canonical) 776 return Canonical->getParam(); 777 778 // Build a canonical template parameter list. 779 TemplateParameterList *Params = TTP->getTemplateParameters(); 780 SmallVector<NamedDecl *, 4> CanonParams; 781 CanonParams.reserve(Params->size()); 782 for (TemplateParameterList::const_iterator P = Params->begin(), 783 PEnd = Params->end(); 784 P != PEnd; ++P) { 785 // Note that, per C++20 [temp.over.link]/6, when determining whether 786 // template-parameters are equivalent, constraints are ignored. 787 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 788 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create( 789 *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 790 TTP->getDepth(), TTP->getIndex(), nullptr, false, 791 TTP->isParameterPack(), /*HasTypeConstraint=*/false, 792 TTP->isExpandedParameterPack() 793 ? std::optional<unsigned>(TTP->getNumExpansionParameters()) 794 : std::nullopt); 795 CanonParams.push_back(NewTTP); 796 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 797 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType())); 798 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 799 NonTypeTemplateParmDecl *Param; 800 if (NTTP->isExpandedParameterPack()) { 801 SmallVector<QualType, 2> ExpandedTypes; 802 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 803 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 804 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 805 ExpandedTInfos.push_back( 806 getTrivialTypeSourceInfo(ExpandedTypes.back())); 807 } 808 809 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 810 SourceLocation(), 811 SourceLocation(), 812 NTTP->getDepth(), 813 NTTP->getPosition(), nullptr, 814 T, 815 TInfo, 816 ExpandedTypes, 817 ExpandedTInfos); 818 } else { 819 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 820 SourceLocation(), 821 SourceLocation(), 822 NTTP->getDepth(), 823 NTTP->getPosition(), nullptr, 824 T, 825 NTTP->isParameterPack(), 826 TInfo); 827 } 828 CanonParams.push_back(Param); 829 } else 830 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 831 cast<TemplateTemplateParmDecl>(*P))); 832 } 833 834 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create( 835 *this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(), 836 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false, 837 TemplateParameterList::Create(*this, SourceLocation(), SourceLocation(), 838 CanonParams, SourceLocation(), 839 /*RequiresClause=*/nullptr)); 840 841 // Get the new insert position for the node we care about. 842 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 843 assert(!Canonical && "Shouldn't be in the map!"); 844 (void)Canonical; 845 846 // Create the canonical template template parameter entry. 847 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 848 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 849 return CanonTTP; 850 } 851 852 /// Check if a type can have its sanitizer instrumentation elided based on its 853 /// presence within an ignorelist. 854 bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask, 855 const QualType &Ty) const { 856 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy()); 857 return NoSanitizeL->containsType(Mask, TyName) && 858 !NoSanitizeL->containsType(Mask, TyName, "sanitize"); 859 } 860 861 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 862 auto Kind = getTargetInfo().getCXXABI().getKind(); 863 return getLangOpts().CXXABI.value_or(Kind); 864 } 865 866 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 867 if (!LangOpts.CPlusPlus) return nullptr; 868 869 switch (getCXXABIKind()) { 870 case TargetCXXABI::AppleARM64: 871 case TargetCXXABI::Fuchsia: 872 case TargetCXXABI::GenericARM: // Same as Itanium at this level 873 case TargetCXXABI::iOS: 874 case TargetCXXABI::WatchOS: 875 case TargetCXXABI::GenericAArch64: 876 case TargetCXXABI::GenericMIPS: 877 case TargetCXXABI::GenericItanium: 878 case TargetCXXABI::WebAssembly: 879 case TargetCXXABI::XL: 880 return CreateItaniumCXXABI(*this); 881 case TargetCXXABI::Microsoft: 882 return CreateMicrosoftCXXABI(*this); 883 } 884 llvm_unreachable("Invalid CXXABI type!"); 885 } 886 887 interp::Context &ASTContext::getInterpContext() { 888 if (!InterpContext) { 889 InterpContext.reset(new interp::Context(*this)); 890 } 891 return *InterpContext.get(); 892 } 893 894 ParentMapContext &ASTContext::getParentMapContext() { 895 if (!ParentMapCtx) 896 ParentMapCtx.reset(new ParentMapContext(*this)); 897 return *ParentMapCtx.get(); 898 } 899 900 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 901 const LangOptions &LangOpts) { 902 switch (LangOpts.getAddressSpaceMapMangling()) { 903 case LangOptions::ASMM_Target: 904 return TI.useAddressSpaceMapMangling(); 905 case LangOptions::ASMM_On: 906 return true; 907 case LangOptions::ASMM_Off: 908 return false; 909 } 910 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 911 } 912 913 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 914 IdentifierTable &idents, SelectorTable &sels, 915 Builtin::Context &builtins, TranslationUnitKind TUKind) 916 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 917 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()), 918 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()), 919 DependentSizedMatrixTypes(this_()), 920 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 921 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()), 922 TemplateSpecializationTypes(this_()), 923 DependentTemplateSpecializationTypes(this_()), 924 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()), 925 DeducedTemplates(this_()), ArrayParameterTypes(this_()), 926 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 927 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 928 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 929 LangOpts.XRayNeverInstrumentFiles, 930 LangOpts.XRayAttrListFiles, SM)), 931 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 932 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 933 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 934 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 935 CompCategories(this_()), LastSDM(nullptr, 0) { 936 addTranslationUnitDecl(); 937 } 938 939 void ASTContext::cleanup() { 940 // Release the DenseMaps associated with DeclContext objects. 941 // FIXME: Is this the ideal solution? 942 ReleaseDeclContextMaps(); 943 944 // Call all of the deallocation functions on all of their targets. 945 for (auto &Pair : Deallocations) 946 (Pair.first)(Pair.second); 947 Deallocations.clear(); 948 949 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 950 // because they can contain DenseMaps. 951 for (llvm::DenseMap<const ObjCContainerDecl*, 952 const ASTRecordLayout*>::iterator 953 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 954 // Increment in loop to prevent using deallocated memory. 955 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 956 R->Destroy(*this); 957 ObjCLayouts.clear(); 958 959 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 960 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 961 // Increment in loop to prevent using deallocated memory. 962 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 963 R->Destroy(*this); 964 } 965 ASTRecordLayouts.clear(); 966 967 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 968 AEnd = DeclAttrs.end(); 969 A != AEnd; ++A) 970 A->second->~AttrVec(); 971 DeclAttrs.clear(); 972 973 for (const auto &Value : ModuleInitializers) 974 Value.second->~PerModuleInitializers(); 975 ModuleInitializers.clear(); 976 } 977 978 ASTContext::~ASTContext() { cleanup(); } 979 980 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 981 TraversalScope = TopLevelDecls; 982 getParentMapContext().clear(); 983 } 984 985 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 986 Deallocations.push_back({Callback, Data}); 987 } 988 989 void 990 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 991 ExternalSource = std::move(Source); 992 } 993 994 void ASTContext::PrintStats() const { 995 llvm::errs() << "\n*** AST Context Stats:\n"; 996 llvm::errs() << " " << Types.size() << " types total.\n"; 997 998 unsigned counts[] = { 999 #define TYPE(Name, Parent) 0, 1000 #define ABSTRACT_TYPE(Name, Parent) 1001 #include "clang/AST/TypeNodes.inc" 1002 0 // Extra 1003 }; 1004 1005 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1006 Type *T = Types[i]; 1007 counts[(unsigned)T->getTypeClass()]++; 1008 } 1009 1010 unsigned Idx = 0; 1011 unsigned TotalBytes = 0; 1012 #define TYPE(Name, Parent) \ 1013 if (counts[Idx]) \ 1014 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1015 << " types, " << sizeof(Name##Type) << " each " \ 1016 << "(" << counts[Idx] * sizeof(Name##Type) \ 1017 << " bytes)\n"; \ 1018 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1019 ++Idx; 1020 #define ABSTRACT_TYPE(Name, Parent) 1021 #include "clang/AST/TypeNodes.inc" 1022 1023 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1024 1025 // Implicit special member functions. 1026 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1027 << NumImplicitDefaultConstructors 1028 << " implicit default constructors created\n"; 1029 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1030 << NumImplicitCopyConstructors 1031 << " implicit copy constructors created\n"; 1032 if (getLangOpts().CPlusPlus) 1033 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1034 << NumImplicitMoveConstructors 1035 << " implicit move constructors created\n"; 1036 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1037 << NumImplicitCopyAssignmentOperators 1038 << " implicit copy assignment operators created\n"; 1039 if (getLangOpts().CPlusPlus) 1040 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1041 << NumImplicitMoveAssignmentOperators 1042 << " implicit move assignment operators created\n"; 1043 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1044 << NumImplicitDestructors 1045 << " implicit destructors created\n"; 1046 1047 if (ExternalSource) { 1048 llvm::errs() << "\n"; 1049 ExternalSource->PrintStats(); 1050 } 1051 1052 BumpAlloc.PrintStats(); 1053 } 1054 1055 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1056 bool NotifyListeners) { 1057 if (NotifyListeners) 1058 if (auto *Listener = getASTMutationListener()) 1059 Listener->RedefinedHiddenDefinition(ND, M); 1060 1061 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1062 } 1063 1064 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1065 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1066 if (It == MergedDefModules.end()) 1067 return; 1068 1069 auto &Merged = It->second; 1070 llvm::DenseSet<Module*> Found; 1071 for (Module *&M : Merged) 1072 if (!Found.insert(M).second) 1073 M = nullptr; 1074 llvm::erase(Merged, nullptr); 1075 } 1076 1077 ArrayRef<Module *> 1078 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1079 auto MergedIt = 1080 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1081 if (MergedIt == MergedDefModules.end()) 1082 return {}; 1083 return MergedIt->second; 1084 } 1085 1086 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1087 if (LazyInitializers.empty()) 1088 return; 1089 1090 auto *Source = Ctx.getExternalSource(); 1091 assert(Source && "lazy initializers but no external source"); 1092 1093 auto LazyInits = std::move(LazyInitializers); 1094 LazyInitializers.clear(); 1095 1096 for (auto ID : LazyInits) 1097 Initializers.push_back(Source->GetExternalDecl(ID)); 1098 1099 assert(LazyInitializers.empty() && 1100 "GetExternalDecl for lazy module initializer added more inits"); 1101 } 1102 1103 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1104 // One special case: if we add a module initializer that imports another 1105 // module, and that module's only initializer is an ImportDecl, simplify. 1106 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1107 auto It = ModuleInitializers.find(ID->getImportedModule()); 1108 1109 // Maybe the ImportDecl does nothing at all. (Common case.) 1110 if (It == ModuleInitializers.end()) 1111 return; 1112 1113 // Maybe the ImportDecl only imports another ImportDecl. 1114 auto &Imported = *It->second; 1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1116 Imported.resolve(*this); 1117 auto *OnlyDecl = Imported.Initializers.front(); 1118 if (isa<ImportDecl>(OnlyDecl)) 1119 D = OnlyDecl; 1120 } 1121 } 1122 1123 auto *&Inits = ModuleInitializers[M]; 1124 if (!Inits) 1125 Inits = new (*this) PerModuleInitializers; 1126 Inits->Initializers.push_back(D); 1127 } 1128 1129 void ASTContext::addLazyModuleInitializers(Module *M, 1130 ArrayRef<GlobalDeclID> IDs) { 1131 auto *&Inits = ModuleInitializers[M]; 1132 if (!Inits) 1133 Inits = new (*this) PerModuleInitializers; 1134 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1135 IDs.begin(), IDs.end()); 1136 } 1137 1138 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1139 auto It = ModuleInitializers.find(M); 1140 if (It == ModuleInitializers.end()) 1141 return {}; 1142 1143 auto *Inits = It->second; 1144 Inits->resolve(*this); 1145 return Inits->Initializers; 1146 } 1147 1148 void ASTContext::setCurrentNamedModule(Module *M) { 1149 assert(M->isNamedModule()); 1150 assert(!CurrentCXXNamedModule && 1151 "We should set named module for ASTContext for only once"); 1152 CurrentCXXNamedModule = M; 1153 } 1154 1155 bool ASTContext::isInSameModule(const Module *M1, const Module *M2) { 1156 if (!M1 != !M2) 1157 return false; 1158 1159 /// Get the representative module for M. The representative module is the 1160 /// first module unit for a specific primary module name. So that the module 1161 /// units have the same representative module belongs to the same module. 1162 /// 1163 /// The process is helpful to reduce the expensive string operations. 1164 auto GetRepresentativeModule = [this](const Module *M) { 1165 auto Iter = SameModuleLookupSet.find(M); 1166 if (Iter != SameModuleLookupSet.end()) 1167 return Iter->second; 1168 1169 const Module *RepresentativeModule = 1170 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M) 1171 .first->second; 1172 SameModuleLookupSet[M] = RepresentativeModule; 1173 return RepresentativeModule; 1174 }; 1175 1176 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none."); 1177 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2); 1178 } 1179 1180 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1181 if (!ExternCContext) 1182 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1183 1184 return ExternCContext; 1185 } 1186 1187 BuiltinTemplateDecl * 1188 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1189 const IdentifierInfo *II) const { 1190 auto *BuiltinTemplate = 1191 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1192 BuiltinTemplate->setImplicit(); 1193 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1194 1195 return BuiltinTemplate; 1196 } 1197 1198 BuiltinTemplateDecl * 1199 ASTContext::getMakeIntegerSeqDecl() const { 1200 if (!MakeIntegerSeqDecl) 1201 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1202 getMakeIntegerSeqName()); 1203 return MakeIntegerSeqDecl; 1204 } 1205 1206 BuiltinTemplateDecl * 1207 ASTContext::getTypePackElementDecl() const { 1208 if (!TypePackElementDecl) 1209 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1210 getTypePackElementName()); 1211 return TypePackElementDecl; 1212 } 1213 1214 BuiltinTemplateDecl *ASTContext::getBuiltinCommonTypeDecl() const { 1215 if (!BuiltinCommonTypeDecl) 1216 BuiltinCommonTypeDecl = buildBuiltinTemplateDecl( 1217 BTK__builtin_common_type, getBuiltinCommonTypeName()); 1218 return BuiltinCommonTypeDecl; 1219 } 1220 1221 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1222 RecordDecl::TagKind TK) const { 1223 SourceLocation Loc; 1224 RecordDecl *NewDecl; 1225 if (getLangOpts().CPlusPlus) 1226 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1227 Loc, &Idents.get(Name)); 1228 else 1229 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1230 &Idents.get(Name)); 1231 NewDecl->setImplicit(); 1232 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1233 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1234 return NewDecl; 1235 } 1236 1237 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1238 StringRef Name) const { 1239 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1240 TypedefDecl *NewDecl = TypedefDecl::Create( 1241 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1242 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1243 NewDecl->setImplicit(); 1244 return NewDecl; 1245 } 1246 1247 TypedefDecl *ASTContext::getInt128Decl() const { 1248 if (!Int128Decl) 1249 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1250 return Int128Decl; 1251 } 1252 1253 TypedefDecl *ASTContext::getUInt128Decl() const { 1254 if (!UInt128Decl) 1255 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1256 return UInt128Decl; 1257 } 1258 1259 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1260 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K); 1261 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1262 Types.push_back(Ty); 1263 } 1264 1265 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1266 const TargetInfo *AuxTarget) { 1267 assert((!this->Target || this->Target == &Target) && 1268 "Incorrect target reinitialization"); 1269 assert(VoidTy.isNull() && "Context reinitialized?"); 1270 1271 this->Target = &Target; 1272 this->AuxTarget = AuxTarget; 1273 1274 ABI.reset(createCXXABI(Target)); 1275 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1276 1277 // C99 6.2.5p19. 1278 InitBuiltinType(VoidTy, BuiltinType::Void); 1279 1280 // C99 6.2.5p2. 1281 InitBuiltinType(BoolTy, BuiltinType::Bool); 1282 // C99 6.2.5p3. 1283 if (LangOpts.CharIsSigned) 1284 InitBuiltinType(CharTy, BuiltinType::Char_S); 1285 else 1286 InitBuiltinType(CharTy, BuiltinType::Char_U); 1287 // C99 6.2.5p4. 1288 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1289 InitBuiltinType(ShortTy, BuiltinType::Short); 1290 InitBuiltinType(IntTy, BuiltinType::Int); 1291 InitBuiltinType(LongTy, BuiltinType::Long); 1292 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1293 1294 // C99 6.2.5p6. 1295 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1296 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1297 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1298 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1299 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1300 1301 // C99 6.2.5p10. 1302 InitBuiltinType(FloatTy, BuiltinType::Float); 1303 InitBuiltinType(DoubleTy, BuiltinType::Double); 1304 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1305 1306 // GNU extension, __float128 for IEEE quadruple precision 1307 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1308 1309 // __ibm128 for IBM extended precision 1310 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1311 1312 // C11 extension ISO/IEC TS 18661-3 1313 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1314 1315 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1316 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1317 InitBuiltinType(AccumTy, BuiltinType::Accum); 1318 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1319 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1320 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1321 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1322 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1323 InitBuiltinType(FractTy, BuiltinType::Fract); 1324 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1325 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1326 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1327 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1328 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1329 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1330 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1331 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1332 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1333 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1334 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1335 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1336 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1337 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1338 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1339 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1340 1341 // GNU extension, 128-bit integers. 1342 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1343 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1344 1345 // C++ 3.9.1p5 1346 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1347 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1348 else // -fshort-wchar makes wchar_t be unsigned. 1349 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1350 if (LangOpts.CPlusPlus && LangOpts.WChar) 1351 WideCharTy = WCharTy; 1352 else { 1353 // C99 (or C++ using -fno-wchar). 1354 WideCharTy = getFromTargetType(Target.getWCharType()); 1355 } 1356 1357 WIntTy = getFromTargetType(Target.getWIntType()); 1358 1359 // C++20 (proposed) 1360 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1361 1362 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1363 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1364 else // C99 1365 Char16Ty = getFromTargetType(Target.getChar16Type()); 1366 1367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1368 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1369 else // C99 1370 Char32Ty = getFromTargetType(Target.getChar32Type()); 1371 1372 // Placeholder type for type-dependent expressions whose type is 1373 // completely unknown. No code should ever check a type against 1374 // DependentTy and users should never see it; however, it is here to 1375 // help diagnose failures to properly check for type-dependent 1376 // expressions. 1377 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1378 1379 // Placeholder type for functions. 1380 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1381 1382 // Placeholder type for bound members. 1383 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1384 1385 // Placeholder type for unresolved templates. 1386 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate); 1387 1388 // Placeholder type for pseudo-objects. 1389 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1390 1391 // "any" type; useful for debugger-like clients. 1392 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1393 1394 // Placeholder type for unbridged ARC casts. 1395 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1396 1397 // Placeholder type for builtin functions. 1398 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1399 1400 // Placeholder type for OMP array sections. 1401 if (LangOpts.OpenMP) { 1402 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection); 1403 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1404 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1405 } 1406 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode, 1407 // don't bother, as we're just using the same type as OMP. 1408 if (LangOpts.OpenACC && !LangOpts.OpenMP) { 1409 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection); 1410 } 1411 if (LangOpts.MatrixTypes) 1412 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1413 1414 // Builtin types for 'id', 'Class', and 'SEL'. 1415 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1416 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1417 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1418 1419 if (LangOpts.OpenCL) { 1420 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1421 InitBuiltinType(SingletonId, BuiltinType::Id); 1422 #include "clang/Basic/OpenCLImageTypes.def" 1423 1424 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1425 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1426 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1427 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1428 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1429 1430 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1431 InitBuiltinType(Id##Ty, BuiltinType::Id); 1432 #include "clang/Basic/OpenCLExtensionTypes.def" 1433 } 1434 1435 if (LangOpts.HLSL) { 1436 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ 1437 InitBuiltinType(SingletonId, BuiltinType::Id); 1438 #include "clang/Basic/HLSLIntangibleTypes.def" 1439 } 1440 1441 if (Target.hasAArch64SVETypes() || 1442 (AuxTarget && AuxTarget->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 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) { 1464 #define WASM_TYPE(Name, Id, SingletonId) \ 1465 InitBuiltinType(SingletonId, BuiltinType::Id); 1466 #include "clang/Basic/WebAssemblyReferenceTypes.def" 1467 } 1468 1469 if (Target.getTriple().isAMDGPU() || 1470 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) { 1471 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \ 1472 InitBuiltinType(SingletonId, BuiltinType::Id); 1473 #include "clang/Basic/AMDGPUTypes.def" 1474 } 1475 1476 // Builtin type for __objc_yes and __objc_no 1477 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1478 SignedCharTy : BoolTy); 1479 1480 ObjCConstantStringType = QualType(); 1481 1482 ObjCSuperType = QualType(); 1483 1484 // void * type 1485 if (LangOpts.OpenCLGenericAddressSpace) { 1486 auto Q = VoidTy.getQualifiers(); 1487 Q.setAddressSpace(LangAS::opencl_generic); 1488 VoidPtrTy = getPointerType(getCanonicalType( 1489 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1490 } else { 1491 VoidPtrTy = getPointerType(VoidTy); 1492 } 1493 1494 // nullptr type (C++0x 2.14.7) 1495 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1496 1497 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1498 InitBuiltinType(HalfTy, BuiltinType::Half); 1499 1500 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1501 1502 // Builtin type used to help define __builtin_va_list. 1503 VaListTagDecl = nullptr; 1504 1505 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1506 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1507 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1508 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1509 } 1510 } 1511 1512 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1513 return SourceMgr.getDiagnostics(); 1514 } 1515 1516 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1517 AttrVec *&Result = DeclAttrs[D]; 1518 if (!Result) { 1519 void *Mem = Allocate(sizeof(AttrVec)); 1520 Result = new (Mem) AttrVec; 1521 } 1522 1523 return *Result; 1524 } 1525 1526 /// Erase the attributes corresponding to the given declaration. 1527 void ASTContext::eraseDeclAttrs(const Decl *D) { 1528 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1529 if (Pos != DeclAttrs.end()) { 1530 Pos->second->~AttrVec(); 1531 DeclAttrs.erase(Pos); 1532 } 1533 } 1534 1535 // FIXME: Remove ? 1536 MemberSpecializationInfo * 1537 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1538 assert(Var->isStaticDataMember() && "Not a static data member"); 1539 return getTemplateOrSpecializationInfo(Var) 1540 .dyn_cast<MemberSpecializationInfo *>(); 1541 } 1542 1543 ASTContext::TemplateOrSpecializationInfo 1544 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1545 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1546 TemplateOrInstantiation.find(Var); 1547 if (Pos == TemplateOrInstantiation.end()) 1548 return {}; 1549 1550 return Pos->second; 1551 } 1552 1553 void 1554 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1555 TemplateSpecializationKind TSK, 1556 SourceLocation PointOfInstantiation) { 1557 assert(Inst->isStaticDataMember() && "Not a static data member"); 1558 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1559 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1560 Tmpl, TSK, PointOfInstantiation)); 1561 } 1562 1563 void 1564 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1565 TemplateOrSpecializationInfo TSI) { 1566 assert(!TemplateOrInstantiation[Inst] && 1567 "Already noted what the variable was instantiated from"); 1568 TemplateOrInstantiation[Inst] = TSI; 1569 } 1570 1571 NamedDecl * 1572 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1573 return InstantiatedFromUsingDecl.lookup(UUD); 1574 } 1575 1576 void 1577 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1578 assert((isa<UsingDecl>(Pattern) || 1579 isa<UnresolvedUsingValueDecl>(Pattern) || 1580 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1581 "pattern decl is not a using decl"); 1582 assert((isa<UsingDecl>(Inst) || 1583 isa<UnresolvedUsingValueDecl>(Inst) || 1584 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1585 "instantiation did not produce a using decl"); 1586 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1587 InstantiatedFromUsingDecl[Inst] = Pattern; 1588 } 1589 1590 UsingEnumDecl * 1591 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1592 return InstantiatedFromUsingEnumDecl.lookup(UUD); 1593 } 1594 1595 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1596 UsingEnumDecl *Pattern) { 1597 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1598 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1599 } 1600 1601 UsingShadowDecl * 1602 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1603 return InstantiatedFromUsingShadowDecl.lookup(Inst); 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 * 1614 ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const { 1615 return InstantiatedFromUnnamedFieldDecl.lookup(Field); 1616 } 1617 1618 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1619 FieldDecl *Tmpl) { 1620 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && 1621 "Instantiated field decl is not unnamed"); 1622 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) && 1623 "Template field decl is not unnamed"); 1624 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1625 "Already noted what unnamed field was instantiated from"); 1626 1627 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1628 } 1629 1630 ASTContext::overridden_cxx_method_iterator 1631 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1632 return overridden_methods(Method).begin(); 1633 } 1634 1635 ASTContext::overridden_cxx_method_iterator 1636 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1637 return overridden_methods(Method).end(); 1638 } 1639 1640 unsigned 1641 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1642 auto Range = overridden_methods(Method); 1643 return Range.end() - Range.begin(); 1644 } 1645 1646 ASTContext::overridden_method_range 1647 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1648 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1649 OverriddenMethods.find(Method->getCanonicalDecl()); 1650 if (Pos == OverriddenMethods.end()) 1651 return overridden_method_range(nullptr, nullptr); 1652 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1653 } 1654 1655 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1656 const CXXMethodDecl *Overridden) { 1657 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1658 OverriddenMethods[Method].push_back(Overridden); 1659 } 1660 1661 void ASTContext::getOverriddenMethods( 1662 const NamedDecl *D, 1663 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1664 assert(D); 1665 1666 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1667 Overridden.append(overridden_methods_begin(CXXMethod), 1668 overridden_methods_end(CXXMethod)); 1669 return; 1670 } 1671 1672 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1673 if (!Method) 1674 return; 1675 1676 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1677 Method->getOverriddenMethods(OverDecls); 1678 Overridden.append(OverDecls.begin(), OverDecls.end()); 1679 } 1680 1681 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1682 assert(!Import->getNextLocalImport() && 1683 "Import declaration already in the chain"); 1684 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1685 if (!FirstLocalImport) { 1686 FirstLocalImport = Import; 1687 LastLocalImport = Import; 1688 return; 1689 } 1690 1691 LastLocalImport->setNextLocalImport(Import); 1692 LastLocalImport = Import; 1693 } 1694 1695 //===----------------------------------------------------------------------===// 1696 // Type Sizing and Analysis 1697 //===----------------------------------------------------------------------===// 1698 1699 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1700 /// scalar floating point type. 1701 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1702 switch (T->castAs<BuiltinType>()->getKind()) { 1703 default: 1704 llvm_unreachable("Not a floating point type!"); 1705 case BuiltinType::BFloat16: 1706 return Target->getBFloat16Format(); 1707 case BuiltinType::Float16: 1708 return Target->getHalfFormat(); 1709 case BuiltinType::Half: 1710 return Target->getHalfFormat(); 1711 case BuiltinType::Float: return Target->getFloatFormat(); 1712 case BuiltinType::Double: return Target->getDoubleFormat(); 1713 case BuiltinType::Ibm128: 1714 return Target->getIbm128Format(); 1715 case BuiltinType::LongDouble: 1716 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice) 1717 return AuxTarget->getLongDoubleFormat(); 1718 return Target->getLongDoubleFormat(); 1719 case BuiltinType::Float128: 1720 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice) 1721 return AuxTarget->getFloat128Format(); 1722 return Target->getFloat128Format(); 1723 } 1724 } 1725 1726 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1727 unsigned Align = Target->getCharWidth(); 1728 1729 const unsigned AlignFromAttr = D->getMaxAlignment(); 1730 if (AlignFromAttr) 1731 Align = AlignFromAttr; 1732 1733 // __attribute__((aligned)) can increase or decrease alignment 1734 // *except* on a struct or struct member, where it only increases 1735 // alignment unless 'packed' is also specified. 1736 // 1737 // It is an error for alignas to decrease alignment, so we can 1738 // ignore that possibility; Sema should diagnose it. 1739 bool UseAlignAttrOnly; 1740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) 1741 UseAlignAttrOnly = 1742 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>(); 1743 else 1744 UseAlignAttrOnly = AlignFromAttr != 0; 1745 // If we're using the align attribute only, just ignore everything 1746 // else about the declaration and its type. 1747 if (UseAlignAttrOnly) { 1748 // do nothing 1749 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1750 QualType T = VD->getType(); 1751 if (const auto *RT = T->getAs<ReferenceType>()) { 1752 if (ForAlignof) 1753 T = RT->getPointeeType(); 1754 else 1755 T = getPointerType(RT->getPointeeType()); 1756 } 1757 QualType BaseT = getBaseElementType(T); 1758 if (T->isFunctionType()) 1759 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1760 else if (!BaseT->isIncompleteType()) { 1761 // Adjust alignments of declarations with array type by the 1762 // large-array alignment on the target. 1763 if (const ArrayType *arrayType = getAsArrayType(T)) { 1764 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1765 if (!ForAlignof && MinWidth) { 1766 if (isa<VariableArrayType>(arrayType)) 1767 Align = std::max(Align, Target->getLargeArrayAlign()); 1768 else if (isa<ConstantArrayType>(arrayType) && 1769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1770 Align = std::max(Align, Target->getLargeArrayAlign()); 1771 } 1772 } 1773 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1774 if (BaseT.getQualifiers().hasUnaligned()) 1775 Align = Target->getCharWidth(); 1776 } 1777 1778 // Ensure miminum alignment for global variables. 1779 if (const auto *VD = dyn_cast<VarDecl>(D)) 1780 if (VD->hasGlobalStorage() && !ForAlignof) { 1781 uint64_t TypeSize = 1782 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0; 1783 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD)); 1784 } 1785 1786 // Fields can be subject to extra alignment constraints, like if 1787 // the field is packed, the struct is packed, or the struct has a 1788 // a max-field-alignment constraint (#pragma pack). So calculate 1789 // the actual alignment of the field within the struct, and then 1790 // (as we're expected to) constrain that by the alignment of the type. 1791 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1792 const RecordDecl *Parent = Field->getParent(); 1793 // We can only produce a sensible answer if the record is valid. 1794 if (!Parent->isInvalidDecl()) { 1795 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1796 1797 // Start with the record's overall alignment. 1798 unsigned FieldAlign = toBits(Layout.getAlignment()); 1799 1800 // Use the GCD of that and the offset within the record. 1801 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1802 if (Offset > 0) { 1803 // Alignment is always a power of 2, so the GCD will be a power of 2, 1804 // which means we get to do this crazy thing instead of Euclid's. 1805 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1806 if (LowBitOfOffset < FieldAlign) 1807 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1808 } 1809 1810 Align = std::min(Align, FieldAlign); 1811 } 1812 } 1813 } 1814 1815 // Some targets have hard limitation on the maximum requestable alignment in 1816 // aligned attribute for static variables. 1817 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1818 const auto *VD = dyn_cast<VarDecl>(D); 1819 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1820 Align = std::min(Align, MaxAlignedAttr); 1821 1822 return toCharUnitsFromBits(Align); 1823 } 1824 1825 CharUnits ASTContext::getExnObjectAlignment() const { 1826 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1827 } 1828 1829 // getTypeInfoDataSizeInChars - Return the size of a type, in 1830 // chars. If the type is a record, its data size is returned. This is 1831 // the size of the memcpy that's performed when assigning this type 1832 // using a trivial copy/move assignment operator. 1833 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1834 TypeInfoChars Info = getTypeInfoInChars(T); 1835 1836 // In C++, objects can sometimes be allocated into the tail padding 1837 // of a base-class subobject. We decide whether that's possible 1838 // during class layout, so here we can just trust the layout results. 1839 if (getLangOpts().CPlusPlus) { 1840 if (const auto *RT = T->getAs<RecordType>(); 1841 RT && !RT->getDecl()->isInvalidDecl()) { 1842 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1843 Info.Width = layout.getDataSize(); 1844 } 1845 } 1846 1847 return Info; 1848 } 1849 1850 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1851 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1852 TypeInfoChars 1853 static getConstantArrayInfoInChars(const ASTContext &Context, 1854 const ConstantArrayType *CAT) { 1855 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1856 uint64_t Size = CAT->getZExtSize(); 1857 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1858 (uint64_t)(-1)/Size) && 1859 "Overflow in array type char size evaluation"); 1860 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1861 unsigned Align = EltInfo.Align.getQuantity(); 1862 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1863 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64) 1864 Width = llvm::alignTo(Width, Align); 1865 return TypeInfoChars(CharUnits::fromQuantity(Width), 1866 CharUnits::fromQuantity(Align), 1867 EltInfo.AlignRequirement); 1868 } 1869 1870 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1871 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1872 return getConstantArrayInfoInChars(*this, CAT); 1873 TypeInfo Info = getTypeInfo(T); 1874 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1875 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1876 } 1877 1878 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1879 return getTypeInfoInChars(T.getTypePtr()); 1880 } 1881 1882 bool ASTContext::isPromotableIntegerType(QualType T) const { 1883 // HLSL doesn't promote all small integer types to int, it 1884 // just uses the rank-based promotion rules for all types. 1885 if (getLangOpts().HLSL) 1886 return false; 1887 1888 if (const auto *BT = T->getAs<BuiltinType>()) 1889 switch (BT->getKind()) { 1890 case BuiltinType::Bool: 1891 case BuiltinType::Char_S: 1892 case BuiltinType::Char_U: 1893 case BuiltinType::SChar: 1894 case BuiltinType::UChar: 1895 case BuiltinType::Short: 1896 case BuiltinType::UShort: 1897 case BuiltinType::WChar_S: 1898 case BuiltinType::WChar_U: 1899 case BuiltinType::Char8: 1900 case BuiltinType::Char16: 1901 case BuiltinType::Char32: 1902 return true; 1903 default: 1904 return false; 1905 } 1906 1907 // Enumerated types are promotable to their compatible integer types 1908 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 1909 if (const auto *ET = T->getAs<EnumType>()) { 1910 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() || 1911 ET->getDecl()->isScoped()) 1912 return false; 1913 1914 return true; 1915 } 1916 1917 return false; 1918 } 1919 1920 bool ASTContext::isAlignmentRequired(const Type *T) const { 1921 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1922 } 1923 1924 bool ASTContext::isAlignmentRequired(QualType T) const { 1925 return isAlignmentRequired(T.getTypePtr()); 1926 } 1927 1928 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1929 bool NeedsPreferredAlignment) const { 1930 // An alignment on a typedef overrides anything else. 1931 if (const auto *TT = T->getAs<TypedefType>()) 1932 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1933 return Align; 1934 1935 // If we have an (array of) complete type, we're done. 1936 T = getBaseElementType(T); 1937 if (!T->isIncompleteType()) 1938 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1939 1940 // If we had an array type, its element type might be a typedef 1941 // type with an alignment attribute. 1942 if (const auto *TT = T->getAs<TypedefType>()) 1943 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1944 return Align; 1945 1946 // Otherwise, see if the declaration of the type had an attribute. 1947 if (const auto *TT = T->getAs<TagType>()) 1948 return TT->getDecl()->getMaxAlignment(); 1949 1950 return 0; 1951 } 1952 1953 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1954 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1955 if (I != MemoizedTypeInfo.end()) 1956 return I->second; 1957 1958 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1959 TypeInfo TI = getTypeInfoImpl(T); 1960 MemoizedTypeInfo[T] = TI; 1961 return TI; 1962 } 1963 1964 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1965 /// method does not work on incomplete types. 1966 /// 1967 /// FIXME: Pointers into different addr spaces could have different sizes and 1968 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1969 /// should take a QualType, &c. 1970 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1971 uint64_t Width = 0; 1972 unsigned Align = 8; 1973 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1974 LangAS AS = LangAS::Default; 1975 switch (T->getTypeClass()) { 1976 #define TYPE(Class, Base) 1977 #define ABSTRACT_TYPE(Class, Base) 1978 #define NON_CANONICAL_TYPE(Class, Base) 1979 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1980 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1981 case Type::Class: \ 1982 assert(!T->isDependentType() && "should not see dependent types here"); \ 1983 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1984 #include "clang/AST/TypeNodes.inc" 1985 llvm_unreachable("Should not see dependent types"); 1986 1987 case Type::FunctionNoProto: 1988 case Type::FunctionProto: 1989 // GCC extension: alignof(function) = 32 bits 1990 Width = 0; 1991 Align = 32; 1992 break; 1993 1994 case Type::IncompleteArray: 1995 case Type::VariableArray: 1996 case Type::ConstantArray: 1997 case Type::ArrayParameter: { 1998 // Model non-constant sized arrays as size zero, but track the alignment. 1999 uint64_t Size = 0; 2000 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 2001 Size = CAT->getZExtSize(); 2002 2003 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 2004 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 2005 "Overflow in array type bit size evaluation"); 2006 Width = EltInfo.Width * Size; 2007 Align = EltInfo.Align; 2008 AlignRequirement = EltInfo.AlignRequirement; 2009 if (!getTargetInfo().getCXXABI().isMicrosoft() || 2010 getTargetInfo().getPointerWidth(LangAS::Default) == 64) 2011 Width = llvm::alignTo(Width, Align); 2012 break; 2013 } 2014 2015 case Type::ExtVector: 2016 case Type::Vector: { 2017 const auto *VT = cast<VectorType>(T); 2018 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 2019 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 2020 : EltInfo.Width * VT->getNumElements(); 2021 // Enforce at least byte size and alignment. 2022 Width = std::max<unsigned>(8, Width); 2023 Align = std::max<unsigned>(8, Width); 2024 2025 // If the alignment is not a power of 2, round up to the next power of 2. 2026 // This happens for non-power-of-2 length vectors. 2027 if (Align & (Align-1)) { 2028 Align = llvm::bit_ceil(Align); 2029 Width = llvm::alignTo(Width, Align); 2030 } 2031 // Adjust the alignment based on the target max. 2032 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 2033 if (TargetVectorAlign && TargetVectorAlign < Align) 2034 Align = TargetVectorAlign; 2035 if (VT->getVectorKind() == VectorKind::SveFixedLengthData) 2036 // Adjust the alignment for fixed-length SVE vectors. This is important 2037 // for non-power-of-2 vector lengths. 2038 Align = 128; 2039 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) 2040 // Adjust the alignment for fixed-length SVE predicates. 2041 Align = 16; 2042 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData || 2043 VT->getVectorKind() == VectorKind::RVVFixedLengthMask || 2044 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 || 2045 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 || 2046 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) 2047 // Adjust the alignment for fixed-length RVV vectors. 2048 Align = std::min<unsigned>(64, Width); 2049 break; 2050 } 2051 2052 case Type::ConstantMatrix: { 2053 const auto *MT = cast<ConstantMatrixType>(T); 2054 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2055 // The internal layout of a matrix value is implementation defined. 2056 // Initially be ABI compatible with arrays with respect to alignment and 2057 // size. 2058 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2059 Align = ElementInfo.Align; 2060 break; 2061 } 2062 2063 case Type::Builtin: 2064 switch (cast<BuiltinType>(T)->getKind()) { 2065 default: llvm_unreachable("Unknown builtin type!"); 2066 case BuiltinType::Void: 2067 // GCC extension: alignof(void) = 8 bits. 2068 Width = 0; 2069 Align = 8; 2070 break; 2071 case BuiltinType::Bool: 2072 Width = Target->getBoolWidth(); 2073 Align = Target->getBoolAlign(); 2074 break; 2075 case BuiltinType::Char_S: 2076 case BuiltinType::Char_U: 2077 case BuiltinType::UChar: 2078 case BuiltinType::SChar: 2079 case BuiltinType::Char8: 2080 Width = Target->getCharWidth(); 2081 Align = Target->getCharAlign(); 2082 break; 2083 case BuiltinType::WChar_S: 2084 case BuiltinType::WChar_U: 2085 Width = Target->getWCharWidth(); 2086 Align = Target->getWCharAlign(); 2087 break; 2088 case BuiltinType::Char16: 2089 Width = Target->getChar16Width(); 2090 Align = Target->getChar16Align(); 2091 break; 2092 case BuiltinType::Char32: 2093 Width = Target->getChar32Width(); 2094 Align = Target->getChar32Align(); 2095 break; 2096 case BuiltinType::UShort: 2097 case BuiltinType::Short: 2098 Width = Target->getShortWidth(); 2099 Align = Target->getShortAlign(); 2100 break; 2101 case BuiltinType::UInt: 2102 case BuiltinType::Int: 2103 Width = Target->getIntWidth(); 2104 Align = Target->getIntAlign(); 2105 break; 2106 case BuiltinType::ULong: 2107 case BuiltinType::Long: 2108 Width = Target->getLongWidth(); 2109 Align = Target->getLongAlign(); 2110 break; 2111 case BuiltinType::ULongLong: 2112 case BuiltinType::LongLong: 2113 Width = Target->getLongLongWidth(); 2114 Align = Target->getLongLongAlign(); 2115 break; 2116 case BuiltinType::Int128: 2117 case BuiltinType::UInt128: 2118 Width = 128; 2119 Align = Target->getInt128Align(); 2120 break; 2121 case BuiltinType::ShortAccum: 2122 case BuiltinType::UShortAccum: 2123 case BuiltinType::SatShortAccum: 2124 case BuiltinType::SatUShortAccum: 2125 Width = Target->getShortAccumWidth(); 2126 Align = Target->getShortAccumAlign(); 2127 break; 2128 case BuiltinType::Accum: 2129 case BuiltinType::UAccum: 2130 case BuiltinType::SatAccum: 2131 case BuiltinType::SatUAccum: 2132 Width = Target->getAccumWidth(); 2133 Align = Target->getAccumAlign(); 2134 break; 2135 case BuiltinType::LongAccum: 2136 case BuiltinType::ULongAccum: 2137 case BuiltinType::SatLongAccum: 2138 case BuiltinType::SatULongAccum: 2139 Width = Target->getLongAccumWidth(); 2140 Align = Target->getLongAccumAlign(); 2141 break; 2142 case BuiltinType::ShortFract: 2143 case BuiltinType::UShortFract: 2144 case BuiltinType::SatShortFract: 2145 case BuiltinType::SatUShortFract: 2146 Width = Target->getShortFractWidth(); 2147 Align = Target->getShortFractAlign(); 2148 break; 2149 case BuiltinType::Fract: 2150 case BuiltinType::UFract: 2151 case BuiltinType::SatFract: 2152 case BuiltinType::SatUFract: 2153 Width = Target->getFractWidth(); 2154 Align = Target->getFractAlign(); 2155 break; 2156 case BuiltinType::LongFract: 2157 case BuiltinType::ULongFract: 2158 case BuiltinType::SatLongFract: 2159 case BuiltinType::SatULongFract: 2160 Width = Target->getLongFractWidth(); 2161 Align = Target->getLongFractAlign(); 2162 break; 2163 case BuiltinType::BFloat16: 2164 if (Target->hasBFloat16Type()) { 2165 Width = Target->getBFloat16Width(); 2166 Align = Target->getBFloat16Align(); 2167 } else if ((getLangOpts().SYCLIsDevice || 2168 (getLangOpts().OpenMP && 2169 getLangOpts().OpenMPIsTargetDevice)) && 2170 AuxTarget->hasBFloat16Type()) { 2171 Width = AuxTarget->getBFloat16Width(); 2172 Align = AuxTarget->getBFloat16Align(); 2173 } 2174 break; 2175 case BuiltinType::Float16: 2176 case BuiltinType::Half: 2177 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2178 !getLangOpts().OpenMPIsTargetDevice) { 2179 Width = Target->getHalfWidth(); 2180 Align = Target->getHalfAlign(); 2181 } else { 2182 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && 2183 "Expected OpenMP device compilation."); 2184 Width = AuxTarget->getHalfWidth(); 2185 Align = AuxTarget->getHalfAlign(); 2186 } 2187 break; 2188 case BuiltinType::Float: 2189 Width = Target->getFloatWidth(); 2190 Align = Target->getFloatAlign(); 2191 break; 2192 case BuiltinType::Double: 2193 Width = Target->getDoubleWidth(); 2194 Align = Target->getDoubleAlign(); 2195 break; 2196 case BuiltinType::Ibm128: 2197 Width = Target->getIbm128Width(); 2198 Align = Target->getIbm128Align(); 2199 break; 2200 case BuiltinType::LongDouble: 2201 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && 2202 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2203 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2204 Width = AuxTarget->getLongDoubleWidth(); 2205 Align = AuxTarget->getLongDoubleAlign(); 2206 } else { 2207 Width = Target->getLongDoubleWidth(); 2208 Align = Target->getLongDoubleAlign(); 2209 } 2210 break; 2211 case BuiltinType::Float128: 2212 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2213 !getLangOpts().OpenMPIsTargetDevice) { 2214 Width = Target->getFloat128Width(); 2215 Align = Target->getFloat128Align(); 2216 } else { 2217 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && 2218 "Expected OpenMP device compilation."); 2219 Width = AuxTarget->getFloat128Width(); 2220 Align = AuxTarget->getFloat128Align(); 2221 } 2222 break; 2223 case BuiltinType::NullPtr: 2224 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*) 2225 Width = Target->getPointerWidth(LangAS::Default); 2226 Align = Target->getPointerAlign(LangAS::Default); 2227 break; 2228 case BuiltinType::ObjCId: 2229 case BuiltinType::ObjCClass: 2230 case BuiltinType::ObjCSel: 2231 Width = Target->getPointerWidth(LangAS::Default); 2232 Align = Target->getPointerAlign(LangAS::Default); 2233 break; 2234 case BuiltinType::OCLSampler: 2235 case BuiltinType::OCLEvent: 2236 case BuiltinType::OCLClkEvent: 2237 case BuiltinType::OCLQueue: 2238 case BuiltinType::OCLReserveID: 2239 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2240 case BuiltinType::Id: 2241 #include "clang/Basic/OpenCLImageTypes.def" 2242 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2243 case BuiltinType::Id: 2244 #include "clang/Basic/OpenCLExtensionTypes.def" 2245 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 2246 Width = Target->getPointerWidth(AS); 2247 Align = Target->getPointerAlign(AS); 2248 break; 2249 // The SVE types are effectively target-specific. The length of an 2250 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2251 // of 128 bits. There is one predicate bit for each vector byte, so the 2252 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2253 // 2254 // Because the length is only known at runtime, we use a dummy value 2255 // of 0 for the static length. The alignment values are those defined 2256 // by the Procedure Call Standard for the Arm Architecture. 2257 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \ 2258 case BuiltinType::Id: \ 2259 Width = 0; \ 2260 Align = 128; \ 2261 break; 2262 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \ 2263 case BuiltinType::Id: \ 2264 Width = 0; \ 2265 Align = 16; \ 2266 break; 2267 #define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \ 2268 case BuiltinType::Id: \ 2269 Width = 0; \ 2270 Align = 16; \ 2271 break; 2272 #define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \ 2273 case BuiltinType::Id: \ 2274 Width = Bits; \ 2275 Align = Bits; \ 2276 break; 2277 #include "clang/Basic/AArch64SVEACLETypes.def" 2278 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2279 case BuiltinType::Id: \ 2280 Width = Size; \ 2281 Align = Size; \ 2282 break; 2283 #include "clang/Basic/PPCTypes.def" 2284 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2285 IsFP, IsBF) \ 2286 case BuiltinType::Id: \ 2287 Width = 0; \ 2288 Align = ElBits; \ 2289 break; 2290 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2291 case BuiltinType::Id: \ 2292 Width = 0; \ 2293 Align = 8; \ 2294 break; 2295 #include "clang/Basic/RISCVVTypes.def" 2296 #define WASM_TYPE(Name, Id, SingletonId) \ 2297 case BuiltinType::Id: \ 2298 Width = 0; \ 2299 Align = 8; \ 2300 break; 2301 #include "clang/Basic/WebAssemblyReferenceTypes.def" 2302 #define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \ 2303 case BuiltinType::ID: \ 2304 Width = WIDTH; \ 2305 Align = ALIGN; \ 2306 break; 2307 #include "clang/Basic/AMDGPUTypes.def" 2308 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 2309 #include "clang/Basic/HLSLIntangibleTypes.def" 2310 Width = Target->getPointerWidth(LangAS::Default); 2311 Align = Target->getPointerAlign(LangAS::Default); 2312 break; 2313 } 2314 break; 2315 case Type::ObjCObjectPointer: 2316 Width = Target->getPointerWidth(LangAS::Default); 2317 Align = Target->getPointerAlign(LangAS::Default); 2318 break; 2319 case Type::BlockPointer: 2320 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 2321 Width = Target->getPointerWidth(AS); 2322 Align = Target->getPointerAlign(AS); 2323 break; 2324 case Type::LValueReference: 2325 case Type::RValueReference: 2326 // alignof and sizeof should never enter this code path here, so we go 2327 // the pointer route. 2328 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace(); 2329 Width = Target->getPointerWidth(AS); 2330 Align = Target->getPointerAlign(AS); 2331 break; 2332 case Type::Pointer: 2333 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 2334 Width = Target->getPointerWidth(AS); 2335 Align = Target->getPointerAlign(AS); 2336 break; 2337 case Type::MemberPointer: { 2338 const auto *MPT = cast<MemberPointerType>(T); 2339 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2340 Width = MPI.Width; 2341 Align = MPI.Align; 2342 break; 2343 } 2344 case Type::Complex: { 2345 // Complex types have the same alignment as their elements, but twice the 2346 // size. 2347 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2348 Width = EltInfo.Width * 2; 2349 Align = EltInfo.Align; 2350 break; 2351 } 2352 case Type::ObjCObject: 2353 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2354 case Type::Adjusted: 2355 case Type::Decayed: 2356 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2357 case Type::ObjCInterface: { 2358 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2359 if (ObjCI->getDecl()->isInvalidDecl()) { 2360 Width = 8; 2361 Align = 8; 2362 break; 2363 } 2364 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2365 Width = toBits(Layout.getSize()); 2366 Align = toBits(Layout.getAlignment()); 2367 break; 2368 } 2369 case Type::BitInt: { 2370 const auto *EIT = cast<BitIntType>(T); 2371 Align = Target->getBitIntAlign(EIT->getNumBits()); 2372 Width = Target->getBitIntWidth(EIT->getNumBits()); 2373 break; 2374 } 2375 case Type::Record: 2376 case Type::Enum: { 2377 const auto *TT = cast<TagType>(T); 2378 2379 if (TT->getDecl()->isInvalidDecl()) { 2380 Width = 8; 2381 Align = 8; 2382 break; 2383 } 2384 2385 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2386 const EnumDecl *ED = ET->getDecl(); 2387 TypeInfo Info = 2388 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2389 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2390 Info.Align = AttrAlign; 2391 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2392 } 2393 return Info; 2394 } 2395 2396 const auto *RT = cast<RecordType>(TT); 2397 const RecordDecl *RD = RT->getDecl(); 2398 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2399 Width = toBits(Layout.getSize()); 2400 Align = toBits(Layout.getAlignment()); 2401 AlignRequirement = RD->hasAttr<AlignedAttr>() 2402 ? AlignRequirementKind::RequiredByRecord 2403 : AlignRequirementKind::None; 2404 break; 2405 } 2406 2407 case Type::SubstTemplateTypeParm: 2408 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2409 getReplacementType().getTypePtr()); 2410 2411 case Type::Auto: 2412 case Type::DeducedTemplateSpecialization: { 2413 const auto *A = cast<DeducedType>(T); 2414 assert(!A->getDeducedType().isNull() && 2415 "cannot request the size of an undeduced or dependent auto type"); 2416 return getTypeInfo(A->getDeducedType().getTypePtr()); 2417 } 2418 2419 case Type::Paren: 2420 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2421 2422 case Type::MacroQualified: 2423 return getTypeInfo( 2424 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2425 2426 case Type::ObjCTypeParam: 2427 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2428 2429 case Type::Using: 2430 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2431 2432 case Type::Typedef: { 2433 const auto *TT = cast<TypedefType>(T); 2434 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr()); 2435 // If the typedef has an aligned attribute on it, it overrides any computed 2436 // alignment we have. This violates the GCC documentation (which says that 2437 // attribute(aligned) can only round up) but matches its implementation. 2438 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) { 2439 Align = AttrAlign; 2440 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2441 } else { 2442 Align = Info.Align; 2443 AlignRequirement = Info.AlignRequirement; 2444 } 2445 Width = Info.Width; 2446 break; 2447 } 2448 2449 case Type::Elaborated: 2450 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2451 2452 case Type::Attributed: 2453 return getTypeInfo( 2454 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2455 2456 case Type::CountAttributed: 2457 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr()); 2458 2459 case Type::BTFTagAttributed: 2460 return getTypeInfo( 2461 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr()); 2462 2463 case Type::HLSLAttributedResource: 2464 return getTypeInfo( 2465 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr()); 2466 2467 case Type::Atomic: { 2468 // Start with the base type information. 2469 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2470 Width = Info.Width; 2471 Align = Info.Align; 2472 2473 if (!Width) { 2474 // An otherwise zero-sized type should still generate an 2475 // atomic operation. 2476 Width = Target->getCharWidth(); 2477 assert(Align); 2478 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2479 // If the size of the type doesn't exceed the platform's max 2480 // atomic promotion width, make the size and alignment more 2481 // favorable to atomic operations: 2482 2483 // Round the size up to a power of 2. 2484 Width = llvm::bit_ceil(Width); 2485 2486 // Set the alignment equal to the size. 2487 Align = static_cast<unsigned>(Width); 2488 } 2489 } 2490 break; 2491 2492 case Type::Pipe: 2493 Width = Target->getPointerWidth(LangAS::opencl_global); 2494 Align = Target->getPointerAlign(LangAS::opencl_global); 2495 break; 2496 } 2497 2498 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2499 return TypeInfo(Width, Align, AlignRequirement); 2500 } 2501 2502 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2503 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2504 if (I != MemoizedUnadjustedAlign.end()) 2505 return I->second; 2506 2507 unsigned UnadjustedAlign; 2508 if (const auto *RT = T->getAs<RecordType>()) { 2509 const RecordDecl *RD = RT->getDecl(); 2510 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2511 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2512 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2513 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2514 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2515 } else { 2516 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2517 } 2518 2519 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2520 return UnadjustedAlign; 2521 } 2522 2523 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2524 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign( 2525 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap); 2526 return SimdAlign; 2527 } 2528 2529 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2530 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2531 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2532 } 2533 2534 /// toBits - Convert a size in characters to a size in characters. 2535 int64_t ASTContext::toBits(CharUnits CharSize) const { 2536 return CharSize.getQuantity() * getCharWidth(); 2537 } 2538 2539 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2540 /// This method does not work on incomplete types. 2541 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2542 return getTypeInfoInChars(T).Width; 2543 } 2544 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2545 return getTypeInfoInChars(T).Width; 2546 } 2547 2548 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2549 /// characters. This method does not work on incomplete types. 2550 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2551 return toCharUnitsFromBits(getTypeAlign(T)); 2552 } 2553 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2554 return toCharUnitsFromBits(getTypeAlign(T)); 2555 } 2556 2557 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2558 /// type, in characters, before alignment adjustments. This method does 2559 /// not work on incomplete types. 2560 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2561 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2562 } 2563 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2564 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2565 } 2566 2567 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2568 /// type for the current target in bits. This can be different than the ABI 2569 /// alignment in cases where it is beneficial for performance or backwards 2570 /// compatibility preserving to overalign a data type. (Note: despite the name, 2571 /// the preferred alignment is ABI-impacting, and not an optimization.) 2572 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2573 TypeInfo TI = getTypeInfo(T); 2574 unsigned ABIAlign = TI.Align; 2575 2576 T = T->getBaseElementTypeUnsafe(); 2577 2578 // The preferred alignment of member pointers is that of a pointer. 2579 if (T->isMemberPointerType()) 2580 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2581 2582 if (!Target->allowsLargerPreferedTypeAlignment()) 2583 return ABIAlign; 2584 2585 if (const auto *RT = T->getAs<RecordType>()) { 2586 const RecordDecl *RD = RT->getDecl(); 2587 2588 // When used as part of a typedef, or together with a 'packed' attribute, 2589 // the 'aligned' attribute can be used to decrease alignment. Note that the 2590 // 'packed' case is already taken into consideration when computing the 2591 // alignment, we only need to handle the typedef case here. 2592 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2593 RD->isInvalidDecl()) 2594 return ABIAlign; 2595 2596 unsigned PreferredAlign = static_cast<unsigned>( 2597 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2598 assert(PreferredAlign >= ABIAlign && 2599 "PreferredAlign should be at least as large as ABIAlign."); 2600 return PreferredAlign; 2601 } 2602 2603 // Double (and, for targets supporting AIX `power` alignment, long double) and 2604 // long long should be naturally aligned (despite requiring less alignment) if 2605 // possible. 2606 if (const auto *CT = T->getAs<ComplexType>()) 2607 T = CT->getElementType().getTypePtr(); 2608 if (const auto *ET = T->getAs<EnumType>()) 2609 T = ET->getDecl()->getIntegerType().getTypePtr(); 2610 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2611 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2612 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2613 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2614 Target->defaultsToAIXPowerAlignment())) 2615 // Don't increase the alignment if an alignment attribute was specified on a 2616 // typedef declaration. 2617 if (!TI.isAlignRequired()) 2618 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2619 2620 return ABIAlign; 2621 } 2622 2623 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2624 /// for __attribute__((aligned)) on this target, to be used if no alignment 2625 /// value is specified. 2626 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2627 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2628 } 2629 2630 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2631 /// to a global variable of the specified type. 2632 unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const { 2633 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2634 return std::max(getPreferredTypeAlign(T), 2635 getMinGlobalAlignOfVar(TypeSize, VD)); 2636 } 2637 2638 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2639 /// should be given to a global variable of the specified type. 2640 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T, 2641 const VarDecl *VD) const { 2642 return toCharUnitsFromBits(getAlignOfGlobalVar(T, VD)); 2643 } 2644 2645 unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size, 2646 const VarDecl *VD) const { 2647 // Make the default handling as that of a non-weak definition in the 2648 // current translation unit. 2649 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak()); 2650 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef); 2651 } 2652 2653 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2654 CharUnits Offset = CharUnits::Zero(); 2655 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2656 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2657 Offset += Layout->getBaseClassOffset(Base); 2658 Layout = &getASTRecordLayout(Base); 2659 } 2660 return Offset; 2661 } 2662 2663 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2664 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2665 CharUnits ThisAdjustment = CharUnits::Zero(); 2666 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2667 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2668 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2669 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2670 const CXXRecordDecl *Base = RD; 2671 const CXXRecordDecl *Derived = Path[I]; 2672 if (DerivedMember) 2673 std::swap(Base, Derived); 2674 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2675 RD = Path[I]; 2676 } 2677 if (DerivedMember) 2678 ThisAdjustment = -ThisAdjustment; 2679 return ThisAdjustment; 2680 } 2681 2682 /// DeepCollectObjCIvars - 2683 /// This routine first collects all declared, but not synthesized, ivars in 2684 /// super class and then collects all ivars, including those synthesized for 2685 /// current class. This routine is used for implementation of current class 2686 /// when all ivars, declared and synthesized are known. 2687 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2688 bool leafClass, 2689 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2690 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2691 DeepCollectObjCIvars(SuperClass, false, Ivars); 2692 if (!leafClass) { 2693 llvm::append_range(Ivars, OI->ivars()); 2694 } else { 2695 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2696 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2697 Iv= Iv->getNextIvar()) 2698 Ivars.push_back(Iv); 2699 } 2700 } 2701 2702 /// CollectInheritedProtocols - Collect all protocols in current class and 2703 /// those inherited by it. 2704 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2705 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2706 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2707 // We can use protocol_iterator here instead of 2708 // all_referenced_protocol_iterator since we are walking all categories. 2709 for (auto *Proto : OI->all_referenced_protocols()) { 2710 CollectInheritedProtocols(Proto, Protocols); 2711 } 2712 2713 // Categories of this Interface. 2714 for (const auto *Cat : OI->visible_categories()) 2715 CollectInheritedProtocols(Cat, Protocols); 2716 2717 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2718 while (SD) { 2719 CollectInheritedProtocols(SD, Protocols); 2720 SD = SD->getSuperClass(); 2721 } 2722 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2723 for (auto *Proto : OC->protocols()) { 2724 CollectInheritedProtocols(Proto, Protocols); 2725 } 2726 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2727 // Insert the protocol. 2728 if (!Protocols.insert( 2729 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2730 return; 2731 2732 for (auto *Proto : OP->protocols()) 2733 CollectInheritedProtocols(Proto, Protocols); 2734 } 2735 } 2736 2737 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2738 const RecordDecl *RD, 2739 bool CheckIfTriviallyCopyable) { 2740 assert(RD->isUnion() && "Must be union type"); 2741 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2742 2743 for (const auto *Field : RD->fields()) { 2744 if (!Context.hasUniqueObjectRepresentations(Field->getType(), 2745 CheckIfTriviallyCopyable)) 2746 return false; 2747 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2748 if (FieldSize != UnionSize) 2749 return false; 2750 } 2751 return !RD->field_empty(); 2752 } 2753 2754 static int64_t getSubobjectOffset(const FieldDecl *Field, 2755 const ASTContext &Context, 2756 const clang::ASTRecordLayout & /*Layout*/) { 2757 return Context.getFieldOffset(Field); 2758 } 2759 2760 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2761 const ASTContext &Context, 2762 const clang::ASTRecordLayout &Layout) { 2763 return Context.toBits(Layout.getBaseClassOffset(RD)); 2764 } 2765 2766 static std::optional<int64_t> 2767 structHasUniqueObjectRepresentations(const ASTContext &Context, 2768 const RecordDecl *RD, 2769 bool CheckIfTriviallyCopyable); 2770 2771 static std::optional<int64_t> 2772 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, 2773 bool CheckIfTriviallyCopyable) { 2774 if (Field->getType()->isRecordType()) { 2775 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2776 if (!RD->isUnion()) 2777 return structHasUniqueObjectRepresentations(Context, RD, 2778 CheckIfTriviallyCopyable); 2779 } 2780 2781 // A _BitInt type may not be unique if it has padding bits 2782 // but if it is a bitfield the padding bits are not used. 2783 bool IsBitIntType = Field->getType()->isBitIntType(); 2784 if (!Field->getType()->isReferenceType() && !IsBitIntType && 2785 !Context.hasUniqueObjectRepresentations(Field->getType(), 2786 CheckIfTriviallyCopyable)) 2787 return std::nullopt; 2788 2789 int64_t FieldSizeInBits = 2790 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2791 if (Field->isBitField()) { 2792 // If we have explicit padding bits, they don't contribute bits 2793 // to the actual object representation, so return 0. 2794 if (Field->isUnnamedBitField()) 2795 return 0; 2796 2797 int64_t BitfieldSize = Field->getBitWidthValue(); 2798 if (IsBitIntType) { 2799 if ((unsigned)BitfieldSize > 2800 cast<BitIntType>(Field->getType())->getNumBits()) 2801 return std::nullopt; 2802 } else if (BitfieldSize > FieldSizeInBits) { 2803 return std::nullopt; 2804 } 2805 FieldSizeInBits = BitfieldSize; 2806 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations( 2807 Field->getType(), CheckIfTriviallyCopyable)) { 2808 return std::nullopt; 2809 } 2810 return FieldSizeInBits; 2811 } 2812 2813 static std::optional<int64_t> 2814 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context, 2815 bool CheckIfTriviallyCopyable) { 2816 return structHasUniqueObjectRepresentations(Context, RD, 2817 CheckIfTriviallyCopyable); 2818 } 2819 2820 template <typename RangeT> 2821 static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2822 const RangeT &Subobjects, int64_t CurOffsetInBits, 2823 const ASTContext &Context, const clang::ASTRecordLayout &Layout, 2824 bool CheckIfTriviallyCopyable) { 2825 for (const auto *Subobject : Subobjects) { 2826 std::optional<int64_t> SizeInBits = 2827 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable); 2828 if (!SizeInBits) 2829 return std::nullopt; 2830 if (*SizeInBits != 0) { 2831 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2832 if (Offset != CurOffsetInBits) 2833 return std::nullopt; 2834 CurOffsetInBits += *SizeInBits; 2835 } 2836 } 2837 return CurOffsetInBits; 2838 } 2839 2840 static std::optional<int64_t> 2841 structHasUniqueObjectRepresentations(const ASTContext &Context, 2842 const RecordDecl *RD, 2843 bool CheckIfTriviallyCopyable) { 2844 assert(!RD->isUnion() && "Must be struct/class type"); 2845 const auto &Layout = Context.getASTRecordLayout(RD); 2846 2847 int64_t CurOffsetInBits = 0; 2848 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2849 if (ClassDecl->isDynamicClass()) 2850 return std::nullopt; 2851 2852 SmallVector<CXXRecordDecl *, 4> Bases; 2853 for (const auto &Base : ClassDecl->bases()) { 2854 // Empty types can be inherited from, and non-empty types can potentially 2855 // have tail padding, so just make sure there isn't an error. 2856 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2857 } 2858 2859 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2860 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2861 }); 2862 2863 std::optional<int64_t> OffsetAfterBases = 2864 structSubobjectsHaveUniqueObjectRepresentations( 2865 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable); 2866 if (!OffsetAfterBases) 2867 return std::nullopt; 2868 CurOffsetInBits = *OffsetAfterBases; 2869 } 2870 2871 std::optional<int64_t> OffsetAfterFields = 2872 structSubobjectsHaveUniqueObjectRepresentations( 2873 RD->fields(), CurOffsetInBits, Context, Layout, 2874 CheckIfTriviallyCopyable); 2875 if (!OffsetAfterFields) 2876 return std::nullopt; 2877 CurOffsetInBits = *OffsetAfterFields; 2878 2879 return CurOffsetInBits; 2880 } 2881 2882 bool ASTContext::hasUniqueObjectRepresentations( 2883 QualType Ty, bool CheckIfTriviallyCopyable) const { 2884 // C++17 [meta.unary.prop]: 2885 // The predicate condition for a template specialization 2886 // has_unique_object_representations<T> shall be satisfied if and only if: 2887 // (9.1) - T is trivially copyable, and 2888 // (9.2) - any two objects of type T with the same value have the same 2889 // object representation, where: 2890 // - two objects of array or non-union class type are considered to have 2891 // the same value if their respective sequences of direct subobjects 2892 // have the same values, and 2893 // - two objects of union type are considered to have the same value if 2894 // they have the same active member and the corresponding members have 2895 // the same value. 2896 // The set of scalar types for which this condition holds is 2897 // implementation-defined. [ Note: If a type has padding bits, the condition 2898 // does not hold; otherwise, the condition holds true for unsigned integral 2899 // types. -- end note ] 2900 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2901 2902 // Arrays are unique only if their element type is unique. 2903 if (Ty->isArrayType()) 2904 return hasUniqueObjectRepresentations(getBaseElementType(Ty), 2905 CheckIfTriviallyCopyable); 2906 2907 assert((Ty->isVoidType() || !Ty->isIncompleteType()) && 2908 "hasUniqueObjectRepresentations should not be called with an " 2909 "incomplete type"); 2910 2911 // (9.1) - T is trivially copyable... 2912 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this)) 2913 return false; 2914 2915 // All integrals and enums are unique. 2916 if (Ty->isIntegralOrEnumerationType()) { 2917 // Except _BitInt types that have padding bits. 2918 if (const auto *BIT = Ty->getAs<BitIntType>()) 2919 return getTypeSize(BIT) == BIT->getNumBits(); 2920 2921 return true; 2922 } 2923 2924 // All other pointers are unique. 2925 if (Ty->isPointerType()) 2926 return true; 2927 2928 if (const auto *MPT = Ty->getAs<MemberPointerType>()) 2929 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2930 2931 if (Ty->isRecordType()) { 2932 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2933 2934 if (Record->isInvalidDecl()) 2935 return false; 2936 2937 if (Record->isUnion()) 2938 return unionHasUniqueObjectRepresentations(*this, Record, 2939 CheckIfTriviallyCopyable); 2940 2941 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations( 2942 *this, Record, CheckIfTriviallyCopyable); 2943 2944 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty)); 2945 } 2946 2947 // FIXME: More cases to handle here (list by rsmith): 2948 // vectors (careful about, eg, vector of 3 foo) 2949 // _Complex int and friends 2950 // _Atomic T 2951 // Obj-C block pointers 2952 // Obj-C object pointers 2953 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2954 // clk_event_t, queue_t, reserve_id_t) 2955 // There're also Obj-C class types and the Obj-C selector type, but I think it 2956 // makes sense for those to return false here. 2957 2958 return false; 2959 } 2960 2961 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2962 unsigned count = 0; 2963 // Count ivars declared in class extension. 2964 for (const auto *Ext : OI->known_extensions()) 2965 count += Ext->ivar_size(); 2966 2967 // Count ivar defined in this class's implementation. This 2968 // includes synthesized ivars. 2969 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2970 count += ImplDecl->ivar_size(); 2971 2972 return count; 2973 } 2974 2975 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2976 if (!E) 2977 return false; 2978 2979 // nullptr_t is always treated as null. 2980 if (E->getType()->isNullPtrType()) return true; 2981 2982 if (E->getType()->isAnyPointerType() && 2983 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2984 Expr::NPC_ValueDependentIsNull)) 2985 return true; 2986 2987 // Unfortunately, __null has type 'int'. 2988 if (isa<GNUNullExpr>(E)) return true; 2989 2990 return false; 2991 } 2992 2993 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2994 /// exists. 2995 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2996 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2997 I = ObjCImpls.find(D); 2998 if (I != ObjCImpls.end()) 2999 return cast<ObjCImplementationDecl>(I->second); 3000 return nullptr; 3001 } 3002 3003 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 3004 /// exists. 3005 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 3006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 3007 I = ObjCImpls.find(D); 3008 if (I != ObjCImpls.end()) 3009 return cast<ObjCCategoryImplDecl>(I->second); 3010 return nullptr; 3011 } 3012 3013 /// Set the implementation of ObjCInterfaceDecl. 3014 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 3015 ObjCImplementationDecl *ImplD) { 3016 assert(IFaceD && ImplD && "Passed null params"); 3017 ObjCImpls[IFaceD] = ImplD; 3018 } 3019 3020 /// Set the implementation of ObjCCategoryDecl. 3021 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 3022 ObjCCategoryImplDecl *ImplD) { 3023 assert(CatD && ImplD && "Passed null params"); 3024 ObjCImpls[CatD] = ImplD; 3025 } 3026 3027 const ObjCMethodDecl * 3028 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 3029 return ObjCMethodRedecls.lookup(MD); 3030 } 3031 3032 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 3033 const ObjCMethodDecl *Redecl) { 3034 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 3035 ObjCMethodRedecls[MD] = Redecl; 3036 } 3037 3038 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 3039 const NamedDecl *ND) const { 3040 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 3041 return ID; 3042 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 3043 return CD->getClassInterface(); 3044 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 3045 return IMD->getClassInterface(); 3046 3047 return nullptr; 3048 } 3049 3050 /// Get the copy initialization expression of VarDecl, or nullptr if 3051 /// none exists. 3052 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 3053 assert(VD && "Passed null params"); 3054 assert(VD->hasAttr<BlocksAttr>() && 3055 "getBlockVarCopyInits - not __block var"); 3056 auto I = BlockVarCopyInits.find(VD); 3057 if (I != BlockVarCopyInits.end()) 3058 return I->second; 3059 return {nullptr, false}; 3060 } 3061 3062 /// Set the copy initialization expression of a block var decl. 3063 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 3064 bool CanThrow) { 3065 assert(VD && CopyExpr && "Passed null params"); 3066 assert(VD->hasAttr<BlocksAttr>() && 3067 "setBlockVarCopyInits - not __block var"); 3068 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 3069 } 3070 3071 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 3072 unsigned DataSize) const { 3073 if (!DataSize) 3074 DataSize = TypeLoc::getFullDataSizeForType(T); 3075 else 3076 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 3077 "incorrect data size provided to CreateTypeSourceInfo!"); 3078 3079 auto *TInfo = 3080 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 3081 new (TInfo) TypeSourceInfo(T, DataSize); 3082 return TInfo; 3083 } 3084 3085 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 3086 SourceLocation L) const { 3087 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 3088 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 3089 return DI; 3090 } 3091 3092 const ASTRecordLayout & 3093 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 3094 return getObjCLayout(D, nullptr); 3095 } 3096 3097 const ASTRecordLayout & 3098 ASTContext::getASTObjCImplementationLayout( 3099 const ObjCImplementationDecl *D) const { 3100 return getObjCLayout(D->getClassInterface(), D); 3101 } 3102 3103 static auto getCanonicalTemplateArguments(const ASTContext &C, 3104 ArrayRef<TemplateArgument> Args, 3105 bool &AnyNonCanonArgs) { 3106 SmallVector<TemplateArgument, 16> CanonArgs(Args); 3107 for (auto &Arg : CanonArgs) { 3108 TemplateArgument OrigArg = Arg; 3109 Arg = C.getCanonicalTemplateArgument(Arg); 3110 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg); 3111 } 3112 return CanonArgs; 3113 } 3114 3115 //===----------------------------------------------------------------------===// 3116 // Type creation/memoization methods 3117 //===----------------------------------------------------------------------===// 3118 3119 QualType 3120 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 3121 unsigned fastQuals = quals.getFastQualifiers(); 3122 quals.removeFastQualifiers(); 3123 3124 // Check if we've already instantiated this type. 3125 llvm::FoldingSetNodeID ID; 3126 ExtQuals::Profile(ID, baseType, quals); 3127 void *insertPos = nullptr; 3128 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 3129 assert(eq->getQualifiers() == quals); 3130 return QualType(eq, fastQuals); 3131 } 3132 3133 // If the base type is not canonical, make the appropriate canonical type. 3134 QualType canon; 3135 if (!baseType->isCanonicalUnqualified()) { 3136 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 3137 canonSplit.Quals.addConsistentQualifiers(quals); 3138 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 3139 3140 // Re-find the insert position. 3141 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3142 } 3143 3144 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals); 3145 ExtQualNodes.InsertNode(eq, insertPos); 3146 return QualType(eq, fastQuals); 3147 } 3148 3149 QualType ASTContext::getAddrSpaceQualType(QualType T, 3150 LangAS AddressSpace) const { 3151 QualType CanT = getCanonicalType(T); 3152 if (CanT.getAddressSpace() == AddressSpace) 3153 return T; 3154 3155 // If we are composing extended qualifiers together, merge together 3156 // into one ExtQuals node. 3157 QualifierCollector Quals; 3158 const Type *TypeNode = Quals.strip(T); 3159 3160 // If this type already has an address space specified, it cannot get 3161 // another one. 3162 assert(!Quals.hasAddressSpace() && 3163 "Type cannot be in multiple addr spaces!"); 3164 Quals.addAddressSpace(AddressSpace); 3165 3166 return getExtQualType(TypeNode, Quals); 3167 } 3168 3169 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3170 // If the type is not qualified with an address space, just return it 3171 // immediately. 3172 if (!T.hasAddressSpace()) 3173 return T; 3174 3175 QualifierCollector Quals; 3176 const Type *TypeNode; 3177 // For arrays, strip the qualifier off the element type, then reconstruct the 3178 // array type 3179 if (T.getTypePtr()->isArrayType()) { 3180 T = getUnqualifiedArrayType(T, Quals); 3181 TypeNode = T.getTypePtr(); 3182 } else { 3183 // If we are composing extended qualifiers together, merge together 3184 // into one ExtQuals node. 3185 while (T.hasAddressSpace()) { 3186 TypeNode = Quals.strip(T); 3187 3188 // If the type no longer has an address space after stripping qualifiers, 3189 // jump out. 3190 if (!QualType(TypeNode, 0).hasAddressSpace()) 3191 break; 3192 3193 // There might be sugar in the way. Strip it and try again. 3194 T = T.getSingleStepDesugaredType(*this); 3195 } 3196 } 3197 3198 Quals.removeAddressSpace(); 3199 3200 // Removal of the address space can mean there are no longer any 3201 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3202 // or required. 3203 if (Quals.hasNonFastQualifiers()) 3204 return getExtQualType(TypeNode, Quals); 3205 else 3206 return QualType(TypeNode, Quals.getFastQualifiers()); 3207 } 3208 3209 uint16_t 3210 ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD) { 3211 assert(RD->isPolymorphic() && 3212 "Attempted to get vtable pointer discriminator on a monomorphic type"); 3213 std::unique_ptr<MangleContext> MC(createMangleContext()); 3214 SmallString<256> Str; 3215 llvm::raw_svector_ostream Out(Str); 3216 MC->mangleCXXVTable(RD, Out); 3217 return llvm::getPointerAuthStableSipHash(Str); 3218 } 3219 3220 /// Encode a function type for use in the discriminator of a function pointer 3221 /// type. We can't use the itanium scheme for this since C has quite permissive 3222 /// rules for type compatibility that we need to be compatible with. 3223 /// 3224 /// Formally, this function associates every function pointer type T with an 3225 /// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as 3226 /// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type 3227 /// compatibility requires equivalent treatment under the ABI, so 3228 /// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be 3229 /// a subset of ~. Crucially, however, it must be a proper subset because 3230 /// CCompatible is not an equivalence relation: for example, int[] is compatible 3231 /// with both int[1] and int[2], but the latter are not compatible with each 3232 /// other. Therefore this encoding function must be careful to only distinguish 3233 /// types if there is no third type with which they are both required to be 3234 /// compatible. 3235 static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, 3236 raw_ostream &OS, QualType QT) { 3237 // FIXME: Consider address space qualifiers. 3238 const Type *T = QT.getCanonicalType().getTypePtr(); 3239 3240 // FIXME: Consider using the C++ type mangling when we encounter a construct 3241 // that is incompatible with C. 3242 3243 switch (T->getTypeClass()) { 3244 case Type::Atomic: 3245 return encodeTypeForFunctionPointerAuth( 3246 Ctx, OS, cast<AtomicType>(T)->getValueType()); 3247 3248 case Type::LValueReference: 3249 OS << "R"; 3250 encodeTypeForFunctionPointerAuth(Ctx, OS, 3251 cast<ReferenceType>(T)->getPointeeType()); 3252 return; 3253 case Type::RValueReference: 3254 OS << "O"; 3255 encodeTypeForFunctionPointerAuth(Ctx, OS, 3256 cast<ReferenceType>(T)->getPointeeType()); 3257 return; 3258 3259 case Type::Pointer: 3260 // C11 6.7.6.1p2: 3261 // For two pointer types to be compatible, both shall be identically 3262 // qualified and both shall be pointers to compatible types. 3263 // FIXME: we should also consider pointee types. 3264 OS << "P"; 3265 return; 3266 3267 case Type::ObjCObjectPointer: 3268 case Type::BlockPointer: 3269 OS << "P"; 3270 return; 3271 3272 case Type::Complex: 3273 OS << "C"; 3274 return encodeTypeForFunctionPointerAuth( 3275 Ctx, OS, cast<ComplexType>(T)->getElementType()); 3276 3277 case Type::VariableArray: 3278 case Type::ConstantArray: 3279 case Type::IncompleteArray: 3280 case Type::ArrayParameter: 3281 // C11 6.7.6.2p6: 3282 // For two array types to be compatible, both shall have compatible 3283 // element types, and if both size specifiers are present, and are integer 3284 // constant expressions, then both size specifiers shall have the same 3285 // constant value [...] 3286 // 3287 // So since ElemType[N] has to be compatible ElemType[], we can't encode the 3288 // width of the array. 3289 OS << "A"; 3290 return encodeTypeForFunctionPointerAuth( 3291 Ctx, OS, cast<ArrayType>(T)->getElementType()); 3292 3293 case Type::ObjCInterface: 3294 case Type::ObjCObject: 3295 OS << "<objc_object>"; 3296 return; 3297 3298 case Type::Enum: { 3299 // C11 6.7.2.2p4: 3300 // Each enumerated type shall be compatible with char, a signed integer 3301 // type, or an unsigned integer type. 3302 // 3303 // So we have to treat enum types as integers. 3304 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType(); 3305 return encodeTypeForFunctionPointerAuth( 3306 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType); 3307 } 3308 3309 case Type::FunctionNoProto: 3310 case Type::FunctionProto: { 3311 // C11 6.7.6.3p15: 3312 // For two function types to be compatible, both shall specify compatible 3313 // return types. Moreover, the parameter type lists, if both are present, 3314 // shall agree in the number of parameters and in the use of the ellipsis 3315 // terminator; corresponding parameters shall have compatible types. 3316 // 3317 // That paragraph goes on to describe how unprototyped functions are to be 3318 // handled, which we ignore here. Unprototyped function pointers are hashed 3319 // as though they were prototyped nullary functions since thats probably 3320 // what the user meant. This behavior is non-conforming. 3321 // FIXME: If we add a "custom discriminator" function type attribute we 3322 // should encode functions as their discriminators. 3323 OS << "F"; 3324 const auto *FuncType = cast<FunctionType>(T); 3325 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType()); 3326 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) { 3327 for (QualType Param : FPT->param_types()) { 3328 Param = Ctx.getSignatureParameterType(Param); 3329 encodeTypeForFunctionPointerAuth(Ctx, OS, Param); 3330 } 3331 if (FPT->isVariadic()) 3332 OS << "z"; 3333 } 3334 OS << "E"; 3335 return; 3336 } 3337 3338 case Type::MemberPointer: { 3339 OS << "M"; 3340 const auto *MPT = T->castAs<MemberPointerType>(); 3341 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0)); 3342 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType()); 3343 return; 3344 } 3345 case Type::ExtVector: 3346 case Type::Vector: 3347 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity(); 3348 break; 3349 3350 // Don't bother discriminating based on these types. 3351 case Type::Pipe: 3352 case Type::BitInt: 3353 case Type::ConstantMatrix: 3354 OS << "?"; 3355 return; 3356 3357 case Type::Builtin: { 3358 const auto *BTy = T->castAs<BuiltinType>(); 3359 switch (BTy->getKind()) { 3360 #define SIGNED_TYPE(Id, SingletonId) \ 3361 case BuiltinType::Id: \ 3362 OS << "i"; \ 3363 return; 3364 #define UNSIGNED_TYPE(Id, SingletonId) \ 3365 case BuiltinType::Id: \ 3366 OS << "i"; \ 3367 return; 3368 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 3369 #define BUILTIN_TYPE(Id, SingletonId) 3370 #include "clang/AST/BuiltinTypes.def" 3371 llvm_unreachable("placeholder types should not appear here."); 3372 3373 case BuiltinType::Half: 3374 OS << "Dh"; 3375 return; 3376 case BuiltinType::Float: 3377 OS << "f"; 3378 return; 3379 case BuiltinType::Double: 3380 OS << "d"; 3381 return; 3382 case BuiltinType::LongDouble: 3383 OS << "e"; 3384 return; 3385 case BuiltinType::Float16: 3386 OS << "DF16_"; 3387 return; 3388 case BuiltinType::Float128: 3389 OS << "g"; 3390 return; 3391 3392 case BuiltinType::Void: 3393 OS << "v"; 3394 return; 3395 3396 case BuiltinType::ObjCId: 3397 case BuiltinType::ObjCClass: 3398 case BuiltinType::ObjCSel: 3399 case BuiltinType::NullPtr: 3400 OS << "P"; 3401 return; 3402 3403 // Don't bother discriminating based on OpenCL types. 3404 case BuiltinType::OCLSampler: 3405 case BuiltinType::OCLEvent: 3406 case BuiltinType::OCLClkEvent: 3407 case BuiltinType::OCLQueue: 3408 case BuiltinType::OCLReserveID: 3409 case BuiltinType::BFloat16: 3410 case BuiltinType::VectorQuad: 3411 case BuiltinType::VectorPair: 3412 OS << "?"; 3413 return; 3414 3415 // Don't bother discriminating based on these seldom-used types. 3416 case BuiltinType::Ibm128: 3417 return; 3418 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3419 case BuiltinType::Id: \ 3420 return; 3421 #include "clang/Basic/OpenCLImageTypes.def" 3422 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3423 case BuiltinType::Id: \ 3424 return; 3425 #include "clang/Basic/OpenCLExtensionTypes.def" 3426 #define SVE_TYPE(Name, Id, SingletonId) \ 3427 case BuiltinType::Id: \ 3428 return; 3429 #include "clang/Basic/AArch64SVEACLETypes.def" 3430 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ 3431 case BuiltinType::Id: \ 3432 return; 3433 #include "clang/Basic/HLSLIntangibleTypes.def" 3434 case BuiltinType::Dependent: 3435 llvm_unreachable("should never get here"); 3436 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: 3437 #include "clang/Basic/AMDGPUTypes.def" 3438 case BuiltinType::WasmExternRef: 3439 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 3440 #include "clang/Basic/RISCVVTypes.def" 3441 llvm_unreachable("not yet implemented"); 3442 } 3443 llvm_unreachable("should never get here"); 3444 } 3445 case Type::Record: { 3446 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 3447 const IdentifierInfo *II = RD->getIdentifier(); 3448 3449 // In C++, an immediate typedef of an anonymous struct or union 3450 // is considered to name it for ODR purposes, but C's specification 3451 // of type compatibility does not have a similar rule. Using the typedef 3452 // name in function type discriminators anyway, as we do here, 3453 // therefore technically violates the C standard: two function pointer 3454 // types defined in terms of two typedef'd anonymous structs with 3455 // different names are formally still compatible, but we are assigning 3456 // them different discriminators and therefore incompatible ABIs. 3457 // 3458 // This is a relatively minor violation that significantly improves 3459 // discrimination in some cases and has not caused problems in 3460 // practice. Regardless, it is now part of the ABI in places where 3461 // function type discrimination is used, and it can no longer be 3462 // changed except on new platforms. 3463 3464 if (!II) 3465 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl()) 3466 II = Typedef->getDeclName().getAsIdentifierInfo(); 3467 3468 if (!II) { 3469 OS << "<anonymous_record>"; 3470 return; 3471 } 3472 OS << II->getLength() << II->getName(); 3473 return; 3474 } 3475 case Type::HLSLAttributedResource: 3476 llvm_unreachable("should never get here"); 3477 break; 3478 case Type::DeducedTemplateSpecialization: 3479 case Type::Auto: 3480 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3481 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3482 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 3483 #define ABSTRACT_TYPE(Class, Base) 3484 #define TYPE(Class, Base) 3485 #include "clang/AST/TypeNodes.inc" 3486 llvm_unreachable("unexpected non-canonical or dependent type!"); 3487 return; 3488 } 3489 } 3490 3491 uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) { 3492 assert(!T->isDependentType() && 3493 "cannot compute type discriminator of a dependent type"); 3494 3495 SmallString<256> Str; 3496 llvm::raw_svector_ostream Out(Str); 3497 3498 if (T->isFunctionPointerType() || T->isFunctionReferenceType()) 3499 T = T->getPointeeType(); 3500 3501 if (T->isFunctionType()) { 3502 encodeTypeForFunctionPointerAuth(*this, Out, T); 3503 } else { 3504 T = T.getUnqualifiedType(); 3505 // Calls to member function pointers don't need to worry about 3506 // language interop or the laxness of the C type compatibility rules. 3507 // We just mangle the member pointer type directly, which is 3508 // implicitly much stricter about type matching. However, we do 3509 // strip any top-level exception specification before this mangling. 3510 // C++23 requires calls to work when the function type is convertible 3511 // to the pointer type by a function pointer conversion, which can 3512 // change the exception specification. This does not technically 3513 // require the exception specification to not affect representation, 3514 // because the function pointer conversion is still always a direct 3515 // value conversion and therefore an opportunity to resign the 3516 // pointer. (This is in contrast to e.g. qualification conversions, 3517 // which can be applied in nested pointer positions, effectively 3518 // requiring qualified and unqualified representations to match.) 3519 // However, it is pragmatic to ignore exception specifications 3520 // because it allows a certain amount of `noexcept` mismatching 3521 // to not become a visible ODR problem. This also leaves some 3522 // room for the committee to add laxness to function pointer 3523 // conversions in future standards. 3524 if (auto *MPT = T->getAs<MemberPointerType>()) 3525 if (MPT->isMemberFunctionPointer()) { 3526 QualType PointeeType = MPT->getPointeeType(); 3527 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() != 3528 EST_None) { 3529 QualType FT = getFunctionTypeWithExceptionSpec(PointeeType, EST_None); 3530 T = getMemberPointerType(FT, MPT->getClass()); 3531 } 3532 } 3533 std::unique_ptr<MangleContext> MC(createMangleContext()); 3534 MC->mangleCanonicalTypeName(T, Out); 3535 } 3536 3537 return llvm::getPointerAuthStableSipHash(Str); 3538 } 3539 3540 QualType ASTContext::getObjCGCQualType(QualType T, 3541 Qualifiers::GC GCAttr) const { 3542 QualType CanT = getCanonicalType(T); 3543 if (CanT.getObjCGCAttr() == GCAttr) 3544 return T; 3545 3546 if (const auto *ptr = T->getAs<PointerType>()) { 3547 QualType Pointee = ptr->getPointeeType(); 3548 if (Pointee->isAnyPointerType()) { 3549 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3550 return getPointerType(ResultType); 3551 } 3552 } 3553 3554 // If we are composing extended qualifiers together, merge together 3555 // into one ExtQuals node. 3556 QualifierCollector Quals; 3557 const Type *TypeNode = Quals.strip(T); 3558 3559 // If this type already has an ObjCGC specified, it cannot get 3560 // another one. 3561 assert(!Quals.hasObjCGCAttr() && 3562 "Type cannot have multiple ObjCGCs!"); 3563 Quals.addObjCGCAttr(GCAttr); 3564 3565 return getExtQualType(TypeNode, Quals); 3566 } 3567 3568 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3569 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3570 QualType Pointee = Ptr->getPointeeType(); 3571 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3572 return getPointerType(removeAddrSpaceQualType(Pointee)); 3573 } 3574 } 3575 return T; 3576 } 3577 3578 QualType ASTContext::getCountAttributedType( 3579 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull, 3580 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const { 3581 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType()); 3582 3583 llvm::FoldingSetNodeID ID; 3584 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull); 3585 3586 void *InsertPos = nullptr; 3587 CountAttributedType *CATy = 3588 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 3589 if (CATy) 3590 return QualType(CATy, 0); 3591 3592 QualType CanonTy = getCanonicalType(WrappedTy); 3593 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>( 3594 DependentDecls.size()); 3595 CATy = (CountAttributedType *)Allocate(Size, TypeAlignment); 3596 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes, 3597 OrNull, DependentDecls); 3598 Types.push_back(CATy); 3599 CountAttributedTypes.InsertNode(CATy, InsertPos); 3600 3601 return QualType(CATy, 0); 3602 } 3603 3604 QualType 3605 ASTContext::adjustType(QualType Orig, 3606 llvm::function_ref<QualType(QualType)> Adjust) const { 3607 switch (Orig->getTypeClass()) { 3608 case Type::Attributed: { 3609 const auto *AT = cast<AttributedType>(Orig); 3610 return getAttributedType(AT->getAttrKind(), 3611 adjustType(AT->getModifiedType(), Adjust), 3612 adjustType(AT->getEquivalentType(), Adjust), 3613 AT->getAttr()); 3614 } 3615 3616 case Type::BTFTagAttributed: { 3617 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig); 3618 return getBTFTagAttributedType(BTFT->getAttr(), 3619 adjustType(BTFT->getWrappedType(), Adjust)); 3620 } 3621 3622 case Type::Elaborated: { 3623 const auto *ET = cast<ElaboratedType>(Orig); 3624 return getElaboratedType(ET->getKeyword(), ET->getQualifier(), 3625 adjustType(ET->getNamedType(), Adjust)); 3626 } 3627 3628 case Type::Paren: 3629 return getParenType( 3630 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust)); 3631 3632 case Type::Adjusted: { 3633 const auto *AT = cast<AdjustedType>(Orig); 3634 return getAdjustedType(AT->getOriginalType(), 3635 adjustType(AT->getAdjustedType(), Adjust)); 3636 } 3637 3638 case Type::MacroQualified: { 3639 const auto *MQT = cast<MacroQualifiedType>(Orig); 3640 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust), 3641 MQT->getMacroIdentifier()); 3642 } 3643 3644 default: 3645 return Adjust(Orig); 3646 } 3647 } 3648 3649 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3650 FunctionType::ExtInfo Info) { 3651 if (T->getExtInfo() == Info) 3652 return T; 3653 3654 QualType Result; 3655 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3656 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3657 } else { 3658 const auto *FPT = cast<FunctionProtoType>(T); 3659 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3660 EPI.ExtInfo = Info; 3661 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3662 } 3663 3664 return cast<FunctionType>(Result.getTypePtr()); 3665 } 3666 3667 QualType ASTContext::adjustFunctionResultType(QualType FunctionType, 3668 QualType ResultType) { 3669 return adjustType(FunctionType, [&](QualType Orig) { 3670 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>()) 3671 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo()); 3672 3673 const auto *FPT = Orig->castAs<FunctionProtoType>(); 3674 return getFunctionType(ResultType, FPT->getParamTypes(), 3675 FPT->getExtProtoInfo()); 3676 }); 3677 } 3678 3679 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3680 QualType ResultType) { 3681 FD = FD->getMostRecentDecl(); 3682 while (true) { 3683 FD->setType(adjustFunctionResultType(FD->getType(), ResultType)); 3684 if (FunctionDecl *Next = FD->getPreviousDecl()) 3685 FD = Next; 3686 else 3687 break; 3688 } 3689 if (ASTMutationListener *L = getASTMutationListener()) 3690 L->DeducedReturnType(FD, ResultType); 3691 } 3692 3693 /// Get a function type and produce the equivalent function type with the 3694 /// specified exception specification. Type sugar that can be present on a 3695 /// declaration of a function with an exception specification is permitted 3696 /// and preserved. Other type sugar (for instance, typedefs) is not. 3697 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3698 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const { 3699 return adjustType(Orig, [&](QualType Ty) { 3700 const auto *Proto = Ty->castAs<FunctionProtoType>(); 3701 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(), 3702 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3703 }); 3704 } 3705 3706 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3707 QualType U) const { 3708 return hasSameType(T, U) || 3709 (getLangOpts().CPlusPlus17 && 3710 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3711 getFunctionTypeWithExceptionSpec(U, EST_None))); 3712 } 3713 3714 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3715 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3716 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3717 SmallVector<QualType, 16> Args(Proto->param_types().size()); 3718 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3719 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]); 3720 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3721 } 3722 3723 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3724 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3725 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3726 } 3727 3728 return T; 3729 } 3730 3731 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3732 return hasSameType(T, U) || 3733 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3734 getFunctionTypeWithoutPtrSizes(U)); 3735 } 3736 3737 QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const { 3738 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3739 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3740 EPI.ExtParameterInfos = nullptr; 3741 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI); 3742 } 3743 return T; 3744 } 3745 3746 bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T, 3747 QualType U) const { 3748 return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutParamABIs(T), 3749 getFunctionTypeWithoutParamABIs(U)); 3750 } 3751 3752 void ASTContext::adjustExceptionSpec( 3753 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3754 bool AsWritten) { 3755 // Update the type. 3756 QualType Updated = 3757 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3758 FD->setType(Updated); 3759 3760 if (!AsWritten) 3761 return; 3762 3763 // Update the type in the type source information too. 3764 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3765 // If the type and the type-as-written differ, we may need to update 3766 // the type-as-written too. 3767 if (TSInfo->getType() != FD->getType()) 3768 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3769 3770 // FIXME: When we get proper type location information for exceptions, 3771 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3772 // up the TypeSourceInfo; 3773 assert(TypeLoc::getFullDataSizeForType(Updated) == 3774 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3775 "TypeLoc size mismatch from updating exception specification"); 3776 TSInfo->overrideType(Updated); 3777 } 3778 } 3779 3780 /// getComplexType - Return the uniqued reference to the type for a complex 3781 /// number with the specified element type. 3782 QualType ASTContext::getComplexType(QualType T) const { 3783 // Unique pointers, to guarantee there is only one pointer of a particular 3784 // structure. 3785 llvm::FoldingSetNodeID ID; 3786 ComplexType::Profile(ID, T); 3787 3788 void *InsertPos = nullptr; 3789 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3790 return QualType(CT, 0); 3791 3792 // If the pointee type isn't canonical, this won't be a canonical type either, 3793 // so fill in the canonical type field. 3794 QualType Canonical; 3795 if (!T.isCanonical()) { 3796 Canonical = getComplexType(getCanonicalType(T)); 3797 3798 // Get the new insert position for the node we care about. 3799 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3800 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3801 } 3802 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical); 3803 Types.push_back(New); 3804 ComplexTypes.InsertNode(New, InsertPos); 3805 return QualType(New, 0); 3806 } 3807 3808 /// getPointerType - Return the uniqued reference to the type for a pointer to 3809 /// the specified type. 3810 QualType ASTContext::getPointerType(QualType T) const { 3811 // Unique pointers, to guarantee there is only one pointer of a particular 3812 // structure. 3813 llvm::FoldingSetNodeID ID; 3814 PointerType::Profile(ID, T); 3815 3816 void *InsertPos = nullptr; 3817 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3818 return QualType(PT, 0); 3819 3820 // If the pointee type isn't canonical, this won't be a canonical type either, 3821 // so fill in the canonical type field. 3822 QualType Canonical; 3823 if (!T.isCanonical()) { 3824 Canonical = getPointerType(getCanonicalType(T)); 3825 3826 // Get the new insert position for the node we care about. 3827 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3828 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3829 } 3830 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical); 3831 Types.push_back(New); 3832 PointerTypes.InsertNode(New, InsertPos); 3833 return QualType(New, 0); 3834 } 3835 3836 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3837 llvm::FoldingSetNodeID ID; 3838 AdjustedType::Profile(ID, Orig, New); 3839 void *InsertPos = nullptr; 3840 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3841 if (AT) 3842 return QualType(AT, 0); 3843 3844 QualType Canonical = getCanonicalType(New); 3845 3846 // Get the new insert position for the node we care about. 3847 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3848 assert(!AT && "Shouldn't be in the map!"); 3849 3850 AT = new (*this, alignof(AdjustedType)) 3851 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3852 Types.push_back(AT); 3853 AdjustedTypes.InsertNode(AT, InsertPos); 3854 return QualType(AT, 0); 3855 } 3856 3857 QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const { 3858 llvm::FoldingSetNodeID ID; 3859 AdjustedType::Profile(ID, Orig, Decayed); 3860 void *InsertPos = nullptr; 3861 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3862 if (AT) 3863 return QualType(AT, 0); 3864 3865 QualType Canonical = getCanonicalType(Decayed); 3866 3867 // Get the new insert position for the node we care about. 3868 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3869 assert(!AT && "Shouldn't be in the map!"); 3870 3871 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical); 3872 Types.push_back(AT); 3873 AdjustedTypes.InsertNode(AT, InsertPos); 3874 return QualType(AT, 0); 3875 } 3876 3877 QualType ASTContext::getDecayedType(QualType T) const { 3878 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3879 3880 QualType Decayed; 3881 3882 // C99 6.7.5.3p7: 3883 // A declaration of a parameter as "array of type" shall be 3884 // adjusted to "qualified pointer to type", where the type 3885 // qualifiers (if any) are those specified within the [ and ] of 3886 // the array type derivation. 3887 if (T->isArrayType()) 3888 Decayed = getArrayDecayedType(T); 3889 3890 // C99 6.7.5.3p8: 3891 // A declaration of a parameter as "function returning type" 3892 // shall be adjusted to "pointer to function returning type", as 3893 // in 6.3.2.1. 3894 if (T->isFunctionType()) 3895 Decayed = getPointerType(T); 3896 3897 return getDecayedType(T, Decayed); 3898 } 3899 3900 QualType ASTContext::getArrayParameterType(QualType Ty) const { 3901 if (Ty->isArrayParameterType()) 3902 return Ty; 3903 assert(Ty->isConstantArrayType() && "Ty must be an array type."); 3904 const auto *ATy = cast<ConstantArrayType>(Ty); 3905 llvm::FoldingSetNodeID ID; 3906 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(), 3907 ATy->getSizeExpr(), ATy->getSizeModifier(), 3908 ATy->getIndexTypeQualifiers().getAsOpaqueValue()); 3909 void *InsertPos = nullptr; 3910 ArrayParameterType *AT = 3911 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos); 3912 if (AT) 3913 return QualType(AT, 0); 3914 3915 QualType Canonical; 3916 if (!Ty.isCanonical()) { 3917 Canonical = getArrayParameterType(getCanonicalType(Ty)); 3918 3919 // Get the new insert position for the node we care about. 3920 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos); 3921 assert(!AT && "Shouldn't be in the map!"); 3922 } 3923 3924 AT = new (*this, alignof(ArrayParameterType)) 3925 ArrayParameterType(ATy, Canonical); 3926 Types.push_back(AT); 3927 ArrayParameterTypes.InsertNode(AT, InsertPos); 3928 return QualType(AT, 0); 3929 } 3930 3931 /// getBlockPointerType - Return the uniqued reference to the type for 3932 /// a pointer to the specified block. 3933 QualType ASTContext::getBlockPointerType(QualType T) const { 3934 assert(T->isFunctionType() && "block of function types only"); 3935 // Unique pointers, to guarantee there is only one block of a particular 3936 // structure. 3937 llvm::FoldingSetNodeID ID; 3938 BlockPointerType::Profile(ID, T); 3939 3940 void *InsertPos = nullptr; 3941 if (BlockPointerType *PT = 3942 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3943 return QualType(PT, 0); 3944 3945 // If the block pointee type isn't canonical, this won't be a canonical 3946 // type either so fill in the canonical type field. 3947 QualType Canonical; 3948 if (!T.isCanonical()) { 3949 Canonical = getBlockPointerType(getCanonicalType(T)); 3950 3951 // Get the new insert position for the node we care about. 3952 BlockPointerType *NewIP = 3953 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3954 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3955 } 3956 auto *New = 3957 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical); 3958 Types.push_back(New); 3959 BlockPointerTypes.InsertNode(New, InsertPos); 3960 return QualType(New, 0); 3961 } 3962 3963 /// getLValueReferenceType - Return the uniqued reference to the type for an 3964 /// lvalue reference to the specified type. 3965 QualType 3966 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3967 assert((!T->isPlaceholderType() || 3968 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3969 "Unresolved placeholder type"); 3970 3971 // Unique pointers, to guarantee there is only one pointer of a particular 3972 // structure. 3973 llvm::FoldingSetNodeID ID; 3974 ReferenceType::Profile(ID, T, SpelledAsLValue); 3975 3976 void *InsertPos = nullptr; 3977 if (LValueReferenceType *RT = 3978 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3979 return QualType(RT, 0); 3980 3981 const auto *InnerRef = T->getAs<ReferenceType>(); 3982 3983 // If the referencee type isn't canonical, this won't be a canonical type 3984 // either, so fill in the canonical type field. 3985 QualType Canonical; 3986 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3987 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3988 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3989 3990 // Get the new insert position for the node we care about. 3991 LValueReferenceType *NewIP = 3992 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3993 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3994 } 3995 3996 auto *New = new (*this, alignof(LValueReferenceType)) 3997 LValueReferenceType(T, Canonical, SpelledAsLValue); 3998 Types.push_back(New); 3999 LValueReferenceTypes.InsertNode(New, InsertPos); 4000 4001 return QualType(New, 0); 4002 } 4003 4004 /// getRValueReferenceType - Return the uniqued reference to the type for an 4005 /// rvalue reference to the specified type. 4006 QualType ASTContext::getRValueReferenceType(QualType T) const { 4007 assert((!T->isPlaceholderType() || 4008 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 4009 "Unresolved placeholder type"); 4010 4011 // Unique pointers, to guarantee there is only one pointer of a particular 4012 // structure. 4013 llvm::FoldingSetNodeID ID; 4014 ReferenceType::Profile(ID, T, false); 4015 4016 void *InsertPos = nullptr; 4017 if (RValueReferenceType *RT = 4018 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 4019 return QualType(RT, 0); 4020 4021 const auto *InnerRef = T->getAs<ReferenceType>(); 4022 4023 // If the referencee type isn't canonical, this won't be a canonical type 4024 // either, so fill in the canonical type field. 4025 QualType Canonical; 4026 if (InnerRef || !T.isCanonical()) { 4027 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 4028 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 4029 4030 // Get the new insert position for the node we care about. 4031 RValueReferenceType *NewIP = 4032 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 4033 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4034 } 4035 4036 auto *New = new (*this, alignof(RValueReferenceType)) 4037 RValueReferenceType(T, Canonical); 4038 Types.push_back(New); 4039 RValueReferenceTypes.InsertNode(New, InsertPos); 4040 return QualType(New, 0); 4041 } 4042 4043 /// getMemberPointerType - Return the uniqued reference to the type for a 4044 /// member pointer to the specified type, in the specified class. 4045 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 4046 // Unique pointers, to guarantee there is only one pointer of a particular 4047 // structure. 4048 llvm::FoldingSetNodeID ID; 4049 MemberPointerType::Profile(ID, T, Cls); 4050 4051 void *InsertPos = nullptr; 4052 if (MemberPointerType *PT = 4053 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 4054 return QualType(PT, 0); 4055 4056 // If the pointee or class type isn't canonical, this won't be a canonical 4057 // type either, so fill in the canonical type field. 4058 QualType Canonical; 4059 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 4060 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 4061 4062 // Get the new insert position for the node we care about. 4063 MemberPointerType *NewIP = 4064 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 4065 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4066 } 4067 auto *New = new (*this, alignof(MemberPointerType)) 4068 MemberPointerType(T, Cls, Canonical); 4069 Types.push_back(New); 4070 MemberPointerTypes.InsertNode(New, InsertPos); 4071 return QualType(New, 0); 4072 } 4073 4074 /// getConstantArrayType - Return the unique reference to the type for an 4075 /// array of the specified element type. 4076 QualType ASTContext::getConstantArrayType(QualType EltTy, 4077 const llvm::APInt &ArySizeIn, 4078 const Expr *SizeExpr, 4079 ArraySizeModifier ASM, 4080 unsigned IndexTypeQuals) const { 4081 assert((EltTy->isDependentType() || 4082 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 4083 "Constant array of VLAs is illegal!"); 4084 4085 // We only need the size as part of the type if it's instantiation-dependent. 4086 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 4087 SizeExpr = nullptr; 4088 4089 // Convert the array size into a canonical width matching the pointer size for 4090 // the target. 4091 llvm::APInt ArySize(ArySizeIn); 4092 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 4093 4094 llvm::FoldingSetNodeID ID; 4095 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr, 4096 ASM, IndexTypeQuals); 4097 4098 void *InsertPos = nullptr; 4099 if (ConstantArrayType *ATP = 4100 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 4101 return QualType(ATP, 0); 4102 4103 // If the element type isn't canonical or has qualifiers, or the array bound 4104 // is instantiation-dependent, this won't be a canonical type either, so fill 4105 // in the canonical type field. 4106 QualType Canon; 4107 // FIXME: Check below should look for qualifiers behind sugar. 4108 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 4109 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 4110 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 4111 ASM, IndexTypeQuals); 4112 Canon = getQualifiedType(Canon, canonSplit.Quals); 4113 4114 // Get the new insert position for the node we care about. 4115 ConstantArrayType *NewIP = 4116 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 4117 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4118 } 4119 4120 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr, 4121 ASM, IndexTypeQuals); 4122 ConstantArrayTypes.InsertNode(New, InsertPos); 4123 Types.push_back(New); 4124 return QualType(New, 0); 4125 } 4126 4127 /// getVariableArrayDecayedType - Turns the given type, which may be 4128 /// variably-modified, into the corresponding type with all the known 4129 /// sizes replaced with [*]. 4130 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 4131 // Vastly most common case. 4132 if (!type->isVariablyModifiedType()) return type; 4133 4134 QualType result; 4135 4136 SplitQualType split = type.getSplitDesugaredType(); 4137 const Type *ty = split.Ty; 4138 switch (ty->getTypeClass()) { 4139 #define TYPE(Class, Base) 4140 #define ABSTRACT_TYPE(Class, Base) 4141 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 4142 #include "clang/AST/TypeNodes.inc" 4143 llvm_unreachable("didn't desugar past all non-canonical types?"); 4144 4145 // These types should never be variably-modified. 4146 case Type::Builtin: 4147 case Type::Complex: 4148 case Type::Vector: 4149 case Type::DependentVector: 4150 case Type::ExtVector: 4151 case Type::DependentSizedExtVector: 4152 case Type::ConstantMatrix: 4153 case Type::DependentSizedMatrix: 4154 case Type::DependentAddressSpace: 4155 case Type::ObjCObject: 4156 case Type::ObjCInterface: 4157 case Type::ObjCObjectPointer: 4158 case Type::Record: 4159 case Type::Enum: 4160 case Type::UnresolvedUsing: 4161 case Type::TypeOfExpr: 4162 case Type::TypeOf: 4163 case Type::Decltype: 4164 case Type::UnaryTransform: 4165 case Type::DependentName: 4166 case Type::InjectedClassName: 4167 case Type::TemplateSpecialization: 4168 case Type::DependentTemplateSpecialization: 4169 case Type::TemplateTypeParm: 4170 case Type::SubstTemplateTypeParmPack: 4171 case Type::Auto: 4172 case Type::DeducedTemplateSpecialization: 4173 case Type::PackExpansion: 4174 case Type::PackIndexing: 4175 case Type::BitInt: 4176 case Type::DependentBitInt: 4177 case Type::ArrayParameter: 4178 case Type::HLSLAttributedResource: 4179 llvm_unreachable("type should never be variably-modified"); 4180 4181 // These types can be variably-modified but should never need to 4182 // further decay. 4183 case Type::FunctionNoProto: 4184 case Type::FunctionProto: 4185 case Type::BlockPointer: 4186 case Type::MemberPointer: 4187 case Type::Pipe: 4188 return type; 4189 4190 // These types can be variably-modified. All these modifications 4191 // preserve structure except as noted by comments. 4192 // TODO: if we ever care about optimizing VLAs, there are no-op 4193 // optimizations available here. 4194 case Type::Pointer: 4195 result = getPointerType(getVariableArrayDecayedType( 4196 cast<PointerType>(ty)->getPointeeType())); 4197 break; 4198 4199 case Type::LValueReference: { 4200 const auto *lv = cast<LValueReferenceType>(ty); 4201 result = getLValueReferenceType( 4202 getVariableArrayDecayedType(lv->getPointeeType()), 4203 lv->isSpelledAsLValue()); 4204 break; 4205 } 4206 4207 case Type::RValueReference: { 4208 const auto *lv = cast<RValueReferenceType>(ty); 4209 result = getRValueReferenceType( 4210 getVariableArrayDecayedType(lv->getPointeeType())); 4211 break; 4212 } 4213 4214 case Type::Atomic: { 4215 const auto *at = cast<AtomicType>(ty); 4216 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 4217 break; 4218 } 4219 4220 case Type::ConstantArray: { 4221 const auto *cat = cast<ConstantArrayType>(ty); 4222 result = getConstantArrayType( 4223 getVariableArrayDecayedType(cat->getElementType()), 4224 cat->getSize(), 4225 cat->getSizeExpr(), 4226 cat->getSizeModifier(), 4227 cat->getIndexTypeCVRQualifiers()); 4228 break; 4229 } 4230 4231 case Type::DependentSizedArray: { 4232 const auto *dat = cast<DependentSizedArrayType>(ty); 4233 result = getDependentSizedArrayType( 4234 getVariableArrayDecayedType(dat->getElementType()), 4235 dat->getSizeExpr(), 4236 dat->getSizeModifier(), 4237 dat->getIndexTypeCVRQualifiers(), 4238 dat->getBracketsRange()); 4239 break; 4240 } 4241 4242 // Turn incomplete types into [*] types. 4243 case Type::IncompleteArray: { 4244 const auto *iat = cast<IncompleteArrayType>(ty); 4245 result = 4246 getVariableArrayType(getVariableArrayDecayedType(iat->getElementType()), 4247 /*size*/ nullptr, ArraySizeModifier::Normal, 4248 iat->getIndexTypeCVRQualifiers(), SourceRange()); 4249 break; 4250 } 4251 4252 // Turn VLA types into [*] types. 4253 case Type::VariableArray: { 4254 const auto *vat = cast<VariableArrayType>(ty); 4255 result = getVariableArrayType( 4256 getVariableArrayDecayedType(vat->getElementType()), 4257 /*size*/ nullptr, ArraySizeModifier::Star, 4258 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange()); 4259 break; 4260 } 4261 } 4262 4263 // Apply the top-level qualifiers from the original. 4264 return getQualifiedType(result, split.Quals); 4265 } 4266 4267 /// getVariableArrayType - Returns a non-unique reference to the type for a 4268 /// variable array of the specified element type. 4269 QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 4270 ArraySizeModifier ASM, 4271 unsigned IndexTypeQuals, 4272 SourceRange Brackets) const { 4273 // Since we don't unique expressions, it isn't possible to unique VLA's 4274 // that have an expression provided for their size. 4275 QualType Canon; 4276 4277 // Be sure to pull qualifiers off the element type. 4278 // FIXME: Check below should look for qualifiers behind sugar. 4279 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 4280 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 4281 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 4282 IndexTypeQuals, Brackets); 4283 Canon = getQualifiedType(Canon, canonSplit.Quals); 4284 } 4285 4286 auto *New = new (*this, alignof(VariableArrayType)) 4287 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 4288 4289 VariableArrayTypes.push_back(New); 4290 Types.push_back(New); 4291 return QualType(New, 0); 4292 } 4293 4294 /// getDependentSizedArrayType - Returns a non-unique reference to 4295 /// the type for a dependently-sized array of the specified element 4296 /// type. 4297 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 4298 Expr *numElements, 4299 ArraySizeModifier ASM, 4300 unsigned elementTypeQuals, 4301 SourceRange brackets) const { 4302 assert((!numElements || numElements->isTypeDependent() || 4303 numElements->isValueDependent()) && 4304 "Size must be type- or value-dependent!"); 4305 4306 SplitQualType canonElementType = getCanonicalType(elementType).split(); 4307 4308 void *insertPos = nullptr; 4309 llvm::FoldingSetNodeID ID; 4310 DependentSizedArrayType::Profile( 4311 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType, 4312 ASM, elementTypeQuals, numElements); 4313 4314 // Look for an existing type with these properties. 4315 DependentSizedArrayType *canonTy = 4316 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 4317 4318 // Dependently-sized array types that do not have a specified number 4319 // of elements will have their sizes deduced from a dependent 4320 // initializer. 4321 if (!numElements) { 4322 if (canonTy) 4323 return QualType(canonTy, 0); 4324 4325 auto *newType = new (*this, alignof(DependentSizedArrayType)) 4326 DependentSizedArrayType(elementType, QualType(), numElements, ASM, 4327 elementTypeQuals, brackets); 4328 DependentSizedArrayTypes.InsertNode(newType, insertPos); 4329 Types.push_back(newType); 4330 return QualType(newType, 0); 4331 } 4332 4333 // If we don't have one, build one. 4334 if (!canonTy) { 4335 canonTy = new (*this, alignof(DependentSizedArrayType)) 4336 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(), 4337 numElements, ASM, elementTypeQuals, brackets); 4338 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 4339 Types.push_back(canonTy); 4340 } 4341 4342 // Apply qualifiers from the element type to the array. 4343 QualType canon = getQualifiedType(QualType(canonTy,0), 4344 canonElementType.Quals); 4345 4346 // If we didn't need extra canonicalization for the element type or the size 4347 // expression, then just use that as our result. 4348 if (QualType(canonElementType.Ty, 0) == elementType && 4349 canonTy->getSizeExpr() == numElements) 4350 return canon; 4351 4352 // Otherwise, we need to build a type which follows the spelling 4353 // of the element type. 4354 auto *sugaredType = new (*this, alignof(DependentSizedArrayType)) 4355 DependentSizedArrayType(elementType, canon, numElements, ASM, 4356 elementTypeQuals, brackets); 4357 Types.push_back(sugaredType); 4358 return QualType(sugaredType, 0); 4359 } 4360 4361 QualType ASTContext::getIncompleteArrayType(QualType elementType, 4362 ArraySizeModifier ASM, 4363 unsigned elementTypeQuals) const { 4364 llvm::FoldingSetNodeID ID; 4365 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 4366 4367 void *insertPos = nullptr; 4368 if (IncompleteArrayType *iat = 4369 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 4370 return QualType(iat, 0); 4371 4372 // If the element type isn't canonical, this won't be a canonical type 4373 // either, so fill in the canonical type field. We also have to pull 4374 // qualifiers off the element type. 4375 QualType canon; 4376 4377 // FIXME: Check below should look for qualifiers behind sugar. 4378 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 4379 SplitQualType canonSplit = getCanonicalType(elementType).split(); 4380 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 4381 ASM, elementTypeQuals); 4382 canon = getQualifiedType(canon, canonSplit.Quals); 4383 4384 // Get the new insert position for the node we care about. 4385 IncompleteArrayType *existing = 4386 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 4387 assert(!existing && "Shouldn't be in the map!"); (void) existing; 4388 } 4389 4390 auto *newType = new (*this, alignof(IncompleteArrayType)) 4391 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 4392 4393 IncompleteArrayTypes.InsertNode(newType, insertPos); 4394 Types.push_back(newType); 4395 return QualType(newType, 0); 4396 } 4397 4398 ASTContext::BuiltinVectorTypeInfo 4399 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 4400 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 4401 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 4402 NUMVECTORS}; 4403 4404 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 4405 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 4406 4407 switch (Ty->getKind()) { 4408 default: 4409 llvm_unreachable("Unsupported builtin vector type"); 4410 4411 #define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \ 4412 ElBits, NF, IsSigned) \ 4413 case BuiltinType::Id: \ 4414 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 4415 llvm::ElementCount::getScalable(NumEls), NF}; 4416 #define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4417 ElBits, NF) \ 4418 case BuiltinType::Id: \ 4419 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \ 4420 llvm::ElementCount::getScalable(NumEls), NF}; 4421 #define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4422 ElBits, NF) \ 4423 case BuiltinType::Id: \ 4424 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF}; 4425 #define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4426 ElBits, NF) \ 4427 case BuiltinType::Id: \ 4428 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF}; 4429 #define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \ 4430 case BuiltinType::Id: \ 4431 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF}; 4432 #define SVE_TYPE(Name, Id, SingletonId) 4433 #include "clang/Basic/AArch64SVEACLETypes.def" 4434 4435 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 4436 IsSigned) \ 4437 case BuiltinType::Id: \ 4438 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 4439 llvm::ElementCount::getScalable(NumEls), NF}; 4440 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 4441 case BuiltinType::Id: \ 4442 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 4443 llvm::ElementCount::getScalable(NumEls), NF}; 4444 #define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 4445 case BuiltinType::Id: \ 4446 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF}; 4447 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 4448 case BuiltinType::Id: \ 4449 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 4450 #include "clang/Basic/RISCVVTypes.def" 4451 } 4452 } 4453 4454 /// getExternrefType - Return a WebAssembly externref type, which represents an 4455 /// opaque reference to a host value. 4456 QualType ASTContext::getWebAssemblyExternrefType() const { 4457 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) { 4458 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \ 4459 if (BuiltinType::Id == BuiltinType::WasmExternRef) \ 4460 return SingletonId; 4461 #include "clang/Basic/WebAssemblyReferenceTypes.def" 4462 } 4463 llvm_unreachable( 4464 "shouldn't try to generate type externref outside WebAssembly target"); 4465 } 4466 4467 /// getScalableVectorType - Return the unique reference to a scalable vector 4468 /// type of the specified element type and size. VectorType must be a built-in 4469 /// type. 4470 QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts, 4471 unsigned NumFields) const { 4472 if (Target->hasAArch64SVETypes()) { 4473 uint64_t EltTySize = getTypeSize(EltTy); 4474 4475 #define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \ 4476 ElBits, NF, IsSigned) \ 4477 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \ 4478 EltTy->hasSignedIntegerRepresentation() == IsSigned && \ 4479 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \ 4480 return SingletonId; \ 4481 } 4482 #define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4483 ElBits, NF) \ 4484 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 4485 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \ 4486 return SingletonId; \ 4487 } 4488 #define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4489 ElBits, NF) \ 4490 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 4491 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \ 4492 return SingletonId; \ 4493 } 4494 #define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \ 4495 ElBits, NF) \ 4496 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \ 4497 NumElts == (NumEls * NF) && NumFields == 1) { \ 4498 return SingletonId; \ 4499 } 4500 #define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \ 4501 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \ 4502 return SingletonId; 4503 #define SVE_TYPE(Name, Id, SingletonId) 4504 #include "clang/Basic/AArch64SVEACLETypes.def" 4505 } else if (Target->hasRISCVVTypes()) { 4506 uint64_t EltTySize = getTypeSize(EltTy); 4507 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 4508 IsFP, IsBF) \ 4509 if (!EltTy->isBooleanType() && \ 4510 ((EltTy->hasIntegerRepresentation() && \ 4511 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 4512 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 4513 IsFP && !IsBF) || \ 4514 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 4515 IsBF && !IsFP)) && \ 4516 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \ 4517 return SingletonId; 4518 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 4519 if (EltTy->isBooleanType() && NumElts == NumEls) \ 4520 return SingletonId; 4521 #include "clang/Basic/RISCVVTypes.def" 4522 } 4523 return QualType(); 4524 } 4525 4526 /// getVectorType - Return the unique reference to a vector type of 4527 /// the specified element type and size. VectorType must be a built-in type. 4528 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 4529 VectorKind VecKind) const { 4530 assert(vecType->isBuiltinType() || 4531 (vecType->isBitIntType() && 4532 // Only support _BitInt elements with byte-sized power of 2 NumBits. 4533 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) && 4534 vecType->castAs<BitIntType>()->getNumBits() >= 8)); 4535 4536 // Check if we've already instantiated a vector of this type. 4537 llvm::FoldingSetNodeID ID; 4538 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 4539 4540 void *InsertPos = nullptr; 4541 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4542 return QualType(VTP, 0); 4543 4544 // If the element type isn't canonical, this won't be a canonical type either, 4545 // so fill in the canonical type field. 4546 QualType Canonical; 4547 if (!vecType.isCanonical()) { 4548 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 4549 4550 // Get the new insert position for the node we care about. 4551 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4553 } 4554 auto *New = new (*this, alignof(VectorType)) 4555 VectorType(vecType, NumElts, Canonical, VecKind); 4556 VectorTypes.InsertNode(New, InsertPos); 4557 Types.push_back(New); 4558 return QualType(New, 0); 4559 } 4560 4561 QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4562 SourceLocation AttrLoc, 4563 VectorKind VecKind) const { 4564 llvm::FoldingSetNodeID ID; 4565 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4566 VecKind); 4567 void *InsertPos = nullptr; 4568 DependentVectorType *Canon = 4569 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4570 DependentVectorType *New; 4571 4572 if (Canon) { 4573 New = new (*this, alignof(DependentVectorType)) DependentVectorType( 4574 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4575 } else { 4576 QualType CanonVecTy = getCanonicalType(VecType); 4577 if (CanonVecTy == VecType) { 4578 New = new (*this, alignof(DependentVectorType)) 4579 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4580 4581 DependentVectorType *CanonCheck = 4582 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4583 assert(!CanonCheck && 4584 "Dependent-sized vector_size canonical type broken"); 4585 (void)CanonCheck; 4586 DependentVectorTypes.InsertNode(New, InsertPos); 4587 } else { 4588 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4589 SourceLocation(), VecKind); 4590 New = new (*this, alignof(DependentVectorType)) 4591 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4592 } 4593 } 4594 4595 Types.push_back(New); 4596 return QualType(New, 0); 4597 } 4598 4599 /// getExtVectorType - Return the unique reference to an extended vector type of 4600 /// the specified element type and size. VectorType must be a built-in type. 4601 QualType ASTContext::getExtVectorType(QualType vecType, 4602 unsigned NumElts) const { 4603 assert(vecType->isBuiltinType() || vecType->isDependentType() || 4604 (vecType->isBitIntType() && 4605 // Only support _BitInt elements with byte-sized power of 2 NumBits. 4606 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) && 4607 vecType->castAs<BitIntType>()->getNumBits() >= 8)); 4608 4609 // Check if we've already instantiated a vector of this type. 4610 llvm::FoldingSetNodeID ID; 4611 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4612 VectorKind::Generic); 4613 void *InsertPos = nullptr; 4614 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4615 return QualType(VTP, 0); 4616 4617 // If the element type isn't canonical, this won't be a canonical type either, 4618 // so fill in the canonical type field. 4619 QualType Canonical; 4620 if (!vecType.isCanonical()) { 4621 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4622 4623 // Get the new insert position for the node we care about. 4624 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4625 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4626 } 4627 auto *New = new (*this, alignof(ExtVectorType)) 4628 ExtVectorType(vecType, NumElts, Canonical); 4629 VectorTypes.InsertNode(New, InsertPos); 4630 Types.push_back(New); 4631 return QualType(New, 0); 4632 } 4633 4634 QualType 4635 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4636 Expr *SizeExpr, 4637 SourceLocation AttrLoc) const { 4638 llvm::FoldingSetNodeID ID; 4639 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4640 SizeExpr); 4641 4642 void *InsertPos = nullptr; 4643 DependentSizedExtVectorType *Canon 4644 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4645 DependentSizedExtVectorType *New; 4646 if (Canon) { 4647 // We already have a canonical version of this array type; use it as 4648 // the canonical type for a newly-built type. 4649 New = new (*this, alignof(DependentSizedExtVectorType)) 4650 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr, 4651 AttrLoc); 4652 } else { 4653 QualType CanonVecTy = getCanonicalType(vecType); 4654 if (CanonVecTy == vecType) { 4655 New = new (*this, alignof(DependentSizedExtVectorType)) 4656 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc); 4657 4658 DependentSizedExtVectorType *CanonCheck 4659 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4660 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4661 (void)CanonCheck; 4662 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4663 } else { 4664 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4665 SourceLocation()); 4666 New = new (*this, alignof(DependentSizedExtVectorType)) 4667 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc); 4668 } 4669 } 4670 4671 Types.push_back(New); 4672 return QualType(New, 0); 4673 } 4674 4675 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4676 unsigned NumColumns) const { 4677 llvm::FoldingSetNodeID ID; 4678 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4679 Type::ConstantMatrix); 4680 4681 assert(MatrixType::isValidElementType(ElementTy) && 4682 "need a valid element type"); 4683 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4684 ConstantMatrixType::isDimensionValid(NumColumns) && 4685 "need valid matrix dimensions"); 4686 void *InsertPos = nullptr; 4687 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4688 return QualType(MTP, 0); 4689 4690 QualType Canonical; 4691 if (!ElementTy.isCanonical()) { 4692 Canonical = 4693 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4694 4695 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4696 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4697 (void)NewIP; 4698 } 4699 4700 auto *New = new (*this, alignof(ConstantMatrixType)) 4701 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4702 MatrixTypes.InsertNode(New, InsertPos); 4703 Types.push_back(New); 4704 return QualType(New, 0); 4705 } 4706 4707 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4708 Expr *RowExpr, 4709 Expr *ColumnExpr, 4710 SourceLocation AttrLoc) const { 4711 QualType CanonElementTy = getCanonicalType(ElementTy); 4712 llvm::FoldingSetNodeID ID; 4713 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4714 ColumnExpr); 4715 4716 void *InsertPos = nullptr; 4717 DependentSizedMatrixType *Canon = 4718 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4719 4720 if (!Canon) { 4721 Canon = new (*this, alignof(DependentSizedMatrixType)) 4722 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr, 4723 ColumnExpr, AttrLoc); 4724 #ifndef NDEBUG 4725 DependentSizedMatrixType *CanonCheck = 4726 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4727 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4728 #endif 4729 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4730 Types.push_back(Canon); 4731 } 4732 4733 // Already have a canonical version of the matrix type 4734 // 4735 // If it exactly matches the requested type, use it directly. 4736 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4737 Canon->getRowExpr() == ColumnExpr) 4738 return QualType(Canon, 0); 4739 4740 // Use Canon as the canonical type for newly-built type. 4741 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType)) 4742 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr, 4743 ColumnExpr, AttrLoc); 4744 Types.push_back(New); 4745 return QualType(New, 0); 4746 } 4747 4748 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4749 Expr *AddrSpaceExpr, 4750 SourceLocation AttrLoc) const { 4751 assert(AddrSpaceExpr->isInstantiationDependent()); 4752 4753 QualType canonPointeeType = getCanonicalType(PointeeType); 4754 4755 void *insertPos = nullptr; 4756 llvm::FoldingSetNodeID ID; 4757 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4758 AddrSpaceExpr); 4759 4760 DependentAddressSpaceType *canonTy = 4761 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4762 4763 if (!canonTy) { 4764 canonTy = new (*this, alignof(DependentAddressSpaceType)) 4765 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr, 4766 AttrLoc); 4767 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4768 Types.push_back(canonTy); 4769 } 4770 4771 if (canonPointeeType == PointeeType && 4772 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4773 return QualType(canonTy, 0); 4774 4775 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType)) 4776 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0), 4777 AddrSpaceExpr, AttrLoc); 4778 Types.push_back(sugaredType); 4779 return QualType(sugaredType, 0); 4780 } 4781 4782 /// Determine whether \p T is canonical as the result type of a function. 4783 static bool isCanonicalResultType(QualType T) { 4784 return T.isCanonical() && 4785 (T.getObjCLifetime() == Qualifiers::OCL_None || 4786 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4787 } 4788 4789 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4790 QualType 4791 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4792 const FunctionType::ExtInfo &Info) const { 4793 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter 4794 // functionality creates a function without a prototype regardless of 4795 // language mode (so it makes them even in C++). Once the rewriter has been 4796 // fixed, this assertion can be enabled again. 4797 //assert(!LangOpts.requiresStrictPrototypes() && 4798 // "strict prototypes are disabled"); 4799 4800 // Unique functions, to guarantee there is only one function of a particular 4801 // structure. 4802 llvm::FoldingSetNodeID ID; 4803 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4804 4805 void *InsertPos = nullptr; 4806 if (FunctionNoProtoType *FT = 4807 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4808 return QualType(FT, 0); 4809 4810 QualType Canonical; 4811 if (!isCanonicalResultType(ResultTy)) { 4812 Canonical = 4813 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4814 4815 // Get the new insert position for the node we care about. 4816 FunctionNoProtoType *NewIP = 4817 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4818 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4819 } 4820 4821 auto *New = new (*this, alignof(FunctionNoProtoType)) 4822 FunctionNoProtoType(ResultTy, Canonical, Info); 4823 Types.push_back(New); 4824 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4825 return QualType(New, 0); 4826 } 4827 4828 CanQualType 4829 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4830 CanQualType CanResultType = getCanonicalType(ResultType); 4831 4832 // Canonical result types do not have ARC lifetime qualifiers. 4833 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4834 Qualifiers Qs = CanResultType.getQualifiers(); 4835 Qs.removeObjCLifetime(); 4836 return CanQualType::CreateUnsafe( 4837 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4838 } 4839 4840 return CanResultType; 4841 } 4842 4843 static bool isCanonicalExceptionSpecification( 4844 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4845 if (ESI.Type == EST_None) 4846 return true; 4847 if (!NoexceptInType) 4848 return false; 4849 4850 // C++17 onwards: exception specification is part of the type, as a simple 4851 // boolean "can this function type throw". 4852 if (ESI.Type == EST_BasicNoexcept) 4853 return true; 4854 4855 // A noexcept(expr) specification is (possibly) canonical if expr is 4856 // value-dependent. 4857 if (ESI.Type == EST_DependentNoexcept) 4858 return true; 4859 4860 // A dynamic exception specification is canonical if it only contains pack 4861 // expansions (so we can't tell whether it's non-throwing) and all its 4862 // contained types are canonical. 4863 if (ESI.Type == EST_Dynamic) { 4864 bool AnyPackExpansions = false; 4865 for (QualType ET : ESI.Exceptions) { 4866 if (!ET.isCanonical()) 4867 return false; 4868 if (ET->getAs<PackExpansionType>()) 4869 AnyPackExpansions = true; 4870 } 4871 return AnyPackExpansions; 4872 } 4873 4874 return false; 4875 } 4876 4877 QualType ASTContext::getFunctionTypeInternal( 4878 QualType ResultTy, ArrayRef<QualType> ArgArray, 4879 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4880 size_t NumArgs = ArgArray.size(); 4881 4882 // Unique functions, to guarantee there is only one function of a particular 4883 // structure. 4884 llvm::FoldingSetNodeID ID; 4885 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4886 *this, true); 4887 4888 QualType Canonical; 4889 bool Unique = false; 4890 4891 void *InsertPos = nullptr; 4892 if (FunctionProtoType *FPT = 4893 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4894 QualType Existing = QualType(FPT, 0); 4895 4896 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4897 // it so long as our exception specification doesn't contain a dependent 4898 // noexcept expression, or we're just looking for a canonical type. 4899 // Otherwise, we're going to need to create a type 4900 // sugar node to hold the concrete expression. 4901 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4902 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4903 return Existing; 4904 4905 // We need a new type sugar node for this one, to hold the new noexcept 4906 // expression. We do no canonicalization here, but that's OK since we don't 4907 // expect to see the same noexcept expression much more than once. 4908 Canonical = getCanonicalType(Existing); 4909 Unique = true; 4910 } 4911 4912 bool NoexceptInType = getLangOpts().CPlusPlus17; 4913 bool IsCanonicalExceptionSpec = 4914 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4915 4916 // Determine whether the type being created is already canonical or not. 4917 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4918 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4919 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4920 if (!ArgArray[i].isCanonicalAsParam()) 4921 isCanonical = false; 4922 4923 if (OnlyWantCanonical) 4924 assert(isCanonical && 4925 "given non-canonical parameters constructing canonical type"); 4926 4927 // If this type isn't canonical, get the canonical version of it if we don't 4928 // already have it. The exception spec is only partially part of the 4929 // canonical type, and only in C++17 onwards. 4930 if (!isCanonical && Canonical.isNull()) { 4931 SmallVector<QualType, 16> CanonicalArgs; 4932 CanonicalArgs.reserve(NumArgs); 4933 for (unsigned i = 0; i != NumArgs; ++i) 4934 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4935 4936 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4937 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4938 CanonicalEPI.HasTrailingReturn = false; 4939 4940 if (IsCanonicalExceptionSpec) { 4941 // Exception spec is already OK. 4942 } else if (NoexceptInType) { 4943 switch (EPI.ExceptionSpec.Type) { 4944 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4945 // We don't know yet. It shouldn't matter what we pick here; no-one 4946 // should ever look at this. 4947 [[fallthrough]]; 4948 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4949 CanonicalEPI.ExceptionSpec.Type = EST_None; 4950 break; 4951 4952 // A dynamic exception specification is almost always "not noexcept", 4953 // with the exception that a pack expansion might expand to no types. 4954 case EST_Dynamic: { 4955 bool AnyPacks = false; 4956 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4957 if (ET->getAs<PackExpansionType>()) 4958 AnyPacks = true; 4959 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4960 } 4961 if (!AnyPacks) 4962 CanonicalEPI.ExceptionSpec.Type = EST_None; 4963 else { 4964 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4965 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4966 } 4967 break; 4968 } 4969 4970 case EST_DynamicNone: 4971 case EST_BasicNoexcept: 4972 case EST_NoexceptTrue: 4973 case EST_NoThrow: 4974 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4975 break; 4976 4977 case EST_DependentNoexcept: 4978 llvm_unreachable("dependent noexcept is already canonical"); 4979 } 4980 } else { 4981 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4982 } 4983 4984 // Adjust the canonical function result type. 4985 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4986 Canonical = 4987 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4988 4989 // Get the new insert position for the node we care about. 4990 FunctionProtoType *NewIP = 4991 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4992 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4993 } 4994 4995 // Compute the needed size to hold this FunctionProtoType and the 4996 // various trailing objects. 4997 auto ESH = FunctionProtoType::getExceptionSpecSize( 4998 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4999 size_t Size = FunctionProtoType::totalSizeToAlloc< 5000 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 5001 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType, 5002 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers, 5003 FunctionEffect, EffectConditionExpr>( 5004 NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(), 5005 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType, 5006 ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 5007 EPI.ExtParameterInfos ? NumArgs : 0, 5008 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, EPI.FunctionEffects.size(), 5009 EPI.FunctionEffects.conditions().size()); 5010 5011 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType)); 5012 FunctionProtoType::ExtProtoInfo newEPI = EPI; 5013 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 5014 Types.push_back(FTP); 5015 if (!Unique) 5016 FunctionProtoTypes.InsertNode(FTP, InsertPos); 5017 if (!EPI.FunctionEffects.empty()) 5018 AnyFunctionEffects = true; 5019 return QualType(FTP, 0); 5020 } 5021 5022 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 5023 llvm::FoldingSetNodeID ID; 5024 PipeType::Profile(ID, T, ReadOnly); 5025 5026 void *InsertPos = nullptr; 5027 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 5028 return QualType(PT, 0); 5029 5030 // If the pipe element type isn't canonical, this won't be a canonical type 5031 // either, so fill in the canonical type field. 5032 QualType Canonical; 5033 if (!T.isCanonical()) { 5034 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 5035 5036 // Get the new insert position for the node we care about. 5037 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 5038 assert(!NewIP && "Shouldn't be in the map!"); 5039 (void)NewIP; 5040 } 5041 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly); 5042 Types.push_back(New); 5043 PipeTypes.InsertNode(New, InsertPos); 5044 return QualType(New, 0); 5045 } 5046 5047 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 5048 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 5049 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 5050 : Ty; 5051 } 5052 5053 QualType ASTContext::getReadPipeType(QualType T) const { 5054 return getPipeType(T, true); 5055 } 5056 5057 QualType ASTContext::getWritePipeType(QualType T) const { 5058 return getPipeType(T, false); 5059 } 5060 5061 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 5062 llvm::FoldingSetNodeID ID; 5063 BitIntType::Profile(ID, IsUnsigned, NumBits); 5064 5065 void *InsertPos = nullptr; 5066 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 5067 return QualType(EIT, 0); 5068 5069 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits); 5070 BitIntTypes.InsertNode(New, InsertPos); 5071 Types.push_back(New); 5072 return QualType(New, 0); 5073 } 5074 5075 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 5076 Expr *NumBitsExpr) const { 5077 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 5078 llvm::FoldingSetNodeID ID; 5079 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 5080 5081 void *InsertPos = nullptr; 5082 if (DependentBitIntType *Existing = 5083 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 5084 return QualType(Existing, 0); 5085 5086 auto *New = new (*this, alignof(DependentBitIntType)) 5087 DependentBitIntType(IsUnsigned, NumBitsExpr); 5088 DependentBitIntTypes.InsertNode(New, InsertPos); 5089 5090 Types.push_back(New); 5091 return QualType(New, 0); 5092 } 5093 5094 #ifndef NDEBUG 5095 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 5096 if (!isa<CXXRecordDecl>(D)) return false; 5097 const auto *RD = cast<CXXRecordDecl>(D); 5098 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 5099 return true; 5100 if (RD->getDescribedClassTemplate() && 5101 !isa<ClassTemplateSpecializationDecl>(RD)) 5102 return true; 5103 return false; 5104 } 5105 #endif 5106 5107 /// getInjectedClassNameType - Return the unique reference to the 5108 /// injected class name type for the specified templated declaration. 5109 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 5110 QualType TST) const { 5111 assert(NeedsInjectedClassNameType(Decl)); 5112 if (Decl->TypeForDecl) { 5113 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 5114 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 5115 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 5116 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5117 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 5118 } else { 5119 Type *newType = new (*this, alignof(InjectedClassNameType)) 5120 InjectedClassNameType(Decl, TST); 5121 Decl->TypeForDecl = newType; 5122 Types.push_back(newType); 5123 } 5124 return QualType(Decl->TypeForDecl, 0); 5125 } 5126 5127 /// getTypeDeclType - Return the unique reference to the type for the 5128 /// specified type declaration. 5129 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 5130 assert(Decl && "Passed null for Decl param"); 5131 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 5132 5133 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 5134 return getTypedefType(Typedef); 5135 5136 assert(!isa<TemplateTypeParmDecl>(Decl) && 5137 "Template type parameter types are always available."); 5138 5139 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 5140 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 5141 assert(!NeedsInjectedClassNameType(Record)); 5142 return getRecordType(Record); 5143 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 5144 assert(Enum->isFirstDecl() && "enum has previous declaration"); 5145 return getEnumType(Enum); 5146 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 5147 return getUnresolvedUsingType(Using); 5148 } else 5149 llvm_unreachable("TypeDecl without a type?"); 5150 5151 return QualType(Decl->TypeForDecl, 0); 5152 } 5153 5154 /// getTypedefType - Return the unique reference to the type for the 5155 /// specified typedef name decl. 5156 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 5157 QualType Underlying) const { 5158 if (!Decl->TypeForDecl) { 5159 if (Underlying.isNull()) 5160 Underlying = Decl->getUnderlyingType(); 5161 auto *NewType = new (*this, alignof(TypedefType)) TypedefType( 5162 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying)); 5163 Decl->TypeForDecl = NewType; 5164 Types.push_back(NewType); 5165 return QualType(NewType, 0); 5166 } 5167 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying) 5168 return QualType(Decl->TypeForDecl, 0); 5169 assert(hasSameType(Decl->getUnderlyingType(), Underlying)); 5170 5171 llvm::FoldingSetNodeID ID; 5172 TypedefType::Profile(ID, Decl, Underlying); 5173 5174 void *InsertPos = nullptr; 5175 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) { 5176 assert(!T->typeMatchesDecl() && 5177 "non-divergent case should be handled with TypeDecl"); 5178 return QualType(T, 0); 5179 } 5180 5181 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true), 5182 alignof(TypedefType)); 5183 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying, 5184 getCanonicalType(Underlying)); 5185 TypedefTypes.InsertNode(NewType, InsertPos); 5186 Types.push_back(NewType); 5187 return QualType(NewType, 0); 5188 } 5189 5190 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 5191 QualType Underlying) const { 5192 llvm::FoldingSetNodeID ID; 5193 UsingType::Profile(ID, Found, Underlying); 5194 5195 void *InsertPos = nullptr; 5196 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos)) 5197 return QualType(T, 0); 5198 5199 const Type *TypeForDecl = 5200 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(); 5201 5202 assert(!Underlying.hasLocalQualifiers()); 5203 QualType Canon = Underlying->getCanonicalTypeInternal(); 5204 assert(TypeForDecl->getCanonicalTypeInternal() == Canon); 5205 5206 if (Underlying.getTypePtr() == TypeForDecl) 5207 Underlying = QualType(); 5208 void *Mem = 5209 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()), 5210 alignof(UsingType)); 5211 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon); 5212 Types.push_back(NewType); 5213 UsingTypes.InsertNode(NewType, InsertPos); 5214 return QualType(NewType, 0); 5215 } 5216 5217 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 5218 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 5219 5220 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 5221 if (PrevDecl->TypeForDecl) 5222 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 5223 5224 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl); 5225 Decl->TypeForDecl = newType; 5226 Types.push_back(newType); 5227 return QualType(newType, 0); 5228 } 5229 5230 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 5231 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 5232 5233 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 5234 if (PrevDecl->TypeForDecl) 5235 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 5236 5237 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl); 5238 Decl->TypeForDecl = newType; 5239 Types.push_back(newType); 5240 return QualType(newType, 0); 5241 } 5242 5243 bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, 5244 unsigned NumPositiveBits, 5245 QualType &BestType, 5246 QualType &BestPromotionType) { 5247 unsigned IntWidth = Target->getIntWidth(); 5248 unsigned CharWidth = Target->getCharWidth(); 5249 unsigned ShortWidth = Target->getShortWidth(); 5250 bool EnumTooLarge = false; 5251 unsigned BestWidth; 5252 if (NumNegativeBits) { 5253 // If there is a negative value, figure out the smallest integer type (of 5254 // int/long/longlong) that fits. 5255 // If it's packed, check also if it fits a char or a short. 5256 if (IsPacked && NumNegativeBits <= CharWidth && 5257 NumPositiveBits < CharWidth) { 5258 BestType = SignedCharTy; 5259 BestWidth = CharWidth; 5260 } else if (IsPacked && NumNegativeBits <= ShortWidth && 5261 NumPositiveBits < ShortWidth) { 5262 BestType = ShortTy; 5263 BestWidth = ShortWidth; 5264 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 5265 BestType = IntTy; 5266 BestWidth = IntWidth; 5267 } else { 5268 BestWidth = Target->getLongWidth(); 5269 5270 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 5271 BestType = LongTy; 5272 } else { 5273 BestWidth = Target->getLongLongWidth(); 5274 5275 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 5276 EnumTooLarge = true; 5277 BestType = LongLongTy; 5278 } 5279 } 5280 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType); 5281 } else { 5282 // If there is no negative value, figure out the smallest type that fits 5283 // all of the enumerator values. 5284 // If it's packed, check also if it fits a char or a short. 5285 if (IsPacked && NumPositiveBits <= CharWidth) { 5286 BestType = UnsignedCharTy; 5287 BestPromotionType = IntTy; 5288 BestWidth = CharWidth; 5289 } else if (IsPacked && NumPositiveBits <= ShortWidth) { 5290 BestType = UnsignedShortTy; 5291 BestPromotionType = IntTy; 5292 BestWidth = ShortWidth; 5293 } else if (NumPositiveBits <= IntWidth) { 5294 BestType = UnsignedIntTy; 5295 BestWidth = IntWidth; 5296 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus) 5297 ? UnsignedIntTy 5298 : IntTy; 5299 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) { 5300 BestType = UnsignedLongTy; 5301 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus) 5302 ? UnsignedLongTy 5303 : LongTy; 5304 } else { 5305 BestWidth = Target->getLongLongWidth(); 5306 if (NumPositiveBits > BestWidth) { 5307 // This can happen with bit-precise integer types, but those are not 5308 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12. 5309 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within 5310 // a 128-bit integer, we should consider doing the same. 5311 EnumTooLarge = true; 5312 } 5313 BestType = UnsignedLongLongTy; 5314 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus) 5315 ? UnsignedLongLongTy 5316 : LongLongTy; 5317 } 5318 } 5319 return EnumTooLarge; 5320 } 5321 5322 QualType ASTContext::getUnresolvedUsingType( 5323 const UnresolvedUsingTypenameDecl *Decl) const { 5324 if (Decl->TypeForDecl) 5325 return QualType(Decl->TypeForDecl, 0); 5326 5327 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 5328 Decl->getCanonicalDecl()) 5329 if (CanonicalDecl->TypeForDecl) 5330 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 5331 5332 Type *newType = 5333 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl); 5334 Decl->TypeForDecl = newType; 5335 Types.push_back(newType); 5336 return QualType(newType, 0); 5337 } 5338 5339 QualType ASTContext::getAttributedType(attr::Kind attrKind, 5340 QualType modifiedType, 5341 QualType equivalentType, 5342 const Attr *attr) const { 5343 llvm::FoldingSetNodeID id; 5344 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr); 5345 5346 void *insertPos = nullptr; 5347 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 5348 if (type) return QualType(type, 0); 5349 5350 assert(!attr || attr->getKind() == attrKind); 5351 5352 QualType canon = getCanonicalType(equivalentType); 5353 type = new (*this, alignof(AttributedType)) 5354 AttributedType(canon, attrKind, attr, modifiedType, equivalentType); 5355 5356 Types.push_back(type); 5357 AttributedTypes.InsertNode(type, insertPos); 5358 5359 return QualType(type, 0); 5360 } 5361 5362 QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType, 5363 QualType equivalentType) const { 5364 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr); 5365 } 5366 5367 QualType ASTContext::getAttributedType(NullabilityKind nullability, 5368 QualType modifiedType, 5369 QualType equivalentType) { 5370 switch (nullability) { 5371 case NullabilityKind::NonNull: 5372 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType); 5373 5374 case NullabilityKind::Nullable: 5375 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType); 5376 5377 case NullabilityKind::NullableResult: 5378 return getAttributedType(attr::TypeNullableResult, modifiedType, 5379 equivalentType); 5380 5381 case NullabilityKind::Unspecified: 5382 return getAttributedType(attr::TypeNullUnspecified, modifiedType, 5383 equivalentType); 5384 } 5385 5386 llvm_unreachable("Unknown nullability kind"); 5387 } 5388 5389 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 5390 QualType Wrapped) const { 5391 llvm::FoldingSetNodeID ID; 5392 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr); 5393 5394 void *InsertPos = nullptr; 5395 BTFTagAttributedType *Ty = 5396 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 5397 if (Ty) 5398 return QualType(Ty, 0); 5399 5400 QualType Canon = getCanonicalType(Wrapped); 5401 Ty = new (*this, alignof(BTFTagAttributedType)) 5402 BTFTagAttributedType(Canon, Wrapped, BTFAttr); 5403 5404 Types.push_back(Ty); 5405 BTFTagAttributedTypes.InsertNode(Ty, InsertPos); 5406 5407 return QualType(Ty, 0); 5408 } 5409 5410 QualType ASTContext::getHLSLAttributedResourceType( 5411 QualType Wrapped, QualType Contained, 5412 const HLSLAttributedResourceType::Attributes &Attrs) { 5413 5414 llvm::FoldingSetNodeID ID; 5415 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs); 5416 5417 void *InsertPos = nullptr; 5418 HLSLAttributedResourceType *Ty = 5419 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos); 5420 if (Ty) 5421 return QualType(Ty, 0); 5422 5423 Ty = new (*this, alignof(HLSLAttributedResourceType)) 5424 HLSLAttributedResourceType(Wrapped, Contained, Attrs); 5425 5426 Types.push_back(Ty); 5427 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos); 5428 5429 return QualType(Ty, 0); 5430 } 5431 /// Retrieve a substitution-result type. 5432 QualType ASTContext::getSubstTemplateTypeParmType( 5433 QualType Replacement, Decl *AssociatedDecl, unsigned Index, 5434 std::optional<unsigned> PackIndex, 5435 SubstTemplateTypeParmTypeFlag Flag) const { 5436 llvm::FoldingSetNodeID ID; 5437 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index, 5438 PackIndex, Flag); 5439 void *InsertPos = nullptr; 5440 SubstTemplateTypeParmType *SubstParm = 5441 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 5442 5443 if (!SubstParm) { 5444 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>( 5445 !Replacement.isCanonical()), 5446 alignof(SubstTemplateTypeParmType)); 5447 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl, 5448 Index, PackIndex, Flag); 5449 Types.push_back(SubstParm); 5450 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 5451 } 5452 5453 return QualType(SubstParm, 0); 5454 } 5455 5456 /// Retrieve a 5457 QualType 5458 ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, 5459 unsigned Index, bool Final, 5460 const TemplateArgument &ArgPack) { 5461 #ifndef NDEBUG 5462 for (const auto &P : ArgPack.pack_elements()) 5463 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type"); 5464 #endif 5465 5466 llvm::FoldingSetNodeID ID; 5467 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final, 5468 ArgPack); 5469 void *InsertPos = nullptr; 5470 if (SubstTemplateTypeParmPackType *SubstParm = 5471 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 5472 return QualType(SubstParm, 0); 5473 5474 QualType Canon; 5475 { 5476 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack); 5477 if (!AssociatedDecl->isCanonicalDecl() || 5478 !CanonArgPack.structurallyEquals(ArgPack)) { 5479 Canon = getSubstTemplateTypeParmPackType( 5480 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack); 5481 [[maybe_unused]] const auto *Nothing = 5482 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 5483 assert(!Nothing); 5484 } 5485 } 5486 5487 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType)) 5488 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final, 5489 ArgPack); 5490 Types.push_back(SubstParm); 5491 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 5492 return QualType(SubstParm, 0); 5493 } 5494 5495 /// Retrieve the template type parameter type for a template 5496 /// parameter or parameter pack with the given depth, index, and (optionally) 5497 /// name. 5498 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 5499 bool ParameterPack, 5500 TemplateTypeParmDecl *TTPDecl) const { 5501 llvm::FoldingSetNodeID ID; 5502 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 5503 void *InsertPos = nullptr; 5504 TemplateTypeParmType *TypeParm 5505 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 5506 5507 if (TypeParm) 5508 return QualType(TypeParm, 0); 5509 5510 if (TTPDecl) { 5511 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 5512 TypeParm = new (*this, alignof(TemplateTypeParmType)) 5513 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon); 5514 5515 TemplateTypeParmType *TypeCheck 5516 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 5517 assert(!TypeCheck && "Template type parameter canonical type broken"); 5518 (void)TypeCheck; 5519 } else 5520 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType( 5521 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType()); 5522 5523 Types.push_back(TypeParm); 5524 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 5525 5526 return QualType(TypeParm, 0); 5527 } 5528 5529 TypeSourceInfo * 5530 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 5531 SourceLocation NameLoc, 5532 const TemplateArgumentListInfo &Args, 5533 QualType Underlying) const { 5534 assert(!Name.getAsDependentTemplateName() && 5535 "No dependent template names here!"); 5536 QualType TST = 5537 getTemplateSpecializationType(Name, Args.arguments(), Underlying); 5538 5539 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 5540 TemplateSpecializationTypeLoc TL = 5541 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 5542 TL.setTemplateKeywordLoc(SourceLocation()); 5543 TL.setTemplateNameLoc(NameLoc); 5544 TL.setLAngleLoc(Args.getLAngleLoc()); 5545 TL.setRAngleLoc(Args.getRAngleLoc()); 5546 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 5547 TL.setArgLocInfo(i, Args[i].getLocInfo()); 5548 return DI; 5549 } 5550 5551 QualType 5552 ASTContext::getTemplateSpecializationType(TemplateName Template, 5553 ArrayRef<TemplateArgumentLoc> Args, 5554 QualType Underlying) const { 5555 assert(!Template.getAsDependentTemplateName() && 5556 "No dependent template names here!"); 5557 5558 SmallVector<TemplateArgument, 4> ArgVec; 5559 ArgVec.reserve(Args.size()); 5560 for (const TemplateArgumentLoc &Arg : Args) 5561 ArgVec.push_back(Arg.getArgument()); 5562 5563 return getTemplateSpecializationType(Template, ArgVec, Underlying); 5564 } 5565 5566 #ifndef NDEBUG 5567 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 5568 for (const TemplateArgument &Arg : Args) 5569 if (Arg.isPackExpansion()) 5570 return true; 5571 5572 return true; 5573 } 5574 #endif 5575 5576 QualType 5577 ASTContext::getTemplateSpecializationType(TemplateName Template, 5578 ArrayRef<TemplateArgument> Args, 5579 QualType Underlying) const { 5580 assert(!Template.getAsDependentTemplateName() && 5581 "No dependent template names here!"); 5582 5583 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true); 5584 bool IsTypeAlias = TD && TD->isTypeAlias(); 5585 QualType CanonType; 5586 if (!Underlying.isNull()) 5587 CanonType = getCanonicalType(Underlying); 5588 else { 5589 // We can get here with an alias template when the specialization contains 5590 // a pack expansion that does not match up with a parameter pack. 5591 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 5592 "Caller must compute aliased type"); 5593 IsTypeAlias = false; 5594 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 5595 } 5596 5597 // Allocate the (non-canonical) template specialization type, but don't 5598 // try to unique it: these types typically have location information that 5599 // we don't unique and don't want to lose. 5600 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 5601 sizeof(TemplateArgument) * Args.size() + 5602 (IsTypeAlias ? sizeof(QualType) : 0), 5603 alignof(TemplateSpecializationType)); 5604 auto *Spec 5605 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 5606 IsTypeAlias ? Underlying : QualType()); 5607 5608 Types.push_back(Spec); 5609 return QualType(Spec, 0); 5610 } 5611 5612 QualType ASTContext::getCanonicalTemplateSpecializationType( 5613 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 5614 assert(!Template.getAsDependentTemplateName() && 5615 "No dependent template names here!"); 5616 5617 // Build the canonical template specialization type. 5618 // Any DeducedTemplateNames are ignored, because the effective name of a TST 5619 // accounts for the TST arguments laid over any default arguments contained in 5620 // its name. 5621 TemplateName CanonTemplate = 5622 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true); 5623 5624 bool AnyNonCanonArgs = false; 5625 auto CanonArgs = 5626 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs); 5627 5628 // Determine whether this canonical template specialization type already 5629 // exists. 5630 llvm::FoldingSetNodeID ID; 5631 TemplateSpecializationType::Profile(ID, CanonTemplate, 5632 CanonArgs, *this); 5633 5634 void *InsertPos = nullptr; 5635 TemplateSpecializationType *Spec 5636 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5637 5638 if (!Spec) { 5639 // Allocate a new canonical template specialization type. 5640 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 5641 sizeof(TemplateArgument) * CanonArgs.size()), 5642 alignof(TemplateSpecializationType)); 5643 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 5644 CanonArgs, 5645 QualType(), QualType()); 5646 Types.push_back(Spec); 5647 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 5648 } 5649 5650 assert(Spec->isDependentType() && 5651 "Non-dependent template-id type must have a canonical type"); 5652 return QualType(Spec, 0); 5653 } 5654 5655 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 5656 NestedNameSpecifier *NNS, 5657 QualType NamedType, 5658 TagDecl *OwnedTagDecl) const { 5659 llvm::FoldingSetNodeID ID; 5660 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 5661 5662 void *InsertPos = nullptr; 5663 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 5664 if (T) 5665 return QualType(T, 0); 5666 5667 QualType Canon = NamedType; 5668 if (!Canon.isCanonical()) { 5669 Canon = getCanonicalType(NamedType); 5670 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 5671 assert(!CheckT && "Elaborated canonical type broken"); 5672 (void)CheckT; 5673 } 5674 5675 void *Mem = 5676 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 5677 alignof(ElaboratedType)); 5678 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 5679 5680 Types.push_back(T); 5681 ElaboratedTypes.InsertNode(T, InsertPos); 5682 return QualType(T, 0); 5683 } 5684 5685 QualType 5686 ASTContext::getParenType(QualType InnerType) const { 5687 llvm::FoldingSetNodeID ID; 5688 ParenType::Profile(ID, InnerType); 5689 5690 void *InsertPos = nullptr; 5691 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 5692 if (T) 5693 return QualType(T, 0); 5694 5695 QualType Canon = InnerType; 5696 if (!Canon.isCanonical()) { 5697 Canon = getCanonicalType(InnerType); 5698 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 5699 assert(!CheckT && "Paren canonical type broken"); 5700 (void)CheckT; 5701 } 5702 5703 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon); 5704 Types.push_back(T); 5705 ParenTypes.InsertNode(T, InsertPos); 5706 return QualType(T, 0); 5707 } 5708 5709 QualType 5710 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 5711 const IdentifierInfo *MacroII) const { 5712 QualType Canon = UnderlyingTy; 5713 if (!Canon.isCanonical()) 5714 Canon = getCanonicalType(UnderlyingTy); 5715 5716 auto *newType = new (*this, alignof(MacroQualifiedType)) 5717 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 5718 Types.push_back(newType); 5719 return QualType(newType, 0); 5720 } 5721 5722 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 5723 NestedNameSpecifier *NNS, 5724 const IdentifierInfo *Name, 5725 QualType Canon) const { 5726 if (Canon.isNull()) { 5727 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5728 if (CanonNNS != NNS) 5729 Canon = getDependentNameType(Keyword, CanonNNS, Name); 5730 } 5731 5732 llvm::FoldingSetNodeID ID; 5733 DependentNameType::Profile(ID, Keyword, NNS, Name); 5734 5735 void *InsertPos = nullptr; 5736 DependentNameType *T 5737 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5738 if (T) 5739 return QualType(T, 0); 5740 5741 T = new (*this, alignof(DependentNameType)) 5742 DependentNameType(Keyword, NNS, Name, Canon); 5743 Types.push_back(T); 5744 DependentNameTypes.InsertNode(T, InsertPos); 5745 return QualType(T, 0); 5746 } 5747 5748 QualType ASTContext::getDependentTemplateSpecializationType( 5749 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 5750 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const { 5751 // TODO: avoid this copy 5752 SmallVector<TemplateArgument, 16> ArgCopy; 5753 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5754 ArgCopy.push_back(Args[I].getArgument()); 5755 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5756 } 5757 5758 QualType 5759 ASTContext::getDependentTemplateSpecializationType( 5760 ElaboratedTypeKeyword Keyword, 5761 NestedNameSpecifier *NNS, 5762 const IdentifierInfo *Name, 5763 ArrayRef<TemplateArgument> Args) const { 5764 assert((!NNS || NNS->isDependent()) && 5765 "nested-name-specifier must be dependent"); 5766 5767 llvm::FoldingSetNodeID ID; 5768 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5769 Name, Args); 5770 5771 void *InsertPos = nullptr; 5772 DependentTemplateSpecializationType *T 5773 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5774 if (T) 5775 return QualType(T, 0); 5776 5777 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5778 5779 ElaboratedTypeKeyword CanonKeyword = Keyword; 5780 if (Keyword == ElaboratedTypeKeyword::None) 5781 CanonKeyword = ElaboratedTypeKeyword::Typename; 5782 5783 bool AnyNonCanonArgs = false; 5784 auto CanonArgs = 5785 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs); 5786 5787 QualType Canon; 5788 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5789 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5790 Name, 5791 CanonArgs); 5792 5793 // Find the insert position again. 5794 [[maybe_unused]] auto *Nothing = 5795 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5796 assert(!Nothing && "canonical type broken"); 5797 } 5798 5799 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5800 sizeof(TemplateArgument) * Args.size()), 5801 alignof(DependentTemplateSpecializationType)); 5802 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5803 Name, Args, Canon); 5804 Types.push_back(T); 5805 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5806 return QualType(T, 0); 5807 } 5808 5809 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const { 5810 TemplateArgument Arg; 5811 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5812 QualType ArgType = getTypeDeclType(TTP); 5813 if (TTP->isParameterPack()) 5814 ArgType = getPackExpansionType(ArgType, std::nullopt); 5815 5816 Arg = TemplateArgument(ArgType); 5817 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5818 QualType T = 5819 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5820 // For class NTTPs, ensure we include the 'const' so the type matches that 5821 // of a real template argument. 5822 // FIXME: It would be more faithful to model this as something like an 5823 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5824 ExprValueKind VK; 5825 if (T->isRecordType()) { 5826 // C++ [temp.param]p8: An id-expression naming a non-type 5827 // template-parameter of class type T denotes a static storage duration 5828 // object of type const T. 5829 T.addConst(); 5830 VK = VK_LValue; 5831 } else { 5832 VK = Expr::getValueKindForType(NTTP->getType()); 5833 } 5834 Expr *E = new (*this) 5835 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false, 5836 T, VK, NTTP->getLocation()); 5837 5838 if (NTTP->isParameterPack()) 5839 E = new (*this) 5840 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt); 5841 Arg = TemplateArgument(E); 5842 } else { 5843 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5844 TemplateName Name = getQualifiedTemplateName( 5845 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP)); 5846 if (TTP->isParameterPack()) 5847 Arg = TemplateArgument(Name, std::optional<unsigned>()); 5848 else 5849 Arg = TemplateArgument(Name); 5850 } 5851 5852 if (Param->isTemplateParameterPack()) 5853 Arg = 5854 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg); 5855 5856 return Arg; 5857 } 5858 5859 QualType ASTContext::getPackExpansionType(QualType Pattern, 5860 std::optional<unsigned> NumExpansions, 5861 bool ExpectPackInType) const { 5862 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5863 "Pack expansions must expand one or more parameter packs"); 5864 5865 llvm::FoldingSetNodeID ID; 5866 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5867 5868 void *InsertPos = nullptr; 5869 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5870 if (T) 5871 return QualType(T, 0); 5872 5873 QualType Canon; 5874 if (!Pattern.isCanonical()) { 5875 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5876 /*ExpectPackInType=*/false); 5877 5878 // Find the insert position again, in case we inserted an element into 5879 // PackExpansionTypes and invalidated our insert position. 5880 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5881 } 5882 5883 T = new (*this, alignof(PackExpansionType)) 5884 PackExpansionType(Pattern, Canon, NumExpansions); 5885 Types.push_back(T); 5886 PackExpansionTypes.InsertNode(T, InsertPos); 5887 return QualType(T, 0); 5888 } 5889 5890 /// CmpProtocolNames - Comparison predicate for sorting protocols 5891 /// alphabetically. 5892 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5893 ObjCProtocolDecl *const *RHS) { 5894 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5895 } 5896 5897 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5898 if (Protocols.empty()) return true; 5899 5900 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5901 return false; 5902 5903 for (unsigned i = 1; i != Protocols.size(); ++i) 5904 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5905 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5906 return false; 5907 return true; 5908 } 5909 5910 static void 5911 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5912 // Sort protocols, keyed by name. 5913 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5914 5915 // Canonicalize. 5916 for (ObjCProtocolDecl *&P : Protocols) 5917 P = P->getCanonicalDecl(); 5918 5919 // Remove duplicates. 5920 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5921 Protocols.erase(ProtocolsEnd, Protocols.end()); 5922 } 5923 5924 QualType ASTContext::getObjCObjectType(QualType BaseType, 5925 ObjCProtocolDecl * const *Protocols, 5926 unsigned NumProtocols) const { 5927 return getObjCObjectType(BaseType, {}, 5928 llvm::ArrayRef(Protocols, NumProtocols), 5929 /*isKindOf=*/false); 5930 } 5931 5932 QualType ASTContext::getObjCObjectType( 5933 QualType baseType, 5934 ArrayRef<QualType> typeArgs, 5935 ArrayRef<ObjCProtocolDecl *> protocols, 5936 bool isKindOf) const { 5937 // If the base type is an interface and there aren't any protocols or 5938 // type arguments to add, then the interface type will do just fine. 5939 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5940 isa<ObjCInterfaceType>(baseType)) 5941 return baseType; 5942 5943 // Look in the folding set for an existing type. 5944 llvm::FoldingSetNodeID ID; 5945 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5946 void *InsertPos = nullptr; 5947 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5948 return QualType(QT, 0); 5949 5950 // Determine the type arguments to be used for canonicalization, 5951 // which may be explicitly specified here or written on the base 5952 // type. 5953 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5954 if (effectiveTypeArgs.empty()) { 5955 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5956 effectiveTypeArgs = baseObject->getTypeArgs(); 5957 } 5958 5959 // Build the canonical type, which has the canonical base type and a 5960 // sorted-and-uniqued list of protocols and the type arguments 5961 // canonicalized. 5962 QualType canonical; 5963 bool typeArgsAreCanonical = llvm::all_of( 5964 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5965 bool protocolsSorted = areSortedAndUniqued(protocols); 5966 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5967 // Determine the canonical type arguments. 5968 ArrayRef<QualType> canonTypeArgs; 5969 SmallVector<QualType, 4> canonTypeArgsVec; 5970 if (!typeArgsAreCanonical) { 5971 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5972 for (auto typeArg : effectiveTypeArgs) 5973 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5974 canonTypeArgs = canonTypeArgsVec; 5975 } else { 5976 canonTypeArgs = effectiveTypeArgs; 5977 } 5978 5979 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5980 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5981 if (!protocolsSorted) { 5982 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5983 SortAndUniqueProtocols(canonProtocolsVec); 5984 canonProtocols = canonProtocolsVec; 5985 } else { 5986 canonProtocols = protocols; 5987 } 5988 5989 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5990 canonProtocols, isKindOf); 5991 5992 // Regenerate InsertPos. 5993 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5994 } 5995 5996 unsigned size = sizeof(ObjCObjectTypeImpl); 5997 size += typeArgs.size() * sizeof(QualType); 5998 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5999 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl)); 6000 auto *T = 6001 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 6002 isKindOf); 6003 6004 Types.push_back(T); 6005 ObjCObjectTypes.InsertNode(T, InsertPos); 6006 return QualType(T, 0); 6007 } 6008 6009 /// Apply Objective-C protocol qualifiers to the given type. 6010 /// If this is for the canonical type of a type parameter, we can apply 6011 /// protocol qualifiers on the ObjCObjectPointerType. 6012 QualType 6013 ASTContext::applyObjCProtocolQualifiers(QualType type, 6014 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 6015 bool allowOnPointerType) const { 6016 hasError = false; 6017 6018 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 6019 return getObjCTypeParamType(objT->getDecl(), protocols); 6020 } 6021 6022 // Apply protocol qualifiers to ObjCObjectPointerType. 6023 if (allowOnPointerType) { 6024 if (const auto *objPtr = 6025 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 6026 const ObjCObjectType *objT = objPtr->getObjectType(); 6027 // Merge protocol lists and construct ObjCObjectType. 6028 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 6029 protocolsVec.append(objT->qual_begin(), 6030 objT->qual_end()); 6031 protocolsVec.append(protocols.begin(), protocols.end()); 6032 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 6033 type = getObjCObjectType( 6034 objT->getBaseType(), 6035 objT->getTypeArgsAsWritten(), 6036 protocols, 6037 objT->isKindOfTypeAsWritten()); 6038 return getObjCObjectPointerType(type); 6039 } 6040 } 6041 6042 // Apply protocol qualifiers to ObjCObjectType. 6043 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 6044 // FIXME: Check for protocols to which the class type is already 6045 // known to conform. 6046 6047 return getObjCObjectType(objT->getBaseType(), 6048 objT->getTypeArgsAsWritten(), 6049 protocols, 6050 objT->isKindOfTypeAsWritten()); 6051 } 6052 6053 // If the canonical type is ObjCObjectType, ... 6054 if (type->isObjCObjectType()) { 6055 // Silently overwrite any existing protocol qualifiers. 6056 // TODO: determine whether that's the right thing to do. 6057 6058 // FIXME: Check for protocols to which the class type is already 6059 // known to conform. 6060 return getObjCObjectType(type, {}, protocols, false); 6061 } 6062 6063 // id<protocol-list> 6064 if (type->isObjCIdType()) { 6065 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 6066 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 6067 objPtr->isKindOfType()); 6068 return getObjCObjectPointerType(type); 6069 } 6070 6071 // Class<protocol-list> 6072 if (type->isObjCClassType()) { 6073 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 6074 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 6075 objPtr->isKindOfType()); 6076 return getObjCObjectPointerType(type); 6077 } 6078 6079 hasError = true; 6080 return type; 6081 } 6082 6083 QualType 6084 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 6085 ArrayRef<ObjCProtocolDecl *> protocols) const { 6086 // Look in the folding set for an existing type. 6087 llvm::FoldingSetNodeID ID; 6088 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 6089 void *InsertPos = nullptr; 6090 if (ObjCTypeParamType *TypeParam = 6091 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 6092 return QualType(TypeParam, 0); 6093 6094 // We canonicalize to the underlying type. 6095 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 6096 if (!protocols.empty()) { 6097 // Apply the protocol qualifers. 6098 bool hasError; 6099 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 6100 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 6101 assert(!hasError && "Error when apply protocol qualifier to bound type"); 6102 } 6103 6104 unsigned size = sizeof(ObjCTypeParamType); 6105 size += protocols.size() * sizeof(ObjCProtocolDecl *); 6106 void *mem = Allocate(size, alignof(ObjCTypeParamType)); 6107 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 6108 6109 Types.push_back(newType); 6110 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 6111 return QualType(newType, 0); 6112 } 6113 6114 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 6115 ObjCTypeParamDecl *New) const { 6116 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 6117 // Update TypeForDecl after updating TypeSourceInfo. 6118 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 6119 SmallVector<ObjCProtocolDecl *, 8> protocols; 6120 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 6121 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 6122 New->setTypeForDecl(UpdatedTy.getTypePtr()); 6123 } 6124 6125 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 6126 /// protocol list adopt all protocols in QT's qualified-id protocol 6127 /// list. 6128 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 6129 ObjCInterfaceDecl *IC) { 6130 if (!QT->isObjCQualifiedIdType()) 6131 return false; 6132 6133 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 6134 // If both the right and left sides have qualifiers. 6135 for (auto *Proto : OPT->quals()) { 6136 if (!IC->ClassImplementsProtocol(Proto, false)) 6137 return false; 6138 } 6139 return true; 6140 } 6141 return false; 6142 } 6143 6144 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 6145 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 6146 /// of protocols. 6147 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 6148 ObjCInterfaceDecl *IDecl) { 6149 if (!QT->isObjCQualifiedIdType()) 6150 return false; 6151 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 6152 if (!OPT) 6153 return false; 6154 if (!IDecl->hasDefinition()) 6155 return false; 6156 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 6157 CollectInheritedProtocols(IDecl, InheritedProtocols); 6158 if (InheritedProtocols.empty()) 6159 return false; 6160 // Check that if every protocol in list of id<plist> conforms to a protocol 6161 // of IDecl's, then bridge casting is ok. 6162 bool Conforms = false; 6163 for (auto *Proto : OPT->quals()) { 6164 Conforms = false; 6165 for (auto *PI : InheritedProtocols) { 6166 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 6167 Conforms = true; 6168 break; 6169 } 6170 } 6171 if (!Conforms) 6172 break; 6173 } 6174 if (Conforms) 6175 return true; 6176 6177 for (auto *PI : InheritedProtocols) { 6178 // If both the right and left sides have qualifiers. 6179 bool Adopts = false; 6180 for (auto *Proto : OPT->quals()) { 6181 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 6182 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 6183 break; 6184 } 6185 if (!Adopts) 6186 return false; 6187 } 6188 return true; 6189 } 6190 6191 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 6192 /// the given object type. 6193 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 6194 llvm::FoldingSetNodeID ID; 6195 ObjCObjectPointerType::Profile(ID, ObjectT); 6196 6197 void *InsertPos = nullptr; 6198 if (ObjCObjectPointerType *QT = 6199 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 6200 return QualType(QT, 0); 6201 6202 // Find the canonical object type. 6203 QualType Canonical; 6204 if (!ObjectT.isCanonical()) { 6205 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 6206 6207 // Regenerate InsertPos. 6208 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 6209 } 6210 6211 // No match. 6212 void *Mem = 6213 Allocate(sizeof(ObjCObjectPointerType), alignof(ObjCObjectPointerType)); 6214 auto *QType = 6215 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 6216 6217 Types.push_back(QType); 6218 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 6219 return QualType(QType, 0); 6220 } 6221 6222 /// getObjCInterfaceType - Return the unique reference to the type for the 6223 /// specified ObjC interface decl. The list of protocols is optional. 6224 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 6225 ObjCInterfaceDecl *PrevDecl) const { 6226 if (Decl->TypeForDecl) 6227 return QualType(Decl->TypeForDecl, 0); 6228 6229 if (PrevDecl) { 6230 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 6231 Decl->TypeForDecl = PrevDecl->TypeForDecl; 6232 return QualType(PrevDecl->TypeForDecl, 0); 6233 } 6234 6235 // Prefer the definition, if there is one. 6236 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 6237 Decl = Def; 6238 6239 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType)); 6240 auto *T = new (Mem) ObjCInterfaceType(Decl); 6241 Decl->TypeForDecl = T; 6242 Types.push_back(T); 6243 return QualType(T, 0); 6244 } 6245 6246 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 6247 /// TypeOfExprType AST's (since expression's are never shared). For example, 6248 /// multiple declarations that refer to "typeof(x)" all contain different 6249 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 6250 /// on canonical type's (which are always unique). 6251 QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const { 6252 TypeOfExprType *toe; 6253 if (tofExpr->isTypeDependent()) { 6254 llvm::FoldingSetNodeID ID; 6255 DependentTypeOfExprType::Profile(ID, *this, tofExpr, 6256 Kind == TypeOfKind::Unqualified); 6257 6258 void *InsertPos = nullptr; 6259 DependentTypeOfExprType *Canon = 6260 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 6261 if (Canon) { 6262 // We already have a "canonical" version of an identical, dependent 6263 // typeof(expr) type. Use that as our canonical type. 6264 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType( 6265 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0)); 6266 } else { 6267 // Build a new, canonical typeof(expr) type. 6268 Canon = new (*this, alignof(DependentTypeOfExprType)) 6269 DependentTypeOfExprType(*this, tofExpr, Kind); 6270 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 6271 toe = Canon; 6272 } 6273 } else { 6274 QualType Canonical = getCanonicalType(tofExpr->getType()); 6275 toe = new (*this, alignof(TypeOfExprType)) 6276 TypeOfExprType(*this, tofExpr, Kind, Canonical); 6277 } 6278 Types.push_back(toe); 6279 return QualType(toe, 0); 6280 } 6281 6282 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 6283 /// TypeOfType nodes. The only motivation to unique these nodes would be 6284 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 6285 /// an issue. This doesn't affect the type checker, since it operates 6286 /// on canonical types (which are always unique). 6287 QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const { 6288 QualType Canonical = getCanonicalType(tofType); 6289 auto *tot = new (*this, alignof(TypeOfType)) 6290 TypeOfType(*this, tofType, Canonical, Kind); 6291 Types.push_back(tot); 6292 return QualType(tot, 0); 6293 } 6294 6295 /// getReferenceQualifiedType - Given an expr, will return the type for 6296 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 6297 /// and class member access into account. 6298 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 6299 // C++11 [dcl.type.simple]p4: 6300 // [...] 6301 QualType T = E->getType(); 6302 switch (E->getValueKind()) { 6303 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 6304 // type of e; 6305 case VK_XValue: 6306 return getRValueReferenceType(T); 6307 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 6308 // type of e; 6309 case VK_LValue: 6310 return getLValueReferenceType(T); 6311 // - otherwise, decltype(e) is the type of e. 6312 case VK_PRValue: 6313 return T; 6314 } 6315 llvm_unreachable("Unknown value kind"); 6316 } 6317 6318 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 6319 /// nodes. This would never be helpful, since each such type has its own 6320 /// expression, and would not give a significant memory saving, since there 6321 /// is an Expr tree under each such type. 6322 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 6323 DecltypeType *dt; 6324 6325 // C++11 [temp.type]p2: 6326 // If an expression e involves a template parameter, decltype(e) denotes a 6327 // unique dependent type. Two such decltype-specifiers refer to the same 6328 // type only if their expressions are equivalent (14.5.6.1). 6329 if (e->isInstantiationDependent()) { 6330 llvm::FoldingSetNodeID ID; 6331 DependentDecltypeType::Profile(ID, *this, e); 6332 6333 void *InsertPos = nullptr; 6334 DependentDecltypeType *Canon 6335 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 6336 if (!Canon) { 6337 // Build a new, canonical decltype(expr) type. 6338 Canon = new (*this, alignof(DependentDecltypeType)) 6339 DependentDecltypeType(e, DependentTy); 6340 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 6341 } 6342 dt = new (*this, alignof(DecltypeType)) 6343 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 6344 } else { 6345 dt = new (*this, alignof(DecltypeType)) 6346 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 6347 } 6348 Types.push_back(dt); 6349 return QualType(dt, 0); 6350 } 6351 6352 QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr, 6353 bool FullySubstituted, 6354 ArrayRef<QualType> Expansions, 6355 int Index) const { 6356 QualType Canonical; 6357 if (FullySubstituted && Index != -1) { 6358 Canonical = getCanonicalType(Expansions[Index]); 6359 } else { 6360 llvm::FoldingSetNodeID ID; 6361 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr, 6362 FullySubstituted); 6363 void *InsertPos = nullptr; 6364 PackIndexingType *Canon = 6365 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos); 6366 if (!Canon) { 6367 void *Mem = Allocate( 6368 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()), 6369 TypeAlignment); 6370 Canon = new (Mem) 6371 PackIndexingType(*this, QualType(), Pattern.getCanonicalType(), 6372 IndexExpr, FullySubstituted, Expansions); 6373 DependentPackIndexingTypes.InsertNode(Canon, InsertPos); 6374 } 6375 Canonical = QualType(Canon, 0); 6376 } 6377 6378 void *Mem = 6379 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()), 6380 TypeAlignment); 6381 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr, 6382 FullySubstituted, Expansions); 6383 Types.push_back(T); 6384 return QualType(T, 0); 6385 } 6386 6387 /// getUnaryTransformationType - We don't unique these, since the memory 6388 /// savings are minimal and these are rare. 6389 QualType ASTContext::getUnaryTransformType(QualType BaseType, 6390 QualType UnderlyingType, 6391 UnaryTransformType::UTTKind Kind) 6392 const { 6393 UnaryTransformType *ut = nullptr; 6394 6395 if (BaseType->isDependentType()) { 6396 // Look in the folding set for an existing type. 6397 llvm::FoldingSetNodeID ID; 6398 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 6399 6400 void *InsertPos = nullptr; 6401 DependentUnaryTransformType *Canon 6402 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 6403 6404 if (!Canon) { 6405 // Build a new, canonical __underlying_type(type) type. 6406 Canon = new (*this, alignof(DependentUnaryTransformType)) 6407 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind); 6408 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 6409 } 6410 ut = new (*this, alignof(UnaryTransformType)) 6411 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0)); 6412 } else { 6413 QualType CanonType = getCanonicalType(UnderlyingType); 6414 ut = new (*this, alignof(UnaryTransformType)) 6415 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType); 6416 } 6417 Types.push_back(ut); 6418 return QualType(ut, 0); 6419 } 6420 6421 QualType ASTContext::getAutoTypeInternal( 6422 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 6423 bool IsPack, ConceptDecl *TypeConstraintConcept, 6424 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 6425 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 6426 !TypeConstraintConcept && !IsDependent) 6427 return getAutoDeductType(); 6428 6429 // Look in the folding set for an existing type. 6430 llvm::FoldingSetNodeID ID; 6431 bool IsDeducedDependent = 6432 !DeducedType.isNull() && DeducedType->isDependentType(); 6433 AutoType::Profile(ID, *this, DeducedType, Keyword, 6434 IsDependent || IsDeducedDependent, TypeConstraintConcept, 6435 TypeConstraintArgs); 6436 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end()) 6437 return QualType(AT_iter->getSecond(), 0); 6438 6439 QualType Canon; 6440 if (!IsCanon) { 6441 if (!DeducedType.isNull()) { 6442 Canon = DeducedType.getCanonicalType(); 6443 } else if (TypeConstraintConcept) { 6444 bool AnyNonCanonArgs = false; 6445 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl(); 6446 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments( 6447 *this, TypeConstraintArgs, AnyNonCanonArgs); 6448 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) { 6449 Canon = 6450 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 6451 CanonicalConcept, CanonicalConceptArgs, true); 6452 } 6453 } 6454 } 6455 6456 void *Mem = Allocate(sizeof(AutoType) + 6457 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 6458 alignof(AutoType)); 6459 auto *AT = new (Mem) AutoType( 6460 DeducedType, Keyword, 6461 (IsDependent ? TypeDependence::DependentInstantiation 6462 : TypeDependence::None) | 6463 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 6464 Canon, TypeConstraintConcept, TypeConstraintArgs); 6465 #ifndef NDEBUG 6466 llvm::FoldingSetNodeID InsertedID; 6467 AT->Profile(InsertedID, *this); 6468 assert(InsertedID == ID && "ID does not match"); 6469 #endif 6470 Types.push_back(AT); 6471 AutoTypes.try_emplace(ID, AT); 6472 return QualType(AT, 0); 6473 } 6474 6475 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 6476 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 6477 /// canonical deduced-but-dependent 'auto' type. 6478 QualType 6479 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 6480 bool IsDependent, bool IsPack, 6481 ConceptDecl *TypeConstraintConcept, 6482 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 6483 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 6484 assert((!IsDependent || DeducedType.isNull()) && 6485 "A dependent auto should be undeduced"); 6486 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 6487 TypeConstraintConcept, TypeConstraintArgs); 6488 } 6489 6490 QualType ASTContext::getUnconstrainedType(QualType T) const { 6491 QualType CanonT = T.getNonPackExpansionType().getCanonicalType(); 6492 6493 // Remove a type-constraint from a top-level auto or decltype(auto). 6494 if (auto *AT = CanonT->getAs<AutoType>()) { 6495 if (!AT->isConstrained()) 6496 return T; 6497 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(), 6498 AT->isDependentType(), 6499 AT->containsUnexpandedParameterPack()), 6500 T.getQualifiers()); 6501 } 6502 6503 // FIXME: We only support constrained auto at the top level in the type of a 6504 // non-type template parameter at the moment. Once we lift that restriction, 6505 // we'll need to recursively build types containing auto here. 6506 assert(!CanonT->getContainedAutoType() || 6507 !CanonT->getContainedAutoType()->isConstrained()); 6508 return T; 6509 } 6510 6511 QualType ASTContext::getDeducedTemplateSpecializationTypeInternal( 6512 TemplateName Template, QualType DeducedType, bool IsDependent, 6513 QualType Canon) const { 6514 // Look in the folding set for an existing type. 6515 void *InsertPos = nullptr; 6516 llvm::FoldingSetNodeID ID; 6517 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 6518 IsDependent); 6519 if (DeducedTemplateSpecializationType *DTST = 6520 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 6521 return QualType(DTST, 0); 6522 6523 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType)) 6524 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent, 6525 Canon); 6526 llvm::FoldingSetNodeID TempID; 6527 DTST->Profile(TempID); 6528 assert(ID == TempID && "ID does not match"); 6529 Types.push_back(DTST); 6530 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 6531 return QualType(DTST, 0); 6532 } 6533 6534 /// Return the uniqued reference to the deduced template specialization type 6535 /// which has been deduced to the given type, or to the canonical undeduced 6536 /// such type, or the canonical deduced-but-dependent such type. 6537 QualType ASTContext::getDeducedTemplateSpecializationType( 6538 TemplateName Template, QualType DeducedType, bool IsDependent) const { 6539 QualType Canon = DeducedType.isNull() 6540 ? getDeducedTemplateSpecializationTypeInternal( 6541 getCanonicalTemplateName(Template), QualType(), 6542 IsDependent, QualType()) 6543 : DeducedType.getCanonicalType(); 6544 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType, 6545 IsDependent, Canon); 6546 } 6547 6548 /// getAtomicType - Return the uniqued reference to the atomic type for 6549 /// the given value type. 6550 QualType ASTContext::getAtomicType(QualType T) const { 6551 // Unique pointers, to guarantee there is only one pointer of a particular 6552 // structure. 6553 llvm::FoldingSetNodeID ID; 6554 AtomicType::Profile(ID, T); 6555 6556 void *InsertPos = nullptr; 6557 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 6558 return QualType(AT, 0); 6559 6560 // If the atomic value type isn't canonical, this won't be a canonical type 6561 // either, so fill in the canonical type field. 6562 QualType Canonical; 6563 if (!T.isCanonical()) { 6564 Canonical = getAtomicType(getCanonicalType(T)); 6565 6566 // Get the new insert position for the node we care about. 6567 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 6568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 6569 } 6570 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical); 6571 Types.push_back(New); 6572 AtomicTypes.InsertNode(New, InsertPos); 6573 return QualType(New, 0); 6574 } 6575 6576 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 6577 QualType ASTContext::getAutoDeductType() const { 6578 if (AutoDeductTy.isNull()) 6579 AutoDeductTy = QualType(new (*this, alignof(AutoType)) 6580 AutoType(QualType(), AutoTypeKeyword::Auto, 6581 TypeDependence::None, QualType(), 6582 /*concept*/ nullptr, /*args*/ {}), 6583 0); 6584 return AutoDeductTy; 6585 } 6586 6587 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 6588 QualType ASTContext::getAutoRRefDeductType() const { 6589 if (AutoRRefDeductTy.isNull()) 6590 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 6591 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 6592 return AutoRRefDeductTy; 6593 } 6594 6595 /// getTagDeclType - Return the unique reference to the type for the 6596 /// specified TagDecl (struct/union/class/enum) decl. 6597 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 6598 assert(Decl); 6599 // FIXME: What is the design on getTagDeclType when it requires casting 6600 // away const? mutable? 6601 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 6602 } 6603 6604 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 6605 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 6606 /// needs to agree with the definition in <stddef.h>. 6607 CanQualType ASTContext::getSizeType() const { 6608 return getFromTargetType(Target->getSizeType()); 6609 } 6610 6611 /// Return the unique signed counterpart of the integer type 6612 /// corresponding to size_t. 6613 CanQualType ASTContext::getSignedSizeType() const { 6614 return getFromTargetType(Target->getSignedSizeType()); 6615 } 6616 6617 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 6618 CanQualType ASTContext::getIntMaxType() const { 6619 return getFromTargetType(Target->getIntMaxType()); 6620 } 6621 6622 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 6623 CanQualType ASTContext::getUIntMaxType() const { 6624 return getFromTargetType(Target->getUIntMaxType()); 6625 } 6626 6627 /// getSignedWCharType - Return the type of "signed wchar_t". 6628 /// Used when in C++, as a GCC extension. 6629 QualType ASTContext::getSignedWCharType() const { 6630 // FIXME: derive from "Target" ? 6631 return WCharTy; 6632 } 6633 6634 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 6635 /// Used when in C++, as a GCC extension. 6636 QualType ASTContext::getUnsignedWCharType() const { 6637 // FIXME: derive from "Target" ? 6638 return UnsignedIntTy; 6639 } 6640 6641 QualType ASTContext::getIntPtrType() const { 6642 return getFromTargetType(Target->getIntPtrType()); 6643 } 6644 6645 QualType ASTContext::getUIntPtrType() const { 6646 return getCorrespondingUnsignedType(getIntPtrType()); 6647 } 6648 6649 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 6650 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 6651 QualType ASTContext::getPointerDiffType() const { 6652 return getFromTargetType(Target->getPtrDiffType(LangAS::Default)); 6653 } 6654 6655 /// Return the unique unsigned counterpart of "ptrdiff_t" 6656 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 6657 /// in the definition of %tu format specifier. 6658 QualType ASTContext::getUnsignedPointerDiffType() const { 6659 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default)); 6660 } 6661 6662 /// Return the unique type for "pid_t" defined in 6663 /// <sys/types.h>. We need this to compute the correct type for vfork(). 6664 QualType ASTContext::getProcessIDType() const { 6665 return getFromTargetType(Target->getProcessIDType()); 6666 } 6667 6668 //===----------------------------------------------------------------------===// 6669 // Type Operators 6670 //===----------------------------------------------------------------------===// 6671 6672 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 6673 // Push qualifiers into arrays, and then discard any remaining 6674 // qualifiers. 6675 T = getCanonicalType(T); 6676 T = getVariableArrayDecayedType(T); 6677 const Type *Ty = T.getTypePtr(); 6678 QualType Result; 6679 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) { 6680 Result = getArrayParameterType(QualType(Ty, 0)); 6681 } else if (isa<ArrayType>(Ty)) { 6682 Result = getArrayDecayedType(QualType(Ty,0)); 6683 } else if (isa<FunctionType>(Ty)) { 6684 Result = getPointerType(QualType(Ty, 0)); 6685 } else { 6686 Result = QualType(Ty, 0); 6687 } 6688 6689 return CanQualType::CreateUnsafe(Result); 6690 } 6691 6692 QualType ASTContext::getUnqualifiedArrayType(QualType type, 6693 Qualifiers &quals) const { 6694 SplitQualType splitType = type.getSplitUnqualifiedType(); 6695 6696 // FIXME: getSplitUnqualifiedType() actually walks all the way to 6697 // the unqualified desugared type and then drops it on the floor. 6698 // We then have to strip that sugar back off with 6699 // getUnqualifiedDesugaredType(), which is silly. 6700 const auto *AT = 6701 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 6702 6703 // If we don't have an array, just use the results in splitType. 6704 if (!AT) { 6705 quals = splitType.Quals; 6706 return QualType(splitType.Ty, 0); 6707 } 6708 6709 // Otherwise, recurse on the array's element type. 6710 QualType elementType = AT->getElementType(); 6711 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 6712 6713 // If that didn't change the element type, AT has no qualifiers, so we 6714 // can just use the results in splitType. 6715 if (elementType == unqualElementType) { 6716 assert(quals.empty()); // from the recursive call 6717 quals = splitType.Quals; 6718 return QualType(splitType.Ty, 0); 6719 } 6720 6721 // Otherwise, add in the qualifiers from the outermost type, then 6722 // build the type back up. 6723 quals.addConsistentQualifiers(splitType.Quals); 6724 6725 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 6726 return getConstantArrayType(unqualElementType, CAT->getSize(), 6727 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 6728 } 6729 6730 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 6731 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 6732 } 6733 6734 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 6735 return getVariableArrayType(unqualElementType, 6736 VAT->getSizeExpr(), 6737 VAT->getSizeModifier(), 6738 VAT->getIndexTypeCVRQualifiers(), 6739 VAT->getBracketsRange()); 6740 } 6741 6742 const auto *DSAT = cast<DependentSizedArrayType>(AT); 6743 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 6744 DSAT->getSizeModifier(), 0, 6745 SourceRange()); 6746 } 6747 6748 /// Attempt to unwrap two types that may both be array types with the same bound 6749 /// (or both be array types of unknown bound) for the purpose of comparing the 6750 /// cv-decomposition of two types per C++ [conv.qual]. 6751 /// 6752 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6753 /// C++20 [conv.qual], if permitted by the current language mode. 6754 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 6755 bool AllowPiMismatch) const { 6756 while (true) { 6757 auto *AT1 = getAsArrayType(T1); 6758 if (!AT1) 6759 return; 6760 6761 auto *AT2 = getAsArrayType(T2); 6762 if (!AT2) 6763 return; 6764 6765 // If we don't have two array types with the same constant bound nor two 6766 // incomplete array types, we've unwrapped everything we can. 6767 // C++20 also permits one type to be a constant array type and the other 6768 // to be an incomplete array type. 6769 // FIXME: Consider also unwrapping array of unknown bound and VLA. 6770 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 6771 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 6772 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 6773 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 6774 isa<IncompleteArrayType>(AT2)))) 6775 return; 6776 } else if (isa<IncompleteArrayType>(AT1)) { 6777 if (!(isa<IncompleteArrayType>(AT2) || 6778 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 6779 isa<ConstantArrayType>(AT2)))) 6780 return; 6781 } else { 6782 return; 6783 } 6784 6785 T1 = AT1->getElementType(); 6786 T2 = AT2->getElementType(); 6787 } 6788 } 6789 6790 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 6791 /// 6792 /// If T1 and T2 are both pointer types of the same kind, or both array types 6793 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 6794 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 6795 /// 6796 /// This function will typically be called in a loop that successively 6797 /// "unwraps" pointer and pointer-to-member types to compare them at each 6798 /// level. 6799 /// 6800 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6801 /// C++20 [conv.qual], if permitted by the current language mode. 6802 /// 6803 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 6804 /// pair of types that can't be unwrapped further. 6805 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 6806 bool AllowPiMismatch) const { 6807 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 6808 6809 const auto *T1PtrType = T1->getAs<PointerType>(); 6810 const auto *T2PtrType = T2->getAs<PointerType>(); 6811 if (T1PtrType && T2PtrType) { 6812 T1 = T1PtrType->getPointeeType(); 6813 T2 = T2PtrType->getPointeeType(); 6814 return true; 6815 } 6816 6817 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6818 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6819 if (T1MPType && T2MPType && 6820 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6821 QualType(T2MPType->getClass(), 0))) { 6822 T1 = T1MPType->getPointeeType(); 6823 T2 = T2MPType->getPointeeType(); 6824 return true; 6825 } 6826 6827 if (getLangOpts().ObjC) { 6828 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6829 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6830 if (T1OPType && T2OPType) { 6831 T1 = T1OPType->getPointeeType(); 6832 T2 = T2OPType->getPointeeType(); 6833 return true; 6834 } 6835 } 6836 6837 // FIXME: Block pointers, too? 6838 6839 return false; 6840 } 6841 6842 bool ASTContext::hasSimilarType(QualType T1, QualType T2) const { 6843 while (true) { 6844 Qualifiers Quals; 6845 T1 = getUnqualifiedArrayType(T1, Quals); 6846 T2 = getUnqualifiedArrayType(T2, Quals); 6847 if (hasSameType(T1, T2)) 6848 return true; 6849 if (!UnwrapSimilarTypes(T1, T2)) 6850 return false; 6851 } 6852 } 6853 6854 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6855 while (true) { 6856 Qualifiers Quals1, Quals2; 6857 T1 = getUnqualifiedArrayType(T1, Quals1); 6858 T2 = getUnqualifiedArrayType(T2, Quals2); 6859 6860 Quals1.removeCVRQualifiers(); 6861 Quals2.removeCVRQualifiers(); 6862 if (Quals1 != Quals2) 6863 return false; 6864 6865 if (hasSameType(T1, T2)) 6866 return true; 6867 6868 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6869 return false; 6870 } 6871 } 6872 6873 DeclarationNameInfo 6874 ASTContext::getNameForTemplate(TemplateName Name, 6875 SourceLocation NameLoc) const { 6876 switch (Name.getKind()) { 6877 case TemplateName::QualifiedTemplate: 6878 case TemplateName::Template: 6879 // DNInfo work in progress: CHECKME: what about DNLoc? 6880 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6881 NameLoc); 6882 6883 case TemplateName::OverloadedTemplate: { 6884 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6885 // DNInfo work in progress: CHECKME: what about DNLoc? 6886 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6887 } 6888 6889 case TemplateName::AssumedTemplate: { 6890 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6891 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6892 } 6893 6894 case TemplateName::DependentTemplate: { 6895 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6896 DeclarationName DName; 6897 if (DTN->isIdentifier()) { 6898 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6899 return DeclarationNameInfo(DName, NameLoc); 6900 } else { 6901 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6902 // DNInfo work in progress: FIXME: source locations? 6903 DeclarationNameLoc DNLoc = 6904 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6905 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6906 } 6907 } 6908 6909 case TemplateName::SubstTemplateTemplateParm: { 6910 SubstTemplateTemplateParmStorage *subst 6911 = Name.getAsSubstTemplateTemplateParm(); 6912 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6913 NameLoc); 6914 } 6915 6916 case TemplateName::SubstTemplateTemplateParmPack: { 6917 SubstTemplateTemplateParmPackStorage *subst 6918 = Name.getAsSubstTemplateTemplateParmPack(); 6919 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6920 NameLoc); 6921 } 6922 case TemplateName::UsingTemplate: 6923 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(), 6924 NameLoc); 6925 case TemplateName::DeducedTemplate: { 6926 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName(); 6927 return getNameForTemplate(DTS->getUnderlying(), NameLoc); 6928 } 6929 } 6930 6931 llvm_unreachable("bad template name kind!"); 6932 } 6933 6934 static const TemplateArgument * 6935 getDefaultTemplateArgumentOrNone(const NamedDecl *P) { 6936 auto handleParam = [](auto *TP) -> const TemplateArgument * { 6937 if (!TP->hasDefaultArgument()) 6938 return nullptr; 6939 return &TP->getDefaultArgument().getArgument(); 6940 }; 6941 switch (P->getKind()) { 6942 case NamedDecl::TemplateTypeParm: 6943 return handleParam(cast<TemplateTypeParmDecl>(P)); 6944 case NamedDecl::NonTypeTemplateParm: 6945 return handleParam(cast<NonTypeTemplateParmDecl>(P)); 6946 case NamedDecl::TemplateTemplateParm: 6947 return handleParam(cast<TemplateTemplateParmDecl>(P)); 6948 default: 6949 llvm_unreachable("Unexpected template parameter kind"); 6950 } 6951 } 6952 6953 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name, 6954 bool IgnoreDeduced) const { 6955 while (std::optional<TemplateName> UnderlyingOrNone = 6956 Name.desugar(IgnoreDeduced)) 6957 Name = *UnderlyingOrNone; 6958 6959 switch (Name.getKind()) { 6960 case TemplateName::Template: { 6961 TemplateDecl *Template = Name.getAsTemplateDecl(); 6962 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6963 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6964 6965 // The canonical template name is the canonical template declaration. 6966 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6967 } 6968 6969 case TemplateName::OverloadedTemplate: 6970 case TemplateName::AssumedTemplate: 6971 llvm_unreachable("cannot canonicalize unresolved template"); 6972 6973 case TemplateName::DependentTemplate: { 6974 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6975 assert(DTN && "Non-dependent template names must refer to template decls."); 6976 return DTN->CanonicalTemplateName; 6977 } 6978 6979 case TemplateName::SubstTemplateTemplateParmPack: { 6980 SubstTemplateTemplateParmPackStorage *subst = 6981 Name.getAsSubstTemplateTemplateParmPack(); 6982 TemplateArgument canonArgPack = 6983 getCanonicalTemplateArgument(subst->getArgumentPack()); 6984 return getSubstTemplateTemplateParmPack( 6985 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(), 6986 subst->getFinal(), subst->getIndex()); 6987 } 6988 case TemplateName::DeducedTemplate: { 6989 assert(IgnoreDeduced == false); 6990 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName(); 6991 DefaultArguments DefArgs = DTS->getDefaultArguments(); 6992 TemplateName Underlying = DTS->getUnderlying(); 6993 6994 TemplateName CanonUnderlying = 6995 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true); 6996 bool NonCanonical = CanonUnderlying != Underlying; 6997 auto CanonArgs = 6998 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical); 6999 7000 ArrayRef<NamedDecl *> Params = 7001 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray(); 7002 assert(CanonArgs.size() <= Params.size()); 7003 // A deduced template name which deduces the same default arguments already 7004 // declared in the underlying template is the same template as the 7005 // underlying template. We need need to note any arguments which differ from 7006 // the corresponding declaration. If any argument differs, we must build a 7007 // deduced template name. 7008 for (int I = CanonArgs.size() - 1; I >= 0; --I) { 7009 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(Params[I]); 7010 if (!A) 7011 break; 7012 auto CanonParamDefArg = getCanonicalTemplateArgument(*A); 7013 TemplateArgument &CanonDefArg = CanonArgs[I]; 7014 if (CanonDefArg.structurallyEquals(CanonParamDefArg)) 7015 continue; 7016 // Keep popping from the back any deault arguments which are the same. 7017 if (I == int(CanonArgs.size() - 1)) 7018 CanonArgs.pop_back(); 7019 NonCanonical = true; 7020 } 7021 return NonCanonical ? getDeducedTemplateName( 7022 CanonUnderlying, 7023 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs}) 7024 : Name; 7025 } 7026 case TemplateName::UsingTemplate: 7027 case TemplateName::QualifiedTemplate: 7028 case TemplateName::SubstTemplateTemplateParm: 7029 llvm_unreachable("always sugar node"); 7030 } 7031 7032 llvm_unreachable("bad template name!"); 7033 } 7034 7035 bool ASTContext::hasSameTemplateName(const TemplateName &X, 7036 const TemplateName &Y, 7037 bool IgnoreDeduced) const { 7038 return getCanonicalTemplateName(X, IgnoreDeduced) == 7039 getCanonicalTemplateName(Y, IgnoreDeduced); 7040 } 7041 7042 bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const { 7043 if (!XCE != !YCE) 7044 return false; 7045 7046 if (!XCE) 7047 return true; 7048 7049 llvm::FoldingSetNodeID XCEID, YCEID; 7050 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true); 7051 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true); 7052 return XCEID == YCEID; 7053 } 7054 7055 bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC, 7056 const TypeConstraint *YTC) const { 7057 if (!XTC != !YTC) 7058 return false; 7059 7060 if (!XTC) 7061 return true; 7062 7063 auto *NCX = XTC->getNamedConcept(); 7064 auto *NCY = YTC->getNamedConcept(); 7065 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 7066 return false; 7067 if (XTC->getConceptReference()->hasExplicitTemplateArgs() != 7068 YTC->getConceptReference()->hasExplicitTemplateArgs()) 7069 return false; 7070 if (XTC->getConceptReference()->hasExplicitTemplateArgs()) 7071 if (XTC->getConceptReference() 7072 ->getTemplateArgsAsWritten() 7073 ->NumTemplateArgs != 7074 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs) 7075 return false; 7076 7077 // Compare slowly by profiling. 7078 // 7079 // We couldn't compare the profiling result for the template 7080 // args here. Consider the following example in different modules: 7081 // 7082 // template <__integer_like _Tp, C<_Tp> Sentinel> 7083 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const { 7084 // return __t; 7085 // } 7086 // 7087 // When we compare the profiling result for `C<_Tp>` in different 7088 // modules, it will compare the type of `_Tp` in different modules. 7089 // However, the type of `_Tp` in different modules refer to different 7090 // types here naturally. So we couldn't compare the profiling result 7091 // for the template args directly. 7092 return isSameConstraintExpr(XTC->getImmediatelyDeclaredConstraint(), 7093 YTC->getImmediatelyDeclaredConstraint()); 7094 } 7095 7096 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 7097 const NamedDecl *Y) const { 7098 if (X->getKind() != Y->getKind()) 7099 return false; 7100 7101 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 7102 auto *TY = cast<TemplateTypeParmDecl>(Y); 7103 if (TX->isParameterPack() != TY->isParameterPack()) 7104 return false; 7105 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 7106 return false; 7107 return isSameTypeConstraint(TX->getTypeConstraint(), 7108 TY->getTypeConstraint()); 7109 } 7110 7111 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 7112 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 7113 return TX->isParameterPack() == TY->isParameterPack() && 7114 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) && 7115 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(), 7116 TY->getPlaceholderTypeConstraint()); 7117 } 7118 7119 auto *TX = cast<TemplateTemplateParmDecl>(X); 7120 auto *TY = cast<TemplateTemplateParmDecl>(Y); 7121 return TX->isParameterPack() == TY->isParameterPack() && 7122 isSameTemplateParameterList(TX->getTemplateParameters(), 7123 TY->getTemplateParameters()); 7124 } 7125 7126 bool ASTContext::isSameTemplateParameterList( 7127 const TemplateParameterList *X, const TemplateParameterList *Y) const { 7128 if (X->size() != Y->size()) 7129 return false; 7130 7131 for (unsigned I = 0, N = X->size(); I != N; ++I) 7132 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 7133 return false; 7134 7135 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause()); 7136 } 7137 7138 bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X, 7139 const NamedDecl *Y) const { 7140 // If the type parameter isn't the same already, we don't need to check the 7141 // default argument further. 7142 if (!isSameTemplateParameter(X, Y)) 7143 return false; 7144 7145 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) { 7146 auto *TTPY = cast<TemplateTypeParmDecl>(Y); 7147 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument()) 7148 return false; 7149 7150 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(), 7151 TTPY->getDefaultArgument().getArgument().getAsType()); 7152 } 7153 7154 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 7155 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y); 7156 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument()) 7157 return false; 7158 7159 Expr *DefaultArgumentX = 7160 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts(); 7161 Expr *DefaultArgumentY = 7162 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts(); 7163 llvm::FoldingSetNodeID XID, YID; 7164 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true); 7165 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true); 7166 return XID == YID; 7167 } 7168 7169 auto *TTPX = cast<TemplateTemplateParmDecl>(X); 7170 auto *TTPY = cast<TemplateTemplateParmDecl>(Y); 7171 7172 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument()) 7173 return false; 7174 7175 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument(); 7176 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument(); 7177 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate()); 7178 } 7179 7180 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 7181 if (auto *NS = X->getAsNamespace()) 7182 return NS; 7183 if (auto *NAS = X->getAsNamespaceAlias()) 7184 return NAS->getNamespace(); 7185 return nullptr; 7186 } 7187 7188 static bool isSameQualifier(const NestedNameSpecifier *X, 7189 const NestedNameSpecifier *Y) { 7190 if (auto *NSX = getNamespace(X)) { 7191 auto *NSY = getNamespace(Y); 7192 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 7193 return false; 7194 } else if (X->getKind() != Y->getKind()) 7195 return false; 7196 7197 // FIXME: For namespaces and types, we're permitted to check that the entity 7198 // is named via the same tokens. We should probably do so. 7199 switch (X->getKind()) { 7200 case NestedNameSpecifier::Identifier: 7201 if (X->getAsIdentifier() != Y->getAsIdentifier()) 7202 return false; 7203 break; 7204 case NestedNameSpecifier::Namespace: 7205 case NestedNameSpecifier::NamespaceAlias: 7206 // We've already checked that we named the same namespace. 7207 break; 7208 case NestedNameSpecifier::TypeSpec: 7209 case NestedNameSpecifier::TypeSpecWithTemplate: 7210 if (X->getAsType()->getCanonicalTypeInternal() != 7211 Y->getAsType()->getCanonicalTypeInternal()) 7212 return false; 7213 break; 7214 case NestedNameSpecifier::Global: 7215 case NestedNameSpecifier::Super: 7216 return true; 7217 } 7218 7219 // Recurse into earlier portion of NNS, if any. 7220 auto *PX = X->getPrefix(); 7221 auto *PY = Y->getPrefix(); 7222 if (PX && PY) 7223 return isSameQualifier(PX, PY); 7224 return !PX && !PY; 7225 } 7226 7227 /// Determine whether the attributes we can overload on are identical for A and 7228 /// B. Will ignore any overloadable attrs represented in the type of A and B. 7229 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 7230 const FunctionDecl *B) { 7231 // Note that pass_object_size attributes are represented in the function's 7232 // ExtParameterInfo, so we don't need to check them here. 7233 7234 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 7235 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 7236 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 7237 7238 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 7239 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 7240 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 7241 7242 // Return false if the number of enable_if attributes is different. 7243 if (!Cand1A || !Cand2A) 7244 return false; 7245 7246 Cand1ID.clear(); 7247 Cand2ID.clear(); 7248 7249 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 7250 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 7251 7252 // Return false if any of the enable_if expressions of A and B are 7253 // different. 7254 if (Cand1ID != Cand2ID) 7255 return false; 7256 } 7257 return true; 7258 } 7259 7260 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const { 7261 // Caution: this function is called by the AST reader during deserialization, 7262 // so it cannot rely on AST invariants being met. Non-trivial accessors 7263 // should be avoided, along with any traversal of redeclaration chains. 7264 7265 if (X == Y) 7266 return true; 7267 7268 if (X->getDeclName() != Y->getDeclName()) 7269 return false; 7270 7271 // Must be in the same context. 7272 // 7273 // Note that we can't use DeclContext::Equals here, because the DeclContexts 7274 // could be two different declarations of the same function. (We will fix the 7275 // semantic DC to refer to the primary definition after merging.) 7276 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 7277 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 7278 return false; 7279 7280 // Two typedefs refer to the same entity if they have the same underlying 7281 // type. 7282 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 7283 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 7284 return hasSameType(TypedefX->getUnderlyingType(), 7285 TypedefY->getUnderlyingType()); 7286 7287 // Must have the same kind. 7288 if (X->getKind() != Y->getKind()) 7289 return false; 7290 7291 // Objective-C classes and protocols with the same name always match. 7292 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 7293 return true; 7294 7295 if (isa<ClassTemplateSpecializationDecl>(X)) { 7296 // No need to handle these here: we merge them when adding them to the 7297 // template. 7298 return false; 7299 } 7300 7301 // Compatible tags match. 7302 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 7303 const auto *TagY = cast<TagDecl>(Y); 7304 return (TagX->getTagKind() == TagY->getTagKind()) || 7305 ((TagX->getTagKind() == TagTypeKind::Struct || 7306 TagX->getTagKind() == TagTypeKind::Class || 7307 TagX->getTagKind() == TagTypeKind::Interface) && 7308 (TagY->getTagKind() == TagTypeKind::Struct || 7309 TagY->getTagKind() == TagTypeKind::Class || 7310 TagY->getTagKind() == TagTypeKind::Interface)); 7311 } 7312 7313 // Functions with the same type and linkage match. 7314 // FIXME: This needs to cope with merging of prototyped/non-prototyped 7315 // functions, etc. 7316 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 7317 const auto *FuncY = cast<FunctionDecl>(Y); 7318 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 7319 const auto *CtorY = cast<CXXConstructorDecl>(Y); 7320 if (CtorX->getInheritedConstructor() && 7321 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 7322 CtorY->getInheritedConstructor().getConstructor())) 7323 return false; 7324 } 7325 7326 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 7327 return false; 7328 7329 // Multiversioned functions with different feature strings are represented 7330 // as separate declarations. 7331 if (FuncX->isMultiVersion()) { 7332 const auto *TAX = FuncX->getAttr<TargetAttr>(); 7333 const auto *TAY = FuncY->getAttr<TargetAttr>(); 7334 assert(TAX && TAY && "Multiversion Function without target attribute"); 7335 7336 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 7337 return false; 7338 } 7339 7340 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes 7341 // not the same entity if they are constrained. 7342 if ((FuncX->isMemberLikeConstrainedFriend() || 7343 FuncY->isMemberLikeConstrainedFriend()) && 7344 !FuncX->getLexicalDeclContext()->Equals( 7345 FuncY->getLexicalDeclContext())) { 7346 return false; 7347 } 7348 7349 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(), 7350 FuncY->getTrailingRequiresClause())) 7351 return false; 7352 7353 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 7354 // Map to the first declaration that we've already merged into this one. 7355 // The TSI of redeclarations might not match (due to calling conventions 7356 // being inherited onto the type but not the TSI), but the TSI type of 7357 // the first declaration of the function should match across modules. 7358 FD = FD->getCanonicalDecl(); 7359 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 7360 : FD->getType(); 7361 }; 7362 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 7363 if (!hasSameType(XT, YT)) { 7364 // We can get functions with different types on the redecl chain in C++17 7365 // if they have differing exception specifications and at least one of 7366 // the excpetion specs is unresolved. 7367 auto *XFPT = XT->getAs<FunctionProtoType>(); 7368 auto *YFPT = YT->getAs<FunctionProtoType>(); 7369 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 7370 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 7371 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 7372 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 7373 return true; 7374 return false; 7375 } 7376 7377 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 7378 hasSameOverloadableAttrs(FuncX, FuncY); 7379 } 7380 7381 // Variables with the same type and linkage match. 7382 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 7383 const auto *VarY = cast<VarDecl>(Y); 7384 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 7385 // During deserialization, we might compare variables before we load 7386 // their types. Assume the types will end up being the same. 7387 if (VarX->getType().isNull() || VarY->getType().isNull()) 7388 return true; 7389 7390 if (hasSameType(VarX->getType(), VarY->getType())) 7391 return true; 7392 7393 // We can get decls with different types on the redecl chain. Eg. 7394 // template <typename T> struct S { static T Var[]; }; // #1 7395 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 7396 // Only? happens when completing an incomplete array type. In this case 7397 // when comparing #1 and #2 we should go through their element type. 7398 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 7399 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 7400 if (!VarXTy || !VarYTy) 7401 return false; 7402 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 7403 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 7404 } 7405 return false; 7406 } 7407 7408 // Namespaces with the same name and inlinedness match. 7409 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 7410 const auto *NamespaceY = cast<NamespaceDecl>(Y); 7411 return NamespaceX->isInline() == NamespaceY->isInline(); 7412 } 7413 7414 // Identical template names and kinds match if their template parameter lists 7415 // and patterns match. 7416 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 7417 const auto *TemplateY = cast<TemplateDecl>(Y); 7418 7419 // ConceptDecl wouldn't be the same if their constraint expression differs. 7420 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) { 7421 const auto *ConceptY = cast<ConceptDecl>(Y); 7422 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(), 7423 ConceptY->getConstraintExpr())) 7424 return false; 7425 } 7426 7427 return isSameEntity(TemplateX->getTemplatedDecl(), 7428 TemplateY->getTemplatedDecl()) && 7429 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 7430 TemplateY->getTemplateParameters()); 7431 } 7432 7433 // Fields with the same name and the same type match. 7434 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 7435 const auto *FDY = cast<FieldDecl>(Y); 7436 // FIXME: Also check the bitwidth is odr-equivalent, if any. 7437 return hasSameType(FDX->getType(), FDY->getType()); 7438 } 7439 7440 // Indirect fields with the same target field match. 7441 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 7442 const auto *IFDY = cast<IndirectFieldDecl>(Y); 7443 return IFDX->getAnonField()->getCanonicalDecl() == 7444 IFDY->getAnonField()->getCanonicalDecl(); 7445 } 7446 7447 // Enumerators with the same name match. 7448 if (isa<EnumConstantDecl>(X)) 7449 // FIXME: Also check the value is odr-equivalent. 7450 return true; 7451 7452 // Using shadow declarations with the same target match. 7453 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 7454 const auto *USY = cast<UsingShadowDecl>(Y); 7455 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl()); 7456 } 7457 7458 // Using declarations with the same qualifier match. (We already know that 7459 // the name matches.) 7460 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 7461 const auto *UY = cast<UsingDecl>(Y); 7462 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 7463 UX->hasTypename() == UY->hasTypename() && 7464 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 7465 } 7466 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 7467 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 7468 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 7469 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 7470 } 7471 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 7472 return isSameQualifier( 7473 UX->getQualifier(), 7474 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 7475 } 7476 7477 // Using-pack declarations are only created by instantiation, and match if 7478 // they're instantiated from matching UnresolvedUsing...Decls. 7479 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 7480 return declaresSameEntity( 7481 UX->getInstantiatedFromUsingDecl(), 7482 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 7483 } 7484 7485 // Namespace alias definitions with the same target match. 7486 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 7487 const auto *NAY = cast<NamespaceAliasDecl>(Y); 7488 return NAX->getNamespace()->Equals(NAY->getNamespace()); 7489 } 7490 7491 return false; 7492 } 7493 7494 TemplateArgument 7495 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 7496 switch (Arg.getKind()) { 7497 case TemplateArgument::Null: 7498 return Arg; 7499 7500 case TemplateArgument::Expression: 7501 return Arg; 7502 7503 case TemplateArgument::Declaration: { 7504 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 7505 return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()), 7506 Arg.getIsDefaulted()); 7507 } 7508 7509 case TemplateArgument::NullPtr: 7510 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 7511 /*isNullPtr*/ true, Arg.getIsDefaulted()); 7512 7513 case TemplateArgument::Template: 7514 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()), 7515 Arg.getIsDefaulted()); 7516 7517 case TemplateArgument::TemplateExpansion: 7518 return TemplateArgument( 7519 getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()), 7520 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted()); 7521 7522 case TemplateArgument::Integral: 7523 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 7524 7525 case TemplateArgument::StructuralValue: 7526 return TemplateArgument(*this, 7527 getCanonicalType(Arg.getStructuralValueType()), 7528 Arg.getAsStructuralValue(), Arg.getIsDefaulted()); 7529 7530 case TemplateArgument::Type: 7531 return TemplateArgument(getCanonicalType(Arg.getAsType()), 7532 /*isNullPtr*/ false, Arg.getIsDefaulted()); 7533 7534 case TemplateArgument::Pack: { 7535 bool AnyNonCanonArgs = false; 7536 auto CanonArgs = ::getCanonicalTemplateArguments( 7537 *this, Arg.pack_elements(), AnyNonCanonArgs); 7538 if (!AnyNonCanonArgs) 7539 return Arg; 7540 auto NewArg = TemplateArgument::CreatePackCopy( 7541 const_cast<ASTContext &>(*this), CanonArgs); 7542 NewArg.setIsDefaulted(Arg.getIsDefaulted()); 7543 return NewArg; 7544 } 7545 } 7546 7547 // Silence GCC warning 7548 llvm_unreachable("Unhandled template argument kind"); 7549 } 7550 7551 NestedNameSpecifier * 7552 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 7553 if (!NNS) 7554 return nullptr; 7555 7556 switch (NNS->getKind()) { 7557 case NestedNameSpecifier::Identifier: 7558 // Canonicalize the prefix but keep the identifier the same. 7559 return NestedNameSpecifier::Create(*this, 7560 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 7561 NNS->getAsIdentifier()); 7562 7563 case NestedNameSpecifier::Namespace: 7564 // A namespace is canonical; build a nested-name-specifier with 7565 // this namespace and no prefix. 7566 return NestedNameSpecifier::Create(*this, nullptr, 7567 NNS->getAsNamespace()->getFirstDecl()); 7568 7569 case NestedNameSpecifier::NamespaceAlias: 7570 // A namespace is canonical; build a nested-name-specifier with 7571 // this namespace and no prefix. 7572 return NestedNameSpecifier::Create( 7573 *this, nullptr, 7574 NNS->getAsNamespaceAlias()->getNamespace()->getFirstDecl()); 7575 7576 // The difference between TypeSpec and TypeSpecWithTemplate is that the 7577 // latter will have the 'template' keyword when printed. 7578 case NestedNameSpecifier::TypeSpec: 7579 case NestedNameSpecifier::TypeSpecWithTemplate: { 7580 const Type *T = getCanonicalType(NNS->getAsType()); 7581 7582 // If we have some kind of dependent-named type (e.g., "typename T::type"), 7583 // break it apart into its prefix and identifier, then reconsititute those 7584 // as the canonical nested-name-specifier. This is required to canonicalize 7585 // a dependent nested-name-specifier involving typedefs of dependent-name 7586 // types, e.g., 7587 // typedef typename T::type T1; 7588 // typedef typename T1::type T2; 7589 if (const auto *DNT = T->getAs<DependentNameType>()) 7590 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 7591 DNT->getIdentifier()); 7592 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 7593 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T); 7594 7595 // TODO: Set 'Template' parameter to true for other template types. 7596 return NestedNameSpecifier::Create(*this, nullptr, false, T); 7597 } 7598 7599 case NestedNameSpecifier::Global: 7600 case NestedNameSpecifier::Super: 7601 // The global specifier and __super specifer are canonical and unique. 7602 return NNS; 7603 } 7604 7605 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 7606 } 7607 7608 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 7609 // Handle the non-qualified case efficiently. 7610 if (!T.hasLocalQualifiers()) { 7611 // Handle the common positive case fast. 7612 if (const auto *AT = dyn_cast<ArrayType>(T)) 7613 return AT; 7614 } 7615 7616 // Handle the common negative case fast. 7617 if (!isa<ArrayType>(T.getCanonicalType())) 7618 return nullptr; 7619 7620 // Apply any qualifiers from the array type to the element type. This 7621 // implements C99 6.7.3p8: "If the specification of an array type includes 7622 // any type qualifiers, the element type is so qualified, not the array type." 7623 7624 // If we get here, we either have type qualifiers on the type, or we have 7625 // sugar such as a typedef in the way. If we have type qualifiers on the type 7626 // we must propagate them down into the element type. 7627 7628 SplitQualType split = T.getSplitDesugaredType(); 7629 Qualifiers qs = split.Quals; 7630 7631 // If we have a simple case, just return now. 7632 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 7633 if (!ATy || qs.empty()) 7634 return ATy; 7635 7636 // Otherwise, we have an array and we have qualifiers on it. Push the 7637 // qualifiers into the array element type and return a new array type. 7638 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 7639 7640 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 7641 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 7642 CAT->getSizeExpr(), 7643 CAT->getSizeModifier(), 7644 CAT->getIndexTypeCVRQualifiers())); 7645 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 7646 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 7647 IAT->getSizeModifier(), 7648 IAT->getIndexTypeCVRQualifiers())); 7649 7650 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 7651 return cast<ArrayType>( 7652 getDependentSizedArrayType(NewEltTy, 7653 DSAT->getSizeExpr(), 7654 DSAT->getSizeModifier(), 7655 DSAT->getIndexTypeCVRQualifiers(), 7656 DSAT->getBracketsRange())); 7657 7658 const auto *VAT = cast<VariableArrayType>(ATy); 7659 return cast<ArrayType>(getVariableArrayType(NewEltTy, 7660 VAT->getSizeExpr(), 7661 VAT->getSizeModifier(), 7662 VAT->getIndexTypeCVRQualifiers(), 7663 VAT->getBracketsRange())); 7664 } 7665 7666 QualType ASTContext::getAdjustedParameterType(QualType T) const { 7667 if (getLangOpts().HLSL && T->isConstantArrayType()) 7668 return getArrayParameterType(T); 7669 if (T->isArrayType() || T->isFunctionType()) 7670 return getDecayedType(T); 7671 return T; 7672 } 7673 7674 QualType ASTContext::getSignatureParameterType(QualType T) const { 7675 T = getVariableArrayDecayedType(T); 7676 T = getAdjustedParameterType(T); 7677 return T.getUnqualifiedType(); 7678 } 7679 7680 QualType ASTContext::getExceptionObjectType(QualType T) const { 7681 // C++ [except.throw]p3: 7682 // A throw-expression initializes a temporary object, called the exception 7683 // object, the type of which is determined by removing any top-level 7684 // cv-qualifiers from the static type of the operand of throw and adjusting 7685 // the type from "array of T" or "function returning T" to "pointer to T" 7686 // or "pointer to function returning T", [...] 7687 T = getVariableArrayDecayedType(T); 7688 if (T->isArrayType() || T->isFunctionType()) 7689 T = getDecayedType(T); 7690 return T.getUnqualifiedType(); 7691 } 7692 7693 /// getArrayDecayedType - Return the properly qualified result of decaying the 7694 /// specified array type to a pointer. This operation is non-trivial when 7695 /// handling typedefs etc. The canonical type of "T" must be an array type, 7696 /// this returns a pointer to a properly qualified element of the array. 7697 /// 7698 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 7699 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 7700 // Get the element type with 'getAsArrayType' so that we don't lose any 7701 // typedefs in the element type of the array. This also handles propagation 7702 // of type qualifiers from the array type into the element type if present 7703 // (C99 6.7.3p8). 7704 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 7705 assert(PrettyArrayType && "Not an array type!"); 7706 7707 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 7708 7709 // int x[restrict 4] -> int *restrict 7710 QualType Result = getQualifiedType(PtrTy, 7711 PrettyArrayType->getIndexTypeQualifiers()); 7712 7713 // int x[_Nullable] -> int * _Nullable 7714 if (auto Nullability = Ty->getNullability()) { 7715 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability, 7716 Result, Result); 7717 } 7718 return Result; 7719 } 7720 7721 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 7722 return getBaseElementType(array->getElementType()); 7723 } 7724 7725 QualType ASTContext::getBaseElementType(QualType type) const { 7726 Qualifiers qs; 7727 while (true) { 7728 SplitQualType split = type.getSplitDesugaredType(); 7729 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 7730 if (!array) break; 7731 7732 type = array->getElementType(); 7733 qs.addConsistentQualifiers(split.Quals); 7734 } 7735 7736 return getQualifiedType(type, qs); 7737 } 7738 7739 /// getConstantArrayElementCount - Returns number of constant array elements. 7740 uint64_t 7741 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 7742 uint64_t ElementCount = 1; 7743 do { 7744 ElementCount *= CA->getZExtSize(); 7745 CA = dyn_cast_or_null<ConstantArrayType>( 7746 CA->getElementType()->getAsArrayTypeUnsafe()); 7747 } while (CA); 7748 return ElementCount; 7749 } 7750 7751 uint64_t ASTContext::getArrayInitLoopExprElementCount( 7752 const ArrayInitLoopExpr *AILE) const { 7753 if (!AILE) 7754 return 0; 7755 7756 uint64_t ElementCount = 1; 7757 7758 do { 7759 ElementCount *= AILE->getArraySize().getZExtValue(); 7760 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr()); 7761 } while (AILE); 7762 7763 return ElementCount; 7764 } 7765 7766 /// getFloatingRank - Return a relative rank for floating point types. 7767 /// This routine will assert if passed a built-in type that isn't a float. 7768 static FloatingRank getFloatingRank(QualType T) { 7769 if (const auto *CT = T->getAs<ComplexType>()) 7770 return getFloatingRank(CT->getElementType()); 7771 7772 switch (T->castAs<BuiltinType>()->getKind()) { 7773 default: llvm_unreachable("getFloatingRank(): not a floating type"); 7774 case BuiltinType::Float16: return Float16Rank; 7775 case BuiltinType::Half: return HalfRank; 7776 case BuiltinType::Float: return FloatRank; 7777 case BuiltinType::Double: return DoubleRank; 7778 case BuiltinType::LongDouble: return LongDoubleRank; 7779 case BuiltinType::Float128: return Float128Rank; 7780 case BuiltinType::BFloat16: return BFloat16Rank; 7781 case BuiltinType::Ibm128: return Ibm128Rank; 7782 } 7783 } 7784 7785 /// getFloatingTypeOrder - Compare the rank of the two specified floating 7786 /// point types, ignoring the domain of the type (i.e. 'double' == 7787 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 7788 /// LHS < RHS, return -1. 7789 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 7790 FloatingRank LHSR = getFloatingRank(LHS); 7791 FloatingRank RHSR = getFloatingRank(RHS); 7792 7793 if (LHSR == RHSR) 7794 return 0; 7795 if (LHSR > RHSR) 7796 return 1; 7797 return -1; 7798 } 7799 7800 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 7801 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 7802 return 0; 7803 return getFloatingTypeOrder(LHS, RHS); 7804 } 7805 7806 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 7807 /// routine will assert if passed a built-in type that isn't an integer or enum, 7808 /// or if it is not canonicalized. 7809 unsigned ASTContext::getIntegerRank(const Type *T) const { 7810 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 7811 7812 // Results in this 'losing' to any type of the same size, but winning if 7813 // larger. 7814 if (const auto *EIT = dyn_cast<BitIntType>(T)) 7815 return 0 + (EIT->getNumBits() << 3); 7816 7817 switch (cast<BuiltinType>(T)->getKind()) { 7818 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 7819 case BuiltinType::Bool: 7820 return 1 + (getIntWidth(BoolTy) << 3); 7821 case BuiltinType::Char_S: 7822 case BuiltinType::Char_U: 7823 case BuiltinType::SChar: 7824 case BuiltinType::UChar: 7825 return 2 + (getIntWidth(CharTy) << 3); 7826 case BuiltinType::Short: 7827 case BuiltinType::UShort: 7828 return 3 + (getIntWidth(ShortTy) << 3); 7829 case BuiltinType::Int: 7830 case BuiltinType::UInt: 7831 return 4 + (getIntWidth(IntTy) << 3); 7832 case BuiltinType::Long: 7833 case BuiltinType::ULong: 7834 return 5 + (getIntWidth(LongTy) << 3); 7835 case BuiltinType::LongLong: 7836 case BuiltinType::ULongLong: 7837 return 6 + (getIntWidth(LongLongTy) << 3); 7838 case BuiltinType::Int128: 7839 case BuiltinType::UInt128: 7840 return 7 + (getIntWidth(Int128Ty) << 3); 7841 7842 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of 7843 // their underlying types" [c++20 conv.rank] 7844 case BuiltinType::Char8: 7845 return getIntegerRank(UnsignedCharTy.getTypePtr()); 7846 case BuiltinType::Char16: 7847 return getIntegerRank( 7848 getFromTargetType(Target->getChar16Type()).getTypePtr()); 7849 case BuiltinType::Char32: 7850 return getIntegerRank( 7851 getFromTargetType(Target->getChar32Type()).getTypePtr()); 7852 case BuiltinType::WChar_S: 7853 case BuiltinType::WChar_U: 7854 return getIntegerRank( 7855 getFromTargetType(Target->getWCharType()).getTypePtr()); 7856 } 7857 } 7858 7859 /// Whether this is a promotable bitfield reference according 7860 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 7861 /// 7862 /// \returns the type this bit-field will promote to, or NULL if no 7863 /// promotion occurs. 7864 QualType ASTContext::isPromotableBitField(Expr *E) const { 7865 if (E->isTypeDependent() || E->isValueDependent()) 7866 return {}; 7867 7868 // C++ [conv.prom]p5: 7869 // If the bit-field has an enumerated type, it is treated as any other 7870 // value of that type for promotion purposes. 7871 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 7872 return {}; 7873 7874 // FIXME: We should not do this unless E->refersToBitField() is true. This 7875 // matters in C where getSourceBitField() will find bit-fields for various 7876 // cases where the source expression is not a bit-field designator. 7877 7878 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 7879 if (!Field) 7880 return {}; 7881 7882 QualType FT = Field->getType(); 7883 7884 uint64_t BitWidth = Field->getBitWidthValue(); 7885 uint64_t IntSize = getTypeSize(IntTy); 7886 // C++ [conv.prom]p5: 7887 // A prvalue for an integral bit-field can be converted to a prvalue of type 7888 // int if int can represent all the values of the bit-field; otherwise, it 7889 // can be converted to unsigned int if unsigned int can represent all the 7890 // values of the bit-field. If the bit-field is larger yet, no integral 7891 // promotion applies to it. 7892 // C11 6.3.1.1/2: 7893 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 7894 // If an int can represent all values of the original type (as restricted by 7895 // the width, for a bit-field), the value is converted to an int; otherwise, 7896 // it is converted to an unsigned int. 7897 // 7898 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 7899 // We perform that promotion here to match GCC and C++. 7900 // FIXME: C does not permit promotion of an enum bit-field whose rank is 7901 // greater than that of 'int'. We perform that promotion to match GCC. 7902 // 7903 // C23 6.3.1.1p2: 7904 // The value from a bit-field of a bit-precise integer type is converted to 7905 // the corresponding bit-precise integer type. (The rest is the same as in 7906 // C11.) 7907 if (QualType QT = Field->getType(); QT->isBitIntType()) 7908 return QT; 7909 7910 if (BitWidth < IntSize) 7911 return IntTy; 7912 7913 if (BitWidth == IntSize) 7914 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 7915 7916 // Bit-fields wider than int are not subject to promotions, and therefore act 7917 // like the base type. GCC has some weird bugs in this area that we 7918 // deliberately do not follow (GCC follows a pre-standard resolution to 7919 // C's DR315 which treats bit-width as being part of the type, and this leaks 7920 // into their semantics in some cases). 7921 return {}; 7922 } 7923 7924 /// getPromotedIntegerType - Returns the type that Promotable will 7925 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 7926 /// integer type. 7927 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 7928 assert(!Promotable.isNull()); 7929 assert(isPromotableIntegerType(Promotable)); 7930 if (const auto *ET = Promotable->getAs<EnumType>()) 7931 return ET->getDecl()->getPromotionType(); 7932 7933 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 7934 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 7935 // (3.9.1) can be converted to a prvalue of the first of the following 7936 // types that can represent all the values of its underlying type: 7937 // int, unsigned int, long int, unsigned long int, long long int, or 7938 // unsigned long long int [...] 7939 // FIXME: Is there some better way to compute this? 7940 if (BT->getKind() == BuiltinType::WChar_S || 7941 BT->getKind() == BuiltinType::WChar_U || 7942 BT->getKind() == BuiltinType::Char8 || 7943 BT->getKind() == BuiltinType::Char16 || 7944 BT->getKind() == BuiltinType::Char32) { 7945 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 7946 uint64_t FromSize = getTypeSize(BT); 7947 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 7948 LongLongTy, UnsignedLongLongTy }; 7949 for (const auto &PT : PromoteTypes) { 7950 uint64_t ToSize = getTypeSize(PT); 7951 if (FromSize < ToSize || 7952 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType())) 7953 return PT; 7954 } 7955 llvm_unreachable("char type should fit into long long"); 7956 } 7957 } 7958 7959 // At this point, we should have a signed or unsigned integer type. 7960 if (Promotable->isSignedIntegerType()) 7961 return IntTy; 7962 uint64_t PromotableSize = getIntWidth(Promotable); 7963 uint64_t IntSize = getIntWidth(IntTy); 7964 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 7965 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 7966 } 7967 7968 /// Recurses in pointer/array types until it finds an objc retainable 7969 /// type and returns its ownership. 7970 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 7971 while (!T.isNull()) { 7972 if (T.getObjCLifetime() != Qualifiers::OCL_None) 7973 return T.getObjCLifetime(); 7974 if (T->isArrayType()) 7975 T = getBaseElementType(T); 7976 else if (const auto *PT = T->getAs<PointerType>()) 7977 T = PT->getPointeeType(); 7978 else if (const auto *RT = T->getAs<ReferenceType>()) 7979 T = RT->getPointeeType(); 7980 else 7981 break; 7982 } 7983 7984 return Qualifiers::OCL_None; 7985 } 7986 7987 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 7988 // Incomplete enum types are not treated as integer types. 7989 // FIXME: In C++, enum types are never integer types. 7990 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 7991 return ET->getDecl()->getIntegerType().getTypePtr(); 7992 return nullptr; 7993 } 7994 7995 /// getIntegerTypeOrder - Returns the highest ranked integer type: 7996 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 7997 /// LHS < RHS, return -1. 7998 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 7999 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 8000 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 8001 8002 // Unwrap enums to their underlying type. 8003 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 8004 LHSC = getIntegerTypeForEnum(ET); 8005 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 8006 RHSC = getIntegerTypeForEnum(ET); 8007 8008 if (LHSC == RHSC) return 0; 8009 8010 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 8011 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 8012 8013 unsigned LHSRank = getIntegerRank(LHSC); 8014 unsigned RHSRank = getIntegerRank(RHSC); 8015 8016 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 8017 if (LHSRank == RHSRank) return 0; 8018 return LHSRank > RHSRank ? 1 : -1; 8019 } 8020 8021 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 8022 if (LHSUnsigned) { 8023 // If the unsigned [LHS] type is larger, return it. 8024 if (LHSRank >= RHSRank) 8025 return 1; 8026 8027 // If the signed type can represent all values of the unsigned type, it 8028 // wins. Because we are dealing with 2's complement and types that are 8029 // powers of two larger than each other, this is always safe. 8030 return -1; 8031 } 8032 8033 // If the unsigned [RHS] type is larger, return it. 8034 if (RHSRank >= LHSRank) 8035 return -1; 8036 8037 // If the signed type can represent all values of the unsigned type, it 8038 // wins. Because we are dealing with 2's complement and types that are 8039 // powers of two larger than each other, this is always safe. 8040 return 1; 8041 } 8042 8043 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 8044 if (CFConstantStringTypeDecl) 8045 return CFConstantStringTypeDecl; 8046 8047 assert(!CFConstantStringTagDecl && 8048 "tag and typedef should be initialized together"); 8049 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 8050 CFConstantStringTagDecl->startDefinition(); 8051 8052 struct { 8053 QualType Type; 8054 const char *Name; 8055 } Fields[5]; 8056 unsigned Count = 0; 8057 8058 /// Objective-C ABI 8059 /// 8060 /// typedef struct __NSConstantString_tag { 8061 /// const int *isa; 8062 /// int flags; 8063 /// const char *str; 8064 /// long length; 8065 /// } __NSConstantString; 8066 /// 8067 /// Swift ABI (4.1, 4.2) 8068 /// 8069 /// typedef struct __NSConstantString_tag { 8070 /// uintptr_t _cfisa; 8071 /// uintptr_t _swift_rc; 8072 /// _Atomic(uint64_t) _cfinfoa; 8073 /// const char *_ptr; 8074 /// uint32_t _length; 8075 /// } __NSConstantString; 8076 /// 8077 /// Swift ABI (5.0) 8078 /// 8079 /// typedef struct __NSConstantString_tag { 8080 /// uintptr_t _cfisa; 8081 /// uintptr_t _swift_rc; 8082 /// _Atomic(uint64_t) _cfinfoa; 8083 /// const char *_ptr; 8084 /// uintptr_t _length; 8085 /// } __NSConstantString; 8086 8087 const auto CFRuntime = getLangOpts().CFRuntime; 8088 if (static_cast<unsigned>(CFRuntime) < 8089 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 8090 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 8091 Fields[Count++] = { IntTy, "flags" }; 8092 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 8093 Fields[Count++] = { LongTy, "length" }; 8094 } else { 8095 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 8096 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 8097 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 8098 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 8099 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 8100 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 8101 Fields[Count++] = { IntTy, "_ptr" }; 8102 else 8103 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 8104 } 8105 8106 // Create fields 8107 for (unsigned i = 0; i < Count; ++i) { 8108 FieldDecl *Field = 8109 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 8110 SourceLocation(), &Idents.get(Fields[i].Name), 8111 Fields[i].Type, /*TInfo=*/nullptr, 8112 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 8113 Field->setAccess(AS_public); 8114 CFConstantStringTagDecl->addDecl(Field); 8115 } 8116 8117 CFConstantStringTagDecl->completeDefinition(); 8118 // This type is designed to be compatible with NSConstantString, but cannot 8119 // use the same name, since NSConstantString is an interface. 8120 auto tagType = getTagDeclType(CFConstantStringTagDecl); 8121 CFConstantStringTypeDecl = 8122 buildImplicitTypedef(tagType, "__NSConstantString"); 8123 8124 return CFConstantStringTypeDecl; 8125 } 8126 8127 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 8128 if (!CFConstantStringTagDecl) 8129 getCFConstantStringDecl(); // Build the tag and the typedef. 8130 return CFConstantStringTagDecl; 8131 } 8132 8133 // getCFConstantStringType - Return the type used for constant CFStrings. 8134 QualType ASTContext::getCFConstantStringType() const { 8135 return getTypedefType(getCFConstantStringDecl()); 8136 } 8137 8138 QualType ASTContext::getObjCSuperType() const { 8139 if (ObjCSuperType.isNull()) { 8140 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 8141 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 8142 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 8143 } 8144 return ObjCSuperType; 8145 } 8146 8147 void ASTContext::setCFConstantStringType(QualType T) { 8148 const auto *TD = T->castAs<TypedefType>(); 8149 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 8150 const auto *TagType = 8151 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 8152 CFConstantStringTagDecl = TagType->getDecl(); 8153 } 8154 8155 QualType ASTContext::getBlockDescriptorType() const { 8156 if (BlockDescriptorType) 8157 return getTagDeclType(BlockDescriptorType); 8158 8159 RecordDecl *RD; 8160 // FIXME: Needs the FlagAppleBlock bit. 8161 RD = buildImplicitRecord("__block_descriptor"); 8162 RD->startDefinition(); 8163 8164 QualType FieldTypes[] = { 8165 UnsignedLongTy, 8166 UnsignedLongTy, 8167 }; 8168 8169 static const char *const FieldNames[] = { 8170 "reserved", 8171 "Size" 8172 }; 8173 8174 for (size_t i = 0; i < 2; ++i) { 8175 FieldDecl *Field = FieldDecl::Create( 8176 *this, RD, SourceLocation(), SourceLocation(), 8177 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 8178 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 8179 Field->setAccess(AS_public); 8180 RD->addDecl(Field); 8181 } 8182 8183 RD->completeDefinition(); 8184 8185 BlockDescriptorType = RD; 8186 8187 return getTagDeclType(BlockDescriptorType); 8188 } 8189 8190 QualType ASTContext::getBlockDescriptorExtendedType() const { 8191 if (BlockDescriptorExtendedType) 8192 return getTagDeclType(BlockDescriptorExtendedType); 8193 8194 RecordDecl *RD; 8195 // FIXME: Needs the FlagAppleBlock bit. 8196 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 8197 RD->startDefinition(); 8198 8199 QualType FieldTypes[] = { 8200 UnsignedLongTy, 8201 UnsignedLongTy, 8202 getPointerType(VoidPtrTy), 8203 getPointerType(VoidPtrTy) 8204 }; 8205 8206 static const char *const FieldNames[] = { 8207 "reserved", 8208 "Size", 8209 "CopyFuncPtr", 8210 "DestroyFuncPtr" 8211 }; 8212 8213 for (size_t i = 0; i < 4; ++i) { 8214 FieldDecl *Field = FieldDecl::Create( 8215 *this, RD, SourceLocation(), SourceLocation(), 8216 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 8217 /*BitWidth=*/nullptr, 8218 /*Mutable=*/false, ICIS_NoInit); 8219 Field->setAccess(AS_public); 8220 RD->addDecl(Field); 8221 } 8222 8223 RD->completeDefinition(); 8224 8225 BlockDescriptorExtendedType = RD; 8226 return getTagDeclType(BlockDescriptorExtendedType); 8227 } 8228 8229 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 8230 const auto *BT = dyn_cast<BuiltinType>(T); 8231 8232 if (!BT) { 8233 if (isa<PipeType>(T)) 8234 return OCLTK_Pipe; 8235 8236 return OCLTK_Default; 8237 } 8238 8239 switch (BT->getKind()) { 8240 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8241 case BuiltinType::Id: \ 8242 return OCLTK_Image; 8243 #include "clang/Basic/OpenCLImageTypes.def" 8244 8245 case BuiltinType::OCLClkEvent: 8246 return OCLTK_ClkEvent; 8247 8248 case BuiltinType::OCLEvent: 8249 return OCLTK_Event; 8250 8251 case BuiltinType::OCLQueue: 8252 return OCLTK_Queue; 8253 8254 case BuiltinType::OCLReserveID: 8255 return OCLTK_ReserveID; 8256 8257 case BuiltinType::OCLSampler: 8258 return OCLTK_Sampler; 8259 8260 default: 8261 return OCLTK_Default; 8262 } 8263 } 8264 8265 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 8266 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 8267 } 8268 8269 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 8270 /// requires copy/dispose. Note that this must match the logic 8271 /// in buildByrefHelpers. 8272 bool ASTContext::BlockRequiresCopying(QualType Ty, 8273 const VarDecl *D) { 8274 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 8275 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 8276 if (!copyExpr && record->hasTrivialDestructor()) return false; 8277 8278 return true; 8279 } 8280 8281 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 8282 // move or destroy. 8283 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 8284 return true; 8285 8286 if (!Ty->isObjCRetainableType()) return false; 8287 8288 Qualifiers qs = Ty.getQualifiers(); 8289 8290 // If we have lifetime, that dominates. 8291 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 8292 switch (lifetime) { 8293 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 8294 8295 // These are just bits as far as the runtime is concerned. 8296 case Qualifiers::OCL_ExplicitNone: 8297 case Qualifiers::OCL_Autoreleasing: 8298 return false; 8299 8300 // These cases should have been taken care of when checking the type's 8301 // non-triviality. 8302 case Qualifiers::OCL_Weak: 8303 case Qualifiers::OCL_Strong: 8304 llvm_unreachable("impossible"); 8305 } 8306 llvm_unreachable("fell out of lifetime switch!"); 8307 } 8308 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 8309 Ty->isObjCObjectPointerType()); 8310 } 8311 8312 bool ASTContext::getByrefLifetime(QualType Ty, 8313 Qualifiers::ObjCLifetime &LifeTime, 8314 bool &HasByrefExtendedLayout) const { 8315 if (!getLangOpts().ObjC || 8316 getLangOpts().getGC() != LangOptions::NonGC) 8317 return false; 8318 8319 HasByrefExtendedLayout = false; 8320 if (Ty->isRecordType()) { 8321 HasByrefExtendedLayout = true; 8322 LifeTime = Qualifiers::OCL_None; 8323 } else if ((LifeTime = Ty.getObjCLifetime())) { 8324 // Honor the ARC qualifiers. 8325 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 8326 // The MRR rule. 8327 LifeTime = Qualifiers::OCL_ExplicitNone; 8328 } else { 8329 LifeTime = Qualifiers::OCL_None; 8330 } 8331 return true; 8332 } 8333 8334 CanQualType ASTContext::getNSUIntegerType() const { 8335 assert(Target && "Expected target to be initialized"); 8336 const llvm::Triple &T = Target->getTriple(); 8337 // Windows is LLP64 rather than LP64 8338 if (T.isOSWindows() && T.isArch64Bit()) 8339 return UnsignedLongLongTy; 8340 return UnsignedLongTy; 8341 } 8342 8343 CanQualType ASTContext::getNSIntegerType() const { 8344 assert(Target && "Expected target to be initialized"); 8345 const llvm::Triple &T = Target->getTriple(); 8346 // Windows is LLP64 rather than LP64 8347 if (T.isOSWindows() && T.isArch64Bit()) 8348 return LongLongTy; 8349 return LongTy; 8350 } 8351 8352 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 8353 if (!ObjCInstanceTypeDecl) 8354 ObjCInstanceTypeDecl = 8355 buildImplicitTypedef(getObjCIdType(), "instancetype"); 8356 return ObjCInstanceTypeDecl; 8357 } 8358 8359 // This returns true if a type has been typedefed to BOOL: 8360 // typedef <type> BOOL; 8361 static bool isTypeTypedefedAsBOOL(QualType T) { 8362 if (const auto *TT = dyn_cast<TypedefType>(T)) 8363 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 8364 return II->isStr("BOOL"); 8365 8366 return false; 8367 } 8368 8369 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 8370 /// purpose. 8371 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 8372 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 8373 return CharUnits::Zero(); 8374 8375 CharUnits sz = getTypeSizeInChars(type); 8376 8377 // Make all integer and enum types at least as large as an int 8378 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 8379 sz = std::max(sz, getTypeSizeInChars(IntTy)); 8380 // Treat arrays as pointers, since that's how they're passed in. 8381 else if (type->isArrayType()) 8382 sz = getTypeSizeInChars(VoidPtrTy); 8383 return sz; 8384 } 8385 8386 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 8387 return getTargetInfo().getCXXABI().isMicrosoft() && 8388 VD->isStaticDataMember() && 8389 VD->getType()->isIntegralOrEnumerationType() && 8390 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 8391 } 8392 8393 ASTContext::InlineVariableDefinitionKind 8394 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 8395 if (!VD->isInline()) 8396 return InlineVariableDefinitionKind::None; 8397 8398 // In almost all cases, it's a weak definition. 8399 auto *First = VD->getFirstDecl(); 8400 if (First->isInlineSpecified() || !First->isStaticDataMember()) 8401 return InlineVariableDefinitionKind::Weak; 8402 8403 // If there's a file-context declaration in this translation unit, it's a 8404 // non-discardable definition. 8405 for (auto *D : VD->redecls()) 8406 if (D->getLexicalDeclContext()->isFileContext() && 8407 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 8408 return InlineVariableDefinitionKind::Strong; 8409 8410 // If we've not seen one yet, we don't know. 8411 return InlineVariableDefinitionKind::WeakUnknown; 8412 } 8413 8414 static std::string charUnitsToString(const CharUnits &CU) { 8415 return llvm::itostr(CU.getQuantity()); 8416 } 8417 8418 /// getObjCEncodingForBlock - Return the encoded type for this block 8419 /// declaration. 8420 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 8421 std::string S; 8422 8423 const BlockDecl *Decl = Expr->getBlockDecl(); 8424 QualType BlockTy = 8425 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 8426 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 8427 // Encode result type. 8428 if (getLangOpts().EncodeExtendedBlockSig) 8429 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 8430 true /*Extended*/); 8431 else 8432 getObjCEncodingForType(BlockReturnTy, S); 8433 // Compute size of all parameters. 8434 // Start with computing size of a pointer in number of bytes. 8435 // FIXME: There might(should) be a better way of doing this computation! 8436 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 8437 CharUnits ParmOffset = PtrSize; 8438 for (auto *PI : Decl->parameters()) { 8439 QualType PType = PI->getType(); 8440 CharUnits sz = getObjCEncodingTypeSize(PType); 8441 if (sz.isZero()) 8442 continue; 8443 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 8444 ParmOffset += sz; 8445 } 8446 // Size of the argument frame 8447 S += charUnitsToString(ParmOffset); 8448 // Block pointer and offset. 8449 S += "@?0"; 8450 8451 // Argument types. 8452 ParmOffset = PtrSize; 8453 for (auto *PVDecl : Decl->parameters()) { 8454 QualType PType = PVDecl->getOriginalType(); 8455 if (const auto *AT = 8456 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 8457 // Use array's original type only if it has known number of 8458 // elements. 8459 if (!isa<ConstantArrayType>(AT)) 8460 PType = PVDecl->getType(); 8461 } else if (PType->isFunctionType()) 8462 PType = PVDecl->getType(); 8463 if (getLangOpts().EncodeExtendedBlockSig) 8464 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 8465 S, true /*Extended*/); 8466 else 8467 getObjCEncodingForType(PType, S); 8468 S += charUnitsToString(ParmOffset); 8469 ParmOffset += getObjCEncodingTypeSize(PType); 8470 } 8471 8472 return S; 8473 } 8474 8475 std::string 8476 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 8477 std::string S; 8478 // Encode result type. 8479 getObjCEncodingForType(Decl->getReturnType(), S); 8480 CharUnits ParmOffset; 8481 // Compute size of all parameters. 8482 for (auto *PI : Decl->parameters()) { 8483 QualType PType = PI->getType(); 8484 CharUnits sz = getObjCEncodingTypeSize(PType); 8485 if (sz.isZero()) 8486 continue; 8487 8488 assert(sz.isPositive() && 8489 "getObjCEncodingForFunctionDecl - Incomplete param type"); 8490 ParmOffset += sz; 8491 } 8492 S += charUnitsToString(ParmOffset); 8493 ParmOffset = CharUnits::Zero(); 8494 8495 // Argument types. 8496 for (auto *PVDecl : Decl->parameters()) { 8497 QualType PType = PVDecl->getOriginalType(); 8498 if (const auto *AT = 8499 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 8500 // Use array's original type only if it has known number of 8501 // elements. 8502 if (!isa<ConstantArrayType>(AT)) 8503 PType = PVDecl->getType(); 8504 } else if (PType->isFunctionType()) 8505 PType = PVDecl->getType(); 8506 getObjCEncodingForType(PType, S); 8507 S += charUnitsToString(ParmOffset); 8508 ParmOffset += getObjCEncodingTypeSize(PType); 8509 } 8510 8511 return S; 8512 } 8513 8514 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 8515 /// method parameter or return type. If Extended, include class names and 8516 /// block object types. 8517 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 8518 QualType T, std::string& S, 8519 bool Extended) const { 8520 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 8521 getObjCEncodingForTypeQualifier(QT, S); 8522 // Encode parameter type. 8523 ObjCEncOptions Options = ObjCEncOptions() 8524 .setExpandPointedToStructures() 8525 .setExpandStructures() 8526 .setIsOutermostType(); 8527 if (Extended) 8528 Options.setEncodeBlockParameters().setEncodeClassNames(); 8529 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 8530 } 8531 8532 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 8533 /// declaration. 8534 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 8535 bool Extended) const { 8536 // FIXME: This is not very efficient. 8537 // Encode return type. 8538 std::string S; 8539 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 8540 Decl->getReturnType(), S, Extended); 8541 // Compute size of all parameters. 8542 // Start with computing size of a pointer in number of bytes. 8543 // FIXME: There might(should) be a better way of doing this computation! 8544 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 8545 // The first two arguments (self and _cmd) are pointers; account for 8546 // their size. 8547 CharUnits ParmOffset = 2 * PtrSize; 8548 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 8549 E = Decl->sel_param_end(); PI != E; ++PI) { 8550 QualType PType = (*PI)->getType(); 8551 CharUnits sz = getObjCEncodingTypeSize(PType); 8552 if (sz.isZero()) 8553 continue; 8554 8555 assert(sz.isPositive() && 8556 "getObjCEncodingForMethodDecl - Incomplete param type"); 8557 ParmOffset += sz; 8558 } 8559 S += charUnitsToString(ParmOffset); 8560 S += "@0:"; 8561 S += charUnitsToString(PtrSize); 8562 8563 // Argument types. 8564 ParmOffset = 2 * PtrSize; 8565 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 8566 E = Decl->sel_param_end(); PI != E; ++PI) { 8567 const ParmVarDecl *PVDecl = *PI; 8568 QualType PType = PVDecl->getOriginalType(); 8569 if (const auto *AT = 8570 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 8571 // Use array's original type only if it has known number of 8572 // elements. 8573 if (!isa<ConstantArrayType>(AT)) 8574 PType = PVDecl->getType(); 8575 } else if (PType->isFunctionType()) 8576 PType = PVDecl->getType(); 8577 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 8578 PType, S, Extended); 8579 S += charUnitsToString(ParmOffset); 8580 ParmOffset += getObjCEncodingTypeSize(PType); 8581 } 8582 8583 return S; 8584 } 8585 8586 ObjCPropertyImplDecl * 8587 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 8588 const ObjCPropertyDecl *PD, 8589 const Decl *Container) const { 8590 if (!Container) 8591 return nullptr; 8592 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 8593 for (auto *PID : CID->property_impls()) 8594 if (PID->getPropertyDecl() == PD) 8595 return PID; 8596 } else { 8597 const auto *OID = cast<ObjCImplementationDecl>(Container); 8598 for (auto *PID : OID->property_impls()) 8599 if (PID->getPropertyDecl() == PD) 8600 return PID; 8601 } 8602 return nullptr; 8603 } 8604 8605 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 8606 /// property declaration. If non-NULL, Container must be either an 8607 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 8608 /// NULL when getting encodings for protocol properties. 8609 /// Property attributes are stored as a comma-delimited C string. The simple 8610 /// attributes readonly and bycopy are encoded as single characters. The 8611 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 8612 /// encoded as single characters, followed by an identifier. Property types 8613 /// are also encoded as a parametrized attribute. The characters used to encode 8614 /// these attributes are defined by the following enumeration: 8615 /// @code 8616 /// enum PropertyAttributes { 8617 /// kPropertyReadOnly = 'R', // property is read-only. 8618 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 8619 /// kPropertyByref = '&', // property is a reference to the value last assigned 8620 /// kPropertyDynamic = 'D', // property is dynamic 8621 /// kPropertyGetter = 'G', // followed by getter selector name 8622 /// kPropertySetter = 'S', // followed by setter selector name 8623 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 8624 /// kPropertyType = 'T' // followed by old-style type encoding. 8625 /// kPropertyWeak = 'W' // 'weak' property 8626 /// kPropertyStrong = 'P' // property GC'able 8627 /// kPropertyNonAtomic = 'N' // property non-atomic 8628 /// kPropertyOptional = '?' // property optional 8629 /// }; 8630 /// @endcode 8631 std::string 8632 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 8633 const Decl *Container) const { 8634 // Collect information from the property implementation decl(s). 8635 bool Dynamic = false; 8636 ObjCPropertyImplDecl *SynthesizePID = nullptr; 8637 8638 if (ObjCPropertyImplDecl *PropertyImpDecl = 8639 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 8640 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 8641 Dynamic = true; 8642 else 8643 SynthesizePID = PropertyImpDecl; 8644 } 8645 8646 // FIXME: This is not very efficient. 8647 std::string S = "T"; 8648 8649 // Encode result type. 8650 // GCC has some special rules regarding encoding of properties which 8651 // closely resembles encoding of ivars. 8652 getObjCEncodingForPropertyType(PD->getType(), S); 8653 8654 if (PD->isOptional()) 8655 S += ",?"; 8656 8657 if (PD->isReadOnly()) { 8658 S += ",R"; 8659 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 8660 S += ",C"; 8661 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 8662 S += ",&"; 8663 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 8664 S += ",W"; 8665 } else { 8666 switch (PD->getSetterKind()) { 8667 case ObjCPropertyDecl::Assign: break; 8668 case ObjCPropertyDecl::Copy: S += ",C"; break; 8669 case ObjCPropertyDecl::Retain: S += ",&"; break; 8670 case ObjCPropertyDecl::Weak: S += ",W"; break; 8671 } 8672 } 8673 8674 // It really isn't clear at all what this means, since properties 8675 // are "dynamic by default". 8676 if (Dynamic) 8677 S += ",D"; 8678 8679 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 8680 S += ",N"; 8681 8682 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 8683 S += ",G"; 8684 S += PD->getGetterName().getAsString(); 8685 } 8686 8687 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 8688 S += ",S"; 8689 S += PD->getSetterName().getAsString(); 8690 } 8691 8692 if (SynthesizePID) { 8693 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 8694 S += ",V"; 8695 S += OID->getNameAsString(); 8696 } 8697 8698 // FIXME: OBJCGC: weak & strong 8699 return S; 8700 } 8701 8702 /// getLegacyIntegralTypeEncoding - 8703 /// Another legacy compatibility encoding: 32-bit longs are encoded as 8704 /// 'l' or 'L' , but not always. For typedefs, we need to use 8705 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 8706 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 8707 if (PointeeTy->getAs<TypedefType>()) { 8708 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 8709 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 8710 PointeeTy = UnsignedIntTy; 8711 else 8712 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 8713 PointeeTy = IntTy; 8714 } 8715 } 8716 } 8717 8718 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 8719 const FieldDecl *Field, 8720 QualType *NotEncodedT) const { 8721 // We follow the behavior of gcc, expanding structures which are 8722 // directly pointed to, and expanding embedded structures. Note that 8723 // these rules are sufficient to prevent recursive encoding of the 8724 // same type. 8725 getObjCEncodingForTypeImpl(T, S, 8726 ObjCEncOptions() 8727 .setExpandPointedToStructures() 8728 .setExpandStructures() 8729 .setIsOutermostType(), 8730 Field, NotEncodedT); 8731 } 8732 8733 void ASTContext::getObjCEncodingForPropertyType(QualType T, 8734 std::string& S) const { 8735 // Encode result type. 8736 // GCC has some special rules regarding encoding of properties which 8737 // closely resembles encoding of ivars. 8738 getObjCEncodingForTypeImpl(T, S, 8739 ObjCEncOptions() 8740 .setExpandPointedToStructures() 8741 .setExpandStructures() 8742 .setIsOutermostType() 8743 .setEncodingProperty(), 8744 /*Field=*/nullptr); 8745 } 8746 8747 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 8748 const BuiltinType *BT) { 8749 BuiltinType::Kind kind = BT->getKind(); 8750 switch (kind) { 8751 case BuiltinType::Void: return 'v'; 8752 case BuiltinType::Bool: return 'B'; 8753 case BuiltinType::Char8: 8754 case BuiltinType::Char_U: 8755 case BuiltinType::UChar: return 'C'; 8756 case BuiltinType::Char16: 8757 case BuiltinType::UShort: return 'S'; 8758 case BuiltinType::Char32: 8759 case BuiltinType::UInt: return 'I'; 8760 case BuiltinType::ULong: 8761 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 8762 case BuiltinType::UInt128: return 'T'; 8763 case BuiltinType::ULongLong: return 'Q'; 8764 case BuiltinType::Char_S: 8765 case BuiltinType::SChar: return 'c'; 8766 case BuiltinType::Short: return 's'; 8767 case BuiltinType::WChar_S: 8768 case BuiltinType::WChar_U: 8769 case BuiltinType::Int: return 'i'; 8770 case BuiltinType::Long: 8771 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 8772 case BuiltinType::LongLong: return 'q'; 8773 case BuiltinType::Int128: return 't'; 8774 case BuiltinType::Float: return 'f'; 8775 case BuiltinType::Double: return 'd'; 8776 case BuiltinType::LongDouble: return 'D'; 8777 case BuiltinType::NullPtr: return '*'; // like char* 8778 8779 case BuiltinType::BFloat16: 8780 case BuiltinType::Float16: 8781 case BuiltinType::Float128: 8782 case BuiltinType::Ibm128: 8783 case BuiltinType::Half: 8784 case BuiltinType::ShortAccum: 8785 case BuiltinType::Accum: 8786 case BuiltinType::LongAccum: 8787 case BuiltinType::UShortAccum: 8788 case BuiltinType::UAccum: 8789 case BuiltinType::ULongAccum: 8790 case BuiltinType::ShortFract: 8791 case BuiltinType::Fract: 8792 case BuiltinType::LongFract: 8793 case BuiltinType::UShortFract: 8794 case BuiltinType::UFract: 8795 case BuiltinType::ULongFract: 8796 case BuiltinType::SatShortAccum: 8797 case BuiltinType::SatAccum: 8798 case BuiltinType::SatLongAccum: 8799 case BuiltinType::SatUShortAccum: 8800 case BuiltinType::SatUAccum: 8801 case BuiltinType::SatULongAccum: 8802 case BuiltinType::SatShortFract: 8803 case BuiltinType::SatFract: 8804 case BuiltinType::SatLongFract: 8805 case BuiltinType::SatUShortFract: 8806 case BuiltinType::SatUFract: 8807 case BuiltinType::SatULongFract: 8808 // FIXME: potentially need @encodes for these! 8809 return ' '; 8810 8811 #define SVE_TYPE(Name, Id, SingletonId) \ 8812 case BuiltinType::Id: 8813 #include "clang/Basic/AArch64SVEACLETypes.def" 8814 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 8815 #include "clang/Basic/RISCVVTypes.def" 8816 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 8817 #include "clang/Basic/WebAssemblyReferenceTypes.def" 8818 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: 8819 #include "clang/Basic/AMDGPUTypes.def" 8820 { 8821 DiagnosticsEngine &Diags = C->getDiagnostics(); 8822 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 8823 "cannot yet @encode type %0"); 8824 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 8825 return ' '; 8826 } 8827 8828 case BuiltinType::ObjCId: 8829 case BuiltinType::ObjCClass: 8830 case BuiltinType::ObjCSel: 8831 llvm_unreachable("@encoding ObjC primitive type"); 8832 8833 // OpenCL and placeholder types don't need @encodings. 8834 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8835 case BuiltinType::Id: 8836 #include "clang/Basic/OpenCLImageTypes.def" 8837 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 8838 case BuiltinType::Id: 8839 #include "clang/Basic/OpenCLExtensionTypes.def" 8840 case BuiltinType::OCLEvent: 8841 case BuiltinType::OCLClkEvent: 8842 case BuiltinType::OCLQueue: 8843 case BuiltinType::OCLReserveID: 8844 case BuiltinType::OCLSampler: 8845 case BuiltinType::Dependent: 8846 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 8847 case BuiltinType::Id: 8848 #include "clang/Basic/PPCTypes.def" 8849 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 8850 #include "clang/Basic/HLSLIntangibleTypes.def" 8851 #define BUILTIN_TYPE(KIND, ID) 8852 #define PLACEHOLDER_TYPE(KIND, ID) \ 8853 case BuiltinType::KIND: 8854 #include "clang/AST/BuiltinTypes.def" 8855 llvm_unreachable("invalid builtin type for @encode"); 8856 } 8857 llvm_unreachable("invalid BuiltinType::Kind value"); 8858 } 8859 8860 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 8861 EnumDecl *Enum = ET->getDecl(); 8862 8863 // The encoding of an non-fixed enum type is always 'i', regardless of size. 8864 if (!Enum->isFixed()) 8865 return 'i'; 8866 8867 // The encoding of a fixed enum type matches its fixed underlying type. 8868 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 8869 return getObjCEncodingForPrimitiveType(C, BT); 8870 } 8871 8872 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 8873 QualType T, const FieldDecl *FD) { 8874 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 8875 S += 'b'; 8876 // The NeXT runtime encodes bit fields as b followed by the number of bits. 8877 // The GNU runtime requires more information; bitfields are encoded as b, 8878 // then the offset (in bits) of the first element, then the type of the 8879 // bitfield, then the size in bits. For example, in this structure: 8880 // 8881 // struct 8882 // { 8883 // int integer; 8884 // int flags:2; 8885 // }; 8886 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 8887 // runtime, but b32i2 for the GNU runtime. The reason for this extra 8888 // information is not especially sensible, but we're stuck with it for 8889 // compatibility with GCC, although providing it breaks anything that 8890 // actually uses runtime introspection and wants to work on both runtimes... 8891 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 8892 uint64_t Offset; 8893 8894 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 8895 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 8896 IVD); 8897 } else { 8898 const RecordDecl *RD = FD->getParent(); 8899 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 8900 Offset = RL.getFieldOffset(FD->getFieldIndex()); 8901 } 8902 8903 S += llvm::utostr(Offset); 8904 8905 if (const auto *ET = T->getAs<EnumType>()) 8906 S += ObjCEncodingForEnumType(Ctx, ET); 8907 else { 8908 const auto *BT = T->castAs<BuiltinType>(); 8909 S += getObjCEncodingForPrimitiveType(Ctx, BT); 8910 } 8911 } 8912 S += llvm::utostr(FD->getBitWidthValue()); 8913 } 8914 8915 // Helper function for determining whether the encoded type string would include 8916 // a template specialization type. 8917 static bool hasTemplateSpecializationInEncodedString(const Type *T, 8918 bool VisitBasesAndFields) { 8919 T = T->getBaseElementTypeUnsafe(); 8920 8921 if (auto *PT = T->getAs<PointerType>()) 8922 return hasTemplateSpecializationInEncodedString( 8923 PT->getPointeeType().getTypePtr(), false); 8924 8925 auto *CXXRD = T->getAsCXXRecordDecl(); 8926 8927 if (!CXXRD) 8928 return false; 8929 8930 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 8931 return true; 8932 8933 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 8934 return false; 8935 8936 for (const auto &B : CXXRD->bases()) 8937 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 8938 true)) 8939 return true; 8940 8941 for (auto *FD : CXXRD->fields()) 8942 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 8943 true)) 8944 return true; 8945 8946 return false; 8947 } 8948 8949 // FIXME: Use SmallString for accumulating string. 8950 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 8951 const ObjCEncOptions Options, 8952 const FieldDecl *FD, 8953 QualType *NotEncodedT) const { 8954 CanQualType CT = getCanonicalType(T); 8955 switch (CT->getTypeClass()) { 8956 case Type::Builtin: 8957 case Type::Enum: 8958 if (FD && FD->isBitField()) 8959 return EncodeBitField(this, S, T, FD); 8960 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 8961 S += getObjCEncodingForPrimitiveType(this, BT); 8962 else 8963 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 8964 return; 8965 8966 case Type::Complex: 8967 S += 'j'; 8968 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 8969 ObjCEncOptions(), 8970 /*Field=*/nullptr); 8971 return; 8972 8973 case Type::Atomic: 8974 S += 'A'; 8975 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 8976 ObjCEncOptions(), 8977 /*Field=*/nullptr); 8978 return; 8979 8980 // encoding for pointer or reference types. 8981 case Type::Pointer: 8982 case Type::LValueReference: 8983 case Type::RValueReference: { 8984 QualType PointeeTy; 8985 if (isa<PointerType>(CT)) { 8986 const auto *PT = T->castAs<PointerType>(); 8987 if (PT->isObjCSelType()) { 8988 S += ':'; 8989 return; 8990 } 8991 PointeeTy = PT->getPointeeType(); 8992 } else { 8993 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 8994 } 8995 8996 bool isReadOnly = false; 8997 // For historical/compatibility reasons, the read-only qualifier of the 8998 // pointee gets emitted _before_ the '^'. The read-only qualifier of 8999 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 9000 // Also, do not emit the 'r' for anything but the outermost type! 9001 if (T->getAs<TypedefType>()) { 9002 if (Options.IsOutermostType() && T.isConstQualified()) { 9003 isReadOnly = true; 9004 S += 'r'; 9005 } 9006 } else if (Options.IsOutermostType()) { 9007 QualType P = PointeeTy; 9008 while (auto PT = P->getAs<PointerType>()) 9009 P = PT->getPointeeType(); 9010 if (P.isConstQualified()) { 9011 isReadOnly = true; 9012 S += 'r'; 9013 } 9014 } 9015 if (isReadOnly) { 9016 // Another legacy compatibility encoding. Some ObjC qualifier and type 9017 // combinations need to be rearranged. 9018 // Rewrite "in const" from "nr" to "rn" 9019 if (StringRef(S).ends_with("nr")) 9020 S.replace(S.end()-2, S.end(), "rn"); 9021 } 9022 9023 if (PointeeTy->isCharType()) { 9024 // char pointer types should be encoded as '*' unless it is a 9025 // type that has been typedef'd to 'BOOL'. 9026 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 9027 S += '*'; 9028 return; 9029 } 9030 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 9031 // GCC binary compat: Need to convert "struct objc_class *" to "#". 9032 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 9033 S += '#'; 9034 return; 9035 } 9036 // GCC binary compat: Need to convert "struct objc_object *" to "@". 9037 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 9038 S += '@'; 9039 return; 9040 } 9041 // If the encoded string for the class includes template names, just emit 9042 // "^v" for pointers to the class. 9043 if (getLangOpts().CPlusPlus && 9044 (!getLangOpts().EncodeCXXClassTemplateSpec && 9045 hasTemplateSpecializationInEncodedString( 9046 RTy, Options.ExpandPointedToStructures()))) { 9047 S += "^v"; 9048 return; 9049 } 9050 // fall through... 9051 } 9052 S += '^'; 9053 getLegacyIntegralTypeEncoding(PointeeTy); 9054 9055 ObjCEncOptions NewOptions; 9056 if (Options.ExpandPointedToStructures()) 9057 NewOptions.setExpandStructures(); 9058 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 9059 /*Field=*/nullptr, NotEncodedT); 9060 return; 9061 } 9062 9063 case Type::ConstantArray: 9064 case Type::IncompleteArray: 9065 case Type::VariableArray: { 9066 const auto *AT = cast<ArrayType>(CT); 9067 9068 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 9069 // Incomplete arrays are encoded as a pointer to the array element. 9070 S += '^'; 9071 9072 getObjCEncodingForTypeImpl( 9073 AT->getElementType(), S, 9074 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 9075 } else { 9076 S += '['; 9077 9078 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 9079 S += llvm::utostr(CAT->getZExtSize()); 9080 else { 9081 //Variable length arrays are encoded as a regular array with 0 elements. 9082 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 9083 "Unknown array type!"); 9084 S += '0'; 9085 } 9086 9087 getObjCEncodingForTypeImpl( 9088 AT->getElementType(), S, 9089 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 9090 NotEncodedT); 9091 S += ']'; 9092 } 9093 return; 9094 } 9095 9096 case Type::FunctionNoProto: 9097 case Type::FunctionProto: 9098 S += '?'; 9099 return; 9100 9101 case Type::Record: { 9102 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 9103 S += RDecl->isUnion() ? '(' : '{'; 9104 // Anonymous structures print as '?' 9105 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 9106 S += II->getName(); 9107 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 9108 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 9109 llvm::raw_string_ostream OS(S); 9110 printTemplateArgumentList(OS, TemplateArgs.asArray(), 9111 getPrintingPolicy()); 9112 } 9113 } else { 9114 S += '?'; 9115 } 9116 if (Options.ExpandStructures()) { 9117 S += '='; 9118 if (!RDecl->isUnion()) { 9119 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 9120 } else { 9121 for (const auto *Field : RDecl->fields()) { 9122 if (FD) { 9123 S += '"'; 9124 S += Field->getNameAsString(); 9125 S += '"'; 9126 } 9127 9128 // Special case bit-fields. 9129 if (Field->isBitField()) { 9130 getObjCEncodingForTypeImpl(Field->getType(), S, 9131 ObjCEncOptions().setExpandStructures(), 9132 Field); 9133 } else { 9134 QualType qt = Field->getType(); 9135 getLegacyIntegralTypeEncoding(qt); 9136 getObjCEncodingForTypeImpl( 9137 qt, S, 9138 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 9139 NotEncodedT); 9140 } 9141 } 9142 } 9143 } 9144 S += RDecl->isUnion() ? ')' : '}'; 9145 return; 9146 } 9147 9148 case Type::BlockPointer: { 9149 const auto *BT = T->castAs<BlockPointerType>(); 9150 S += "@?"; // Unlike a pointer-to-function, which is "^?". 9151 if (Options.EncodeBlockParameters()) { 9152 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 9153 9154 S += '<'; 9155 // Block return type 9156 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 9157 Options.forComponentType(), FD, NotEncodedT); 9158 // Block self 9159 S += "@?"; 9160 // Block parameters 9161 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 9162 for (const auto &I : FPT->param_types()) 9163 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 9164 NotEncodedT); 9165 } 9166 S += '>'; 9167 } 9168 return; 9169 } 9170 9171 case Type::ObjCObject: { 9172 // hack to match legacy encoding of *id and *Class 9173 QualType Ty = getObjCObjectPointerType(CT); 9174 if (Ty->isObjCIdType()) { 9175 S += "{objc_object=}"; 9176 return; 9177 } 9178 else if (Ty->isObjCClassType()) { 9179 S += "{objc_class=}"; 9180 return; 9181 } 9182 // TODO: Double check to make sure this intentionally falls through. 9183 [[fallthrough]]; 9184 } 9185 9186 case Type::ObjCInterface: { 9187 // Ignore protocol qualifiers when mangling at this level. 9188 // @encode(class_name) 9189 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 9190 S += '{'; 9191 S += OI->getObjCRuntimeNameAsString(); 9192 if (Options.ExpandStructures()) { 9193 S += '='; 9194 SmallVector<const ObjCIvarDecl*, 32> Ivars; 9195 DeepCollectObjCIvars(OI, true, Ivars); 9196 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 9197 const FieldDecl *Field = Ivars[i]; 9198 if (Field->isBitField()) 9199 getObjCEncodingForTypeImpl(Field->getType(), S, 9200 ObjCEncOptions().setExpandStructures(), 9201 Field); 9202 else 9203 getObjCEncodingForTypeImpl(Field->getType(), S, 9204 ObjCEncOptions().setExpandStructures(), FD, 9205 NotEncodedT); 9206 } 9207 } 9208 S += '}'; 9209 return; 9210 } 9211 9212 case Type::ObjCObjectPointer: { 9213 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 9214 if (OPT->isObjCIdType()) { 9215 S += '@'; 9216 return; 9217 } 9218 9219 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 9220 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 9221 // Since this is a binary compatibility issue, need to consult with 9222 // runtime folks. Fortunately, this is a *very* obscure construct. 9223 S += '#'; 9224 return; 9225 } 9226 9227 if (OPT->isObjCQualifiedIdType()) { 9228 getObjCEncodingForTypeImpl( 9229 getObjCIdType(), S, 9230 Options.keepingOnly(ObjCEncOptions() 9231 .setExpandPointedToStructures() 9232 .setExpandStructures()), 9233 FD); 9234 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 9235 // Note that we do extended encoding of protocol qualifier list 9236 // Only when doing ivar or property encoding. 9237 S += '"'; 9238 for (const auto *I : OPT->quals()) { 9239 S += '<'; 9240 S += I->getObjCRuntimeNameAsString(); 9241 S += '>'; 9242 } 9243 S += '"'; 9244 } 9245 return; 9246 } 9247 9248 S += '@'; 9249 if (OPT->getInterfaceDecl() && 9250 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 9251 S += '"'; 9252 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 9253 for (const auto *I : OPT->quals()) { 9254 S += '<'; 9255 S += I->getObjCRuntimeNameAsString(); 9256 S += '>'; 9257 } 9258 S += '"'; 9259 } 9260 return; 9261 } 9262 9263 // gcc just blithely ignores member pointers. 9264 // FIXME: we should do better than that. 'M' is available. 9265 case Type::MemberPointer: 9266 // This matches gcc's encoding, even though technically it is insufficient. 9267 //FIXME. We should do a better job than gcc. 9268 case Type::Vector: 9269 case Type::ExtVector: 9270 // Until we have a coherent encoding of these three types, issue warning. 9271 if (NotEncodedT) 9272 *NotEncodedT = T; 9273 return; 9274 9275 case Type::ConstantMatrix: 9276 if (NotEncodedT) 9277 *NotEncodedT = T; 9278 return; 9279 9280 case Type::BitInt: 9281 if (NotEncodedT) 9282 *NotEncodedT = T; 9283 return; 9284 9285 // We could see an undeduced auto type here during error recovery. 9286 // Just ignore it. 9287 case Type::Auto: 9288 case Type::DeducedTemplateSpecialization: 9289 return; 9290 9291 case Type::HLSLAttributedResource: 9292 llvm_unreachable("unexpected type"); 9293 9294 case Type::ArrayParameter: 9295 case Type::Pipe: 9296 #define ABSTRACT_TYPE(KIND, BASE) 9297 #define TYPE(KIND, BASE) 9298 #define DEPENDENT_TYPE(KIND, BASE) \ 9299 case Type::KIND: 9300 #define NON_CANONICAL_TYPE(KIND, BASE) \ 9301 case Type::KIND: 9302 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 9303 case Type::KIND: 9304 #include "clang/AST/TypeNodes.inc" 9305 llvm_unreachable("@encode for dependent type!"); 9306 } 9307 llvm_unreachable("bad type kind!"); 9308 } 9309 9310 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 9311 std::string &S, 9312 const FieldDecl *FD, 9313 bool includeVBases, 9314 QualType *NotEncodedT) const { 9315 assert(RDecl && "Expected non-null RecordDecl"); 9316 assert(!RDecl->isUnion() && "Should not be called for unions"); 9317 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 9318 return; 9319 9320 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 9321 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 9322 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 9323 9324 if (CXXRec) { 9325 for (const auto &BI : CXXRec->bases()) { 9326 if (!BI.isVirtual()) { 9327 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 9328 if (base->isEmpty()) 9329 continue; 9330 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 9331 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 9332 std::make_pair(offs, base)); 9333 } 9334 } 9335 } 9336 9337 for (FieldDecl *Field : RDecl->fields()) { 9338 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this)) 9339 continue; 9340 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex()); 9341 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 9342 std::make_pair(offs, Field)); 9343 } 9344 9345 if (CXXRec && includeVBases) { 9346 for (const auto &BI : CXXRec->vbases()) { 9347 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 9348 if (base->isEmpty()) 9349 continue; 9350 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 9351 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 9352 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 9353 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 9354 std::make_pair(offs, base)); 9355 } 9356 } 9357 9358 CharUnits size; 9359 if (CXXRec) { 9360 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 9361 } else { 9362 size = layout.getSize(); 9363 } 9364 9365 #ifndef NDEBUG 9366 uint64_t CurOffs = 0; 9367 #endif 9368 std::multimap<uint64_t, NamedDecl *>::iterator 9369 CurLayObj = FieldOrBaseOffsets.begin(); 9370 9371 if (CXXRec && CXXRec->isDynamicClass() && 9372 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 9373 if (FD) { 9374 S += "\"_vptr$"; 9375 std::string recname = CXXRec->getNameAsString(); 9376 if (recname.empty()) recname = "?"; 9377 S += recname; 9378 S += '"'; 9379 } 9380 S += "^^?"; 9381 #ifndef NDEBUG 9382 CurOffs += getTypeSize(VoidPtrTy); 9383 #endif 9384 } 9385 9386 if (!RDecl->hasFlexibleArrayMember()) { 9387 // Mark the end of the structure. 9388 uint64_t offs = toBits(size); 9389 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 9390 std::make_pair(offs, nullptr)); 9391 } 9392 9393 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 9394 #ifndef NDEBUG 9395 assert(CurOffs <= CurLayObj->first); 9396 if (CurOffs < CurLayObj->first) { 9397 uint64_t padding = CurLayObj->first - CurOffs; 9398 // FIXME: There doesn't seem to be a way to indicate in the encoding that 9399 // packing/alignment of members is different that normal, in which case 9400 // the encoding will be out-of-sync with the real layout. 9401 // If the runtime switches to just consider the size of types without 9402 // taking into account alignment, we could make padding explicit in the 9403 // encoding (e.g. using arrays of chars). The encoding strings would be 9404 // longer then though. 9405 CurOffs += padding; 9406 } 9407 #endif 9408 9409 NamedDecl *dcl = CurLayObj->second; 9410 if (!dcl) 9411 break; // reached end of structure. 9412 9413 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 9414 // We expand the bases without their virtual bases since those are going 9415 // in the initial structure. Note that this differs from gcc which 9416 // expands virtual bases each time one is encountered in the hierarchy, 9417 // making the encoding type bigger than it really is. 9418 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 9419 NotEncodedT); 9420 assert(!base->isEmpty()); 9421 #ifndef NDEBUG 9422 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 9423 #endif 9424 } else { 9425 const auto *field = cast<FieldDecl>(dcl); 9426 if (FD) { 9427 S += '"'; 9428 S += field->getNameAsString(); 9429 S += '"'; 9430 } 9431 9432 if (field->isBitField()) { 9433 EncodeBitField(this, S, field->getType(), field); 9434 #ifndef NDEBUG 9435 CurOffs += field->getBitWidthValue(); 9436 #endif 9437 } else { 9438 QualType qt = field->getType(); 9439 getLegacyIntegralTypeEncoding(qt); 9440 getObjCEncodingForTypeImpl( 9441 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 9442 FD, NotEncodedT); 9443 #ifndef NDEBUG 9444 CurOffs += getTypeSize(field->getType()); 9445 #endif 9446 } 9447 } 9448 } 9449 } 9450 9451 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 9452 std::string& S) const { 9453 if (QT & Decl::OBJC_TQ_In) 9454 S += 'n'; 9455 if (QT & Decl::OBJC_TQ_Inout) 9456 S += 'N'; 9457 if (QT & Decl::OBJC_TQ_Out) 9458 S += 'o'; 9459 if (QT & Decl::OBJC_TQ_Bycopy) 9460 S += 'O'; 9461 if (QT & Decl::OBJC_TQ_Byref) 9462 S += 'R'; 9463 if (QT & Decl::OBJC_TQ_Oneway) 9464 S += 'V'; 9465 } 9466 9467 TypedefDecl *ASTContext::getObjCIdDecl() const { 9468 if (!ObjCIdDecl) { 9469 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 9470 T = getObjCObjectPointerType(T); 9471 ObjCIdDecl = buildImplicitTypedef(T, "id"); 9472 } 9473 return ObjCIdDecl; 9474 } 9475 9476 TypedefDecl *ASTContext::getObjCSelDecl() const { 9477 if (!ObjCSelDecl) { 9478 QualType T = getPointerType(ObjCBuiltinSelTy); 9479 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 9480 } 9481 return ObjCSelDecl; 9482 } 9483 9484 TypedefDecl *ASTContext::getObjCClassDecl() const { 9485 if (!ObjCClassDecl) { 9486 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 9487 T = getObjCObjectPointerType(T); 9488 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 9489 } 9490 return ObjCClassDecl; 9491 } 9492 9493 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 9494 if (!ObjCProtocolClassDecl) { 9495 ObjCProtocolClassDecl 9496 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 9497 SourceLocation(), 9498 &Idents.get("Protocol"), 9499 /*typeParamList=*/nullptr, 9500 /*PrevDecl=*/nullptr, 9501 SourceLocation(), true); 9502 } 9503 9504 return ObjCProtocolClassDecl; 9505 } 9506 9507 //===----------------------------------------------------------------------===// 9508 // __builtin_va_list Construction Functions 9509 //===----------------------------------------------------------------------===// 9510 9511 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 9512 StringRef Name) { 9513 // typedef char* __builtin[_ms]_va_list; 9514 QualType T = Context->getPointerType(Context->CharTy); 9515 return Context->buildImplicitTypedef(T, Name); 9516 } 9517 9518 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 9519 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 9520 } 9521 9522 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 9523 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 9524 } 9525 9526 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 9527 // typedef void* __builtin_va_list; 9528 QualType T = Context->getPointerType(Context->VoidTy); 9529 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 9530 } 9531 9532 static TypedefDecl * 9533 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 9534 // struct __va_list 9535 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 9536 if (Context->getLangOpts().CPlusPlus) { 9537 // namespace std { struct __va_list { 9538 auto *NS = NamespaceDecl::Create( 9539 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 9540 /*Inline=*/false, SourceLocation(), SourceLocation(), 9541 &Context->Idents.get("std"), 9542 /*PrevDecl=*/nullptr, /*Nested=*/false); 9543 NS->setImplicit(); 9544 VaListTagDecl->setDeclContext(NS); 9545 } 9546 9547 VaListTagDecl->startDefinition(); 9548 9549 const size_t NumFields = 5; 9550 QualType FieldTypes[NumFields]; 9551 const char *FieldNames[NumFields]; 9552 9553 // void *__stack; 9554 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 9555 FieldNames[0] = "__stack"; 9556 9557 // void *__gr_top; 9558 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 9559 FieldNames[1] = "__gr_top"; 9560 9561 // void *__vr_top; 9562 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 9563 FieldNames[2] = "__vr_top"; 9564 9565 // int __gr_offs; 9566 FieldTypes[3] = Context->IntTy; 9567 FieldNames[3] = "__gr_offs"; 9568 9569 // int __vr_offs; 9570 FieldTypes[4] = Context->IntTy; 9571 FieldNames[4] = "__vr_offs"; 9572 9573 // Create fields 9574 for (unsigned i = 0; i < NumFields; ++i) { 9575 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 9576 VaListTagDecl, 9577 SourceLocation(), 9578 SourceLocation(), 9579 &Context->Idents.get(FieldNames[i]), 9580 FieldTypes[i], /*TInfo=*/nullptr, 9581 /*BitWidth=*/nullptr, 9582 /*Mutable=*/false, 9583 ICIS_NoInit); 9584 Field->setAccess(AS_public); 9585 VaListTagDecl->addDecl(Field); 9586 } 9587 VaListTagDecl->completeDefinition(); 9588 Context->VaListTagDecl = VaListTagDecl; 9589 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9590 9591 // } __builtin_va_list; 9592 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 9593 } 9594 9595 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 9596 // typedef struct __va_list_tag { 9597 RecordDecl *VaListTagDecl; 9598 9599 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 9600 VaListTagDecl->startDefinition(); 9601 9602 const size_t NumFields = 5; 9603 QualType FieldTypes[NumFields]; 9604 const char *FieldNames[NumFields]; 9605 9606 // unsigned char gpr; 9607 FieldTypes[0] = Context->UnsignedCharTy; 9608 FieldNames[0] = "gpr"; 9609 9610 // unsigned char fpr; 9611 FieldTypes[1] = Context->UnsignedCharTy; 9612 FieldNames[1] = "fpr"; 9613 9614 // unsigned short reserved; 9615 FieldTypes[2] = Context->UnsignedShortTy; 9616 FieldNames[2] = "reserved"; 9617 9618 // void* overflow_arg_area; 9619 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 9620 FieldNames[3] = "overflow_arg_area"; 9621 9622 // void* reg_save_area; 9623 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 9624 FieldNames[4] = "reg_save_area"; 9625 9626 // Create fields 9627 for (unsigned i = 0; i < NumFields; ++i) { 9628 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 9629 SourceLocation(), 9630 SourceLocation(), 9631 &Context->Idents.get(FieldNames[i]), 9632 FieldTypes[i], /*TInfo=*/nullptr, 9633 /*BitWidth=*/nullptr, 9634 /*Mutable=*/false, 9635 ICIS_NoInit); 9636 Field->setAccess(AS_public); 9637 VaListTagDecl->addDecl(Field); 9638 } 9639 VaListTagDecl->completeDefinition(); 9640 Context->VaListTagDecl = VaListTagDecl; 9641 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9642 9643 // } __va_list_tag; 9644 TypedefDecl *VaListTagTypedefDecl = 9645 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 9646 9647 QualType VaListTagTypedefType = 9648 Context->getTypedefType(VaListTagTypedefDecl); 9649 9650 // typedef __va_list_tag __builtin_va_list[1]; 9651 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 9652 QualType VaListTagArrayType = Context->getConstantArrayType( 9653 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0); 9654 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 9655 } 9656 9657 static TypedefDecl * 9658 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 9659 // struct __va_list_tag { 9660 RecordDecl *VaListTagDecl; 9661 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 9662 VaListTagDecl->startDefinition(); 9663 9664 const size_t NumFields = 4; 9665 QualType FieldTypes[NumFields]; 9666 const char *FieldNames[NumFields]; 9667 9668 // unsigned gp_offset; 9669 FieldTypes[0] = Context->UnsignedIntTy; 9670 FieldNames[0] = "gp_offset"; 9671 9672 // unsigned fp_offset; 9673 FieldTypes[1] = Context->UnsignedIntTy; 9674 FieldNames[1] = "fp_offset"; 9675 9676 // void* overflow_arg_area; 9677 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 9678 FieldNames[2] = "overflow_arg_area"; 9679 9680 // void* reg_save_area; 9681 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 9682 FieldNames[3] = "reg_save_area"; 9683 9684 // Create fields 9685 for (unsigned i = 0; i < NumFields; ++i) { 9686 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 9687 VaListTagDecl, 9688 SourceLocation(), 9689 SourceLocation(), 9690 &Context->Idents.get(FieldNames[i]), 9691 FieldTypes[i], /*TInfo=*/nullptr, 9692 /*BitWidth=*/nullptr, 9693 /*Mutable=*/false, 9694 ICIS_NoInit); 9695 Field->setAccess(AS_public); 9696 VaListTagDecl->addDecl(Field); 9697 } 9698 VaListTagDecl->completeDefinition(); 9699 Context->VaListTagDecl = VaListTagDecl; 9700 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9701 9702 // }; 9703 9704 // typedef struct __va_list_tag __builtin_va_list[1]; 9705 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 9706 QualType VaListTagArrayType = Context->getConstantArrayType( 9707 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0); 9708 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 9709 } 9710 9711 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 9712 // typedef int __builtin_va_list[4]; 9713 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 9714 QualType IntArrayType = Context->getConstantArrayType( 9715 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0); 9716 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 9717 } 9718 9719 static TypedefDecl * 9720 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 9721 // struct __va_list 9722 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 9723 if (Context->getLangOpts().CPlusPlus) { 9724 // namespace std { struct __va_list { 9725 NamespaceDecl *NS; 9726 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 9727 Context->getTranslationUnitDecl(), 9728 /*Inline=*/false, SourceLocation(), 9729 SourceLocation(), &Context->Idents.get("std"), 9730 /*PrevDecl=*/nullptr, /*Nested=*/false); 9731 NS->setImplicit(); 9732 VaListDecl->setDeclContext(NS); 9733 } 9734 9735 VaListDecl->startDefinition(); 9736 9737 // void * __ap; 9738 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 9739 VaListDecl, 9740 SourceLocation(), 9741 SourceLocation(), 9742 &Context->Idents.get("__ap"), 9743 Context->getPointerType(Context->VoidTy), 9744 /*TInfo=*/nullptr, 9745 /*BitWidth=*/nullptr, 9746 /*Mutable=*/false, 9747 ICIS_NoInit); 9748 Field->setAccess(AS_public); 9749 VaListDecl->addDecl(Field); 9750 9751 // }; 9752 VaListDecl->completeDefinition(); 9753 Context->VaListTagDecl = VaListDecl; 9754 9755 // typedef struct __va_list __builtin_va_list; 9756 QualType T = Context->getRecordType(VaListDecl); 9757 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 9758 } 9759 9760 static TypedefDecl * 9761 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 9762 // struct __va_list_tag { 9763 RecordDecl *VaListTagDecl; 9764 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 9765 VaListTagDecl->startDefinition(); 9766 9767 const size_t NumFields = 4; 9768 QualType FieldTypes[NumFields]; 9769 const char *FieldNames[NumFields]; 9770 9771 // long __gpr; 9772 FieldTypes[0] = Context->LongTy; 9773 FieldNames[0] = "__gpr"; 9774 9775 // long __fpr; 9776 FieldTypes[1] = Context->LongTy; 9777 FieldNames[1] = "__fpr"; 9778 9779 // void *__overflow_arg_area; 9780 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 9781 FieldNames[2] = "__overflow_arg_area"; 9782 9783 // void *__reg_save_area; 9784 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 9785 FieldNames[3] = "__reg_save_area"; 9786 9787 // Create fields 9788 for (unsigned i = 0; i < NumFields; ++i) { 9789 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 9790 VaListTagDecl, 9791 SourceLocation(), 9792 SourceLocation(), 9793 &Context->Idents.get(FieldNames[i]), 9794 FieldTypes[i], /*TInfo=*/nullptr, 9795 /*BitWidth=*/nullptr, 9796 /*Mutable=*/false, 9797 ICIS_NoInit); 9798 Field->setAccess(AS_public); 9799 VaListTagDecl->addDecl(Field); 9800 } 9801 VaListTagDecl->completeDefinition(); 9802 Context->VaListTagDecl = VaListTagDecl; 9803 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9804 9805 // }; 9806 9807 // typedef __va_list_tag __builtin_va_list[1]; 9808 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 9809 QualType VaListTagArrayType = Context->getConstantArrayType( 9810 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0); 9811 9812 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 9813 } 9814 9815 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 9816 // typedef struct __va_list_tag { 9817 RecordDecl *VaListTagDecl; 9818 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 9819 VaListTagDecl->startDefinition(); 9820 9821 const size_t NumFields = 3; 9822 QualType FieldTypes[NumFields]; 9823 const char *FieldNames[NumFields]; 9824 9825 // void *CurrentSavedRegisterArea; 9826 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 9827 FieldNames[0] = "__current_saved_reg_area_pointer"; 9828 9829 // void *SavedRegAreaEnd; 9830 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 9831 FieldNames[1] = "__saved_reg_area_end_pointer"; 9832 9833 // void *OverflowArea; 9834 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 9835 FieldNames[2] = "__overflow_area_pointer"; 9836 9837 // Create fields 9838 for (unsigned i = 0; i < NumFields; ++i) { 9839 FieldDecl *Field = FieldDecl::Create( 9840 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 9841 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 9842 /*TInfo=*/nullptr, 9843 /*BitWidth=*/nullptr, 9844 /*Mutable=*/false, ICIS_NoInit); 9845 Field->setAccess(AS_public); 9846 VaListTagDecl->addDecl(Field); 9847 } 9848 VaListTagDecl->completeDefinition(); 9849 Context->VaListTagDecl = VaListTagDecl; 9850 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9851 9852 // } __va_list_tag; 9853 TypedefDecl *VaListTagTypedefDecl = 9854 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 9855 9856 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 9857 9858 // typedef __va_list_tag __builtin_va_list[1]; 9859 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 9860 QualType VaListTagArrayType = Context->getConstantArrayType( 9861 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0); 9862 9863 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 9864 } 9865 9866 static TypedefDecl * 9867 CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) { 9868 // typedef struct __va_list_tag { 9869 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 9870 9871 VaListTagDecl->startDefinition(); 9872 9873 // int* __va_stk; 9874 // int* __va_reg; 9875 // int __va_ndx; 9876 constexpr size_t NumFields = 3; 9877 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy), 9878 Context->getPointerType(Context->IntTy), 9879 Context->IntTy}; 9880 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"}; 9881 9882 // Create fields 9883 for (unsigned i = 0; i < NumFields; ++i) { 9884 FieldDecl *Field = FieldDecl::Create( 9885 *Context, VaListTagDecl, SourceLocation(), SourceLocation(), 9886 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 9887 /*BitWidth=*/nullptr, 9888 /*Mutable=*/false, ICIS_NoInit); 9889 Field->setAccess(AS_public); 9890 VaListTagDecl->addDecl(Field); 9891 } 9892 VaListTagDecl->completeDefinition(); 9893 Context->VaListTagDecl = VaListTagDecl; 9894 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 9895 9896 // } __va_list_tag; 9897 TypedefDecl *VaListTagTypedefDecl = 9898 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 9899 9900 return VaListTagTypedefDecl; 9901 } 9902 9903 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 9904 TargetInfo::BuiltinVaListKind Kind) { 9905 switch (Kind) { 9906 case TargetInfo::CharPtrBuiltinVaList: 9907 return CreateCharPtrBuiltinVaListDecl(Context); 9908 case TargetInfo::VoidPtrBuiltinVaList: 9909 return CreateVoidPtrBuiltinVaListDecl(Context); 9910 case TargetInfo::AArch64ABIBuiltinVaList: 9911 return CreateAArch64ABIBuiltinVaListDecl(Context); 9912 case TargetInfo::PowerABIBuiltinVaList: 9913 return CreatePowerABIBuiltinVaListDecl(Context); 9914 case TargetInfo::X86_64ABIBuiltinVaList: 9915 return CreateX86_64ABIBuiltinVaListDecl(Context); 9916 case TargetInfo::PNaClABIBuiltinVaList: 9917 return CreatePNaClABIBuiltinVaListDecl(Context); 9918 case TargetInfo::AAPCSABIBuiltinVaList: 9919 return CreateAAPCSABIBuiltinVaListDecl(Context); 9920 case TargetInfo::SystemZBuiltinVaList: 9921 return CreateSystemZBuiltinVaListDecl(Context); 9922 case TargetInfo::HexagonBuiltinVaList: 9923 return CreateHexagonBuiltinVaListDecl(Context); 9924 case TargetInfo::XtensaABIBuiltinVaList: 9925 return CreateXtensaABIBuiltinVaListDecl(Context); 9926 } 9927 9928 llvm_unreachable("Unhandled __builtin_va_list type kind"); 9929 } 9930 9931 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 9932 if (!BuiltinVaListDecl) { 9933 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 9934 assert(BuiltinVaListDecl->isImplicit()); 9935 } 9936 9937 return BuiltinVaListDecl; 9938 } 9939 9940 Decl *ASTContext::getVaListTagDecl() const { 9941 // Force the creation of VaListTagDecl by building the __builtin_va_list 9942 // declaration. 9943 if (!VaListTagDecl) 9944 (void)getBuiltinVaListDecl(); 9945 9946 return VaListTagDecl; 9947 } 9948 9949 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 9950 if (!BuiltinMSVaListDecl) 9951 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 9952 9953 return BuiltinMSVaListDecl; 9954 } 9955 9956 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 9957 // Allow redecl custom type checking builtin for HLSL. 9958 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin && 9959 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID())) 9960 return true; 9961 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 9962 } 9963 9964 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 9965 assert(ObjCConstantStringType.isNull() && 9966 "'NSConstantString' type already set!"); 9967 9968 ObjCConstantStringType = getObjCInterfaceType(Decl); 9969 } 9970 9971 /// Retrieve the template name that corresponds to a non-empty 9972 /// lookup. 9973 TemplateName 9974 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 9975 UnresolvedSetIterator End) const { 9976 unsigned size = End - Begin; 9977 assert(size > 1 && "set is not overloaded!"); 9978 9979 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 9980 size * sizeof(FunctionTemplateDecl*)); 9981 auto *OT = new (memory) OverloadedTemplateStorage(size); 9982 9983 NamedDecl **Storage = OT->getStorage(); 9984 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 9985 NamedDecl *D = *I; 9986 assert(isa<FunctionTemplateDecl>(D) || 9987 isa<UnresolvedUsingValueDecl>(D) || 9988 (isa<UsingShadowDecl>(D) && 9989 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 9990 *Storage++ = D; 9991 } 9992 9993 return TemplateName(OT); 9994 } 9995 9996 /// Retrieve a template name representing an unqualified-id that has been 9997 /// assumed to name a template for ADL purposes. 9998 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 9999 auto *OT = new (*this) AssumedTemplateStorage(Name); 10000 return TemplateName(OT); 10001 } 10002 10003 /// Retrieve the template name that represents a qualified 10004 /// template name such as \c std::vector. 10005 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 10006 bool TemplateKeyword, 10007 TemplateName Template) const { 10008 assert(Template.getKind() == TemplateName::Template || 10009 Template.getKind() == TemplateName::UsingTemplate); 10010 10011 // FIXME: Canonicalization? 10012 llvm::FoldingSetNodeID ID; 10013 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 10014 10015 void *InsertPos = nullptr; 10016 QualifiedTemplateName *QTN = 10017 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 10018 if (!QTN) { 10019 QTN = new (*this, alignof(QualifiedTemplateName)) 10020 QualifiedTemplateName(NNS, TemplateKeyword, Template); 10021 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 10022 } 10023 10024 return TemplateName(QTN); 10025 } 10026 10027 /// Retrieve the template name that represents a dependent 10028 /// template name such as \c MetaFun::template apply. 10029 TemplateName 10030 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 10031 const IdentifierInfo *Name) const { 10032 assert((!NNS || NNS->isDependent()) && 10033 "Nested name specifier must be dependent"); 10034 10035 llvm::FoldingSetNodeID ID; 10036 DependentTemplateName::Profile(ID, NNS, Name); 10037 10038 void *InsertPos = nullptr; 10039 DependentTemplateName *QTN = 10040 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 10041 10042 if (QTN) 10043 return TemplateName(QTN); 10044 10045 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 10046 if (CanonNNS == NNS) { 10047 QTN = new (*this, alignof(DependentTemplateName)) 10048 DependentTemplateName(NNS, Name); 10049 } else { 10050 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 10051 QTN = new (*this, alignof(DependentTemplateName)) 10052 DependentTemplateName(NNS, Name, Canon); 10053 DependentTemplateName *CheckQTN = 10054 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 10055 assert(!CheckQTN && "Dependent type name canonicalization broken"); 10056 (void)CheckQTN; 10057 } 10058 10059 DependentTemplateNames.InsertNode(QTN, InsertPos); 10060 return TemplateName(QTN); 10061 } 10062 10063 /// Retrieve the template name that represents a dependent 10064 /// template name such as \c MetaFun::template operator+. 10065 TemplateName 10066 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 10067 OverloadedOperatorKind Operator) const { 10068 assert((!NNS || NNS->isDependent()) && 10069 "Nested name specifier must be dependent"); 10070 10071 llvm::FoldingSetNodeID ID; 10072 DependentTemplateName::Profile(ID, NNS, Operator); 10073 10074 void *InsertPos = nullptr; 10075 DependentTemplateName *QTN 10076 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 10077 10078 if (QTN) 10079 return TemplateName(QTN); 10080 10081 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 10082 if (CanonNNS == NNS) { 10083 QTN = new (*this, alignof(DependentTemplateName)) 10084 DependentTemplateName(NNS, Operator); 10085 } else { 10086 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 10087 QTN = new (*this, alignof(DependentTemplateName)) 10088 DependentTemplateName(NNS, Operator, Canon); 10089 10090 DependentTemplateName *CheckQTN 10091 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 10092 assert(!CheckQTN && "Dependent template name canonicalization broken"); 10093 (void)CheckQTN; 10094 } 10095 10096 DependentTemplateNames.InsertNode(QTN, InsertPos); 10097 return TemplateName(QTN); 10098 } 10099 10100 TemplateName ASTContext::getSubstTemplateTemplateParm( 10101 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index, 10102 std::optional<unsigned> PackIndex) const { 10103 llvm::FoldingSetNodeID ID; 10104 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl, 10105 Index, PackIndex); 10106 10107 void *insertPos = nullptr; 10108 SubstTemplateTemplateParmStorage *subst 10109 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 10110 10111 if (!subst) { 10112 subst = new (*this) SubstTemplateTemplateParmStorage( 10113 Replacement, AssociatedDecl, Index, PackIndex); 10114 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 10115 } 10116 10117 return TemplateName(subst); 10118 } 10119 10120 TemplateName 10121 ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, 10122 Decl *AssociatedDecl, 10123 unsigned Index, bool Final) const { 10124 auto &Self = const_cast<ASTContext &>(*this); 10125 llvm::FoldingSetNodeID ID; 10126 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, ArgPack, 10127 AssociatedDecl, Index, Final); 10128 10129 void *InsertPos = nullptr; 10130 SubstTemplateTemplateParmPackStorage *Subst 10131 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 10132 10133 if (!Subst) { 10134 Subst = new (*this) SubstTemplateTemplateParmPackStorage( 10135 ArgPack.pack_elements(), AssociatedDecl, Index, Final); 10136 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 10137 } 10138 10139 return TemplateName(Subst); 10140 } 10141 10142 /// Retrieve the template name that represents a template name 10143 /// deduced from a specialization. 10144 TemplateName 10145 ASTContext::getDeducedTemplateName(TemplateName Underlying, 10146 DefaultArguments DefaultArgs) const { 10147 if (!DefaultArgs) 10148 return Underlying; 10149 10150 llvm::FoldingSetNodeID ID; 10151 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs); 10152 10153 void *InsertPos = nullptr; 10154 DeducedTemplateStorage *DTS = 10155 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos); 10156 if (!DTS) { 10157 void *Mem = Allocate(sizeof(DeducedTemplateStorage) + 10158 sizeof(TemplateArgument) * DefaultArgs.Args.size(), 10159 alignof(DeducedTemplateStorage)); 10160 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs); 10161 DeducedTemplates.InsertNode(DTS, InsertPos); 10162 } 10163 return TemplateName(DTS); 10164 } 10165 10166 /// getFromTargetType - Given one of the integer types provided by 10167 /// TargetInfo, produce the corresponding type. The unsigned @p Type 10168 /// is actually a value of type @c TargetInfo::IntType. 10169 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 10170 switch (Type) { 10171 case TargetInfo::NoInt: return {}; 10172 case TargetInfo::SignedChar: return SignedCharTy; 10173 case TargetInfo::UnsignedChar: return UnsignedCharTy; 10174 case TargetInfo::SignedShort: return ShortTy; 10175 case TargetInfo::UnsignedShort: return UnsignedShortTy; 10176 case TargetInfo::SignedInt: return IntTy; 10177 case TargetInfo::UnsignedInt: return UnsignedIntTy; 10178 case TargetInfo::SignedLong: return LongTy; 10179 case TargetInfo::UnsignedLong: return UnsignedLongTy; 10180 case TargetInfo::SignedLongLong: return LongLongTy; 10181 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 10182 } 10183 10184 llvm_unreachable("Unhandled TargetInfo::IntType value"); 10185 } 10186 10187 //===----------------------------------------------------------------------===// 10188 // Type Predicates. 10189 //===----------------------------------------------------------------------===// 10190 10191 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 10192 /// garbage collection attribute. 10193 /// 10194 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 10195 if (getLangOpts().getGC() == LangOptions::NonGC) 10196 return Qualifiers::GCNone; 10197 10198 assert(getLangOpts().ObjC); 10199 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 10200 10201 // Default behaviour under objective-C's gc is for ObjC pointers 10202 // (or pointers to them) be treated as though they were declared 10203 // as __strong. 10204 if (GCAttrs == Qualifiers::GCNone) { 10205 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 10206 return Qualifiers::Strong; 10207 else if (Ty->isPointerType()) 10208 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 10209 } else { 10210 // It's not valid to set GC attributes on anything that isn't a 10211 // pointer. 10212 #ifndef NDEBUG 10213 QualType CT = Ty->getCanonicalTypeInternal(); 10214 while (const auto *AT = dyn_cast<ArrayType>(CT)) 10215 CT = AT->getElementType(); 10216 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 10217 #endif 10218 } 10219 return GCAttrs; 10220 } 10221 10222 //===----------------------------------------------------------------------===// 10223 // Type Compatibility Testing 10224 //===----------------------------------------------------------------------===// 10225 10226 /// areCompatVectorTypes - Return true if the two specified vector types are 10227 /// compatible. 10228 static bool areCompatVectorTypes(const VectorType *LHS, 10229 const VectorType *RHS) { 10230 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 10231 return LHS->getElementType() == RHS->getElementType() && 10232 LHS->getNumElements() == RHS->getNumElements(); 10233 } 10234 10235 /// areCompatMatrixTypes - Return true if the two specified matrix types are 10236 /// compatible. 10237 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 10238 const ConstantMatrixType *RHS) { 10239 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 10240 return LHS->getElementType() == RHS->getElementType() && 10241 LHS->getNumRows() == RHS->getNumRows() && 10242 LHS->getNumColumns() == RHS->getNumColumns(); 10243 } 10244 10245 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 10246 QualType SecondVec) { 10247 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 10248 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 10249 10250 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 10251 return true; 10252 10253 // Treat Neon vector types and most AltiVec vector types as if they are the 10254 // equivalent GCC vector types. 10255 const auto *First = FirstVec->castAs<VectorType>(); 10256 const auto *Second = SecondVec->castAs<VectorType>(); 10257 if (First->getNumElements() == Second->getNumElements() && 10258 hasSameType(First->getElementType(), Second->getElementType()) && 10259 First->getVectorKind() != VectorKind::AltiVecPixel && 10260 First->getVectorKind() != VectorKind::AltiVecBool && 10261 Second->getVectorKind() != VectorKind::AltiVecPixel && 10262 Second->getVectorKind() != VectorKind::AltiVecBool && 10263 First->getVectorKind() != VectorKind::SveFixedLengthData && 10264 First->getVectorKind() != VectorKind::SveFixedLengthPredicate && 10265 Second->getVectorKind() != VectorKind::SveFixedLengthData && 10266 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate && 10267 First->getVectorKind() != VectorKind::RVVFixedLengthData && 10268 Second->getVectorKind() != VectorKind::RVVFixedLengthData && 10269 First->getVectorKind() != VectorKind::RVVFixedLengthMask && 10270 Second->getVectorKind() != VectorKind::RVVFixedLengthMask && 10271 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 && 10272 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 && 10273 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 && 10274 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 && 10275 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 && 10276 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4) 10277 return true; 10278 10279 return false; 10280 } 10281 10282 /// getSVETypeSize - Return SVE vector or predicate register size. 10283 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 10284 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type"); 10285 if (Ty->getKind() == BuiltinType::SveBool || 10286 Ty->getKind() == BuiltinType::SveCount) 10287 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth(); 10288 return Context.getLangOpts().VScaleMin * 128; 10289 } 10290 10291 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 10292 QualType SecondType) { 10293 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 10294 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 10295 if (const auto *VT = SecondType->getAs<VectorType>()) { 10296 // Predicates have the same representation as uint8 so we also have to 10297 // check the kind to make these types incompatible. 10298 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) 10299 return BT->getKind() == BuiltinType::SveBool; 10300 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData) 10301 return VT->getElementType().getCanonicalType() == 10302 FirstType->getSveEltType(*this); 10303 else if (VT->getVectorKind() == VectorKind::Generic) 10304 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 10305 hasSameType(VT->getElementType(), 10306 getBuiltinVectorTypeInfo(BT).ElementType); 10307 } 10308 } 10309 return false; 10310 }; 10311 10312 return IsValidCast(FirstType, SecondType) || 10313 IsValidCast(SecondType, FirstType); 10314 } 10315 10316 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 10317 QualType SecondType) { 10318 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 10319 const auto *BT = FirstType->getAs<BuiltinType>(); 10320 if (!BT) 10321 return false; 10322 10323 const auto *VecTy = SecondType->getAs<VectorType>(); 10324 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData || 10325 VecTy->getVectorKind() == VectorKind::Generic)) { 10326 const LangOptions::LaxVectorConversionKind LVCKind = 10327 getLangOpts().getLaxVectorConversions(); 10328 10329 // Can not convert between sve predicates and sve vectors because of 10330 // different size. 10331 if (BT->getKind() == BuiltinType::SveBool && 10332 VecTy->getVectorKind() == VectorKind::SveFixedLengthData) 10333 return false; 10334 10335 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 10336 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 10337 // converts to VLAT and VLAT implicitly converts to GNUT." 10338 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 10339 // predicates. 10340 if (VecTy->getVectorKind() == VectorKind::Generic && 10341 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 10342 return false; 10343 10344 // If -flax-vector-conversions=all is specified, the types are 10345 // certainly compatible. 10346 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 10347 return true; 10348 10349 // If -flax-vector-conversions=integer is specified, the types are 10350 // compatible if the elements are integer types. 10351 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 10352 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 10353 FirstType->getSveEltType(*this)->isIntegerType(); 10354 } 10355 10356 return false; 10357 }; 10358 10359 return IsLaxCompatible(FirstType, SecondType) || 10360 IsLaxCompatible(SecondType, FirstType); 10361 } 10362 10363 /// getRVVTypeSize - Return RVV vector register size. 10364 static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) { 10365 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type"); 10366 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts()); 10367 if (!VScale) 10368 return 0; 10369 10370 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty); 10371 10372 uint64_t EltSize = Context.getTypeSize(Info.ElementType); 10373 if (Info.ElementType == Context.BoolTy) 10374 EltSize = 1; 10375 10376 uint64_t MinElts = Info.EC.getKnownMinValue(); 10377 return VScale->first * MinElts * EltSize; 10378 } 10379 10380 bool ASTContext::areCompatibleRVVTypes(QualType FirstType, 10381 QualType SecondType) { 10382 assert( 10383 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) || 10384 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) && 10385 "Expected RVV builtin type and vector type!"); 10386 10387 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 10388 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 10389 if (const auto *VT = SecondType->getAs<VectorType>()) { 10390 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) { 10391 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT); 10392 return FirstType->isRVVVLSBuiltinType() && 10393 Info.ElementType == BoolTy && 10394 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT))); 10395 } 10396 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) { 10397 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT); 10398 return FirstType->isRVVVLSBuiltinType() && 10399 Info.ElementType == BoolTy && 10400 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8)); 10401 } 10402 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) { 10403 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT); 10404 return FirstType->isRVVVLSBuiltinType() && 10405 Info.ElementType == BoolTy && 10406 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4); 10407 } 10408 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) { 10409 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT); 10410 return FirstType->isRVVVLSBuiltinType() && 10411 Info.ElementType == BoolTy && 10412 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2); 10413 } 10414 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData || 10415 VT->getVectorKind() == VectorKind::Generic) 10416 return FirstType->isRVVVLSBuiltinType() && 10417 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) && 10418 hasSameType(VT->getElementType(), 10419 getBuiltinVectorTypeInfo(BT).ElementType); 10420 } 10421 } 10422 return false; 10423 }; 10424 10425 return IsValidCast(FirstType, SecondType) || 10426 IsValidCast(SecondType, FirstType); 10427 } 10428 10429 bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType, 10430 QualType SecondType) { 10431 assert( 10432 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) || 10433 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) && 10434 "Expected RVV builtin type and vector type!"); 10435 10436 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 10437 const auto *BT = FirstType->getAs<BuiltinType>(); 10438 if (!BT) 10439 return false; 10440 10441 if (!BT->isRVVVLSBuiltinType()) 10442 return false; 10443 10444 const auto *VecTy = SecondType->getAs<VectorType>(); 10445 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) { 10446 const LangOptions::LaxVectorConversionKind LVCKind = 10447 getLangOpts().getLaxVectorConversions(); 10448 10449 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion. 10450 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT)) 10451 return false; 10452 10453 // If -flax-vector-conversions=all is specified, the types are 10454 // certainly compatible. 10455 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 10456 return true; 10457 10458 // If -flax-vector-conversions=integer is specified, the types are 10459 // compatible if the elements are integer types. 10460 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 10461 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 10462 FirstType->getRVVEltType(*this)->isIntegerType(); 10463 } 10464 10465 return false; 10466 }; 10467 10468 return IsLaxCompatible(FirstType, SecondType) || 10469 IsLaxCompatible(SecondType, FirstType); 10470 } 10471 10472 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 10473 while (true) { 10474 // __strong id 10475 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 10476 if (Attr->getAttrKind() == attr::ObjCOwnership) 10477 return true; 10478 10479 Ty = Attr->getModifiedType(); 10480 10481 // X *__strong (...) 10482 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 10483 Ty = Paren->getInnerType(); 10484 10485 // We do not want to look through typedefs, typeof(expr), 10486 // typeof(type), or any other way that the type is somehow 10487 // abstracted. 10488 } else { 10489 return false; 10490 } 10491 } 10492 } 10493 10494 //===----------------------------------------------------------------------===// 10495 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 10496 //===----------------------------------------------------------------------===// 10497 10498 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 10499 /// inheritance hierarchy of 'rProto'. 10500 bool 10501 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 10502 ObjCProtocolDecl *rProto) const { 10503 if (declaresSameEntity(lProto, rProto)) 10504 return true; 10505 for (auto *PI : rProto->protocols()) 10506 if (ProtocolCompatibleWithProtocol(lProto, PI)) 10507 return true; 10508 return false; 10509 } 10510 10511 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 10512 /// Class<pr1, ...>. 10513 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 10514 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 10515 for (auto *lhsProto : lhs->quals()) { 10516 bool match = false; 10517 for (auto *rhsProto : rhs->quals()) { 10518 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 10519 match = true; 10520 break; 10521 } 10522 } 10523 if (!match) 10524 return false; 10525 } 10526 return true; 10527 } 10528 10529 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 10530 /// ObjCQualifiedIDType. 10531 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 10532 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 10533 bool compare) { 10534 // Allow id<P..> and an 'id' in all cases. 10535 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 10536 return true; 10537 10538 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 10539 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 10540 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 10541 return false; 10542 10543 if (lhs->isObjCQualifiedIdType()) { 10544 if (rhs->qual_empty()) { 10545 // If the RHS is a unqualified interface pointer "NSString*", 10546 // make sure we check the class hierarchy. 10547 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 10548 for (auto *I : lhs->quals()) { 10549 // when comparing an id<P> on lhs with a static type on rhs, 10550 // see if static class implements all of id's protocols, directly or 10551 // through its super class and categories. 10552 if (!rhsID->ClassImplementsProtocol(I, true)) 10553 return false; 10554 } 10555 } 10556 // If there are no qualifiers and no interface, we have an 'id'. 10557 return true; 10558 } 10559 // Both the right and left sides have qualifiers. 10560 for (auto *lhsProto : lhs->quals()) { 10561 bool match = false; 10562 10563 // when comparing an id<P> on lhs with a static type on rhs, 10564 // see if static class implements all of id's protocols, directly or 10565 // through its super class and categories. 10566 for (auto *rhsProto : rhs->quals()) { 10567 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 10568 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 10569 match = true; 10570 break; 10571 } 10572 } 10573 // If the RHS is a qualified interface pointer "NSString<P>*", 10574 // make sure we check the class hierarchy. 10575 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 10576 for (auto *I : lhs->quals()) { 10577 // when comparing an id<P> on lhs with a static type on rhs, 10578 // see if static class implements all of id's protocols, directly or 10579 // through its super class and categories. 10580 if (rhsID->ClassImplementsProtocol(I, true)) { 10581 match = true; 10582 break; 10583 } 10584 } 10585 } 10586 if (!match) 10587 return false; 10588 } 10589 10590 return true; 10591 } 10592 10593 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 10594 10595 if (lhs->getInterfaceType()) { 10596 // If both the right and left sides have qualifiers. 10597 for (auto *lhsProto : lhs->quals()) { 10598 bool match = false; 10599 10600 // when comparing an id<P> on rhs with a static type on lhs, 10601 // see if static class implements all of id's protocols, directly or 10602 // through its super class and categories. 10603 // First, lhs protocols in the qualifier list must be found, direct 10604 // or indirect in rhs's qualifier list or it is a mismatch. 10605 for (auto *rhsProto : rhs->quals()) { 10606 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 10607 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 10608 match = true; 10609 break; 10610 } 10611 } 10612 if (!match) 10613 return false; 10614 } 10615 10616 // Static class's protocols, or its super class or category protocols 10617 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 10618 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 10619 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 10620 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 10621 // This is rather dubious but matches gcc's behavior. If lhs has 10622 // no type qualifier and its class has no static protocol(s) 10623 // assume that it is mismatch. 10624 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 10625 return false; 10626 for (auto *lhsProto : LHSInheritedProtocols) { 10627 bool match = false; 10628 for (auto *rhsProto : rhs->quals()) { 10629 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 10630 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 10631 match = true; 10632 break; 10633 } 10634 } 10635 if (!match) 10636 return false; 10637 } 10638 } 10639 return true; 10640 } 10641 return false; 10642 } 10643 10644 /// canAssignObjCInterfaces - Return true if the two interface types are 10645 /// compatible for assignment from RHS to LHS. This handles validation of any 10646 /// protocol qualifiers on the LHS or RHS. 10647 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 10648 const ObjCObjectPointerType *RHSOPT) { 10649 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 10650 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 10651 10652 // If either type represents the built-in 'id' type, return true. 10653 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 10654 return true; 10655 10656 // Function object that propagates a successful result or handles 10657 // __kindof types. 10658 auto finish = [&](bool succeeded) -> bool { 10659 if (succeeded) 10660 return true; 10661 10662 if (!RHS->isKindOfType()) 10663 return false; 10664 10665 // Strip off __kindof and protocol qualifiers, then check whether 10666 // we can assign the other way. 10667 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 10668 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 10669 }; 10670 10671 // Casts from or to id<P> are allowed when the other side has compatible 10672 // protocols. 10673 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 10674 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 10675 } 10676 10677 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 10678 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 10679 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 10680 } 10681 10682 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 10683 if (LHS->isObjCClass() && RHS->isObjCClass()) { 10684 return true; 10685 } 10686 10687 // If we have 2 user-defined types, fall into that path. 10688 if (LHS->getInterface() && RHS->getInterface()) { 10689 return finish(canAssignObjCInterfaces(LHS, RHS)); 10690 } 10691 10692 return false; 10693 } 10694 10695 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 10696 /// for providing type-safety for objective-c pointers used to pass/return 10697 /// arguments in block literals. When passed as arguments, passing 'A*' where 10698 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 10699 /// not OK. For the return type, the opposite is not OK. 10700 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 10701 const ObjCObjectPointerType *LHSOPT, 10702 const ObjCObjectPointerType *RHSOPT, 10703 bool BlockReturnType) { 10704 10705 // Function object that propagates a successful result or handles 10706 // __kindof types. 10707 auto finish = [&](bool succeeded) -> bool { 10708 if (succeeded) 10709 return true; 10710 10711 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 10712 if (!Expected->isKindOfType()) 10713 return false; 10714 10715 // Strip off __kindof and protocol qualifiers, then check whether 10716 // we can assign the other way. 10717 return canAssignObjCInterfacesInBlockPointer( 10718 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 10719 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 10720 BlockReturnType); 10721 }; 10722 10723 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 10724 return true; 10725 10726 if (LHSOPT->isObjCBuiltinType()) { 10727 return finish(RHSOPT->isObjCBuiltinType() || 10728 RHSOPT->isObjCQualifiedIdType()); 10729 } 10730 10731 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 10732 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 10733 // Use for block parameters previous type checking for compatibility. 10734 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 10735 // Or corrected type checking as in non-compat mode. 10736 (!BlockReturnType && 10737 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 10738 else 10739 return finish(ObjCQualifiedIdTypesAreCompatible( 10740 (BlockReturnType ? LHSOPT : RHSOPT), 10741 (BlockReturnType ? RHSOPT : LHSOPT), false)); 10742 } 10743 10744 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 10745 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 10746 if (LHS && RHS) { // We have 2 user-defined types. 10747 if (LHS != RHS) { 10748 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 10749 return finish(BlockReturnType); 10750 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 10751 return finish(!BlockReturnType); 10752 } 10753 else 10754 return true; 10755 } 10756 return false; 10757 } 10758 10759 /// Comparison routine for Objective-C protocols to be used with 10760 /// llvm::array_pod_sort. 10761 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 10762 ObjCProtocolDecl * const *rhs) { 10763 return (*lhs)->getName().compare((*rhs)->getName()); 10764 } 10765 10766 /// getIntersectionOfProtocols - This routine finds the intersection of set 10767 /// of protocols inherited from two distinct objective-c pointer objects with 10768 /// the given common base. 10769 /// It is used to build composite qualifier list of the composite type of 10770 /// the conditional expression involving two objective-c pointer objects. 10771 static 10772 void getIntersectionOfProtocols(ASTContext &Context, 10773 const ObjCInterfaceDecl *CommonBase, 10774 const ObjCObjectPointerType *LHSOPT, 10775 const ObjCObjectPointerType *RHSOPT, 10776 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 10777 10778 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 10779 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 10780 assert(LHS->getInterface() && "LHS must have an interface base"); 10781 assert(RHS->getInterface() && "RHS must have an interface base"); 10782 10783 // Add all of the protocols for the LHS. 10784 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 10785 10786 // Start with the protocol qualifiers. 10787 for (auto *proto : LHS->quals()) { 10788 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 10789 } 10790 10791 // Also add the protocols associated with the LHS interface. 10792 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 10793 10794 // Add all of the protocols for the RHS. 10795 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 10796 10797 // Start with the protocol qualifiers. 10798 for (auto *proto : RHS->quals()) { 10799 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 10800 } 10801 10802 // Also add the protocols associated with the RHS interface. 10803 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 10804 10805 // Compute the intersection of the collected protocol sets. 10806 for (auto *proto : LHSProtocolSet) { 10807 if (RHSProtocolSet.count(proto)) 10808 IntersectionSet.push_back(proto); 10809 } 10810 10811 // Compute the set of protocols that is implied by either the common type or 10812 // the protocols within the intersection. 10813 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 10814 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 10815 10816 // Remove any implied protocols from the list of inherited protocols. 10817 if (!ImpliedProtocols.empty()) { 10818 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 10819 return ImpliedProtocols.contains(proto); 10820 }); 10821 } 10822 10823 // Sort the remaining protocols by name. 10824 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 10825 compareObjCProtocolsByName); 10826 } 10827 10828 /// Determine whether the first type is a subtype of the second. 10829 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 10830 QualType rhs) { 10831 // Common case: two object pointers. 10832 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 10833 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 10834 if (lhsOPT && rhsOPT) 10835 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 10836 10837 // Two block pointers. 10838 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 10839 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 10840 if (lhsBlock && rhsBlock) 10841 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 10842 10843 // If either is an unqualified 'id' and the other is a block, it's 10844 // acceptable. 10845 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 10846 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 10847 return true; 10848 10849 return false; 10850 } 10851 10852 // Check that the given Objective-C type argument lists are equivalent. 10853 static bool sameObjCTypeArgs(ASTContext &ctx, 10854 const ObjCInterfaceDecl *iface, 10855 ArrayRef<QualType> lhsArgs, 10856 ArrayRef<QualType> rhsArgs, 10857 bool stripKindOf) { 10858 if (lhsArgs.size() != rhsArgs.size()) 10859 return false; 10860 10861 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 10862 if (!typeParams) 10863 return false; 10864 10865 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 10866 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 10867 continue; 10868 10869 switch (typeParams->begin()[i]->getVariance()) { 10870 case ObjCTypeParamVariance::Invariant: 10871 if (!stripKindOf || 10872 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 10873 rhsArgs[i].stripObjCKindOfType(ctx))) { 10874 return false; 10875 } 10876 break; 10877 10878 case ObjCTypeParamVariance::Covariant: 10879 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 10880 return false; 10881 break; 10882 10883 case ObjCTypeParamVariance::Contravariant: 10884 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 10885 return false; 10886 break; 10887 } 10888 } 10889 10890 return true; 10891 } 10892 10893 QualType ASTContext::areCommonBaseCompatible( 10894 const ObjCObjectPointerType *Lptr, 10895 const ObjCObjectPointerType *Rptr) { 10896 const ObjCObjectType *LHS = Lptr->getObjectType(); 10897 const ObjCObjectType *RHS = Rptr->getObjectType(); 10898 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 10899 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 10900 10901 if (!LDecl || !RDecl) 10902 return {}; 10903 10904 // When either LHS or RHS is a kindof type, we should return a kindof type. 10905 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 10906 // kindof(A). 10907 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 10908 10909 // Follow the left-hand side up the class hierarchy until we either hit a 10910 // root or find the RHS. Record the ancestors in case we don't find it. 10911 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 10912 LHSAncestors; 10913 while (true) { 10914 // Record this ancestor. We'll need this if the common type isn't in the 10915 // path from the LHS to the root. 10916 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 10917 10918 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 10919 // Get the type arguments. 10920 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 10921 bool anyChanges = false; 10922 if (LHS->isSpecialized() && RHS->isSpecialized()) { 10923 // Both have type arguments, compare them. 10924 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 10925 LHS->getTypeArgs(), RHS->getTypeArgs(), 10926 /*stripKindOf=*/true)) 10927 return {}; 10928 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 10929 // If only one has type arguments, the result will not have type 10930 // arguments. 10931 LHSTypeArgs = {}; 10932 anyChanges = true; 10933 } 10934 10935 // Compute the intersection of protocols. 10936 SmallVector<ObjCProtocolDecl *, 8> Protocols; 10937 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 10938 Protocols); 10939 if (!Protocols.empty()) 10940 anyChanges = true; 10941 10942 // If anything in the LHS will have changed, build a new result type. 10943 // If we need to return a kindof type but LHS is not a kindof type, we 10944 // build a new result type. 10945 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 10946 QualType Result = getObjCInterfaceType(LHS->getInterface()); 10947 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 10948 anyKindOf || LHS->isKindOfType()); 10949 return getObjCObjectPointerType(Result); 10950 } 10951 10952 return getObjCObjectPointerType(QualType(LHS, 0)); 10953 } 10954 10955 // Find the superclass. 10956 QualType LHSSuperType = LHS->getSuperClassType(); 10957 if (LHSSuperType.isNull()) 10958 break; 10959 10960 LHS = LHSSuperType->castAs<ObjCObjectType>(); 10961 } 10962 10963 // We didn't find anything by following the LHS to its root; now check 10964 // the RHS against the cached set of ancestors. 10965 while (true) { 10966 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 10967 if (KnownLHS != LHSAncestors.end()) { 10968 LHS = KnownLHS->second; 10969 10970 // Get the type arguments. 10971 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 10972 bool anyChanges = false; 10973 if (LHS->isSpecialized() && RHS->isSpecialized()) { 10974 // Both have type arguments, compare them. 10975 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 10976 LHS->getTypeArgs(), RHS->getTypeArgs(), 10977 /*stripKindOf=*/true)) 10978 return {}; 10979 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 10980 // If only one has type arguments, the result will not have type 10981 // arguments. 10982 RHSTypeArgs = {}; 10983 anyChanges = true; 10984 } 10985 10986 // Compute the intersection of protocols. 10987 SmallVector<ObjCProtocolDecl *, 8> Protocols; 10988 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 10989 Protocols); 10990 if (!Protocols.empty()) 10991 anyChanges = true; 10992 10993 // If we need to return a kindof type but RHS is not a kindof type, we 10994 // build a new result type. 10995 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 10996 QualType Result = getObjCInterfaceType(RHS->getInterface()); 10997 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 10998 anyKindOf || RHS->isKindOfType()); 10999 return getObjCObjectPointerType(Result); 11000 } 11001 11002 return getObjCObjectPointerType(QualType(RHS, 0)); 11003 } 11004 11005 // Find the superclass of the RHS. 11006 QualType RHSSuperType = RHS->getSuperClassType(); 11007 if (RHSSuperType.isNull()) 11008 break; 11009 11010 RHS = RHSSuperType->castAs<ObjCObjectType>(); 11011 } 11012 11013 return {}; 11014 } 11015 11016 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 11017 const ObjCObjectType *RHS) { 11018 assert(LHS->getInterface() && "LHS is not an interface type"); 11019 assert(RHS->getInterface() && "RHS is not an interface type"); 11020 11021 // Verify that the base decls are compatible: the RHS must be a subclass of 11022 // the LHS. 11023 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 11024 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 11025 if (!IsSuperClass) 11026 return false; 11027 11028 // If the LHS has protocol qualifiers, determine whether all of them are 11029 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 11030 // LHS). 11031 if (LHS->getNumProtocols() > 0) { 11032 // OK if conversion of LHS to SuperClass results in narrowing of types 11033 // ; i.e., SuperClass may implement at least one of the protocols 11034 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 11035 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 11036 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 11037 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 11038 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 11039 // qualifiers. 11040 for (auto *RHSPI : RHS->quals()) 11041 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 11042 // If there is no protocols associated with RHS, it is not a match. 11043 if (SuperClassInheritedProtocols.empty()) 11044 return false; 11045 11046 for (const auto *LHSProto : LHS->quals()) { 11047 bool SuperImplementsProtocol = false; 11048 for (auto *SuperClassProto : SuperClassInheritedProtocols) 11049 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 11050 SuperImplementsProtocol = true; 11051 break; 11052 } 11053 if (!SuperImplementsProtocol) 11054 return false; 11055 } 11056 } 11057 11058 // If the LHS is specialized, we may need to check type arguments. 11059 if (LHS->isSpecialized()) { 11060 // Follow the superclass chain until we've matched the LHS class in the 11061 // hierarchy. This substitutes type arguments through. 11062 const ObjCObjectType *RHSSuper = RHS; 11063 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 11064 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 11065 11066 // If the RHS is specializd, compare type arguments. 11067 if (RHSSuper->isSpecialized() && 11068 !sameObjCTypeArgs(*this, LHS->getInterface(), 11069 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 11070 /*stripKindOf=*/true)) { 11071 return false; 11072 } 11073 } 11074 11075 return true; 11076 } 11077 11078 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 11079 // get the "pointed to" types 11080 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 11081 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 11082 11083 if (!LHSOPT || !RHSOPT) 11084 return false; 11085 11086 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 11087 canAssignObjCInterfaces(RHSOPT, LHSOPT); 11088 } 11089 11090 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 11091 return canAssignObjCInterfaces( 11092 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 11093 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 11094 } 11095 11096 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 11097 /// both shall have the identically qualified version of a compatible type. 11098 /// C99 6.2.7p1: Two types have compatible types if their types are the 11099 /// same. See 6.7.[2,3,5] for additional rules. 11100 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 11101 bool CompareUnqualified) { 11102 if (getLangOpts().CPlusPlus) 11103 return hasSameType(LHS, RHS); 11104 11105 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 11106 } 11107 11108 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 11109 return typesAreCompatible(LHS, RHS); 11110 } 11111 11112 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 11113 return !mergeTypes(LHS, RHS, true).isNull(); 11114 } 11115 11116 /// mergeTransparentUnionType - if T is a transparent union type and a member 11117 /// of T is compatible with SubType, return the merged type, else return 11118 /// QualType() 11119 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 11120 bool OfBlockPointer, 11121 bool Unqualified) { 11122 if (const RecordType *UT = T->getAsUnionType()) { 11123 RecordDecl *UD = UT->getDecl(); 11124 if (UD->hasAttr<TransparentUnionAttr>()) { 11125 for (const auto *I : UD->fields()) { 11126 QualType ET = I->getType().getUnqualifiedType(); 11127 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 11128 if (!MT.isNull()) 11129 return MT; 11130 } 11131 } 11132 } 11133 11134 return {}; 11135 } 11136 11137 /// mergeFunctionParameterTypes - merge two types which appear as function 11138 /// parameter types 11139 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 11140 bool OfBlockPointer, 11141 bool Unqualified) { 11142 // GNU extension: two types are compatible if they appear as a function 11143 // argument, one of the types is a transparent union type and the other 11144 // type is compatible with a union member 11145 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 11146 Unqualified); 11147 if (!lmerge.isNull()) 11148 return lmerge; 11149 11150 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 11151 Unqualified); 11152 if (!rmerge.isNull()) 11153 return rmerge; 11154 11155 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 11156 } 11157 11158 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 11159 bool OfBlockPointer, bool Unqualified, 11160 bool AllowCXX, 11161 bool IsConditionalOperator) { 11162 const auto *lbase = lhs->castAs<FunctionType>(); 11163 const auto *rbase = rhs->castAs<FunctionType>(); 11164 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 11165 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 11166 bool allLTypes = true; 11167 bool allRTypes = true; 11168 11169 // Check return type 11170 QualType retType; 11171 if (OfBlockPointer) { 11172 QualType RHS = rbase->getReturnType(); 11173 QualType LHS = lbase->getReturnType(); 11174 bool UnqualifiedResult = Unqualified; 11175 if (!UnqualifiedResult) 11176 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 11177 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 11178 } 11179 else 11180 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 11181 Unqualified); 11182 if (retType.isNull()) 11183 return {}; 11184 11185 if (Unqualified) 11186 retType = retType.getUnqualifiedType(); 11187 11188 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 11189 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 11190 if (Unqualified) { 11191 LRetType = LRetType.getUnqualifiedType(); 11192 RRetType = RRetType.getUnqualifiedType(); 11193 } 11194 11195 if (getCanonicalType(retType) != LRetType) 11196 allLTypes = false; 11197 if (getCanonicalType(retType) != RRetType) 11198 allRTypes = false; 11199 11200 // FIXME: double check this 11201 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 11202 // rbase->getRegParmAttr() != 0 && 11203 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 11204 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 11205 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 11206 11207 // Compatible functions must have compatible calling conventions 11208 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 11209 return {}; 11210 11211 // Regparm is part of the calling convention. 11212 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 11213 return {}; 11214 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 11215 return {}; 11216 11217 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 11218 return {}; 11219 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 11220 return {}; 11221 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 11222 return {}; 11223 11224 // When merging declarations, it's common for supplemental information like 11225 // attributes to only be present in one of the declarations, and we generally 11226 // want type merging to preserve the union of information. So a merged 11227 // function type should be noreturn if it was noreturn in *either* operand 11228 // type. 11229 // 11230 // But for the conditional operator, this is backwards. The result of the 11231 // operator could be either operand, and its type should conservatively 11232 // reflect that. So a function type in a composite type is noreturn only 11233 // if it's noreturn in *both* operand types. 11234 // 11235 // Arguably, noreturn is a kind of subtype, and the conditional operator 11236 // ought to produce the most specific common supertype of its operand types. 11237 // That would differ from this rule in contravariant positions. However, 11238 // neither C nor C++ generally uses this kind of subtype reasoning. Also, 11239 // as a practical matter, it would only affect C code that does abstraction of 11240 // higher-order functions (taking noreturn callbacks!), which is uncommon to 11241 // say the least. So we use the simpler rule. 11242 bool NoReturn = IsConditionalOperator 11243 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn() 11244 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 11245 if (lbaseInfo.getNoReturn() != NoReturn) 11246 allLTypes = false; 11247 if (rbaseInfo.getNoReturn() != NoReturn) 11248 allRTypes = false; 11249 11250 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 11251 11252 std::optional<FunctionEffectSet> MergedFX; 11253 11254 if (lproto && rproto) { // two C99 style function prototypes 11255 assert((AllowCXX || 11256 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 11257 "C++ shouldn't be here"); 11258 // Compatible functions must have the same number of parameters 11259 if (lproto->getNumParams() != rproto->getNumParams()) 11260 return {}; 11261 11262 // Variadic and non-variadic functions aren't compatible 11263 if (lproto->isVariadic() != rproto->isVariadic()) 11264 return {}; 11265 11266 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 11267 return {}; 11268 11269 // Function effects are handled similarly to noreturn, see above. 11270 FunctionEffectsRef LHSFX = lproto->getFunctionEffects(); 11271 FunctionEffectsRef RHSFX = rproto->getFunctionEffects(); 11272 if (LHSFX != RHSFX) { 11273 if (IsConditionalOperator) 11274 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX); 11275 else { 11276 FunctionEffectSet::Conflicts Errs; 11277 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs); 11278 // Here we're discarding a possible error due to conflicts in the effect 11279 // sets. But we're not in a context where we can report it. The 11280 // operation does however guarantee maintenance of invariants. 11281 } 11282 if (*MergedFX != LHSFX) 11283 allLTypes = false; 11284 if (*MergedFX != RHSFX) 11285 allRTypes = false; 11286 } 11287 11288 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 11289 bool canUseLeft, canUseRight; 11290 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 11291 newParamInfos)) 11292 return {}; 11293 11294 if (!canUseLeft) 11295 allLTypes = false; 11296 if (!canUseRight) 11297 allRTypes = false; 11298 11299 // Check parameter type compatibility 11300 SmallVector<QualType, 10> types; 11301 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 11302 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 11303 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 11304 QualType paramType = mergeFunctionParameterTypes( 11305 lParamType, rParamType, OfBlockPointer, Unqualified); 11306 if (paramType.isNull()) 11307 return {}; 11308 11309 if (Unqualified) 11310 paramType = paramType.getUnqualifiedType(); 11311 11312 types.push_back(paramType); 11313 if (Unqualified) { 11314 lParamType = lParamType.getUnqualifiedType(); 11315 rParamType = rParamType.getUnqualifiedType(); 11316 } 11317 11318 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 11319 allLTypes = false; 11320 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 11321 allRTypes = false; 11322 } 11323 11324 if (allLTypes) return lhs; 11325 if (allRTypes) return rhs; 11326 11327 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 11328 EPI.ExtInfo = einfo; 11329 EPI.ExtParameterInfos = 11330 newParamInfos.empty() ? nullptr : newParamInfos.data(); 11331 if (MergedFX) 11332 EPI.FunctionEffects = *MergedFX; 11333 return getFunctionType(retType, types, EPI); 11334 } 11335 11336 if (lproto) allRTypes = false; 11337 if (rproto) allLTypes = false; 11338 11339 const FunctionProtoType *proto = lproto ? lproto : rproto; 11340 if (proto) { 11341 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 11342 if (proto->isVariadic()) 11343 return {}; 11344 // Check that the types are compatible with the types that 11345 // would result from default argument promotions (C99 6.7.5.3p15). 11346 // The only types actually affected are promotable integer 11347 // types and floats, which would be passed as a different 11348 // type depending on whether the prototype is visible. 11349 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 11350 QualType paramTy = proto->getParamType(i); 11351 11352 // Look at the converted type of enum types, since that is the type used 11353 // to pass enum values. 11354 if (const auto *Enum = paramTy->getAs<EnumType>()) { 11355 paramTy = Enum->getDecl()->getIntegerType(); 11356 if (paramTy.isNull()) 11357 return {}; 11358 } 11359 11360 if (isPromotableIntegerType(paramTy) || 11361 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 11362 return {}; 11363 } 11364 11365 if (allLTypes) return lhs; 11366 if (allRTypes) return rhs; 11367 11368 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 11369 EPI.ExtInfo = einfo; 11370 if (MergedFX) 11371 EPI.FunctionEffects = *MergedFX; 11372 return getFunctionType(retType, proto->getParamTypes(), EPI); 11373 } 11374 11375 if (allLTypes) return lhs; 11376 if (allRTypes) return rhs; 11377 return getFunctionNoProtoType(retType, einfo); 11378 } 11379 11380 /// Given that we have an enum type and a non-enum type, try to merge them. 11381 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 11382 QualType other, bool isBlockReturnType) { 11383 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 11384 // a signed integer type, or an unsigned integer type. 11385 // Compatibility is based on the underlying type, not the promotion 11386 // type. 11387 QualType underlyingType = ET->getDecl()->getIntegerType(); 11388 if (underlyingType.isNull()) 11389 return {}; 11390 if (Context.hasSameType(underlyingType, other)) 11391 return other; 11392 11393 // In block return types, we're more permissive and accept any 11394 // integral type of the same size. 11395 if (isBlockReturnType && other->isIntegerType() && 11396 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 11397 return other; 11398 11399 return {}; 11400 } 11401 11402 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, 11403 bool Unqualified, bool BlockReturnType, 11404 bool IsConditionalOperator) { 11405 // For C++ we will not reach this code with reference types (see below), 11406 // for OpenMP variant call overloading we might. 11407 // 11408 // C++ [expr]: If an expression initially has the type "reference to T", the 11409 // type is adjusted to "T" prior to any further analysis, the expression 11410 // designates the object or function denoted by the reference, and the 11411 // expression is an lvalue unless the reference is an rvalue reference and 11412 // the expression is a function call (possibly inside parentheses). 11413 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 11414 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 11415 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 11416 LHS->getTypeClass() == RHS->getTypeClass()) 11417 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 11418 OfBlockPointer, Unqualified, BlockReturnType); 11419 if (LHSRefTy || RHSRefTy) 11420 return {}; 11421 11422 if (Unqualified) { 11423 LHS = LHS.getUnqualifiedType(); 11424 RHS = RHS.getUnqualifiedType(); 11425 } 11426 11427 QualType LHSCan = getCanonicalType(LHS), 11428 RHSCan = getCanonicalType(RHS); 11429 11430 // If two types are identical, they are compatible. 11431 if (LHSCan == RHSCan) 11432 return LHS; 11433 11434 // If the qualifiers are different, the types aren't compatible... mostly. 11435 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 11436 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 11437 if (LQuals != RQuals) { 11438 // If any of these qualifiers are different, we have a type 11439 // mismatch. 11440 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 11441 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 11442 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 11443 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 11444 return {}; 11445 11446 // Exactly one GC qualifier difference is allowed: __strong is 11447 // okay if the other type has no GC qualifier but is an Objective 11448 // C object pointer (i.e. implicitly strong by default). We fix 11449 // this by pretending that the unqualified type was actually 11450 // qualified __strong. 11451 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 11452 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 11453 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 11454 11455 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 11456 return {}; 11457 11458 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 11459 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 11460 } 11461 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 11462 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 11463 } 11464 return {}; 11465 } 11466 11467 // Okay, qualifiers are equal. 11468 11469 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 11470 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 11471 11472 // We want to consider the two function types to be the same for these 11473 // comparisons, just force one to the other. 11474 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 11475 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 11476 11477 // Same as above for arrays 11478 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 11479 LHSClass = Type::ConstantArray; 11480 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 11481 RHSClass = Type::ConstantArray; 11482 11483 // ObjCInterfaces are just specialized ObjCObjects. 11484 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 11485 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 11486 11487 // Canonicalize ExtVector -> Vector. 11488 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 11489 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 11490 11491 // If the canonical type classes don't match. 11492 if (LHSClass != RHSClass) { 11493 // Note that we only have special rules for turning block enum 11494 // returns into block int returns, not vice-versa. 11495 if (const auto *ETy = LHS->getAs<EnumType>()) { 11496 return mergeEnumWithInteger(*this, ETy, RHS, false); 11497 } 11498 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 11499 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 11500 } 11501 // allow block pointer type to match an 'id' type. 11502 if (OfBlockPointer && !BlockReturnType) { 11503 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 11504 return LHS; 11505 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 11506 return RHS; 11507 } 11508 // Allow __auto_type to match anything; it merges to the type with more 11509 // information. 11510 if (const auto *AT = LHS->getAs<AutoType>()) { 11511 if (!AT->isDeduced() && AT->isGNUAutoType()) 11512 return RHS; 11513 } 11514 if (const auto *AT = RHS->getAs<AutoType>()) { 11515 if (!AT->isDeduced() && AT->isGNUAutoType()) 11516 return LHS; 11517 } 11518 return {}; 11519 } 11520 11521 // The canonical type classes match. 11522 switch (LHSClass) { 11523 #define TYPE(Class, Base) 11524 #define ABSTRACT_TYPE(Class, Base) 11525 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 11526 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 11527 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 11528 #include "clang/AST/TypeNodes.inc" 11529 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 11530 11531 case Type::Auto: 11532 case Type::DeducedTemplateSpecialization: 11533 case Type::LValueReference: 11534 case Type::RValueReference: 11535 case Type::MemberPointer: 11536 llvm_unreachable("C++ should never be in mergeTypes"); 11537 11538 case Type::ObjCInterface: 11539 case Type::IncompleteArray: 11540 case Type::VariableArray: 11541 case Type::FunctionProto: 11542 case Type::ExtVector: 11543 llvm_unreachable("Types are eliminated above"); 11544 11545 case Type::Pointer: 11546 { 11547 // Merge two pointer types, while trying to preserve typedef info 11548 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 11549 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 11550 if (Unqualified) { 11551 LHSPointee = LHSPointee.getUnqualifiedType(); 11552 RHSPointee = RHSPointee.getUnqualifiedType(); 11553 } 11554 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 11555 Unqualified); 11556 if (ResultType.isNull()) 11557 return {}; 11558 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 11559 return LHS; 11560 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 11561 return RHS; 11562 return getPointerType(ResultType); 11563 } 11564 case Type::BlockPointer: 11565 { 11566 // Merge two block pointer types, while trying to preserve typedef info 11567 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 11568 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 11569 if (Unqualified) { 11570 LHSPointee = LHSPointee.getUnqualifiedType(); 11571 RHSPointee = RHSPointee.getUnqualifiedType(); 11572 } 11573 if (getLangOpts().OpenCL) { 11574 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 11575 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 11576 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 11577 // 6.12.5) thus the following check is asymmetric. 11578 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this)) 11579 return {}; 11580 LHSPteeQual.removeAddressSpace(); 11581 RHSPteeQual.removeAddressSpace(); 11582 LHSPointee = 11583 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 11584 RHSPointee = 11585 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 11586 } 11587 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 11588 Unqualified); 11589 if (ResultType.isNull()) 11590 return {}; 11591 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 11592 return LHS; 11593 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 11594 return RHS; 11595 return getBlockPointerType(ResultType); 11596 } 11597 case Type::Atomic: 11598 { 11599 // Merge two pointer types, while trying to preserve typedef info 11600 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 11601 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 11602 if (Unqualified) { 11603 LHSValue = LHSValue.getUnqualifiedType(); 11604 RHSValue = RHSValue.getUnqualifiedType(); 11605 } 11606 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 11607 Unqualified); 11608 if (ResultType.isNull()) 11609 return {}; 11610 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 11611 return LHS; 11612 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 11613 return RHS; 11614 return getAtomicType(ResultType); 11615 } 11616 case Type::ConstantArray: 11617 { 11618 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 11619 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 11620 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize()) 11621 return {}; 11622 11623 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 11624 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 11625 if (Unqualified) { 11626 LHSElem = LHSElem.getUnqualifiedType(); 11627 RHSElem = RHSElem.getUnqualifiedType(); 11628 } 11629 11630 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 11631 if (ResultType.isNull()) 11632 return {}; 11633 11634 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 11635 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 11636 11637 // If either side is a variable array, and both are complete, check whether 11638 // the current dimension is definite. 11639 if (LVAT || RVAT) { 11640 auto SizeFetch = [this](const VariableArrayType* VAT, 11641 const ConstantArrayType* CAT) 11642 -> std::pair<bool,llvm::APInt> { 11643 if (VAT) { 11644 std::optional<llvm::APSInt> TheInt; 11645 Expr *E = VAT->getSizeExpr(); 11646 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 11647 return std::make_pair(true, *TheInt); 11648 return std::make_pair(false, llvm::APSInt()); 11649 } 11650 if (CAT) 11651 return std::make_pair(true, CAT->getSize()); 11652 return std::make_pair(false, llvm::APInt()); 11653 }; 11654 11655 bool HaveLSize, HaveRSize; 11656 llvm::APInt LSize, RSize; 11657 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 11658 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 11659 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 11660 return {}; // Definite, but unequal, array dimension 11661 } 11662 11663 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 11664 return LHS; 11665 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 11666 return RHS; 11667 if (LCAT) 11668 return getConstantArrayType(ResultType, LCAT->getSize(), 11669 LCAT->getSizeExpr(), ArraySizeModifier(), 0); 11670 if (RCAT) 11671 return getConstantArrayType(ResultType, RCAT->getSize(), 11672 RCAT->getSizeExpr(), ArraySizeModifier(), 0); 11673 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 11674 return LHS; 11675 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 11676 return RHS; 11677 if (LVAT) { 11678 // FIXME: This isn't correct! But tricky to implement because 11679 // the array's size has to be the size of LHS, but the type 11680 // has to be different. 11681 return LHS; 11682 } 11683 if (RVAT) { 11684 // FIXME: This isn't correct! But tricky to implement because 11685 // the array's size has to be the size of RHS, but the type 11686 // has to be different. 11687 return RHS; 11688 } 11689 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 11690 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 11691 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0); 11692 } 11693 case Type::FunctionNoProto: 11694 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified, 11695 /*AllowCXX=*/false, IsConditionalOperator); 11696 case Type::Record: 11697 case Type::Enum: 11698 return {}; 11699 case Type::Builtin: 11700 // Only exactly equal builtin types are compatible, which is tested above. 11701 return {}; 11702 case Type::Complex: 11703 // Distinct complex types are incompatible. 11704 return {}; 11705 case Type::Vector: 11706 // FIXME: The merged type should be an ExtVector! 11707 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 11708 RHSCan->castAs<VectorType>())) 11709 return LHS; 11710 return {}; 11711 case Type::ConstantMatrix: 11712 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 11713 RHSCan->castAs<ConstantMatrixType>())) 11714 return LHS; 11715 return {}; 11716 case Type::ObjCObject: { 11717 // Check if the types are assignment compatible. 11718 // FIXME: This should be type compatibility, e.g. whether 11719 // "LHS x; RHS x;" at global scope is legal. 11720 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 11721 RHS->castAs<ObjCObjectType>())) 11722 return LHS; 11723 return {}; 11724 } 11725 case Type::ObjCObjectPointer: 11726 if (OfBlockPointer) { 11727 if (canAssignObjCInterfacesInBlockPointer( 11728 LHS->castAs<ObjCObjectPointerType>(), 11729 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 11730 return LHS; 11731 return {}; 11732 } 11733 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 11734 RHS->castAs<ObjCObjectPointerType>())) 11735 return LHS; 11736 return {}; 11737 case Type::Pipe: 11738 assert(LHS != RHS && 11739 "Equivalent pipe types should have already been handled!"); 11740 return {}; 11741 case Type::ArrayParameter: 11742 assert(LHS != RHS && 11743 "Equivalent ArrayParameter types should have already been handled!"); 11744 return {}; 11745 case Type::BitInt: { 11746 // Merge two bit-precise int types, while trying to preserve typedef info. 11747 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 11748 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 11749 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 11750 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 11751 11752 // Like unsigned/int, shouldn't have a type if they don't match. 11753 if (LHSUnsigned != RHSUnsigned) 11754 return {}; 11755 11756 if (LHSBits != RHSBits) 11757 return {}; 11758 return LHS; 11759 } 11760 case Type::HLSLAttributedResource: { 11761 const HLSLAttributedResourceType *LHSTy = 11762 LHS->castAs<HLSLAttributedResourceType>(); 11763 const HLSLAttributedResourceType *RHSTy = 11764 RHS->castAs<HLSLAttributedResourceType>(); 11765 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() && 11766 LHSTy->getWrappedType()->isHLSLResourceType() && 11767 "HLSLAttributedResourceType should always wrap __hlsl_resource_t"); 11768 11769 if (LHSTy->getAttrs() == RHSTy->getAttrs() && 11770 LHSTy->getContainedType() == RHSTy->getContainedType()) 11771 return LHS; 11772 return {}; 11773 } 11774 } 11775 11776 llvm_unreachable("Invalid Type::Class!"); 11777 } 11778 11779 bool ASTContext::mergeExtParameterInfo( 11780 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 11781 bool &CanUseFirst, bool &CanUseSecond, 11782 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 11783 assert(NewParamInfos.empty() && "param info list not empty"); 11784 CanUseFirst = CanUseSecond = true; 11785 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 11786 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 11787 11788 // Fast path: if the first type doesn't have ext parameter infos, 11789 // we match if and only if the second type also doesn't have them. 11790 if (!FirstHasInfo && !SecondHasInfo) 11791 return true; 11792 11793 bool NeedParamInfo = false; 11794 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 11795 : SecondFnType->getExtParameterInfos().size(); 11796 11797 for (size_t I = 0; I < E; ++I) { 11798 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 11799 if (FirstHasInfo) 11800 FirstParam = FirstFnType->getExtParameterInfo(I); 11801 if (SecondHasInfo) 11802 SecondParam = SecondFnType->getExtParameterInfo(I); 11803 11804 // Cannot merge unless everything except the noescape flag matches. 11805 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 11806 return false; 11807 11808 bool FirstNoEscape = FirstParam.isNoEscape(); 11809 bool SecondNoEscape = SecondParam.isNoEscape(); 11810 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 11811 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 11812 if (NewParamInfos.back().getOpaqueValue()) 11813 NeedParamInfo = true; 11814 if (FirstNoEscape != IsNoEscape) 11815 CanUseFirst = false; 11816 if (SecondNoEscape != IsNoEscape) 11817 CanUseSecond = false; 11818 } 11819 11820 if (!NeedParamInfo) 11821 NewParamInfos.clear(); 11822 11823 return true; 11824 } 11825 11826 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 11827 ObjCLayouts[CD] = nullptr; 11828 } 11829 11830 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 11831 /// 'RHS' attributes and returns the merged version; including for function 11832 /// return types. 11833 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 11834 QualType LHSCan = getCanonicalType(LHS), 11835 RHSCan = getCanonicalType(RHS); 11836 // If two types are identical, they are compatible. 11837 if (LHSCan == RHSCan) 11838 return LHS; 11839 if (RHSCan->isFunctionType()) { 11840 if (!LHSCan->isFunctionType()) 11841 return {}; 11842 QualType OldReturnType = 11843 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 11844 QualType NewReturnType = 11845 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 11846 QualType ResReturnType = 11847 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 11848 if (ResReturnType.isNull()) 11849 return {}; 11850 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 11851 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 11852 // In either case, use OldReturnType to build the new function type. 11853 const auto *F = LHS->castAs<FunctionType>(); 11854 if (const auto *FPT = cast<FunctionProtoType>(F)) { 11855 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11856 EPI.ExtInfo = getFunctionExtInfo(LHS); 11857 QualType ResultType = 11858 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 11859 return ResultType; 11860 } 11861 } 11862 return {}; 11863 } 11864 11865 // If the qualifiers are different, the types can still be merged. 11866 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 11867 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 11868 if (LQuals != RQuals) { 11869 // If any of these qualifiers are different, we have a type mismatch. 11870 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 11871 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 11872 return {}; 11873 11874 // Exactly one GC qualifier difference is allowed: __strong is 11875 // okay if the other type has no GC qualifier but is an Objective 11876 // C object pointer (i.e. implicitly strong by default). We fix 11877 // this by pretending that the unqualified type was actually 11878 // qualified __strong. 11879 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 11880 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 11881 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 11882 11883 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 11884 return {}; 11885 11886 if (GC_L == Qualifiers::Strong) 11887 return LHS; 11888 if (GC_R == Qualifiers::Strong) 11889 return RHS; 11890 return {}; 11891 } 11892 11893 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 11894 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 11895 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 11896 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 11897 if (ResQT == LHSBaseQT) 11898 return LHS; 11899 if (ResQT == RHSBaseQT) 11900 return RHS; 11901 } 11902 return {}; 11903 } 11904 11905 //===----------------------------------------------------------------------===// 11906 // Integer Predicates 11907 //===----------------------------------------------------------------------===// 11908 11909 unsigned ASTContext::getIntWidth(QualType T) const { 11910 if (const auto *ET = T->getAs<EnumType>()) 11911 T = ET->getDecl()->getIntegerType(); 11912 if (T->isBooleanType()) 11913 return 1; 11914 if (const auto *EIT = T->getAs<BitIntType>()) 11915 return EIT->getNumBits(); 11916 // For builtin types, just use the standard type sizing method 11917 return (unsigned)getTypeSize(T); 11918 } 11919 11920 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 11921 assert((T->hasIntegerRepresentation() || T->isEnumeralType() || 11922 T->isFixedPointType()) && 11923 "Unexpected type"); 11924 11925 // Turn <4 x signed int> -> <4 x unsigned int> 11926 if (const auto *VTy = T->getAs<VectorType>()) 11927 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 11928 VTy->getNumElements(), VTy->getVectorKind()); 11929 11930 // For _BitInt, return an unsigned _BitInt with same width. 11931 if (const auto *EITy = T->getAs<BitIntType>()) 11932 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 11933 11934 // For enums, get the underlying integer type of the enum, and let the general 11935 // integer type signchanging code handle it. 11936 if (const auto *ETy = T->getAs<EnumType>()) 11937 T = ETy->getDecl()->getIntegerType(); 11938 11939 switch (T->castAs<BuiltinType>()->getKind()) { 11940 case BuiltinType::Char_U: 11941 // Plain `char` is mapped to `unsigned char` even if it's already unsigned 11942 case BuiltinType::Char_S: 11943 case BuiltinType::SChar: 11944 case BuiltinType::Char8: 11945 return UnsignedCharTy; 11946 case BuiltinType::Short: 11947 return UnsignedShortTy; 11948 case BuiltinType::Int: 11949 return UnsignedIntTy; 11950 case BuiltinType::Long: 11951 return UnsignedLongTy; 11952 case BuiltinType::LongLong: 11953 return UnsignedLongLongTy; 11954 case BuiltinType::Int128: 11955 return UnsignedInt128Ty; 11956 // wchar_t is special. It is either signed or not, but when it's signed, 11957 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 11958 // version of its underlying type instead. 11959 case BuiltinType::WChar_S: 11960 return getUnsignedWCharType(); 11961 11962 case BuiltinType::ShortAccum: 11963 return UnsignedShortAccumTy; 11964 case BuiltinType::Accum: 11965 return UnsignedAccumTy; 11966 case BuiltinType::LongAccum: 11967 return UnsignedLongAccumTy; 11968 case BuiltinType::SatShortAccum: 11969 return SatUnsignedShortAccumTy; 11970 case BuiltinType::SatAccum: 11971 return SatUnsignedAccumTy; 11972 case BuiltinType::SatLongAccum: 11973 return SatUnsignedLongAccumTy; 11974 case BuiltinType::ShortFract: 11975 return UnsignedShortFractTy; 11976 case BuiltinType::Fract: 11977 return UnsignedFractTy; 11978 case BuiltinType::LongFract: 11979 return UnsignedLongFractTy; 11980 case BuiltinType::SatShortFract: 11981 return SatUnsignedShortFractTy; 11982 case BuiltinType::SatFract: 11983 return SatUnsignedFractTy; 11984 case BuiltinType::SatLongFract: 11985 return SatUnsignedLongFractTy; 11986 default: 11987 assert((T->hasUnsignedIntegerRepresentation() || 11988 T->isUnsignedFixedPointType()) && 11989 "Unexpected signed integer or fixed point type"); 11990 return T; 11991 } 11992 } 11993 11994 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 11995 assert((T->hasIntegerRepresentation() || T->isEnumeralType() || 11996 T->isFixedPointType()) && 11997 "Unexpected type"); 11998 11999 // Turn <4 x unsigned int> -> <4 x signed int> 12000 if (const auto *VTy = T->getAs<VectorType>()) 12001 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 12002 VTy->getNumElements(), VTy->getVectorKind()); 12003 12004 // For _BitInt, return a signed _BitInt with same width. 12005 if (const auto *EITy = T->getAs<BitIntType>()) 12006 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 12007 12008 // For enums, get the underlying integer type of the enum, and let the general 12009 // integer type signchanging code handle it. 12010 if (const auto *ETy = T->getAs<EnumType>()) 12011 T = ETy->getDecl()->getIntegerType(); 12012 12013 switch (T->castAs<BuiltinType>()->getKind()) { 12014 case BuiltinType::Char_S: 12015 // Plain `char` is mapped to `signed char` even if it's already signed 12016 case BuiltinType::Char_U: 12017 case BuiltinType::UChar: 12018 case BuiltinType::Char8: 12019 return SignedCharTy; 12020 case BuiltinType::UShort: 12021 return ShortTy; 12022 case BuiltinType::UInt: 12023 return IntTy; 12024 case BuiltinType::ULong: 12025 return LongTy; 12026 case BuiltinType::ULongLong: 12027 return LongLongTy; 12028 case BuiltinType::UInt128: 12029 return Int128Ty; 12030 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 12031 // there's no matching "signed wchar_t". Therefore we return the signed 12032 // version of its underlying type instead. 12033 case BuiltinType::WChar_U: 12034 return getSignedWCharType(); 12035 12036 case BuiltinType::UShortAccum: 12037 return ShortAccumTy; 12038 case BuiltinType::UAccum: 12039 return AccumTy; 12040 case BuiltinType::ULongAccum: 12041 return LongAccumTy; 12042 case BuiltinType::SatUShortAccum: 12043 return SatShortAccumTy; 12044 case BuiltinType::SatUAccum: 12045 return SatAccumTy; 12046 case BuiltinType::SatULongAccum: 12047 return SatLongAccumTy; 12048 case BuiltinType::UShortFract: 12049 return ShortFractTy; 12050 case BuiltinType::UFract: 12051 return FractTy; 12052 case BuiltinType::ULongFract: 12053 return LongFractTy; 12054 case BuiltinType::SatUShortFract: 12055 return SatShortFractTy; 12056 case BuiltinType::SatUFract: 12057 return SatFractTy; 12058 case BuiltinType::SatULongFract: 12059 return SatLongFractTy; 12060 default: 12061 assert( 12062 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 12063 "Unexpected signed integer or fixed point type"); 12064 return T; 12065 } 12066 } 12067 12068 ASTMutationListener::~ASTMutationListener() = default; 12069 12070 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 12071 QualType ReturnType) {} 12072 12073 //===----------------------------------------------------------------------===// 12074 // Builtin Type Computation 12075 //===----------------------------------------------------------------------===// 12076 12077 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 12078 /// pointer over the consumed characters. This returns the resultant type. If 12079 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 12080 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 12081 /// a vector of "i*". 12082 /// 12083 /// RequiresICE is filled in on return to indicate whether the value is required 12084 /// to be an Integer Constant Expression. 12085 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 12086 ASTContext::GetBuiltinTypeError &Error, 12087 bool &RequiresICE, 12088 bool AllowTypeModifiers) { 12089 // Modifiers. 12090 int HowLong = 0; 12091 bool Signed = false, Unsigned = false; 12092 RequiresICE = false; 12093 12094 // Read the prefixed modifiers first. 12095 bool Done = false; 12096 #ifndef NDEBUG 12097 bool IsSpecial = false; 12098 #endif 12099 while (!Done) { 12100 switch (*Str++) { 12101 default: Done = true; --Str; break; 12102 case 'I': 12103 RequiresICE = true; 12104 break; 12105 case 'S': 12106 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 12107 assert(!Signed && "Can't use 'S' modifier multiple times!"); 12108 Signed = true; 12109 break; 12110 case 'U': 12111 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 12112 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 12113 Unsigned = true; 12114 break; 12115 case 'L': 12116 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 12117 assert(HowLong <= 2 && "Can't have LLLL modifier"); 12118 ++HowLong; 12119 break; 12120 case 'N': 12121 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 12122 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 12123 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 12124 #ifndef NDEBUG 12125 IsSpecial = true; 12126 #endif 12127 if (Context.getTargetInfo().getLongWidth() == 32) 12128 ++HowLong; 12129 break; 12130 case 'W': 12131 // This modifier represents int64 type. 12132 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 12133 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 12134 #ifndef NDEBUG 12135 IsSpecial = true; 12136 #endif 12137 switch (Context.getTargetInfo().getInt64Type()) { 12138 default: 12139 llvm_unreachable("Unexpected integer type"); 12140 case TargetInfo::SignedLong: 12141 HowLong = 1; 12142 break; 12143 case TargetInfo::SignedLongLong: 12144 HowLong = 2; 12145 break; 12146 } 12147 break; 12148 case 'Z': 12149 // This modifier represents int32 type. 12150 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 12151 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 12152 #ifndef NDEBUG 12153 IsSpecial = true; 12154 #endif 12155 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 12156 default: 12157 llvm_unreachable("Unexpected integer type"); 12158 case TargetInfo::SignedInt: 12159 HowLong = 0; 12160 break; 12161 case TargetInfo::SignedLong: 12162 HowLong = 1; 12163 break; 12164 case TargetInfo::SignedLongLong: 12165 HowLong = 2; 12166 break; 12167 } 12168 break; 12169 case 'O': 12170 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 12171 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 12172 #ifndef NDEBUG 12173 IsSpecial = true; 12174 #endif 12175 if (Context.getLangOpts().OpenCL) 12176 HowLong = 1; 12177 else 12178 HowLong = 2; 12179 break; 12180 } 12181 } 12182 12183 QualType Type; 12184 12185 // Read the base type. 12186 switch (*Str++) { 12187 default: llvm_unreachable("Unknown builtin type letter!"); 12188 case 'x': 12189 assert(HowLong == 0 && !Signed && !Unsigned && 12190 "Bad modifiers used with 'x'!"); 12191 Type = Context.Float16Ty; 12192 break; 12193 case 'y': 12194 assert(HowLong == 0 && !Signed && !Unsigned && 12195 "Bad modifiers used with 'y'!"); 12196 Type = Context.BFloat16Ty; 12197 break; 12198 case 'v': 12199 assert(HowLong == 0 && !Signed && !Unsigned && 12200 "Bad modifiers used with 'v'!"); 12201 Type = Context.VoidTy; 12202 break; 12203 case 'h': 12204 assert(HowLong == 0 && !Signed && !Unsigned && 12205 "Bad modifiers used with 'h'!"); 12206 Type = Context.HalfTy; 12207 break; 12208 case 'f': 12209 assert(HowLong == 0 && !Signed && !Unsigned && 12210 "Bad modifiers used with 'f'!"); 12211 Type = Context.FloatTy; 12212 break; 12213 case 'd': 12214 assert(HowLong < 3 && !Signed && !Unsigned && 12215 "Bad modifiers used with 'd'!"); 12216 if (HowLong == 1) 12217 Type = Context.LongDoubleTy; 12218 else if (HowLong == 2) 12219 Type = Context.Float128Ty; 12220 else 12221 Type = Context.DoubleTy; 12222 break; 12223 case 's': 12224 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 12225 if (Unsigned) 12226 Type = Context.UnsignedShortTy; 12227 else 12228 Type = Context.ShortTy; 12229 break; 12230 case 'i': 12231 if (HowLong == 3) 12232 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 12233 else if (HowLong == 2) 12234 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 12235 else if (HowLong == 1) 12236 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 12237 else 12238 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 12239 break; 12240 case 'c': 12241 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 12242 if (Signed) 12243 Type = Context.SignedCharTy; 12244 else if (Unsigned) 12245 Type = Context.UnsignedCharTy; 12246 else 12247 Type = Context.CharTy; 12248 break; 12249 case 'b': // boolean 12250 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 12251 Type = Context.BoolTy; 12252 break; 12253 case 'z': // size_t. 12254 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 12255 Type = Context.getSizeType(); 12256 break; 12257 case 'w': // wchar_t. 12258 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 12259 Type = Context.getWideCharType(); 12260 break; 12261 case 'F': 12262 Type = Context.getCFConstantStringType(); 12263 break; 12264 case 'G': 12265 Type = Context.getObjCIdType(); 12266 break; 12267 case 'H': 12268 Type = Context.getObjCSelType(); 12269 break; 12270 case 'M': 12271 Type = Context.getObjCSuperType(); 12272 break; 12273 case 'a': 12274 Type = Context.getBuiltinVaListType(); 12275 assert(!Type.isNull() && "builtin va list type not initialized!"); 12276 break; 12277 case 'A': 12278 // This is a "reference" to a va_list; however, what exactly 12279 // this means depends on how va_list is defined. There are two 12280 // different kinds of va_list: ones passed by value, and ones 12281 // passed by reference. An example of a by-value va_list is 12282 // x86, where va_list is a char*. An example of by-ref va_list 12283 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 12284 // we want this argument to be a char*&; for x86-64, we want 12285 // it to be a __va_list_tag*. 12286 Type = Context.getBuiltinVaListType(); 12287 assert(!Type.isNull() && "builtin va list type not initialized!"); 12288 if (Type->isArrayType()) 12289 Type = Context.getArrayDecayedType(Type); 12290 else 12291 Type = Context.getLValueReferenceType(Type); 12292 break; 12293 case 'q': { 12294 char *End; 12295 unsigned NumElements = strtoul(Str, &End, 10); 12296 assert(End != Str && "Missing vector size"); 12297 Str = End; 12298 12299 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 12300 RequiresICE, false); 12301 assert(!RequiresICE && "Can't require vector ICE"); 12302 12303 Type = Context.getScalableVectorType(ElementType, NumElements); 12304 break; 12305 } 12306 case 'Q': { 12307 switch (*Str++) { 12308 case 'a': { 12309 Type = Context.SveCountTy; 12310 break; 12311 } 12312 case 'b': { 12313 Type = Context.AMDGPUBufferRsrcTy; 12314 break; 12315 } 12316 default: 12317 llvm_unreachable("Unexpected target builtin type"); 12318 } 12319 break; 12320 } 12321 case 'V': { 12322 char *End; 12323 unsigned NumElements = strtoul(Str, &End, 10); 12324 assert(End != Str && "Missing vector size"); 12325 Str = End; 12326 12327 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 12328 RequiresICE, false); 12329 assert(!RequiresICE && "Can't require vector ICE"); 12330 12331 // TODO: No way to make AltiVec vectors in builtins yet. 12332 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic); 12333 break; 12334 } 12335 case 'E': { 12336 char *End; 12337 12338 unsigned NumElements = strtoul(Str, &End, 10); 12339 assert(End != Str && "Missing vector size"); 12340 12341 Str = End; 12342 12343 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 12344 false); 12345 Type = Context.getExtVectorType(ElementType, NumElements); 12346 break; 12347 } 12348 case 'X': { 12349 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 12350 false); 12351 assert(!RequiresICE && "Can't require complex ICE"); 12352 Type = Context.getComplexType(ElementType); 12353 break; 12354 } 12355 case 'Y': 12356 Type = Context.getPointerDiffType(); 12357 break; 12358 case 'P': 12359 Type = Context.getFILEType(); 12360 if (Type.isNull()) { 12361 Error = ASTContext::GE_Missing_stdio; 12362 return {}; 12363 } 12364 break; 12365 case 'J': 12366 if (Signed) 12367 Type = Context.getsigjmp_bufType(); 12368 else 12369 Type = Context.getjmp_bufType(); 12370 12371 if (Type.isNull()) { 12372 Error = ASTContext::GE_Missing_setjmp; 12373 return {}; 12374 } 12375 break; 12376 case 'K': 12377 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 12378 Type = Context.getucontext_tType(); 12379 12380 if (Type.isNull()) { 12381 Error = ASTContext::GE_Missing_ucontext; 12382 return {}; 12383 } 12384 break; 12385 case 'p': 12386 Type = Context.getProcessIDType(); 12387 break; 12388 case 'm': 12389 Type = Context.MFloat8Ty; 12390 break; 12391 } 12392 12393 // If there are modifiers and if we're allowed to parse them, go for it. 12394 Done = !AllowTypeModifiers; 12395 while (!Done) { 12396 switch (char c = *Str++) { 12397 default: Done = true; --Str; break; 12398 case '*': 12399 case '&': { 12400 // Both pointers and references can have their pointee types 12401 // qualified with an address space. 12402 char *End; 12403 unsigned AddrSpace = strtoul(Str, &End, 10); 12404 if (End != Str) { 12405 // Note AddrSpace == 0 is not the same as an unspecified address space. 12406 Type = Context.getAddrSpaceQualType( 12407 Type, 12408 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 12409 Str = End; 12410 } 12411 if (c == '*') 12412 Type = Context.getPointerType(Type); 12413 else 12414 Type = Context.getLValueReferenceType(Type); 12415 break; 12416 } 12417 // FIXME: There's no way to have a built-in with an rvalue ref arg. 12418 case 'C': 12419 Type = Type.withConst(); 12420 break; 12421 case 'D': 12422 Type = Context.getVolatileType(Type); 12423 break; 12424 case 'R': 12425 Type = Type.withRestrict(); 12426 break; 12427 } 12428 } 12429 12430 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 12431 "Integer constant 'I' type must be an integer"); 12432 12433 return Type; 12434 } 12435 12436 // On some targets such as PowerPC, some of the builtins are defined with custom 12437 // type descriptors for target-dependent types. These descriptors are decoded in 12438 // other functions, but it may be useful to be able to fall back to default 12439 // descriptor decoding to define builtins mixing target-dependent and target- 12440 // independent types. This function allows decoding one type descriptor with 12441 // default decoding. 12442 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 12443 GetBuiltinTypeError &Error, bool &RequireICE, 12444 bool AllowTypeModifiers) const { 12445 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 12446 } 12447 12448 /// GetBuiltinType - Return the type for the specified builtin. 12449 QualType ASTContext::GetBuiltinType(unsigned Id, 12450 GetBuiltinTypeError &Error, 12451 unsigned *IntegerConstantArgs) const { 12452 const char *TypeStr = BuiltinInfo.getTypeString(Id); 12453 if (TypeStr[0] == '\0') { 12454 Error = GE_Missing_type; 12455 return {}; 12456 } 12457 12458 SmallVector<QualType, 8> ArgTypes; 12459 12460 bool RequiresICE = false; 12461 Error = GE_None; 12462 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 12463 RequiresICE, true); 12464 if (Error != GE_None) 12465 return {}; 12466 12467 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 12468 12469 while (TypeStr[0] && TypeStr[0] != '.') { 12470 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 12471 if (Error != GE_None) 12472 return {}; 12473 12474 // If this argument is required to be an IntegerConstantExpression and the 12475 // caller cares, fill in the bitmask we return. 12476 if (RequiresICE && IntegerConstantArgs) 12477 *IntegerConstantArgs |= 1 << ArgTypes.size(); 12478 12479 // Do array -> pointer decay. The builtin should use the decayed type. 12480 if (Ty->isArrayType()) 12481 Ty = getArrayDecayedType(Ty); 12482 12483 ArgTypes.push_back(Ty); 12484 } 12485 12486 if (Id == Builtin::BI__GetExceptionInfo) 12487 return {}; 12488 12489 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 12490 "'.' should only occur at end of builtin type list!"); 12491 12492 bool Variadic = (TypeStr[0] == '.'); 12493 12494 FunctionType::ExtInfo EI(getDefaultCallingConvention( 12495 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 12496 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 12497 12498 12499 // We really shouldn't be making a no-proto type here. 12500 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes()) 12501 return getFunctionNoProtoType(ResType, EI); 12502 12503 FunctionProtoType::ExtProtoInfo EPI; 12504 EPI.ExtInfo = EI; 12505 EPI.Variadic = Variadic; 12506 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 12507 EPI.ExceptionSpec.Type = 12508 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 12509 12510 return getFunctionType(ResType, ArgTypes, EPI); 12511 } 12512 12513 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 12514 const FunctionDecl *FD) { 12515 if (!FD->isExternallyVisible()) 12516 return GVA_Internal; 12517 12518 // Non-user-provided functions get emitted as weak definitions with every 12519 // use, no matter whether they've been explicitly instantiated etc. 12520 if (!FD->isUserProvided()) 12521 return GVA_DiscardableODR; 12522 12523 GVALinkage External; 12524 switch (FD->getTemplateSpecializationKind()) { 12525 case TSK_Undeclared: 12526 case TSK_ExplicitSpecialization: 12527 External = GVA_StrongExternal; 12528 break; 12529 12530 case TSK_ExplicitInstantiationDefinition: 12531 return GVA_StrongODR; 12532 12533 // C++11 [temp.explicit]p10: 12534 // [ Note: The intent is that an inline function that is the subject of 12535 // an explicit instantiation declaration will still be implicitly 12536 // instantiated when used so that the body can be considered for 12537 // inlining, but that no out-of-line copy of the inline function would be 12538 // generated in the translation unit. -- end note ] 12539 case TSK_ExplicitInstantiationDeclaration: 12540 return GVA_AvailableExternally; 12541 12542 case TSK_ImplicitInstantiation: 12543 External = GVA_DiscardableODR; 12544 break; 12545 } 12546 12547 if (!FD->isInlined()) 12548 return External; 12549 12550 if ((!Context.getLangOpts().CPlusPlus && 12551 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 12552 !FD->hasAttr<DLLExportAttr>()) || 12553 FD->hasAttr<GNUInlineAttr>()) { 12554 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 12555 12556 // GNU or C99 inline semantics. Determine whether this symbol should be 12557 // externally visible. 12558 if (FD->isInlineDefinitionExternallyVisible()) 12559 return External; 12560 12561 // C99 inline semantics, where the symbol is not externally visible. 12562 return GVA_AvailableExternally; 12563 } 12564 12565 // Functions specified with extern and inline in -fms-compatibility mode 12566 // forcibly get emitted. While the body of the function cannot be later 12567 // replaced, the function definition cannot be discarded. 12568 if (FD->isMSExternInline()) 12569 return GVA_StrongODR; 12570 12571 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12572 isa<CXXConstructorDecl>(FD) && 12573 cast<CXXConstructorDecl>(FD)->isInheritingConstructor()) 12574 // Our approach to inheriting constructors is fundamentally different from 12575 // that used by the MS ABI, so keep our inheriting constructor thunks 12576 // internal rather than trying to pick an unambiguous mangling for them. 12577 return GVA_Internal; 12578 12579 return GVA_DiscardableODR; 12580 } 12581 12582 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 12583 const Decl *D, GVALinkage L) { 12584 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 12585 // dllexport/dllimport on inline functions. 12586 if (D->hasAttr<DLLImportAttr>()) { 12587 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 12588 return GVA_AvailableExternally; 12589 } else if (D->hasAttr<DLLExportAttr>()) { 12590 if (L == GVA_DiscardableODR) 12591 return GVA_StrongODR; 12592 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 12593 // Device-side functions with __global__ attribute must always be 12594 // visible externally so they can be launched from host. 12595 if (D->hasAttr<CUDAGlobalAttr>() && 12596 (L == GVA_DiscardableODR || L == GVA_Internal)) 12597 return GVA_StrongODR; 12598 // Single source offloading languages like CUDA/HIP need to be able to 12599 // access static device variables from host code of the same compilation 12600 // unit. This is done by externalizing the static variable with a shared 12601 // name between the host and device compilation which is the same for the 12602 // same compilation unit whereas different among different compilation 12603 // units. 12604 if (Context.shouldExternalize(D)) 12605 return GVA_StrongExternal; 12606 } 12607 return L; 12608 } 12609 12610 /// Adjust the GVALinkage for a declaration based on what an external AST source 12611 /// knows about whether there can be other definitions of this declaration. 12612 static GVALinkage 12613 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 12614 GVALinkage L) { 12615 ExternalASTSource *Source = Ctx.getExternalSource(); 12616 if (!Source) 12617 return L; 12618 12619 switch (Source->hasExternalDefinitions(D)) { 12620 case ExternalASTSource::EK_Never: 12621 // Other translation units rely on us to provide the definition. 12622 if (L == GVA_DiscardableODR) 12623 return GVA_StrongODR; 12624 break; 12625 12626 case ExternalASTSource::EK_Always: 12627 return GVA_AvailableExternally; 12628 12629 case ExternalASTSource::EK_ReplyHazy: 12630 break; 12631 } 12632 return L; 12633 } 12634 12635 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 12636 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 12637 adjustGVALinkageForAttributes(*this, FD, 12638 basicGVALinkageForFunction(*this, FD))); 12639 } 12640 12641 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 12642 const VarDecl *VD) { 12643 // As an extension for interactive REPLs, make sure constant variables are 12644 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl 12645 // marking them as internal. 12646 if (Context.getLangOpts().CPlusPlus && 12647 Context.getLangOpts().IncrementalExtensions && 12648 VD->getType().isConstQualified() && 12649 !VD->getType().isVolatileQualified() && !VD->isInline() && 12650 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate()) 12651 return GVA_DiscardableODR; 12652 12653 if (!VD->isExternallyVisible()) 12654 return GVA_Internal; 12655 12656 if (VD->isStaticLocal()) { 12657 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 12658 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 12659 LexicalContext = LexicalContext->getLexicalParent(); 12660 12661 // ObjC Blocks can create local variables that don't have a FunctionDecl 12662 // LexicalContext. 12663 if (!LexicalContext) 12664 return GVA_DiscardableODR; 12665 12666 // Otherwise, let the static local variable inherit its linkage from the 12667 // nearest enclosing function. 12668 auto StaticLocalLinkage = 12669 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 12670 12671 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 12672 // be emitted in any object with references to the symbol for the object it 12673 // contains, whether inline or out-of-line." 12674 // Similar behavior is observed with MSVC. An alternative ABI could use 12675 // StrongODR/AvailableExternally to match the function, but none are 12676 // known/supported currently. 12677 if (StaticLocalLinkage == GVA_StrongODR || 12678 StaticLocalLinkage == GVA_AvailableExternally) 12679 return GVA_DiscardableODR; 12680 return StaticLocalLinkage; 12681 } 12682 12683 // MSVC treats in-class initialized static data members as definitions. 12684 // By giving them non-strong linkage, out-of-line definitions won't 12685 // cause link errors. 12686 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 12687 return GVA_DiscardableODR; 12688 12689 // Most non-template variables have strong linkage; inline variables are 12690 // linkonce_odr or (occasionally, for compatibility) weak_odr. 12691 GVALinkage StrongLinkage; 12692 switch (Context.getInlineVariableDefinitionKind(VD)) { 12693 case ASTContext::InlineVariableDefinitionKind::None: 12694 StrongLinkage = GVA_StrongExternal; 12695 break; 12696 case ASTContext::InlineVariableDefinitionKind::Weak: 12697 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 12698 StrongLinkage = GVA_DiscardableODR; 12699 break; 12700 case ASTContext::InlineVariableDefinitionKind::Strong: 12701 StrongLinkage = GVA_StrongODR; 12702 break; 12703 } 12704 12705 switch (VD->getTemplateSpecializationKind()) { 12706 case TSK_Undeclared: 12707 return StrongLinkage; 12708 12709 case TSK_ExplicitSpecialization: 12710 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 12711 VD->isStaticDataMember() 12712 ? GVA_StrongODR 12713 : StrongLinkage; 12714 12715 case TSK_ExplicitInstantiationDefinition: 12716 return GVA_StrongODR; 12717 12718 case TSK_ExplicitInstantiationDeclaration: 12719 return GVA_AvailableExternally; 12720 12721 case TSK_ImplicitInstantiation: 12722 return GVA_DiscardableODR; 12723 } 12724 12725 llvm_unreachable("Invalid Linkage!"); 12726 } 12727 12728 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const { 12729 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 12730 adjustGVALinkageForAttributes(*this, VD, 12731 basicGVALinkageForVariable(*this, VD))); 12732 } 12733 12734 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 12735 if (const auto *VD = dyn_cast<VarDecl>(D)) { 12736 if (!VD->isFileVarDecl()) 12737 return false; 12738 // Global named register variables (GNU extension) are never emitted. 12739 if (VD->getStorageClass() == SC_Register) 12740 return false; 12741 if (VD->getDescribedVarTemplate() || 12742 isa<VarTemplatePartialSpecializationDecl>(VD)) 12743 return false; 12744 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 12745 // We never need to emit an uninstantiated function template. 12746 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12747 return false; 12748 } else if (isa<PragmaCommentDecl>(D)) 12749 return true; 12750 else if (isa<PragmaDetectMismatchDecl>(D)) 12751 return true; 12752 else if (isa<OMPRequiresDecl>(D)) 12753 return true; 12754 else if (isa<OMPThreadPrivateDecl>(D)) 12755 return !D->getDeclContext()->isDependentContext(); 12756 else if (isa<OMPAllocateDecl>(D)) 12757 return !D->getDeclContext()->isDependentContext(); 12758 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 12759 return !D->getDeclContext()->isDependentContext(); 12760 else if (isa<ImportDecl>(D)) 12761 return true; 12762 else 12763 return false; 12764 12765 // If this is a member of a class template, we do not need to emit it. 12766 if (D->getDeclContext()->isDependentContext()) 12767 return false; 12768 12769 // Weak references don't produce any output by themselves. 12770 if (D->hasAttr<WeakRefAttr>()) 12771 return false; 12772 12773 // Aliases and used decls are required. 12774 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 12775 return true; 12776 12777 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 12778 // Forward declarations aren't required. 12779 if (!FD->doesThisDeclarationHaveABody()) 12780 return FD->doesDeclarationForceExternallyVisibleDefinition(); 12781 12782 // Constructors and destructors are required. 12783 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 12784 return true; 12785 12786 // The key function for a class is required. This rule only comes 12787 // into play when inline functions can be key functions, though. 12788 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12789 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12790 const CXXRecordDecl *RD = MD->getParent(); 12791 if (MD->isOutOfLine() && RD->isDynamicClass()) { 12792 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 12793 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 12794 return true; 12795 } 12796 } 12797 } 12798 12799 GVALinkage Linkage = GetGVALinkageForFunction(FD); 12800 12801 // static, static inline, always_inline, and extern inline functions can 12802 // always be deferred. Normal inline functions can be deferred in C99/C++. 12803 // Implicit template instantiations can also be deferred in C++. 12804 return !isDiscardableGVALinkage(Linkage); 12805 } 12806 12807 const auto *VD = cast<VarDecl>(D); 12808 assert(VD->isFileVarDecl() && "Expected file scoped var"); 12809 12810 // If the decl is marked as `declare target to`, it should be emitted for the 12811 // host and for the device. 12812 if (LangOpts.OpenMP && 12813 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 12814 return true; 12815 12816 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 12817 !isMSStaticDataMemberInlineDefinition(VD)) 12818 return false; 12819 12820 if (VD->shouldEmitInExternalSource()) 12821 return false; 12822 12823 // Variables that can be needed in other TUs are required. 12824 auto Linkage = GetGVALinkageForVariable(VD); 12825 if (!isDiscardableGVALinkage(Linkage)) 12826 return true; 12827 12828 // We never need to emit a variable that is available in another TU. 12829 if (Linkage == GVA_AvailableExternally) 12830 return false; 12831 12832 // Variables that have destruction with side-effects are required. 12833 if (VD->needsDestruction(*this)) 12834 return true; 12835 12836 // Variables that have initialization with side-effects are required. 12837 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 12838 // We can get a value-dependent initializer during error recovery. 12839 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 12840 return true; 12841 12842 // Likewise, variables with tuple-like bindings are required if their 12843 // bindings have side-effects. 12844 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) { 12845 for (const auto *BD : DD->flat_bindings()) 12846 if (const auto *BindingVD = BD->getHoldingVar()) 12847 if (DeclMustBeEmitted(BindingVD)) 12848 return true; 12849 } 12850 12851 return false; 12852 } 12853 12854 void ASTContext::forEachMultiversionedFunctionVersion( 12855 const FunctionDecl *FD, 12856 llvm::function_ref<void(FunctionDecl *)> Pred) const { 12857 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 12858 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 12859 FD = FD->getMostRecentDecl(); 12860 // FIXME: The order of traversal here matters and depends on the order of 12861 // lookup results, which happens to be (mostly) oldest-to-newest, but we 12862 // shouldn't rely on that. 12863 for (auto *CurDecl : 12864 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 12865 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 12866 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 12867 SeenDecls.insert(CurFD).second) { 12868 Pred(CurFD); 12869 } 12870 } 12871 } 12872 12873 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 12874 bool IsCXXMethod, 12875 bool IsBuiltin) const { 12876 // Pass through to the C++ ABI object 12877 if (IsCXXMethod) 12878 return ABI->getDefaultMethodCallConv(IsVariadic); 12879 12880 // Builtins ignore user-specified default calling convention and remain the 12881 // Target's default calling convention. 12882 if (!IsBuiltin) { 12883 switch (LangOpts.getDefaultCallingConv()) { 12884 case LangOptions::DCC_None: 12885 break; 12886 case LangOptions::DCC_CDecl: 12887 return CC_C; 12888 case LangOptions::DCC_FastCall: 12889 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 12890 return CC_X86FastCall; 12891 break; 12892 case LangOptions::DCC_StdCall: 12893 if (!IsVariadic) 12894 return CC_X86StdCall; 12895 break; 12896 case LangOptions::DCC_VectorCall: 12897 // __vectorcall cannot be applied to variadic functions. 12898 if (!IsVariadic) 12899 return CC_X86VectorCall; 12900 break; 12901 case LangOptions::DCC_RegCall: 12902 // __regcall cannot be applied to variadic functions. 12903 if (!IsVariadic) 12904 return CC_X86RegCall; 12905 break; 12906 case LangOptions::DCC_RtdCall: 12907 if (!IsVariadic) 12908 return CC_M68kRTD; 12909 break; 12910 } 12911 } 12912 return Target->getDefaultCallingConv(); 12913 } 12914 12915 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 12916 // Pass through to the C++ ABI object 12917 return ABI->isNearlyEmpty(RD); 12918 } 12919 12920 VTableContextBase *ASTContext::getVTableContext() { 12921 if (!VTContext.get()) { 12922 auto ABI = Target->getCXXABI(); 12923 if (ABI.isMicrosoft()) 12924 VTContext.reset(new MicrosoftVTableContext(*this)); 12925 else { 12926 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 12927 ? ItaniumVTableContext::Relative 12928 : ItaniumVTableContext::Pointer; 12929 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 12930 } 12931 } 12932 return VTContext.get(); 12933 } 12934 12935 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 12936 if (!T) 12937 T = Target; 12938 switch (T->getCXXABI().getKind()) { 12939 case TargetCXXABI::AppleARM64: 12940 case TargetCXXABI::Fuchsia: 12941 case TargetCXXABI::GenericAArch64: 12942 case TargetCXXABI::GenericItanium: 12943 case TargetCXXABI::GenericARM: 12944 case TargetCXXABI::GenericMIPS: 12945 case TargetCXXABI::iOS: 12946 case TargetCXXABI::WebAssembly: 12947 case TargetCXXABI::WatchOS: 12948 case TargetCXXABI::XL: 12949 return ItaniumMangleContext::create(*this, getDiagnostics()); 12950 case TargetCXXABI::Microsoft: 12951 return MicrosoftMangleContext::create(*this, getDiagnostics()); 12952 } 12953 llvm_unreachable("Unsupported ABI"); 12954 } 12955 12956 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 12957 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 12958 "Device mangle context does not support Microsoft mangling."); 12959 switch (T.getCXXABI().getKind()) { 12960 case TargetCXXABI::AppleARM64: 12961 case TargetCXXABI::Fuchsia: 12962 case TargetCXXABI::GenericAArch64: 12963 case TargetCXXABI::GenericItanium: 12964 case TargetCXXABI::GenericARM: 12965 case TargetCXXABI::GenericMIPS: 12966 case TargetCXXABI::iOS: 12967 case TargetCXXABI::WebAssembly: 12968 case TargetCXXABI::WatchOS: 12969 case TargetCXXABI::XL: 12970 return ItaniumMangleContext::create( 12971 *this, getDiagnostics(), 12972 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> { 12973 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 12974 return RD->getDeviceLambdaManglingNumber(); 12975 return std::nullopt; 12976 }, 12977 /*IsAux=*/true); 12978 case TargetCXXABI::Microsoft: 12979 return MicrosoftMangleContext::create(*this, getDiagnostics(), 12980 /*IsAux=*/true); 12981 } 12982 llvm_unreachable("Unsupported ABI"); 12983 } 12984 12985 CXXABI::~CXXABI() = default; 12986 12987 size_t ASTContext::getSideTableAllocatedMemory() const { 12988 return ASTRecordLayouts.getMemorySize() + 12989 llvm::capacity_in_bytes(ObjCLayouts) + 12990 llvm::capacity_in_bytes(KeyFunctions) + 12991 llvm::capacity_in_bytes(ObjCImpls) + 12992 llvm::capacity_in_bytes(BlockVarCopyInits) + 12993 llvm::capacity_in_bytes(DeclAttrs) + 12994 llvm::capacity_in_bytes(TemplateOrInstantiation) + 12995 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 12996 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 12997 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 12998 llvm::capacity_in_bytes(OverriddenMethods) + 12999 llvm::capacity_in_bytes(Types) + 13000 llvm::capacity_in_bytes(VariableArrayTypes); 13001 } 13002 13003 /// getIntTypeForBitwidth - 13004 /// sets integer QualTy according to specified details: 13005 /// bitwidth, signed/unsigned. 13006 /// Returns empty type if there is no appropriate target types. 13007 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 13008 unsigned Signed) const { 13009 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 13010 CanQualType QualTy = getFromTargetType(Ty); 13011 if (!QualTy && DestWidth == 128) 13012 return Signed ? Int128Ty : UnsignedInt128Ty; 13013 return QualTy; 13014 } 13015 13016 /// getRealTypeForBitwidth - 13017 /// sets floating point QualTy according to specified bitwidth. 13018 /// Returns empty type if there is no appropriate target types. 13019 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 13020 FloatModeKind ExplicitType) const { 13021 FloatModeKind Ty = 13022 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 13023 switch (Ty) { 13024 case FloatModeKind::Half: 13025 return HalfTy; 13026 case FloatModeKind::Float: 13027 return FloatTy; 13028 case FloatModeKind::Double: 13029 return DoubleTy; 13030 case FloatModeKind::LongDouble: 13031 return LongDoubleTy; 13032 case FloatModeKind::Float128: 13033 return Float128Ty; 13034 case FloatModeKind::Ibm128: 13035 return Ibm128Ty; 13036 case FloatModeKind::NoFloat: 13037 return {}; 13038 } 13039 13040 llvm_unreachable("Unhandled TargetInfo::RealType value"); 13041 } 13042 13043 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 13044 if (Number <= 1) 13045 return; 13046 13047 MangleNumbers[ND] = Number; 13048 13049 if (Listener) 13050 Listener->AddedManglingNumber(ND, Number); 13051 } 13052 13053 unsigned ASTContext::getManglingNumber(const NamedDecl *ND, 13054 bool ForAuxTarget) const { 13055 auto I = MangleNumbers.find(ND); 13056 unsigned Res = I != MangleNumbers.end() ? I->second : 1; 13057 // CUDA/HIP host compilation encodes host and device mangling numbers 13058 // as lower and upper half of 32 bit integer. 13059 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) { 13060 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF; 13061 } else { 13062 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling " 13063 "number for aux target"); 13064 } 13065 return Res > 1 ? Res : 1; 13066 } 13067 13068 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 13069 if (Number <= 1) 13070 return; 13071 13072 StaticLocalNumbers[VD] = Number; 13073 13074 if (Listener) 13075 Listener->AddedStaticLocalNumbers(VD, Number); 13076 } 13077 13078 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 13079 auto I = StaticLocalNumbers.find(VD); 13080 return I != StaticLocalNumbers.end() ? I->second : 1; 13081 } 13082 13083 MangleNumberingContext & 13084 ASTContext::getManglingNumberContext(const DeclContext *DC) { 13085 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 13086 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 13087 if (!MCtx) 13088 MCtx = createMangleNumberingContext(); 13089 return *MCtx; 13090 } 13091 13092 MangleNumberingContext & 13093 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 13094 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 13095 std::unique_ptr<MangleNumberingContext> &MCtx = 13096 ExtraMangleNumberingContexts[D]; 13097 if (!MCtx) 13098 MCtx = createMangleNumberingContext(); 13099 return *MCtx; 13100 } 13101 13102 std::unique_ptr<MangleNumberingContext> 13103 ASTContext::createMangleNumberingContext() const { 13104 return ABI->createMangleNumberingContext(); 13105 } 13106 13107 const CXXConstructorDecl * 13108 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 13109 return ABI->getCopyConstructorForExceptionObject( 13110 cast<CXXRecordDecl>(RD->getFirstDecl())); 13111 } 13112 13113 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 13114 CXXConstructorDecl *CD) { 13115 return ABI->addCopyConstructorForExceptionObject( 13116 cast<CXXRecordDecl>(RD->getFirstDecl()), 13117 cast<CXXConstructorDecl>(CD->getFirstDecl())); 13118 } 13119 13120 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 13121 TypedefNameDecl *DD) { 13122 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 13123 } 13124 13125 TypedefNameDecl * 13126 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 13127 return ABI->getTypedefNameForUnnamedTagDecl(TD); 13128 } 13129 13130 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 13131 DeclaratorDecl *DD) { 13132 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 13133 } 13134 13135 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 13136 return ABI->getDeclaratorForUnnamedTagDecl(TD); 13137 } 13138 13139 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 13140 ParamIndices[D] = index; 13141 } 13142 13143 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 13144 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 13145 assert(I != ParamIndices.end() && 13146 "ParmIndices lacks entry set by ParmVarDecl"); 13147 return I->second; 13148 } 13149 13150 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 13151 unsigned Length) const { 13152 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 13153 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 13154 EltTy = EltTy.withConst(); 13155 13156 EltTy = adjustStringLiteralBaseType(EltTy); 13157 13158 // Get an array type for the string, according to C99 6.4.5. This includes 13159 // the null terminator character. 13160 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 13161 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0); 13162 } 13163 13164 StringLiteral * 13165 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 13166 StringLiteral *&Result = StringLiteralCache[Key]; 13167 if (!Result) 13168 Result = StringLiteral::Create( 13169 *this, Key, StringLiteralKind::Ordinary, 13170 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 13171 SourceLocation()); 13172 return Result; 13173 } 13174 13175 MSGuidDecl * 13176 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 13177 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 13178 13179 llvm::FoldingSetNodeID ID; 13180 MSGuidDecl::Profile(ID, Parts); 13181 13182 void *InsertPos; 13183 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 13184 return Existing; 13185 13186 QualType GUIDType = getMSGuidType().withConst(); 13187 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 13188 MSGuidDecls.InsertNode(New, InsertPos); 13189 return New; 13190 } 13191 13192 UnnamedGlobalConstantDecl * 13193 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty, 13194 const APValue &APVal) const { 13195 llvm::FoldingSetNodeID ID; 13196 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal); 13197 13198 void *InsertPos; 13199 if (UnnamedGlobalConstantDecl *Existing = 13200 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos)) 13201 return Existing; 13202 13203 UnnamedGlobalConstantDecl *New = 13204 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal); 13205 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos); 13206 return New; 13207 } 13208 13209 TemplateParamObjectDecl * 13210 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 13211 assert(T->isRecordType() && "template param object of unexpected type"); 13212 13213 // C++ [temp.param]p8: 13214 // [...] a static storage duration object of type 'const T' [...] 13215 T.addConst(); 13216 13217 llvm::FoldingSetNodeID ID; 13218 TemplateParamObjectDecl::Profile(ID, T, V); 13219 13220 void *InsertPos; 13221 if (TemplateParamObjectDecl *Existing = 13222 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 13223 return Existing; 13224 13225 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 13226 TemplateParamObjectDecls.InsertNode(New, InsertPos); 13227 return New; 13228 } 13229 13230 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 13231 const llvm::Triple &T = getTargetInfo().getTriple(); 13232 if (!T.isOSDarwin()) 13233 return false; 13234 13235 if (!(T.isiOS() && T.isOSVersionLT(7)) && 13236 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 13237 return false; 13238 13239 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 13240 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 13241 uint64_t Size = sizeChars.getQuantity(); 13242 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 13243 unsigned Align = alignChars.getQuantity(); 13244 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 13245 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 13246 } 13247 13248 bool 13249 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 13250 const ObjCMethodDecl *MethodImpl) { 13251 // No point trying to match an unavailable/deprecated mothod. 13252 if (MethodDecl->hasAttr<UnavailableAttr>() 13253 || MethodDecl->hasAttr<DeprecatedAttr>()) 13254 return false; 13255 if (MethodDecl->getObjCDeclQualifier() != 13256 MethodImpl->getObjCDeclQualifier()) 13257 return false; 13258 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 13259 return false; 13260 13261 if (MethodDecl->param_size() != MethodImpl->param_size()) 13262 return false; 13263 13264 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 13265 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 13266 EF = MethodDecl->param_end(); 13267 IM != EM && IF != EF; ++IM, ++IF) { 13268 const ParmVarDecl *DeclVar = (*IF); 13269 const ParmVarDecl *ImplVar = (*IM); 13270 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 13271 return false; 13272 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 13273 return false; 13274 } 13275 13276 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 13277 } 13278 13279 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 13280 LangAS AS; 13281 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 13282 AS = LangAS::Default; 13283 else 13284 AS = QT->getPointeeType().getAddressSpace(); 13285 13286 return getTargetInfo().getNullPointerValue(AS); 13287 } 13288 13289 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 13290 return getTargetInfo().getTargetAddressSpace(AS); 13291 } 13292 13293 bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const { 13294 if (X == Y) 13295 return true; 13296 if (!X || !Y) 13297 return false; 13298 llvm::FoldingSetNodeID IDX, IDY; 13299 X->Profile(IDX, *this, /*Canonical=*/true); 13300 Y->Profile(IDY, *this, /*Canonical=*/true); 13301 return IDX == IDY; 13302 } 13303 13304 // The getCommon* helpers return, for given 'same' X and Y entities given as 13305 // inputs, another entity which is also the 'same' as the inputs, but which 13306 // is closer to the canonical form of the inputs, each according to a given 13307 // criteria. 13308 // The getCommon*Checked variants are 'null inputs not-allowed' equivalents of 13309 // the regular ones. 13310 13311 static Decl *getCommonDecl(Decl *X, Decl *Y) { 13312 if (!declaresSameEntity(X, Y)) 13313 return nullptr; 13314 for (const Decl *DX : X->redecls()) { 13315 // If we reach Y before reaching the first decl, that means X is older. 13316 if (DX == Y) 13317 return X; 13318 // If we reach the first decl, then Y is older. 13319 if (DX->isFirstDecl()) 13320 return Y; 13321 } 13322 llvm_unreachable("Corrupt redecls chain"); 13323 } 13324 13325 template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true> 13326 static T *getCommonDecl(T *X, T *Y) { 13327 return cast_or_null<T>( 13328 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)), 13329 const_cast<Decl *>(cast_or_null<Decl>(Y)))); 13330 } 13331 13332 template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true> 13333 static T *getCommonDeclChecked(T *X, T *Y) { 13334 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)), 13335 const_cast<Decl *>(cast<Decl>(Y)))); 13336 } 13337 13338 static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, 13339 TemplateName Y, 13340 bool IgnoreDeduced = false) { 13341 if (X.getAsVoidPointer() == Y.getAsVoidPointer()) 13342 return X; 13343 // FIXME: There are cases here where we could find a common template name 13344 // with more sugar. For example one could be a SubstTemplateTemplate* 13345 // replacing the other. 13346 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced); 13347 if (CX.getAsVoidPointer() != 13348 Ctx.getCanonicalTemplateName(Y).getAsVoidPointer()) 13349 return TemplateName(); 13350 return CX; 13351 } 13352 13353 static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, 13354 TemplateName X, TemplateName Y, 13355 bool IgnoreDeduced) { 13356 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced); 13357 assert(R.getAsVoidPointer() != nullptr); 13358 return R; 13359 } 13360 13361 static auto getCommonTypes(ASTContext &Ctx, ArrayRef<QualType> Xs, 13362 ArrayRef<QualType> Ys, bool Unqualified = false) { 13363 assert(Xs.size() == Ys.size()); 13364 SmallVector<QualType, 8> Rs(Xs.size()); 13365 for (size_t I = 0; I < Rs.size(); ++I) 13366 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified); 13367 return Rs; 13368 } 13369 13370 template <class T> 13371 static SourceLocation getCommonAttrLoc(const T *X, const T *Y) { 13372 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc() 13373 : SourceLocation(); 13374 } 13375 13376 static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, 13377 const TemplateArgument &X, 13378 const TemplateArgument &Y) { 13379 if (X.getKind() != Y.getKind()) 13380 return TemplateArgument(); 13381 13382 switch (X.getKind()) { 13383 case TemplateArgument::ArgKind::Type: 13384 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType())) 13385 return TemplateArgument(); 13386 return TemplateArgument( 13387 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType())); 13388 case TemplateArgument::ArgKind::NullPtr: 13389 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType())) 13390 return TemplateArgument(); 13391 return TemplateArgument( 13392 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()), 13393 /*Unqualified=*/true); 13394 case TemplateArgument::ArgKind::Expression: 13395 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType())) 13396 return TemplateArgument(); 13397 // FIXME: Try to keep the common sugar. 13398 return X; 13399 case TemplateArgument::ArgKind::Template: { 13400 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate(); 13401 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY); 13402 if (!CTN.getAsVoidPointer()) 13403 return TemplateArgument(); 13404 return TemplateArgument(CTN); 13405 } 13406 case TemplateArgument::ArgKind::TemplateExpansion: { 13407 TemplateName TX = X.getAsTemplateOrTemplatePattern(), 13408 TY = Y.getAsTemplateOrTemplatePattern(); 13409 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY); 13410 if (!CTN.getAsVoidPointer()) 13411 return TemplateName(); 13412 auto NExpX = X.getNumTemplateExpansions(); 13413 assert(NExpX == Y.getNumTemplateExpansions()); 13414 return TemplateArgument(CTN, NExpX); 13415 } 13416 default: 13417 // FIXME: Handle the other argument kinds. 13418 return X; 13419 } 13420 } 13421 13422 static bool getCommonTemplateArguments(ASTContext &Ctx, 13423 SmallVectorImpl<TemplateArgument> &R, 13424 ArrayRef<TemplateArgument> Xs, 13425 ArrayRef<TemplateArgument> Ys) { 13426 if (Xs.size() != Ys.size()) 13427 return true; 13428 R.resize(Xs.size()); 13429 for (size_t I = 0; I < R.size(); ++I) { 13430 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]); 13431 if (R[I].isNull()) 13432 return true; 13433 } 13434 return false; 13435 } 13436 13437 static auto getCommonTemplateArguments(ASTContext &Ctx, 13438 ArrayRef<TemplateArgument> Xs, 13439 ArrayRef<TemplateArgument> Ys) { 13440 SmallVector<TemplateArgument, 8> R; 13441 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys); 13442 assert(!Different); 13443 (void)Different; 13444 return R; 13445 } 13446 13447 template <class T> 13448 static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y) { 13449 return X->getKeyword() == Y->getKeyword() ? X->getKeyword() 13450 : ElaboratedTypeKeyword::None; 13451 } 13452 13453 template <class T> 13454 static NestedNameSpecifier *getCommonNNS(ASTContext &Ctx, const T *X, 13455 const T *Y) { 13456 // FIXME: Try to keep the common NNS sugar. 13457 return X->getQualifier() == Y->getQualifier() 13458 ? X->getQualifier() 13459 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier()); 13460 } 13461 13462 template <class T> 13463 static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) { 13464 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType()); 13465 } 13466 13467 template <class T> 13468 static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, 13469 Qualifiers &QX, const T *Y, 13470 Qualifiers &QY) { 13471 QualType EX = X->getElementType(), EY = Y->getElementType(); 13472 QualType R = Ctx.getCommonSugaredType(EX, EY, 13473 /*Unqualified=*/true); 13474 Qualifiers RQ = R.getQualifiers(); 13475 QX += EX.getQualifiers() - RQ; 13476 QY += EY.getQualifiers() - RQ; 13477 return R; 13478 } 13479 13480 template <class T> 13481 static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) { 13482 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType()); 13483 } 13484 13485 template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) { 13486 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr())); 13487 return X->getSizeExpr(); 13488 } 13489 13490 static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) { 13491 assert(X->getSizeModifier() == Y->getSizeModifier()); 13492 return X->getSizeModifier(); 13493 } 13494 13495 static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, 13496 const ArrayType *Y) { 13497 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers()); 13498 return X->getIndexTypeCVRQualifiers(); 13499 } 13500 13501 // Merges two type lists such that the resulting vector will contain 13502 // each type (in a canonical sense) only once, in the order they appear 13503 // from X to Y. If they occur in both X and Y, the result will contain 13504 // the common sugared type between them. 13505 static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl<QualType> &Out, 13506 ArrayRef<QualType> X, ArrayRef<QualType> Y) { 13507 llvm::DenseMap<QualType, unsigned> Found; 13508 for (auto Ts : {X, Y}) { 13509 for (QualType T : Ts) { 13510 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size()); 13511 if (!Res.second) { 13512 QualType &U = Out[Res.first->second]; 13513 U = Ctx.getCommonSugaredType(U, T); 13514 } else { 13515 Out.emplace_back(T); 13516 } 13517 } 13518 } 13519 } 13520 13521 FunctionProtoType::ExceptionSpecInfo 13522 ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, 13523 FunctionProtoType::ExceptionSpecInfo ESI2, 13524 SmallVectorImpl<QualType> &ExceptionTypeStorage, 13525 bool AcceptDependent) { 13526 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type; 13527 13528 // If either of them can throw anything, that is the result. 13529 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) { 13530 if (EST1 == I) 13531 return ESI1; 13532 if (EST2 == I) 13533 return ESI2; 13534 } 13535 13536 // If either of them is non-throwing, the result is the other. 13537 for (auto I : 13538 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) { 13539 if (EST1 == I) 13540 return ESI2; 13541 if (EST2 == I) 13542 return ESI1; 13543 } 13544 13545 // If we're left with value-dependent computed noexcept expressions, we're 13546 // stuck. Before C++17, we can just drop the exception specification entirely, 13547 // since it's not actually part of the canonical type. And this should never 13548 // happen in C++17, because it would mean we were computing the composite 13549 // pointer type of dependent types, which should never happen. 13550 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 13551 assert(AcceptDependent && 13552 "computing composite pointer type of dependent types"); 13553 return FunctionProtoType::ExceptionSpecInfo(); 13554 } 13555 13556 // Switch over the possibilities so that people adding new values know to 13557 // update this function. 13558 switch (EST1) { 13559 case EST_None: 13560 case EST_DynamicNone: 13561 case EST_MSAny: 13562 case EST_BasicNoexcept: 13563 case EST_DependentNoexcept: 13564 case EST_NoexceptFalse: 13565 case EST_NoexceptTrue: 13566 case EST_NoThrow: 13567 llvm_unreachable("These ESTs should be handled above"); 13568 13569 case EST_Dynamic: { 13570 // This is the fun case: both exception specifications are dynamic. Form 13571 // the union of the two lists. 13572 assert(EST2 == EST_Dynamic && "other cases should already be handled"); 13573 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions, 13574 ESI2.Exceptions); 13575 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 13576 Result.Exceptions = ExceptionTypeStorage; 13577 return Result; 13578 } 13579 13580 case EST_Unevaluated: 13581 case EST_Uninstantiated: 13582 case EST_Unparsed: 13583 llvm_unreachable("shouldn't see unresolved exception specifications here"); 13584 } 13585 13586 llvm_unreachable("invalid ExceptionSpecificationType"); 13587 } 13588 13589 static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, 13590 Qualifiers &QX, const Type *Y, 13591 Qualifiers &QY) { 13592 Type::TypeClass TC = X->getTypeClass(); 13593 assert(TC == Y->getTypeClass()); 13594 switch (TC) { 13595 #define UNEXPECTED_TYPE(Class, Kind) \ 13596 case Type::Class: \ 13597 llvm_unreachable("Unexpected " Kind ": " #Class); 13598 13599 #define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical") 13600 #define TYPE(Class, Base) 13601 #include "clang/AST/TypeNodes.inc" 13602 13603 #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free") 13604 SUGAR_FREE_TYPE(Builtin) 13605 SUGAR_FREE_TYPE(DeducedTemplateSpecialization) 13606 SUGAR_FREE_TYPE(DependentBitInt) 13607 SUGAR_FREE_TYPE(Enum) 13608 SUGAR_FREE_TYPE(BitInt) 13609 SUGAR_FREE_TYPE(ObjCInterface) 13610 SUGAR_FREE_TYPE(Record) 13611 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack) 13612 SUGAR_FREE_TYPE(UnresolvedUsing) 13613 SUGAR_FREE_TYPE(HLSLAttributedResource) 13614 #undef SUGAR_FREE_TYPE 13615 #define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique") 13616 NON_UNIQUE_TYPE(TypeOfExpr) 13617 NON_UNIQUE_TYPE(VariableArray) 13618 #undef NON_UNIQUE_TYPE 13619 13620 UNEXPECTED_TYPE(TypeOf, "sugar") 13621 13622 #undef UNEXPECTED_TYPE 13623 13624 case Type::Auto: { 13625 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y); 13626 assert(AX->getDeducedType().isNull()); 13627 assert(AY->getDeducedType().isNull()); 13628 assert(AX->getKeyword() == AY->getKeyword()); 13629 assert(AX->isInstantiationDependentType() == 13630 AY->isInstantiationDependentType()); 13631 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(), 13632 AY->getTypeConstraintArguments()); 13633 return Ctx.getAutoType(QualType(), AX->getKeyword(), 13634 AX->isInstantiationDependentType(), 13635 AX->containsUnexpandedParameterPack(), 13636 getCommonDeclChecked(AX->getTypeConstraintConcept(), 13637 AY->getTypeConstraintConcept()), 13638 As); 13639 } 13640 case Type::IncompleteArray: { 13641 const auto *AX = cast<IncompleteArrayType>(X), 13642 *AY = cast<IncompleteArrayType>(Y); 13643 return Ctx.getIncompleteArrayType( 13644 getCommonArrayElementType(Ctx, AX, QX, AY, QY), 13645 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY)); 13646 } 13647 case Type::DependentSizedArray: { 13648 const auto *AX = cast<DependentSizedArrayType>(X), 13649 *AY = cast<DependentSizedArrayType>(Y); 13650 return Ctx.getDependentSizedArrayType( 13651 getCommonArrayElementType(Ctx, AX, QX, AY, QY), 13652 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY), 13653 getCommonIndexTypeCVRQualifiers(AX, AY), 13654 AX->getBracketsRange() == AY->getBracketsRange() 13655 ? AX->getBracketsRange() 13656 : SourceRange()); 13657 } 13658 case Type::ConstantArray: { 13659 const auto *AX = cast<ConstantArrayType>(X), 13660 *AY = cast<ConstantArrayType>(Y); 13661 assert(AX->getSize() == AY->getSize()); 13662 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr()) 13663 ? AX->getSizeExpr() 13664 : nullptr; 13665 return Ctx.getConstantArrayType( 13666 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr, 13667 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY)); 13668 } 13669 case Type::ArrayParameter: { 13670 const auto *AX = cast<ArrayParameterType>(X), 13671 *AY = cast<ArrayParameterType>(Y); 13672 assert(AX->getSize() == AY->getSize()); 13673 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr()) 13674 ? AX->getSizeExpr() 13675 : nullptr; 13676 auto ArrayTy = Ctx.getConstantArrayType( 13677 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr, 13678 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY)); 13679 return Ctx.getArrayParameterType(ArrayTy); 13680 } 13681 case Type::Atomic: { 13682 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y); 13683 return Ctx.getAtomicType( 13684 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType())); 13685 } 13686 case Type::Complex: { 13687 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y); 13688 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY)); 13689 } 13690 case Type::Pointer: { 13691 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y); 13692 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY)); 13693 } 13694 case Type::BlockPointer: { 13695 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y); 13696 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY)); 13697 } 13698 case Type::ObjCObjectPointer: { 13699 const auto *PX = cast<ObjCObjectPointerType>(X), 13700 *PY = cast<ObjCObjectPointerType>(Y); 13701 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY)); 13702 } 13703 case Type::MemberPointer: { 13704 const auto *PX = cast<MemberPointerType>(X), 13705 *PY = cast<MemberPointerType>(Y); 13706 return Ctx.getMemberPointerType( 13707 getCommonPointeeType(Ctx, PX, PY), 13708 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0), 13709 QualType(PY->getClass(), 0)) 13710 .getTypePtr()); 13711 } 13712 case Type::LValueReference: { 13713 const auto *PX = cast<LValueReferenceType>(X), 13714 *PY = cast<LValueReferenceType>(Y); 13715 // FIXME: Preserve PointeeTypeAsWritten. 13716 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY), 13717 PX->isSpelledAsLValue() || 13718 PY->isSpelledAsLValue()); 13719 } 13720 case Type::RValueReference: { 13721 const auto *PX = cast<RValueReferenceType>(X), 13722 *PY = cast<RValueReferenceType>(Y); 13723 // FIXME: Preserve PointeeTypeAsWritten. 13724 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY)); 13725 } 13726 case Type::DependentAddressSpace: { 13727 const auto *PX = cast<DependentAddressSpaceType>(X), 13728 *PY = cast<DependentAddressSpaceType>(Y); 13729 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr())); 13730 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY), 13731 PX->getAddrSpaceExpr(), 13732 getCommonAttrLoc(PX, PY)); 13733 } 13734 case Type::FunctionNoProto: { 13735 const auto *FX = cast<FunctionNoProtoType>(X), 13736 *FY = cast<FunctionNoProtoType>(Y); 13737 assert(FX->getExtInfo() == FY->getExtInfo()); 13738 return Ctx.getFunctionNoProtoType( 13739 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()), 13740 FX->getExtInfo()); 13741 } 13742 case Type::FunctionProto: { 13743 const auto *FX = cast<FunctionProtoType>(X), 13744 *FY = cast<FunctionProtoType>(Y); 13745 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(), 13746 EPIY = FY->getExtProtoInfo(); 13747 assert(EPIX.ExtInfo == EPIY.ExtInfo); 13748 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos); 13749 assert(EPIX.RefQualifier == EPIY.RefQualifier); 13750 assert(EPIX.TypeQuals == EPIY.TypeQuals); 13751 assert(EPIX.Variadic == EPIY.Variadic); 13752 13753 // FIXME: Can we handle an empty EllipsisLoc? 13754 // Use emtpy EllipsisLoc if X and Y differ. 13755 13756 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn; 13757 13758 QualType R = 13759 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()); 13760 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(), 13761 /*Unqualified=*/true); 13762 13763 SmallVector<QualType, 8> Exceptions; 13764 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs( 13765 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true); 13766 return Ctx.getFunctionType(R, P, EPIX); 13767 } 13768 case Type::ObjCObject: { 13769 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y); 13770 assert( 13771 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(), 13772 OY->getProtocols().begin(), OY->getProtocols().end(), 13773 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) { 13774 return P0->getCanonicalDecl() == P1->getCanonicalDecl(); 13775 }) && 13776 "protocol lists must be the same"); 13777 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(), 13778 OY->getTypeArgsAsWritten()); 13779 return Ctx.getObjCObjectType( 13780 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs, 13781 OX->getProtocols(), 13782 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten()); 13783 } 13784 case Type::ConstantMatrix: { 13785 const auto *MX = cast<ConstantMatrixType>(X), 13786 *MY = cast<ConstantMatrixType>(Y); 13787 assert(MX->getNumRows() == MY->getNumRows()); 13788 assert(MX->getNumColumns() == MY->getNumColumns()); 13789 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY), 13790 MX->getNumRows(), MX->getNumColumns()); 13791 } 13792 case Type::DependentSizedMatrix: { 13793 const auto *MX = cast<DependentSizedMatrixType>(X), 13794 *MY = cast<DependentSizedMatrixType>(Y); 13795 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr())); 13796 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr())); 13797 return Ctx.getDependentSizedMatrixType( 13798 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(), 13799 MX->getColumnExpr(), getCommonAttrLoc(MX, MY)); 13800 } 13801 case Type::Vector: { 13802 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y); 13803 assert(VX->getNumElements() == VY->getNumElements()); 13804 assert(VX->getVectorKind() == VY->getVectorKind()); 13805 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY), 13806 VX->getNumElements(), VX->getVectorKind()); 13807 } 13808 case Type::ExtVector: { 13809 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y); 13810 assert(VX->getNumElements() == VY->getNumElements()); 13811 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY), 13812 VX->getNumElements()); 13813 } 13814 case Type::DependentSizedExtVector: { 13815 const auto *VX = cast<DependentSizedExtVectorType>(X), 13816 *VY = cast<DependentSizedExtVectorType>(Y); 13817 return Ctx.getDependentSizedExtVectorType(getCommonElementType(Ctx, VX, VY), 13818 getCommonSizeExpr(Ctx, VX, VY), 13819 getCommonAttrLoc(VX, VY)); 13820 } 13821 case Type::DependentVector: { 13822 const auto *VX = cast<DependentVectorType>(X), 13823 *VY = cast<DependentVectorType>(Y); 13824 assert(VX->getVectorKind() == VY->getVectorKind()); 13825 return Ctx.getDependentVectorType( 13826 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY), 13827 getCommonAttrLoc(VX, VY), VX->getVectorKind()); 13828 } 13829 case Type::InjectedClassName: { 13830 const auto *IX = cast<InjectedClassNameType>(X), 13831 *IY = cast<InjectedClassNameType>(Y); 13832 return Ctx.getInjectedClassNameType( 13833 getCommonDeclChecked(IX->getDecl(), IY->getDecl()), 13834 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(), 13835 IY->getInjectedSpecializationType())); 13836 } 13837 case Type::TemplateSpecialization: { 13838 const auto *TX = cast<TemplateSpecializationType>(X), 13839 *TY = cast<TemplateSpecializationType>(Y); 13840 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(), 13841 TY->template_arguments()); 13842 return Ctx.getTemplateSpecializationType( 13843 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(), 13844 TY->getTemplateName(), 13845 /*IgnoreDeduced=*/true), 13846 As, X->getCanonicalTypeInternal()); 13847 } 13848 case Type::Decltype: { 13849 const auto *DX = cast<DecltypeType>(X); 13850 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y); 13851 assert(DX->isDependentType()); 13852 assert(DY->isDependentType()); 13853 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr())); 13854 // As Decltype is not uniqued, building a common type would be wasteful. 13855 return QualType(DX, 0); 13856 } 13857 case Type::PackIndexing: { 13858 const auto *DX = cast<PackIndexingType>(X); 13859 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y); 13860 assert(DX->isDependentType()); 13861 assert(DY->isDependentType()); 13862 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr())); 13863 return QualType(DX, 0); 13864 } 13865 case Type::DependentName: { 13866 const auto *NX = cast<DependentNameType>(X), 13867 *NY = cast<DependentNameType>(Y); 13868 assert(NX->getIdentifier() == NY->getIdentifier()); 13869 return Ctx.getDependentNameType( 13870 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY), 13871 NX->getIdentifier(), NX->getCanonicalTypeInternal()); 13872 } 13873 case Type::DependentTemplateSpecialization: { 13874 const auto *TX = cast<DependentTemplateSpecializationType>(X), 13875 *TY = cast<DependentTemplateSpecializationType>(Y); 13876 assert(TX->getIdentifier() == TY->getIdentifier()); 13877 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(), 13878 TY->template_arguments()); 13879 return Ctx.getDependentTemplateSpecializationType( 13880 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY), 13881 TX->getIdentifier(), As); 13882 } 13883 case Type::UnaryTransform: { 13884 const auto *TX = cast<UnaryTransformType>(X), 13885 *TY = cast<UnaryTransformType>(Y); 13886 assert(TX->getUTTKind() == TY->getUTTKind()); 13887 return Ctx.getUnaryTransformType( 13888 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()), 13889 Ctx.getCommonSugaredType(TX->getUnderlyingType(), 13890 TY->getUnderlyingType()), 13891 TX->getUTTKind()); 13892 } 13893 case Type::PackExpansion: { 13894 const auto *PX = cast<PackExpansionType>(X), 13895 *PY = cast<PackExpansionType>(Y); 13896 assert(PX->getNumExpansions() == PY->getNumExpansions()); 13897 return Ctx.getPackExpansionType( 13898 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()), 13899 PX->getNumExpansions(), false); 13900 } 13901 case Type::Pipe: { 13902 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y); 13903 assert(PX->isReadOnly() == PY->isReadOnly()); 13904 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType 13905 : &ASTContext::getWritePipeType; 13906 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY)); 13907 } 13908 case Type::TemplateTypeParm: { 13909 const auto *TX = cast<TemplateTypeParmType>(X), 13910 *TY = cast<TemplateTypeParmType>(Y); 13911 assert(TX->getDepth() == TY->getDepth()); 13912 assert(TX->getIndex() == TY->getIndex()); 13913 assert(TX->isParameterPack() == TY->isParameterPack()); 13914 return Ctx.getTemplateTypeParmType( 13915 TX->getDepth(), TX->getIndex(), TX->isParameterPack(), 13916 getCommonDecl(TX->getDecl(), TY->getDecl())); 13917 } 13918 } 13919 llvm_unreachable("Unknown Type Class"); 13920 } 13921 13922 static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, 13923 const Type *Y, 13924 SplitQualType Underlying) { 13925 Type::TypeClass TC = X->getTypeClass(); 13926 if (TC != Y->getTypeClass()) 13927 return QualType(); 13928 switch (TC) { 13929 #define UNEXPECTED_TYPE(Class, Kind) \ 13930 case Type::Class: \ 13931 llvm_unreachable("Unexpected " Kind ": " #Class); 13932 #define TYPE(Class, Base) 13933 #define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent") 13934 #include "clang/AST/TypeNodes.inc" 13935 13936 #define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical") 13937 CANONICAL_TYPE(Atomic) 13938 CANONICAL_TYPE(BitInt) 13939 CANONICAL_TYPE(BlockPointer) 13940 CANONICAL_TYPE(Builtin) 13941 CANONICAL_TYPE(Complex) 13942 CANONICAL_TYPE(ConstantArray) 13943 CANONICAL_TYPE(ArrayParameter) 13944 CANONICAL_TYPE(ConstantMatrix) 13945 CANONICAL_TYPE(Enum) 13946 CANONICAL_TYPE(ExtVector) 13947 CANONICAL_TYPE(FunctionNoProto) 13948 CANONICAL_TYPE(FunctionProto) 13949 CANONICAL_TYPE(IncompleteArray) 13950 CANONICAL_TYPE(HLSLAttributedResource) 13951 CANONICAL_TYPE(LValueReference) 13952 CANONICAL_TYPE(MemberPointer) 13953 CANONICAL_TYPE(ObjCInterface) 13954 CANONICAL_TYPE(ObjCObject) 13955 CANONICAL_TYPE(ObjCObjectPointer) 13956 CANONICAL_TYPE(Pipe) 13957 CANONICAL_TYPE(Pointer) 13958 CANONICAL_TYPE(Record) 13959 CANONICAL_TYPE(RValueReference) 13960 CANONICAL_TYPE(VariableArray) 13961 CANONICAL_TYPE(Vector) 13962 #undef CANONICAL_TYPE 13963 13964 #undef UNEXPECTED_TYPE 13965 13966 case Type::Adjusted: { 13967 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y); 13968 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType(); 13969 if (!Ctx.hasSameType(OX, OY)) 13970 return QualType(); 13971 // FIXME: It's inefficient to have to unify the original types. 13972 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY), 13973 Ctx.getQualifiedType(Underlying)); 13974 } 13975 case Type::Decayed: { 13976 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y); 13977 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType(); 13978 if (!Ctx.hasSameType(OX, OY)) 13979 return QualType(); 13980 // FIXME: It's inefficient to have to unify the original types. 13981 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY), 13982 Ctx.getQualifiedType(Underlying)); 13983 } 13984 case Type::Attributed: { 13985 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y); 13986 AttributedType::Kind Kind = AX->getAttrKind(); 13987 if (Kind != AY->getAttrKind()) 13988 return QualType(); 13989 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType(); 13990 if (!Ctx.hasSameType(MX, MY)) 13991 return QualType(); 13992 // FIXME: It's inefficient to have to unify the modified types. 13993 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY), 13994 Ctx.getQualifiedType(Underlying), 13995 AX->getAttr()); 13996 } 13997 case Type::BTFTagAttributed: { 13998 const auto *BX = cast<BTFTagAttributedType>(X); 13999 const BTFTypeTagAttr *AX = BX->getAttr(); 14000 // The attribute is not uniqued, so just compare the tag. 14001 if (AX->getBTFTypeTag() != 14002 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag()) 14003 return QualType(); 14004 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying)); 14005 } 14006 case Type::Auto: { 14007 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y); 14008 14009 AutoTypeKeyword KW = AX->getKeyword(); 14010 if (KW != AY->getKeyword()) 14011 return QualType(); 14012 14013 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(), 14014 AY->getTypeConstraintConcept()); 14015 SmallVector<TemplateArgument, 8> As; 14016 if (CD && 14017 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(), 14018 AY->getTypeConstraintArguments())) { 14019 CD = nullptr; // The arguments differ, so make it unconstrained. 14020 As.clear(); 14021 } 14022 14023 // Both auto types can't be dependent, otherwise they wouldn't have been 14024 // sugar. This implies they can't contain unexpanded packs either. 14025 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(), 14026 /*IsDependent=*/false, /*IsPack=*/false, CD, As); 14027 } 14028 case Type::PackIndexing: 14029 case Type::Decltype: 14030 return QualType(); 14031 case Type::DeducedTemplateSpecialization: 14032 // FIXME: Try to merge these. 14033 return QualType(); 14034 14035 case Type::Elaborated: { 14036 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y); 14037 return Ctx.getElaboratedType( 14038 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY), 14039 Ctx.getQualifiedType(Underlying), 14040 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl())); 14041 } 14042 case Type::MacroQualified: { 14043 const auto *MX = cast<MacroQualifiedType>(X), 14044 *MY = cast<MacroQualifiedType>(Y); 14045 const IdentifierInfo *IX = MX->getMacroIdentifier(); 14046 if (IX != MY->getMacroIdentifier()) 14047 return QualType(); 14048 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX); 14049 } 14050 case Type::SubstTemplateTypeParm: { 14051 const auto *SX = cast<SubstTemplateTypeParmType>(X), 14052 *SY = cast<SubstTemplateTypeParmType>(Y); 14053 Decl *CD = 14054 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl()); 14055 if (!CD) 14056 return QualType(); 14057 unsigned Index = SX->getIndex(); 14058 if (Index != SY->getIndex()) 14059 return QualType(); 14060 auto PackIndex = SX->getPackIndex(); 14061 if (PackIndex != SY->getPackIndex()) 14062 return QualType(); 14063 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying), 14064 CD, Index, PackIndex); 14065 } 14066 case Type::ObjCTypeParam: 14067 // FIXME: Try to merge these. 14068 return QualType(); 14069 case Type::Paren: 14070 return Ctx.getParenType(Ctx.getQualifiedType(Underlying)); 14071 14072 case Type::TemplateSpecialization: { 14073 const auto *TX = cast<TemplateSpecializationType>(X), 14074 *TY = cast<TemplateSpecializationType>(Y); 14075 TemplateName CTN = 14076 ::getCommonTemplateName(Ctx, TX->getTemplateName(), 14077 TY->getTemplateName(), /*IgnoreDeduced=*/true); 14078 if (!CTN.getAsVoidPointer()) 14079 return QualType(); 14080 SmallVector<TemplateArgument, 8> Args; 14081 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(), 14082 TY->template_arguments())) 14083 return QualType(); 14084 return Ctx.getTemplateSpecializationType(CTN, Args, 14085 Ctx.getQualifiedType(Underlying)); 14086 } 14087 case Type::Typedef: { 14088 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y); 14089 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl()); 14090 if (!CD) 14091 return QualType(); 14092 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying)); 14093 } 14094 case Type::TypeOf: { 14095 // The common sugar between two typeof expressions, where one is 14096 // potentially a typeof_unqual and the other is not, we unify to the 14097 // qualified type as that retains the most information along with the type. 14098 // We only return a typeof_unqual type when both types are unqual types. 14099 TypeOfKind Kind = TypeOfKind::Qualified; 14100 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() && 14101 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified) 14102 Kind = TypeOfKind::Unqualified; 14103 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind); 14104 } 14105 case Type::TypeOfExpr: 14106 return QualType(); 14107 14108 case Type::UnaryTransform: { 14109 const auto *UX = cast<UnaryTransformType>(X), 14110 *UY = cast<UnaryTransformType>(Y); 14111 UnaryTransformType::UTTKind KX = UX->getUTTKind(); 14112 if (KX != UY->getUTTKind()) 14113 return QualType(); 14114 QualType BX = UX->getBaseType(), BY = UY->getBaseType(); 14115 if (!Ctx.hasSameType(BX, BY)) 14116 return QualType(); 14117 // FIXME: It's inefficient to have to unify the base types. 14118 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY), 14119 Ctx.getQualifiedType(Underlying), KX); 14120 } 14121 case Type::Using: { 14122 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y); 14123 const UsingShadowDecl *CD = 14124 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl()); 14125 if (!CD) 14126 return QualType(); 14127 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying)); 14128 } 14129 case Type::CountAttributed: { 14130 const auto *DX = cast<CountAttributedType>(X), 14131 *DY = cast<CountAttributedType>(Y); 14132 if (DX->isCountInBytes() != DY->isCountInBytes()) 14133 return QualType(); 14134 if (DX->isOrNull() != DY->isOrNull()) 14135 return QualType(); 14136 Expr *CEX = DX->getCountExpr(); 14137 Expr *CEY = DY->getCountExpr(); 14138 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls(); 14139 if (Ctx.hasSameExpr(CEX, CEY)) 14140 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX, 14141 DX->isCountInBytes(), DX->isOrNull(), 14142 CDX); 14143 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx)) 14144 return QualType(); 14145 // Two declarations with the same integer constant may still differ in their 14146 // expression pointers, so we need to evaluate them. 14147 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx); 14148 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx); 14149 if (VX != VY) 14150 return QualType(); 14151 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX, 14152 DX->isCountInBytes(), DX->isOrNull(), 14153 CDX); 14154 } 14155 } 14156 llvm_unreachable("Unhandled Type Class"); 14157 } 14158 14159 static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) { 14160 SmallVector<SplitQualType, 8> R; 14161 while (true) { 14162 QTotal.addConsistentQualifiers(T.Quals); 14163 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType(); 14164 if (NT == QualType(T.Ty, 0)) 14165 break; 14166 R.push_back(T); 14167 T = NT.split(); 14168 } 14169 return R; 14170 } 14171 14172 QualType ASTContext::getCommonSugaredType(QualType X, QualType Y, 14173 bool Unqualified) { 14174 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y)); 14175 if (X == Y) 14176 return X; 14177 if (!Unqualified) { 14178 if (X.isCanonical()) 14179 return X; 14180 if (Y.isCanonical()) 14181 return Y; 14182 } 14183 14184 SplitQualType SX = X.split(), SY = Y.split(); 14185 Qualifiers QX, QY; 14186 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys, 14187 // until we reach their underlying "canonical nodes". Note these are not 14188 // necessarily canonical types, as they may still have sugared properties. 14189 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively. 14190 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY); 14191 if (SX.Ty != SY.Ty) { 14192 // The canonical nodes differ. Build a common canonical node out of the two, 14193 // unifying their sugar. This may recurse back here. 14194 SX.Ty = 14195 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr(); 14196 } else { 14197 // The canonical nodes were identical: We may have desugared too much. 14198 // Add any common sugar back in. 14199 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) { 14200 QX -= SX.Quals; 14201 QY -= SY.Quals; 14202 SX = Xs.pop_back_val(); 14203 SY = Ys.pop_back_val(); 14204 } 14205 } 14206 if (Unqualified) 14207 QX = Qualifiers::removeCommonQualifiers(QX, QY); 14208 else 14209 assert(QX == QY); 14210 14211 // Even though the remaining sugar nodes in Xs and Ys differ, some may be 14212 // related. Walk up these nodes, unifying them and adding the result. 14213 while (!Xs.empty() && !Ys.empty()) { 14214 auto Underlying = SplitQualType( 14215 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals)); 14216 SX = Xs.pop_back_val(); 14217 SY = Ys.pop_back_val(); 14218 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying) 14219 .getTypePtrOrNull(); 14220 // Stop at the first pair which is unrelated. 14221 if (!SX.Ty) { 14222 SX.Ty = Underlying.Ty; 14223 break; 14224 } 14225 QX -= Underlying.Quals; 14226 }; 14227 14228 // Add back the missing accumulated qualifiers, which were stripped off 14229 // with the sugar nodes we could not unify. 14230 QualType R = getQualifiedType(SX.Ty, QX); 14231 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X)); 14232 return R; 14233 } 14234 14235 QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const { 14236 assert(Ty->isFixedPointType()); 14237 14238 if (Ty->isUnsaturatedFixedPointType()) 14239 return Ty; 14240 14241 switch (Ty->castAs<BuiltinType>()->getKind()) { 14242 default: 14243 llvm_unreachable("Not a saturated fixed point type!"); 14244 case BuiltinType::SatShortAccum: 14245 return ShortAccumTy; 14246 case BuiltinType::SatAccum: 14247 return AccumTy; 14248 case BuiltinType::SatLongAccum: 14249 return LongAccumTy; 14250 case BuiltinType::SatUShortAccum: 14251 return UnsignedShortAccumTy; 14252 case BuiltinType::SatUAccum: 14253 return UnsignedAccumTy; 14254 case BuiltinType::SatULongAccum: 14255 return UnsignedLongAccumTy; 14256 case BuiltinType::SatShortFract: 14257 return ShortFractTy; 14258 case BuiltinType::SatFract: 14259 return FractTy; 14260 case BuiltinType::SatLongFract: 14261 return LongFractTy; 14262 case BuiltinType::SatUShortFract: 14263 return UnsignedShortFractTy; 14264 case BuiltinType::SatUFract: 14265 return UnsignedFractTy; 14266 case BuiltinType::SatULongFract: 14267 return UnsignedLongFractTy; 14268 } 14269 } 14270 14271 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 14272 assert(Ty->isFixedPointType()); 14273 14274 if (Ty->isSaturatedFixedPointType()) return Ty; 14275 14276 switch (Ty->castAs<BuiltinType>()->getKind()) { 14277 default: 14278 llvm_unreachable("Not a fixed point type!"); 14279 case BuiltinType::ShortAccum: 14280 return SatShortAccumTy; 14281 case BuiltinType::Accum: 14282 return SatAccumTy; 14283 case BuiltinType::LongAccum: 14284 return SatLongAccumTy; 14285 case BuiltinType::UShortAccum: 14286 return SatUnsignedShortAccumTy; 14287 case BuiltinType::UAccum: 14288 return SatUnsignedAccumTy; 14289 case BuiltinType::ULongAccum: 14290 return SatUnsignedLongAccumTy; 14291 case BuiltinType::ShortFract: 14292 return SatShortFractTy; 14293 case BuiltinType::Fract: 14294 return SatFractTy; 14295 case BuiltinType::LongFract: 14296 return SatLongFractTy; 14297 case BuiltinType::UShortFract: 14298 return SatUnsignedShortFractTy; 14299 case BuiltinType::UFract: 14300 return SatUnsignedFractTy; 14301 case BuiltinType::ULongFract: 14302 return SatUnsignedLongFractTy; 14303 } 14304 } 14305 14306 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 14307 if (LangOpts.OpenCL) 14308 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 14309 14310 if (LangOpts.CUDA) 14311 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 14312 14313 return getLangASFromTargetAS(AS); 14314 } 14315 14316 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 14317 // doesn't include ASTContext.h 14318 template 14319 clang::LazyGenerationalUpdatePtr< 14320 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 14321 clang::LazyGenerationalUpdatePtr< 14322 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 14323 const clang::ASTContext &Ctx, Decl *Value); 14324 14325 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 14326 assert(Ty->isFixedPointType()); 14327 14328 const TargetInfo &Target = getTargetInfo(); 14329 switch (Ty->castAs<BuiltinType>()->getKind()) { 14330 default: 14331 llvm_unreachable("Not a fixed point type!"); 14332 case BuiltinType::ShortAccum: 14333 case BuiltinType::SatShortAccum: 14334 return Target.getShortAccumScale(); 14335 case BuiltinType::Accum: 14336 case BuiltinType::SatAccum: 14337 return Target.getAccumScale(); 14338 case BuiltinType::LongAccum: 14339 case BuiltinType::SatLongAccum: 14340 return Target.getLongAccumScale(); 14341 case BuiltinType::UShortAccum: 14342 case BuiltinType::SatUShortAccum: 14343 return Target.getUnsignedShortAccumScale(); 14344 case BuiltinType::UAccum: 14345 case BuiltinType::SatUAccum: 14346 return Target.getUnsignedAccumScale(); 14347 case BuiltinType::ULongAccum: 14348 case BuiltinType::SatULongAccum: 14349 return Target.getUnsignedLongAccumScale(); 14350 case BuiltinType::ShortFract: 14351 case BuiltinType::SatShortFract: 14352 return Target.getShortFractScale(); 14353 case BuiltinType::Fract: 14354 case BuiltinType::SatFract: 14355 return Target.getFractScale(); 14356 case BuiltinType::LongFract: 14357 case BuiltinType::SatLongFract: 14358 return Target.getLongFractScale(); 14359 case BuiltinType::UShortFract: 14360 case BuiltinType::SatUShortFract: 14361 return Target.getUnsignedShortFractScale(); 14362 case BuiltinType::UFract: 14363 case BuiltinType::SatUFract: 14364 return Target.getUnsignedFractScale(); 14365 case BuiltinType::ULongFract: 14366 case BuiltinType::SatULongFract: 14367 return Target.getUnsignedLongFractScale(); 14368 } 14369 } 14370 14371 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 14372 assert(Ty->isFixedPointType()); 14373 14374 const TargetInfo &Target = getTargetInfo(); 14375 switch (Ty->castAs<BuiltinType>()->getKind()) { 14376 default: 14377 llvm_unreachable("Not a fixed point type!"); 14378 case BuiltinType::ShortAccum: 14379 case BuiltinType::SatShortAccum: 14380 return Target.getShortAccumIBits(); 14381 case BuiltinType::Accum: 14382 case BuiltinType::SatAccum: 14383 return Target.getAccumIBits(); 14384 case BuiltinType::LongAccum: 14385 case BuiltinType::SatLongAccum: 14386 return Target.getLongAccumIBits(); 14387 case BuiltinType::UShortAccum: 14388 case BuiltinType::SatUShortAccum: 14389 return Target.getUnsignedShortAccumIBits(); 14390 case BuiltinType::UAccum: 14391 case BuiltinType::SatUAccum: 14392 return Target.getUnsignedAccumIBits(); 14393 case BuiltinType::ULongAccum: 14394 case BuiltinType::SatULongAccum: 14395 return Target.getUnsignedLongAccumIBits(); 14396 case BuiltinType::ShortFract: 14397 case BuiltinType::SatShortFract: 14398 case BuiltinType::Fract: 14399 case BuiltinType::SatFract: 14400 case BuiltinType::LongFract: 14401 case BuiltinType::SatLongFract: 14402 case BuiltinType::UShortFract: 14403 case BuiltinType::SatUShortFract: 14404 case BuiltinType::UFract: 14405 case BuiltinType::SatUFract: 14406 case BuiltinType::ULongFract: 14407 case BuiltinType::SatULongFract: 14408 return 0; 14409 } 14410 } 14411 14412 llvm::FixedPointSemantics 14413 ASTContext::getFixedPointSemantics(QualType Ty) const { 14414 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 14415 "Can only get the fixed point semantics for a " 14416 "fixed point or integer type."); 14417 if (Ty->isIntegerType()) 14418 return llvm::FixedPointSemantics::GetIntegerSemantics( 14419 getIntWidth(Ty), Ty->isSignedIntegerType()); 14420 14421 bool isSigned = Ty->isSignedFixedPointType(); 14422 return llvm::FixedPointSemantics( 14423 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 14424 Ty->isSaturatedFixedPointType(), 14425 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 14426 } 14427 14428 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 14429 assert(Ty->isFixedPointType()); 14430 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 14431 } 14432 14433 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 14434 assert(Ty->isFixedPointType()); 14435 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 14436 } 14437 14438 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 14439 assert(Ty->isUnsignedFixedPointType() && 14440 "Expected unsigned fixed point type"); 14441 14442 switch (Ty->castAs<BuiltinType>()->getKind()) { 14443 case BuiltinType::UShortAccum: 14444 return ShortAccumTy; 14445 case BuiltinType::UAccum: 14446 return AccumTy; 14447 case BuiltinType::ULongAccum: 14448 return LongAccumTy; 14449 case BuiltinType::SatUShortAccum: 14450 return SatShortAccumTy; 14451 case BuiltinType::SatUAccum: 14452 return SatAccumTy; 14453 case BuiltinType::SatULongAccum: 14454 return SatLongAccumTy; 14455 case BuiltinType::UShortFract: 14456 return ShortFractTy; 14457 case BuiltinType::UFract: 14458 return FractTy; 14459 case BuiltinType::ULongFract: 14460 return LongFractTy; 14461 case BuiltinType::SatUShortFract: 14462 return SatShortFractTy; 14463 case BuiltinType::SatUFract: 14464 return SatFractTy; 14465 case BuiltinType::SatULongFract: 14466 return SatLongFractTy; 14467 default: 14468 llvm_unreachable("Unexpected unsigned fixed point type"); 14469 } 14470 } 14471 14472 // Given a list of FMV features, return a concatenated list of the 14473 // corresponding backend features (which may contain duplicates). 14474 static std::vector<std::string> getFMVBackendFeaturesFor( 14475 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) { 14476 std::vector<std::string> BackendFeats; 14477 llvm::AArch64::ExtensionSet FeatureBits; 14478 for (StringRef F : FMVFeatStrings) 14479 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F)) 14480 if (FMVExt->ID) 14481 FeatureBits.enable(*FMVExt->ID); 14482 FeatureBits.toLLVMFeatureList(BackendFeats); 14483 return BackendFeats; 14484 } 14485 14486 ParsedTargetAttr 14487 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 14488 assert(TD != nullptr); 14489 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr()); 14490 14491 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 14492 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 14493 }); 14494 return ParsedAttr; 14495 } 14496 14497 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 14498 const FunctionDecl *FD) const { 14499 if (FD) 14500 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 14501 else 14502 Target->initFeatureMap(FeatureMap, getDiagnostics(), 14503 Target->getTargetOpts().CPU, 14504 Target->getTargetOpts().Features); 14505 } 14506 14507 // Fills in the supplied string map with the set of target features for the 14508 // passed in function. 14509 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 14510 GlobalDecl GD) const { 14511 StringRef TargetCPU = Target->getTargetOpts().CPU; 14512 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 14513 if (const auto *TD = FD->getAttr<TargetAttr>()) { 14514 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 14515 14516 // Make a copy of the features as passed on the command line into the 14517 // beginning of the additional features from the function to override. 14518 // AArch64 handles command line option features in parseTargetAttr(). 14519 if (!Target->getTriple().isAArch64()) 14520 ParsedAttr.Features.insert( 14521 ParsedAttr.Features.begin(), 14522 Target->getTargetOpts().FeaturesAsWritten.begin(), 14523 Target->getTargetOpts().FeaturesAsWritten.end()); 14524 14525 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU)) 14526 TargetCPU = ParsedAttr.CPU; 14527 14528 // Now populate the feature map, first with the TargetCPU which is either 14529 // the default or a new one from the target attribute string. Then we'll use 14530 // the passed in features (FeaturesAsWritten) along with the new ones from 14531 // the attribute. 14532 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 14533 ParsedAttr.Features); 14534 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 14535 llvm::SmallVector<StringRef, 32> FeaturesTmp; 14536 Target->getCPUSpecificCPUDispatchFeatures( 14537 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 14538 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 14539 Features.insert(Features.begin(), 14540 Target->getTargetOpts().FeaturesAsWritten.begin(), 14541 Target->getTargetOpts().FeaturesAsWritten.end()); 14542 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 14543 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 14544 if (Target->getTriple().isAArch64()) { 14545 llvm::SmallVector<StringRef, 8> Feats; 14546 TC->getFeatures(Feats, GD.getMultiVersionIndex()); 14547 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats); 14548 Features.insert(Features.begin(), 14549 Target->getTargetOpts().FeaturesAsWritten.begin(), 14550 Target->getTargetOpts().FeaturesAsWritten.end()); 14551 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 14552 } else if (Target->getTriple().isRISCV()) { 14553 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 14554 std::vector<std::string> Features; 14555 if (VersionStr != "default") { 14556 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr); 14557 Features.insert(Features.begin(), ParsedAttr.Features.begin(), 14558 ParsedAttr.Features.end()); 14559 } 14560 Features.insert(Features.begin(), 14561 Target->getTargetOpts().FeaturesAsWritten.begin(), 14562 Target->getTargetOpts().FeaturesAsWritten.end()); 14563 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 14564 } else { 14565 std::vector<std::string> Features; 14566 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 14567 if (VersionStr.starts_with("arch=")) 14568 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 14569 else if (VersionStr != "default") 14570 Features.push_back((StringRef{"+"} + VersionStr).str()); 14571 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 14572 } 14573 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) { 14574 std::vector<std::string> Features; 14575 if (Target->getTriple().isRISCV()) { 14576 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName()); 14577 Features.insert(Features.begin(), ParsedAttr.Features.begin(), 14578 ParsedAttr.Features.end()); 14579 } else { 14580 assert(Target->getTriple().isAArch64()); 14581 llvm::SmallVector<StringRef, 8> Feats; 14582 TV->getFeatures(Feats); 14583 Features = getFMVBackendFeaturesFor(Feats); 14584 } 14585 Features.insert(Features.begin(), 14586 Target->getTargetOpts().FeaturesAsWritten.begin(), 14587 Target->getTargetOpts().FeaturesAsWritten.end()); 14588 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 14589 } else { 14590 FeatureMap = Target->getTargetOpts().FeatureMap; 14591 } 14592 } 14593 14594 static SYCLKernelInfo BuildSYCLKernelInfo(CanQualType KernelNameType, 14595 const FunctionDecl *FD) { 14596 return {KernelNameType, FD}; 14597 } 14598 14599 void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) { 14600 // If the function declaration to register is invalid or dependent, the 14601 // registration attempt is ignored. 14602 if (FD->isInvalidDecl() || FD->isTemplated()) 14603 return; 14604 14605 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>(); 14606 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute"); 14607 14608 // Be tolerant of multiple registration attempts so long as each attempt 14609 // is for the same entity. Callers are obligated to detect and diagnose 14610 // conflicting kernel names prior to calling this function. 14611 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName()); 14612 auto IT = SYCLKernels.find(KernelNameType); 14613 assert((IT == SYCLKernels.end() || 14614 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) && 14615 "SYCL kernel name conflict"); 14616 (void)IT; 14617 SYCLKernels.insert( 14618 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD))); 14619 } 14620 14621 const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const { 14622 CanQualType KernelNameType = getCanonicalType(T); 14623 return SYCLKernels.at(KernelNameType); 14624 } 14625 14626 const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const { 14627 CanQualType KernelNameType = getCanonicalType(T); 14628 auto IT = SYCLKernels.find(KernelNameType); 14629 if (IT != SYCLKernels.end()) 14630 return &IT->second; 14631 return nullptr; 14632 } 14633 14634 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 14635 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 14636 return *OMPTraitInfoVector.back(); 14637 } 14638 14639 const StreamingDiagnostic &clang:: 14640 operator<<(const StreamingDiagnostic &DB, 14641 const ASTContext::SectionInfo &Section) { 14642 if (Section.Decl) 14643 return DB << Section.Decl; 14644 return DB << "a prior #pragma section"; 14645 } 14646 14647 bool ASTContext::mayExternalize(const Decl *D) const { 14648 bool IsInternalVar = 14649 isa<VarDecl>(D) && 14650 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal; 14651 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 14652 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 14653 (D->hasAttr<CUDAConstantAttr>() && 14654 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 14655 // CUDA/HIP: managed variables need to be externalized since it is 14656 // a declaration in IR, therefore cannot have internal linkage. Kernels in 14657 // anonymous name space needs to be externalized to avoid duplicate symbols. 14658 return (IsInternalVar && 14659 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) || 14660 (D->hasAttr<CUDAGlobalAttr>() && 14661 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) == 14662 GVA_Internal); 14663 } 14664 14665 bool ASTContext::shouldExternalize(const Decl *D) const { 14666 return mayExternalize(D) && 14667 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() || 14668 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 14669 } 14670 14671 StringRef ASTContext::getCUIDHash() const { 14672 if (!CUIDHash.empty()) 14673 return CUIDHash; 14674 if (LangOpts.CUID.empty()) 14675 return StringRef(); 14676 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 14677 return CUIDHash; 14678 } 14679 14680 const CXXRecordDecl * 14681 ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) { 14682 assert(ThisClass); 14683 assert(ThisClass->isPolymorphic()); 14684 const CXXRecordDecl *PrimaryBase = ThisClass; 14685 while (1) { 14686 assert(PrimaryBase); 14687 assert(PrimaryBase->isPolymorphic()); 14688 auto &Layout = getASTRecordLayout(PrimaryBase); 14689 auto Base = Layout.getPrimaryBase(); 14690 if (!Base || Base == PrimaryBase || !Base->isPolymorphic()) 14691 break; 14692 PrimaryBase = Base; 14693 } 14694 return PrimaryBase; 14695 } 14696 14697 bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, 14698 StringRef MangledName) { 14699 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl()); 14700 assert(Method->isVirtual()); 14701 bool DefaultIncludesPointerAuth = 14702 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics; 14703 14704 if (!DefaultIncludesPointerAuth) 14705 return true; 14706 14707 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl); 14708 if (Existing != ThunksToBeAbbreviated.end()) 14709 return Existing->second.contains(MangledName.str()); 14710 14711 std::unique_ptr<MangleContext> Mangler(createMangleContext()); 14712 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks; 14713 auto VtableContext = getVTableContext(); 14714 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) { 14715 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method); 14716 for (const auto &Thunk : *ThunkInfos) { 14717 SmallString<256> ElidedName; 14718 llvm::raw_svector_ostream ElidedNameStream(ElidedName); 14719 if (Destructor) 14720 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(), 14721 Thunk, /* elideOverrideInfo */ true, 14722 ElidedNameStream); 14723 else 14724 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true, 14725 ElidedNameStream); 14726 SmallString<256> MangledName; 14727 llvm::raw_svector_ostream mangledNameStream(MangledName); 14728 if (Destructor) 14729 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(), 14730 Thunk, /* elideOverrideInfo */ false, 14731 mangledNameStream); 14732 else 14733 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false, 14734 mangledNameStream); 14735 14736 Thunks[ElidedName].push_back(std::string(MangledName)); 14737 } 14738 } 14739 llvm::StringSet<> SimplifiedThunkNames; 14740 for (auto &ThunkList : Thunks) { 14741 llvm::sort(ThunkList.second); 14742 SimplifiedThunkNames.insert(ThunkList.second[0]); 14743 } 14744 bool Result = SimplifiedThunkNames.contains(MangledName); 14745 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames); 14746 return Result; 14747 } 14748