1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the ASTContext interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "CXXABI.h" 15 #include "Interp/Context.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTConcept.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTTypeTraits.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/AttrIterator.h" 22 #include "clang/AST/CharUnits.h" 23 #include "clang/AST/Comment.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclBase.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclContextInternals.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/DeclarationName.h" 32 #include "clang/AST/DependenceFlags.h" 33 #include "clang/AST/Expr.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprConcepts.h" 36 #include "clang/AST/ExternalASTSource.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/MangleNumberingContext.h" 39 #include "clang/AST/NestedNameSpecifier.h" 40 #include "clang/AST/ParentMapContext.h" 41 #include "clang/AST/RawCommentList.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/Stmt.h" 44 #include "clang/AST/TemplateBase.h" 45 #include "clang/AST/TemplateName.h" 46 #include "clang/AST/Type.h" 47 #include "clang/AST/TypeLoc.h" 48 #include "clang/AST/UnresolvedSet.h" 49 #include "clang/AST/VTableBuilder.h" 50 #include "clang/Basic/AddressSpaces.h" 51 #include "clang/Basic/Builtins.h" 52 #include "clang/Basic/CommentOptions.h" 53 #include "clang/Basic/ExceptionSpecificationType.h" 54 #include "clang/Basic/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Linkage.h" 58 #include "clang/Basic/Module.h" 59 #include "clang/Basic/NoSanitizeList.h" 60 #include "clang/Basic/ObjCRuntime.h" 61 #include "clang/Basic/SourceLocation.h" 62 #include "clang/Basic/SourceManager.h" 63 #include "clang/Basic/Specifiers.h" 64 #include "clang/Basic/TargetCXXABI.h" 65 #include "clang/Basic/TargetInfo.h" 66 #include "clang/Basic/XRayLists.h" 67 #include "llvm/ADT/APFixedPoint.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/ArrayRef.h" 71 #include "llvm/ADT/DenseMap.h" 72 #include "llvm/ADT/DenseSet.h" 73 #include "llvm/ADT/FoldingSet.h" 74 #include "llvm/ADT/None.h" 75 #include "llvm/ADT/Optional.h" 76 #include "llvm/ADT/PointerUnion.h" 77 #include "llvm/ADT/STLExtras.h" 78 #include "llvm/ADT/SmallPtrSet.h" 79 #include "llvm/ADT/SmallVector.h" 80 #include "llvm/ADT/StringExtras.h" 81 #include "llvm/ADT/StringRef.h" 82 #include "llvm/ADT/Triple.h" 83 #include "llvm/Support/Capacity.h" 84 #include "llvm/Support/Casting.h" 85 #include "llvm/Support/Compiler.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/MD5.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 103 enum FloatingRank { 104 BFloat16Rank, 105 Float16Rank, 106 HalfRank, 107 FloatRank, 108 DoubleRank, 109 LongDoubleRank, 110 Float128Rank, 111 Ibm128Rank 112 }; 113 114 /// \returns location that is relevant when searching for Doc comments related 115 /// to \p D. 116 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 117 SourceManager &SourceMgr) { 118 assert(D); 119 120 // User can not attach documentation to implicit declarations. 121 if (D->isImplicit()) 122 return {}; 123 124 // User can not attach documentation to implicit instantiations. 125 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 126 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 127 return {}; 128 } 129 130 if (const auto *VD = dyn_cast<VarDecl>(D)) { 131 if (VD->isStaticDataMember() && 132 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 133 return {}; 134 } 135 136 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 137 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 138 return {}; 139 } 140 141 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 142 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 143 if (TSK == TSK_ImplicitInstantiation || 144 TSK == TSK_Undeclared) 145 return {}; 146 } 147 148 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 149 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 150 return {}; 151 } 152 if (const auto *TD = dyn_cast<TagDecl>(D)) { 153 // When tag declaration (but not definition!) is part of the 154 // decl-specifier-seq of some other declaration, it doesn't get comment 155 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 156 return {}; 157 } 158 // TODO: handle comments for function parameters properly. 159 if (isa<ParmVarDecl>(D)) 160 return {}; 161 162 // TODO: we could look up template parameter documentation in the template 163 // documentation. 164 if (isa<TemplateTypeParmDecl>(D) || 165 isa<NonTypeTemplateParmDecl>(D) || 166 isa<TemplateTemplateParmDecl>(D)) 167 return {}; 168 169 // Find declaration location. 170 // For Objective-C declarations we generally don't expect to have multiple 171 // declarators, thus use declaration starting location as the "declaration 172 // location". 173 // For all other declarations multiple declarators are used quite frequently, 174 // so we use the location of the identifier as the "declaration location". 175 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 176 isa<ObjCPropertyDecl>(D) || 177 isa<RedeclarableTemplateDecl>(D) || 178 isa<ClassTemplateSpecializationDecl>(D) || 179 // Allow association with Y across {} in `typedef struct X {} Y`. 180 isa<TypedefDecl>(D)) 181 return D->getBeginLoc(); 182 183 const SourceLocation DeclLoc = D->getLocation(); 184 if (DeclLoc.isMacroID()) { 185 if (isa<TypedefDecl>(D)) { 186 // If location of the typedef name is in a macro, it is because being 187 // declared via a macro. Try using declaration's starting location as 188 // the "declaration location". 189 return D->getBeginLoc(); 190 } 191 192 if (const auto *TD = dyn_cast<TagDecl>(D)) { 193 // If location of the tag decl is inside a macro, but the spelling of 194 // the tag name comes from a macro argument, it looks like a special 195 // macro like NS_ENUM is being used to define the tag decl. In that 196 // case, adjust the source location to the expansion loc so that we can 197 // attach the comment to the tag decl. 198 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) 199 return SourceMgr.getExpansionLoc(DeclLoc); 200 } 201 } 202 203 return DeclLoc; 204 } 205 206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 207 const Decl *D, const SourceLocation RepresentativeLocForDecl, 208 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 209 // If the declaration doesn't map directly to a location in a file, we 210 // can't find the comment. 211 if (RepresentativeLocForDecl.isInvalid() || 212 !RepresentativeLocForDecl.isFileID()) 213 return nullptr; 214 215 // If there are no comments anywhere, we won't find anything. 216 if (CommentsInTheFile.empty()) 217 return nullptr; 218 219 // Decompose the location for the declaration and find the beginning of the 220 // file buffer. 221 const std::pair<FileID, unsigned> DeclLocDecomp = 222 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 223 224 // Slow path. 225 auto OffsetCommentBehindDecl = 226 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 227 228 // First check whether we have a trailing comment. 229 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 230 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 231 if ((CommentBehindDecl->isDocumentation() || 232 LangOpts.CommentOpts.ParseAllComments) && 233 CommentBehindDecl->isTrailingComment() && 234 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 235 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 236 237 // Check that Doxygen trailing comment comes after the declaration, starts 238 // on the same line and in the same file as the declaration. 239 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 240 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 241 OffsetCommentBehindDecl->first)) { 242 return CommentBehindDecl; 243 } 244 } 245 } 246 247 // The comment just after the declaration was not a trailing comment. 248 // Let's look at the previous comment. 249 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 250 return nullptr; 251 252 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 253 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 254 255 // Check that we actually have a non-member Doxygen comment. 256 if (!(CommentBeforeDecl->isDocumentation() || 257 LangOpts.CommentOpts.ParseAllComments) || 258 CommentBeforeDecl->isTrailingComment()) 259 return nullptr; 260 261 // Decompose the end of the comment. 262 const unsigned CommentEndOffset = 263 Comments.getCommentEndOffset(CommentBeforeDecl); 264 265 // Get the corresponding buffer. 266 bool Invalid = false; 267 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 268 &Invalid).data(); 269 if (Invalid) 270 return nullptr; 271 272 // Extract text between the comment and declaration. 273 StringRef Text(Buffer + CommentEndOffset, 274 DeclLocDecomp.second - CommentEndOffset); 275 276 // There should be no other declarations or preprocessor directives between 277 // comment and declaration. 278 if (Text.find_first_of(";{}#@") != StringRef::npos) 279 return nullptr; 280 281 return CommentBeforeDecl; 282 } 283 284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 285 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 286 287 // If the declaration doesn't map directly to a location in a file, we 288 // can't find the comment. 289 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 290 return nullptr; 291 292 if (ExternalSource && !CommentsLoaded) { 293 ExternalSource->ReadComments(); 294 CommentsLoaded = true; 295 } 296 297 if (Comments.empty()) 298 return nullptr; 299 300 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 301 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 302 if (!CommentsInThisFile || CommentsInThisFile->empty()) 303 return nullptr; 304 305 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 306 } 307 308 void ASTContext::addComment(const RawComment &RC) { 309 assert(LangOpts.RetainCommentsFromSystemHeaders || 310 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 311 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 312 } 313 314 /// If we have a 'templated' declaration for a template, adjust 'D' to 315 /// refer to the actual template. 316 /// If we have an implicit instantiation, adjust 'D' to refer to template. 317 static const Decl &adjustDeclToTemplate(const Decl &D) { 318 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 319 // Is this function declaration part of a function template? 320 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 321 return *FTD; 322 323 // Nothing to do if function is not an implicit instantiation. 324 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 325 return D; 326 327 // Function is an implicit instantiation of a function template? 328 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 329 return *FTD; 330 331 // Function is instantiated from a member definition of a class template? 332 if (const FunctionDecl *MemberDecl = 333 FD->getInstantiatedFromMemberFunction()) 334 return *MemberDecl; 335 336 return D; 337 } 338 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 339 // Static data member is instantiated from a member definition of a class 340 // template? 341 if (VD->isStaticDataMember()) 342 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 343 return *MemberDecl; 344 345 return D; 346 } 347 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 348 // Is this class declaration part of a class template? 349 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 350 return *CTD; 351 352 // Class is an implicit instantiation of a class template or partial 353 // specialization? 354 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 355 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 356 return D; 357 llvm::PointerUnion<ClassTemplateDecl *, 358 ClassTemplatePartialSpecializationDecl *> 359 PU = CTSD->getSpecializedTemplateOrPartial(); 360 return PU.is<ClassTemplateDecl *>() 361 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 362 : *static_cast<const Decl *>( 363 PU.get<ClassTemplatePartialSpecializationDecl *>()); 364 } 365 366 // Class is instantiated from a member definition of a class template? 367 if (const MemberSpecializationInfo *Info = 368 CRD->getMemberSpecializationInfo()) 369 return *Info->getInstantiatedFrom(); 370 371 return D; 372 } 373 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 374 // Enum is instantiated from a member definition of a class template? 375 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 376 return *MemberDecl; 377 378 return D; 379 } 380 // FIXME: Adjust alias templates? 381 return D; 382 } 383 384 const RawComment *ASTContext::getRawCommentForAnyRedecl( 385 const Decl *D, 386 const Decl **OriginalDecl) const { 387 if (!D) { 388 if (OriginalDecl) 389 OriginalDecl = nullptr; 390 return nullptr; 391 } 392 393 D = &adjustDeclToTemplate(*D); 394 395 // Any comment directly attached to D? 396 { 397 auto DeclComment = DeclRawComments.find(D); 398 if (DeclComment != DeclRawComments.end()) { 399 if (OriginalDecl) 400 *OriginalDecl = D; 401 return DeclComment->second; 402 } 403 } 404 405 // Any comment attached to any redeclaration of D? 406 const Decl *CanonicalD = D->getCanonicalDecl(); 407 if (!CanonicalD) 408 return nullptr; 409 410 { 411 auto RedeclComment = RedeclChainComments.find(CanonicalD); 412 if (RedeclComment != RedeclChainComments.end()) { 413 if (OriginalDecl) 414 *OriginalDecl = RedeclComment->second; 415 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 416 assert(CommentAtRedecl != DeclRawComments.end() && 417 "This decl is supposed to have comment attached."); 418 return CommentAtRedecl->second; 419 } 420 } 421 422 // Any redeclarations of D that we haven't checked for comments yet? 423 // We can't use DenseMap::iterator directly since it'd get invalid. 424 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 425 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 426 if (LookupRes != CommentlessRedeclChains.end()) 427 return LookupRes->second; 428 return nullptr; 429 }(); 430 431 for (const auto Redecl : D->redecls()) { 432 assert(Redecl); 433 // Skip all redeclarations that have been checked previously. 434 if (LastCheckedRedecl) { 435 if (LastCheckedRedecl == Redecl) { 436 LastCheckedRedecl = nullptr; 437 } 438 continue; 439 } 440 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 441 if (RedeclComment) { 442 cacheRawCommentForDecl(*Redecl, *RedeclComment); 443 if (OriginalDecl) 444 *OriginalDecl = Redecl; 445 return RedeclComment; 446 } 447 CommentlessRedeclChains[CanonicalD] = Redecl; 448 } 449 450 if (OriginalDecl) 451 *OriginalDecl = nullptr; 452 return nullptr; 453 } 454 455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 456 const RawComment &Comment) const { 457 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 458 DeclRawComments.try_emplace(&OriginalD, &Comment); 459 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 460 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 461 CommentlessRedeclChains.erase(CanonicalDecl); 462 } 463 464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 465 SmallVectorImpl<const NamedDecl *> &Redeclared) { 466 const DeclContext *DC = ObjCMethod->getDeclContext(); 467 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 468 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 469 if (!ID) 470 return; 471 // Add redeclared method here. 472 for (const auto *Ext : ID->known_extensions()) { 473 if (ObjCMethodDecl *RedeclaredMethod = 474 Ext->getMethod(ObjCMethod->getSelector(), 475 ObjCMethod->isInstanceMethod())) 476 Redeclared.push_back(RedeclaredMethod); 477 } 478 } 479 } 480 481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 482 const Preprocessor *PP) { 483 if (Comments.empty() || Decls.empty()) 484 return; 485 486 FileID File; 487 for (Decl *D : Decls) { 488 SourceLocation Loc = D->getLocation(); 489 if (Loc.isValid()) { 490 // See if there are any new comments that are not attached to a decl. 491 // The location doesn't have to be precise - we care only about the file. 492 File = SourceMgr.getDecomposedLoc(Loc).first; 493 break; 494 } 495 } 496 497 if (File.isInvalid()) 498 return; 499 500 auto CommentsInThisFile = Comments.getCommentsInFile(File); 501 if (!CommentsInThisFile || CommentsInThisFile->empty() || 502 CommentsInThisFile->rbegin()->second->isAttached()) 503 return; 504 505 // There is at least one comment not attached to a decl. 506 // Maybe it should be attached to one of Decls? 507 // 508 // Note that this way we pick up not only comments that precede the 509 // declaration, but also comments that *follow* the declaration -- thanks to 510 // the lookahead in the lexer: we've consumed the semicolon and looked 511 // ahead through comments. 512 513 for (const Decl *D : Decls) { 514 assert(D); 515 if (D->isInvalidDecl()) 516 continue; 517 518 D = &adjustDeclToTemplate(*D); 519 520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 521 522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 523 continue; 524 525 if (DeclRawComments.count(D) > 0) 526 continue; 527 528 if (RawComment *const DocComment = 529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 530 cacheRawCommentForDecl(*D, *DocComment); 531 comments::FullComment *FC = DocComment->parse(*this, PP, D); 532 ParsedComments[D->getCanonicalDecl()] = FC; 533 } 534 } 535 } 536 537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 538 const Decl *D) const { 539 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 540 ThisDeclInfo->CommentDecl = D; 541 ThisDeclInfo->IsFilled = false; 542 ThisDeclInfo->fill(); 543 ThisDeclInfo->CommentDecl = FC->getDecl(); 544 if (!ThisDeclInfo->TemplateParameters) 545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 546 comments::FullComment *CFC = 547 new (*this) comments::FullComment(FC->getBlocks(), 548 ThisDeclInfo); 549 return CFC; 550 } 551 552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 553 const RawComment *RC = getRawCommentForDeclNoCache(D); 554 return RC ? RC->parse(*this, nullptr, D) : nullptr; 555 } 556 557 comments::FullComment *ASTContext::getCommentForDecl( 558 const Decl *D, 559 const Preprocessor *PP) const { 560 if (!D || D->isInvalidDecl()) 561 return nullptr; 562 D = &adjustDeclToTemplate(*D); 563 564 const Decl *Canonical = D->getCanonicalDecl(); 565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 566 ParsedComments.find(Canonical); 567 568 if (Pos != ParsedComments.end()) { 569 if (Canonical != D) { 570 comments::FullComment *FC = Pos->second; 571 comments::FullComment *CFC = cloneFullComment(FC, D); 572 return CFC; 573 } 574 return Pos->second; 575 } 576 577 const Decl *OriginalDecl = nullptr; 578 579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 580 if (!RC) { 581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 582 SmallVector<const NamedDecl*, 8> Overridden; 583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 584 if (OMD && OMD->isPropertyAccessor()) 585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 587 return cloneFullComment(FC, D); 588 if (OMD) 589 addRedeclaredMethods(OMD, Overridden); 590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 591 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 593 return cloneFullComment(FC, D); 594 } 595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 596 // Attach any tag type's documentation to its typedef if latter 597 // does not have one of its own. 598 QualType QT = TD->getUnderlyingType(); 599 if (const auto *TT = QT->getAs<TagType>()) 600 if (const Decl *TD = TT->getDecl()) 601 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 602 return cloneFullComment(FC, D); 603 } 604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 605 while (IC->getSuperClass()) { 606 IC = IC->getSuperClass(); 607 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 608 return cloneFullComment(FC, D); 609 } 610 } 611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 613 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 614 return cloneFullComment(FC, D); 615 } 616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 617 if (!(RD = RD->getDefinition())) 618 return nullptr; 619 // Check non-virtual bases. 620 for (const auto &I : RD->bases()) { 621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 622 continue; 623 QualType Ty = I.getType(); 624 if (Ty.isNull()) 625 continue; 626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 627 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 628 continue; 629 630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 631 return cloneFullComment(FC, D); 632 } 633 } 634 // Check virtual bases. 635 for (const auto &I : RD->vbases()) { 636 if (I.getAccessSpecifier() != AS_public) 637 continue; 638 QualType Ty = I.getType(); 639 if (Ty.isNull()) 640 continue; 641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 642 if (!(VirtualBase= VirtualBase->getDefinition())) 643 continue; 644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 645 return cloneFullComment(FC, D); 646 } 647 } 648 } 649 return nullptr; 650 } 651 652 // If the RawComment was attached to other redeclaration of this Decl, we 653 // should parse the comment in context of that other Decl. This is important 654 // because comments can contain references to parameter names which can be 655 // different across redeclarations. 656 if (D != OriginalDecl && OriginalDecl) 657 return getCommentForDecl(OriginalDecl, PP); 658 659 comments::FullComment *FC = RC->parse(*this, PP, D); 660 ParsedComments[Canonical] = FC; 661 return FC; 662 } 663 664 void 665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 666 const ASTContext &C, 667 TemplateTemplateParmDecl *Parm) { 668 ID.AddInteger(Parm->getDepth()); 669 ID.AddInteger(Parm->getPosition()); 670 ID.AddBoolean(Parm->isParameterPack()); 671 672 TemplateParameterList *Params = Parm->getTemplateParameters(); 673 ID.AddInteger(Params->size()); 674 for (TemplateParameterList::const_iterator P = Params->begin(), 675 PEnd = Params->end(); 676 P != PEnd; ++P) { 677 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 678 ID.AddInteger(0); 679 ID.AddBoolean(TTP->isParameterPack()); 680 const TypeConstraint *TC = TTP->getTypeConstraint(); 681 ID.AddBoolean(TC != nullptr); 682 if (TC) 683 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 684 /*Canonical=*/true); 685 if (TTP->isExpandedParameterPack()) { 686 ID.AddBoolean(true); 687 ID.AddInteger(TTP->getNumExpansionParameters()); 688 } else 689 ID.AddBoolean(false); 690 continue; 691 } 692 693 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 694 ID.AddInteger(1); 695 ID.AddBoolean(NTTP->isParameterPack()); 696 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 697 if (NTTP->isExpandedParameterPack()) { 698 ID.AddBoolean(true); 699 ID.AddInteger(NTTP->getNumExpansionTypes()); 700 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 701 QualType T = NTTP->getExpansionType(I); 702 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 703 } 704 } else 705 ID.AddBoolean(false); 706 continue; 707 } 708 709 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 710 ID.AddInteger(2); 711 Profile(ID, C, TTP); 712 } 713 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 714 ID.AddBoolean(RequiresClause != nullptr); 715 if (RequiresClause) 716 RequiresClause->Profile(ID, C, /*Canonical=*/true); 717 } 718 719 static Expr * 720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 721 QualType ConstrainedType) { 722 // This is a bit ugly - we need to form a new immediately-declared 723 // constraint that references the new parameter; this would ideally 724 // require semantic analysis (e.g. template<C T> struct S {}; - the 725 // converted arguments of C<T> could be an argument pack if C is 726 // declared as template<typename... T> concept C = ...). 727 // We don't have semantic analysis here so we dig deep into the 728 // ready-made constraint expr and change the thing manually. 729 ConceptSpecializationExpr *CSE; 730 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 731 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 732 else 733 CSE = cast<ConceptSpecializationExpr>(IDC); 734 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 735 SmallVector<TemplateArgument, 3> NewConverted; 736 NewConverted.reserve(OldConverted.size()); 737 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 738 // The case: 739 // template<typename... T> concept C = true; 740 // template<C<int> T> struct S; -> constraint is C<{T, int}> 741 NewConverted.push_back(ConstrainedType); 742 llvm::append_range(NewConverted, 743 OldConverted.front().pack_elements().drop_front(1)); 744 TemplateArgument NewPack(NewConverted); 745 746 NewConverted.clear(); 747 NewConverted.push_back(NewPack); 748 assert(OldConverted.size() == 1 && 749 "Template parameter pack should be the last parameter"); 750 } else { 751 assert(OldConverted.front().getKind() == TemplateArgument::Type && 752 "Unexpected first argument kind for immediately-declared " 753 "constraint"); 754 NewConverted.push_back(ConstrainedType); 755 llvm::append_range(NewConverted, OldConverted.drop_front(1)); 756 } 757 Expr *NewIDC = ConceptSpecializationExpr::Create( 758 C, CSE->getNamedConcept(), NewConverted, nullptr, 759 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 760 761 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 762 NewIDC = new (C) CXXFoldExpr( 763 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 764 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 765 SourceLocation(), /*NumExpansions=*/None); 766 return NewIDC; 767 } 768 769 TemplateTemplateParmDecl * 770 ASTContext::getCanonicalTemplateTemplateParmDecl( 771 TemplateTemplateParmDecl *TTP) const { 772 // Check if we already have a canonical template template parameter. 773 llvm::FoldingSetNodeID ID; 774 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 775 void *InsertPos = nullptr; 776 CanonicalTemplateTemplateParm *Canonical 777 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 778 if (Canonical) 779 return Canonical->getParam(); 780 781 // Build a canonical template parameter list. 782 TemplateParameterList *Params = TTP->getTemplateParameters(); 783 SmallVector<NamedDecl *, 4> CanonParams; 784 CanonParams.reserve(Params->size()); 785 for (TemplateParameterList::const_iterator P = Params->begin(), 786 PEnd = Params->end(); 787 P != PEnd; ++P) { 788 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 789 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 790 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 791 TTP->getDepth(), TTP->getIndex(), nullptr, false, 792 TTP->isParameterPack(), TTP->hasTypeConstraint(), 793 TTP->isExpandedParameterPack() ? 794 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 795 if (const auto *TC = TTP->getTypeConstraint()) { 796 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 797 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 798 *this, TC->getImmediatelyDeclaredConstraint(), 799 ParamAsArgument); 800 TemplateArgumentListInfo CanonArgsAsWritten; 801 if (auto *Args = TC->getTemplateArgsAsWritten()) 802 for (const auto &ArgLoc : Args->arguments()) 803 CanonArgsAsWritten.addArgument( 804 TemplateArgumentLoc(ArgLoc.getArgument(), 805 TemplateArgumentLocInfo())); 806 NewTTP->setTypeConstraint( 807 NestedNameSpecifierLoc(), 808 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 809 SourceLocation()), /*FoundDecl=*/nullptr, 810 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 811 // simply omit the ArgsAsWritten 812 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 813 } 814 CanonParams.push_back(NewTTP); 815 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 816 QualType T = getCanonicalType(NTTP->getType()); 817 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 818 NonTypeTemplateParmDecl *Param; 819 if (NTTP->isExpandedParameterPack()) { 820 SmallVector<QualType, 2> ExpandedTypes; 821 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 822 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 823 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 824 ExpandedTInfos.push_back( 825 getTrivialTypeSourceInfo(ExpandedTypes.back())); 826 } 827 828 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 829 SourceLocation(), 830 SourceLocation(), 831 NTTP->getDepth(), 832 NTTP->getPosition(), nullptr, 833 T, 834 TInfo, 835 ExpandedTypes, 836 ExpandedTInfos); 837 } else { 838 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 839 SourceLocation(), 840 SourceLocation(), 841 NTTP->getDepth(), 842 NTTP->getPosition(), nullptr, 843 T, 844 NTTP->isParameterPack(), 845 TInfo); 846 } 847 if (AutoType *AT = T->getContainedAutoType()) { 848 if (AT->isConstrained()) { 849 Param->setPlaceholderTypeConstraint( 850 canonicalizeImmediatelyDeclaredConstraint( 851 *this, NTTP->getPlaceholderTypeConstraint(), T)); 852 } 853 } 854 CanonParams.push_back(Param); 855 856 } else 857 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 858 cast<TemplateTemplateParmDecl>(*P))); 859 } 860 861 Expr *CanonRequiresClause = nullptr; 862 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 863 CanonRequiresClause = RequiresClause; 864 865 TemplateTemplateParmDecl *CanonTTP 866 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 867 SourceLocation(), TTP->getDepth(), 868 TTP->getPosition(), 869 TTP->isParameterPack(), 870 nullptr, 871 TemplateParameterList::Create(*this, SourceLocation(), 872 SourceLocation(), 873 CanonParams, 874 SourceLocation(), 875 CanonRequiresClause)); 876 877 // Get the new insert position for the node we care about. 878 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 879 assert(!Canonical && "Shouldn't be in the map!"); 880 (void)Canonical; 881 882 // Create the canonical template template parameter entry. 883 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 884 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 885 return CanonTTP; 886 } 887 888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 889 auto Kind = getTargetInfo().getCXXABI().getKind(); 890 return getLangOpts().CXXABI.getValueOr(Kind); 891 } 892 893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 894 if (!LangOpts.CPlusPlus) return nullptr; 895 896 switch (getCXXABIKind()) { 897 case TargetCXXABI::AppleARM64: 898 case TargetCXXABI::Fuchsia: 899 case TargetCXXABI::GenericARM: // Same as Itanium at this level 900 case TargetCXXABI::iOS: 901 case TargetCXXABI::WatchOS: 902 case TargetCXXABI::GenericAArch64: 903 case TargetCXXABI::GenericMIPS: 904 case TargetCXXABI::GenericItanium: 905 case TargetCXXABI::WebAssembly: 906 case TargetCXXABI::XL: 907 return CreateItaniumCXXABI(*this); 908 case TargetCXXABI::Microsoft: 909 return CreateMicrosoftCXXABI(*this); 910 } 911 llvm_unreachable("Invalid CXXABI type!"); 912 } 913 914 interp::Context &ASTContext::getInterpContext() { 915 if (!InterpContext) { 916 InterpContext.reset(new interp::Context(*this)); 917 } 918 return *InterpContext.get(); 919 } 920 921 ParentMapContext &ASTContext::getParentMapContext() { 922 if (!ParentMapCtx) 923 ParentMapCtx.reset(new ParentMapContext(*this)); 924 return *ParentMapCtx.get(); 925 } 926 927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 928 const LangOptions &LOpts) { 929 if (LOpts.FakeAddressSpaceMap) { 930 // The fake address space map must have a distinct entry for each 931 // language-specific address space. 932 static const unsigned FakeAddrSpaceMap[] = { 933 0, // Default 934 1, // opencl_global 935 3, // opencl_local 936 2, // opencl_constant 937 0, // opencl_private 938 4, // opencl_generic 939 5, // opencl_global_device 940 6, // opencl_global_host 941 7, // cuda_device 942 8, // cuda_constant 943 9, // cuda_shared 944 1, // sycl_global 945 5, // sycl_global_device 946 6, // sycl_global_host 947 3, // sycl_local 948 0, // sycl_private 949 10, // ptr32_sptr 950 11, // ptr32_uptr 951 12 // ptr64 952 }; 953 return &FakeAddrSpaceMap; 954 } else { 955 return &T.getAddressSpaceMap(); 956 } 957 } 958 959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 960 const LangOptions &LangOpts) { 961 switch (LangOpts.getAddressSpaceMapMangling()) { 962 case LangOptions::ASMM_Target: 963 return TI.useAddressSpaceMapMangling(); 964 case LangOptions::ASMM_On: 965 return true; 966 case LangOptions::ASMM_Off: 967 return false; 968 } 969 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 970 } 971 972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 973 IdentifierTable &idents, SelectorTable &sels, 974 Builtin::Context &builtins, TranslationUnitKind TUKind) 975 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 976 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 977 TemplateSpecializationTypes(this_()), 978 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 979 SubstTemplateTemplateParmPacks(this_()), 980 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 981 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 982 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 983 LangOpts.XRayNeverInstrumentFiles, 984 LangOpts.XRayAttrListFiles, SM)), 985 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 986 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 987 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 988 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 989 CompCategories(this_()), LastSDM(nullptr, 0) { 990 addTranslationUnitDecl(); 991 } 992 993 void ASTContext::cleanup() { 994 // Release the DenseMaps associated with DeclContext objects. 995 // FIXME: Is this the ideal solution? 996 ReleaseDeclContextMaps(); 997 998 // Call all of the deallocation functions on all of their targets. 999 for (auto &Pair : Deallocations) 1000 (Pair.first)(Pair.second); 1001 Deallocations.clear(); 1002 1003 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1004 // because they can contain DenseMaps. 1005 for (llvm::DenseMap<const ObjCContainerDecl*, 1006 const ASTRecordLayout*>::iterator 1007 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1008 // Increment in loop to prevent using deallocated memory. 1009 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1010 R->Destroy(*this); 1011 ObjCLayouts.clear(); 1012 1013 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1014 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1015 // Increment in loop to prevent using deallocated memory. 1016 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1017 R->Destroy(*this); 1018 } 1019 ASTRecordLayouts.clear(); 1020 1021 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1022 AEnd = DeclAttrs.end(); 1023 A != AEnd; ++A) 1024 A->second->~AttrVec(); 1025 DeclAttrs.clear(); 1026 1027 for (const auto &Value : ModuleInitializers) 1028 Value.second->~PerModuleInitializers(); 1029 ModuleInitializers.clear(); 1030 } 1031 1032 ASTContext::~ASTContext() { cleanup(); } 1033 1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1035 TraversalScope = TopLevelDecls; 1036 getParentMapContext().clear(); 1037 } 1038 1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1040 Deallocations.push_back({Callback, Data}); 1041 } 1042 1043 void 1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1045 ExternalSource = std::move(Source); 1046 } 1047 1048 void ASTContext::PrintStats() const { 1049 llvm::errs() << "\n*** AST Context Stats:\n"; 1050 llvm::errs() << " " << Types.size() << " types total.\n"; 1051 1052 unsigned counts[] = { 1053 #define TYPE(Name, Parent) 0, 1054 #define ABSTRACT_TYPE(Name, Parent) 1055 #include "clang/AST/TypeNodes.inc" 1056 0 // Extra 1057 }; 1058 1059 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1060 Type *T = Types[i]; 1061 counts[(unsigned)T->getTypeClass()]++; 1062 } 1063 1064 unsigned Idx = 0; 1065 unsigned TotalBytes = 0; 1066 #define TYPE(Name, Parent) \ 1067 if (counts[Idx]) \ 1068 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1069 << " types, " << sizeof(Name##Type) << " each " \ 1070 << "(" << counts[Idx] * sizeof(Name##Type) \ 1071 << " bytes)\n"; \ 1072 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1073 ++Idx; 1074 #define ABSTRACT_TYPE(Name, Parent) 1075 #include "clang/AST/TypeNodes.inc" 1076 1077 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1078 1079 // Implicit special member functions. 1080 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1081 << NumImplicitDefaultConstructors 1082 << " implicit default constructors created\n"; 1083 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1084 << NumImplicitCopyConstructors 1085 << " implicit copy constructors created\n"; 1086 if (getLangOpts().CPlusPlus) 1087 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1088 << NumImplicitMoveConstructors 1089 << " implicit move constructors created\n"; 1090 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1091 << NumImplicitCopyAssignmentOperators 1092 << " implicit copy assignment operators created\n"; 1093 if (getLangOpts().CPlusPlus) 1094 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1095 << NumImplicitMoveAssignmentOperators 1096 << " implicit move assignment operators created\n"; 1097 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1098 << NumImplicitDestructors 1099 << " implicit destructors created\n"; 1100 1101 if (ExternalSource) { 1102 llvm::errs() << "\n"; 1103 ExternalSource->PrintStats(); 1104 } 1105 1106 BumpAlloc.PrintStats(); 1107 } 1108 1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1110 bool NotifyListeners) { 1111 if (NotifyListeners) 1112 if (auto *Listener = getASTMutationListener()) 1113 Listener->RedefinedHiddenDefinition(ND, M); 1114 1115 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1116 } 1117 1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1119 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1120 if (It == MergedDefModules.end()) 1121 return; 1122 1123 auto &Merged = It->second; 1124 llvm::DenseSet<Module*> Found; 1125 for (Module *&M : Merged) 1126 if (!Found.insert(M).second) 1127 M = nullptr; 1128 llvm::erase_value(Merged, nullptr); 1129 } 1130 1131 ArrayRef<Module *> 1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1133 auto MergedIt = 1134 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1135 if (MergedIt == MergedDefModules.end()) 1136 return None; 1137 return MergedIt->second; 1138 } 1139 1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1141 if (LazyInitializers.empty()) 1142 return; 1143 1144 auto *Source = Ctx.getExternalSource(); 1145 assert(Source && "lazy initializers but no external source"); 1146 1147 auto LazyInits = std::move(LazyInitializers); 1148 LazyInitializers.clear(); 1149 1150 for (auto ID : LazyInits) 1151 Initializers.push_back(Source->GetExternalDecl(ID)); 1152 1153 assert(LazyInitializers.empty() && 1154 "GetExternalDecl for lazy module initializer added more inits"); 1155 } 1156 1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1158 // One special case: if we add a module initializer that imports another 1159 // module, and that module's only initializer is an ImportDecl, simplify. 1160 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1161 auto It = ModuleInitializers.find(ID->getImportedModule()); 1162 1163 // Maybe the ImportDecl does nothing at all. (Common case.) 1164 if (It == ModuleInitializers.end()) 1165 return; 1166 1167 // Maybe the ImportDecl only imports another ImportDecl. 1168 auto &Imported = *It->second; 1169 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1170 Imported.resolve(*this); 1171 auto *OnlyDecl = Imported.Initializers.front(); 1172 if (isa<ImportDecl>(OnlyDecl)) 1173 D = OnlyDecl; 1174 } 1175 } 1176 1177 auto *&Inits = ModuleInitializers[M]; 1178 if (!Inits) 1179 Inits = new (*this) PerModuleInitializers; 1180 Inits->Initializers.push_back(D); 1181 } 1182 1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1184 auto *&Inits = ModuleInitializers[M]; 1185 if (!Inits) 1186 Inits = new (*this) PerModuleInitializers; 1187 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1188 IDs.begin(), IDs.end()); 1189 } 1190 1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1192 auto It = ModuleInitializers.find(M); 1193 if (It == ModuleInitializers.end()) 1194 return None; 1195 1196 auto *Inits = It->second; 1197 Inits->resolve(*this); 1198 return Inits->Initializers; 1199 } 1200 1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1202 if (!ExternCContext) 1203 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1204 1205 return ExternCContext; 1206 } 1207 1208 BuiltinTemplateDecl * 1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1210 const IdentifierInfo *II) const { 1211 auto *BuiltinTemplate = 1212 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1213 BuiltinTemplate->setImplicit(); 1214 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1215 1216 return BuiltinTemplate; 1217 } 1218 1219 BuiltinTemplateDecl * 1220 ASTContext::getMakeIntegerSeqDecl() const { 1221 if (!MakeIntegerSeqDecl) 1222 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1223 getMakeIntegerSeqName()); 1224 return MakeIntegerSeqDecl; 1225 } 1226 1227 BuiltinTemplateDecl * 1228 ASTContext::getTypePackElementDecl() const { 1229 if (!TypePackElementDecl) 1230 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1231 getTypePackElementName()); 1232 return TypePackElementDecl; 1233 } 1234 1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1236 RecordDecl::TagKind TK) const { 1237 SourceLocation Loc; 1238 RecordDecl *NewDecl; 1239 if (getLangOpts().CPlusPlus) 1240 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1241 Loc, &Idents.get(Name)); 1242 else 1243 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1244 &Idents.get(Name)); 1245 NewDecl->setImplicit(); 1246 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1247 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1248 return NewDecl; 1249 } 1250 1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1252 StringRef Name) const { 1253 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1254 TypedefDecl *NewDecl = TypedefDecl::Create( 1255 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1256 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1257 NewDecl->setImplicit(); 1258 return NewDecl; 1259 } 1260 1261 TypedefDecl *ASTContext::getInt128Decl() const { 1262 if (!Int128Decl) 1263 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1264 return Int128Decl; 1265 } 1266 1267 TypedefDecl *ASTContext::getUInt128Decl() const { 1268 if (!UInt128Decl) 1269 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1270 return UInt128Decl; 1271 } 1272 1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1274 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1275 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1276 Types.push_back(Ty); 1277 } 1278 1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1280 const TargetInfo *AuxTarget) { 1281 assert((!this->Target || this->Target == &Target) && 1282 "Incorrect target reinitialization"); 1283 assert(VoidTy.isNull() && "Context reinitialized?"); 1284 1285 this->Target = &Target; 1286 this->AuxTarget = AuxTarget; 1287 1288 ABI.reset(createCXXABI(Target)); 1289 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1291 1292 // C99 6.2.5p19. 1293 InitBuiltinType(VoidTy, BuiltinType::Void); 1294 1295 // C99 6.2.5p2. 1296 InitBuiltinType(BoolTy, BuiltinType::Bool); 1297 // C99 6.2.5p3. 1298 if (LangOpts.CharIsSigned) 1299 InitBuiltinType(CharTy, BuiltinType::Char_S); 1300 else 1301 InitBuiltinType(CharTy, BuiltinType::Char_U); 1302 // C99 6.2.5p4. 1303 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1304 InitBuiltinType(ShortTy, BuiltinType::Short); 1305 InitBuiltinType(IntTy, BuiltinType::Int); 1306 InitBuiltinType(LongTy, BuiltinType::Long); 1307 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1308 1309 // C99 6.2.5p6. 1310 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1311 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1312 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1313 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1314 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1315 1316 // C99 6.2.5p10. 1317 InitBuiltinType(FloatTy, BuiltinType::Float); 1318 InitBuiltinType(DoubleTy, BuiltinType::Double); 1319 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1320 1321 // GNU extension, __float128 for IEEE quadruple precision 1322 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1323 1324 // __ibm128 for IBM extended precision 1325 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1326 1327 // C11 extension ISO/IEC TS 18661-3 1328 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1329 1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1331 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1332 InitBuiltinType(AccumTy, BuiltinType::Accum); 1333 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1334 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1335 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1336 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1337 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1338 InitBuiltinType(FractTy, BuiltinType::Fract); 1339 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1340 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1341 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1342 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1343 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1344 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1345 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1346 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1347 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1348 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1349 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1350 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1351 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1352 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1353 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1354 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1355 1356 // GNU extension, 128-bit integers. 1357 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1359 1360 // C++ 3.9.1p5 1361 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1362 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1363 else // -fshort-wchar makes wchar_t be unsigned. 1364 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1365 if (LangOpts.CPlusPlus && LangOpts.WChar) 1366 WideCharTy = WCharTy; 1367 else { 1368 // C99 (or C++ using -fno-wchar). 1369 WideCharTy = getFromTargetType(Target.getWCharType()); 1370 } 1371 1372 WIntTy = getFromTargetType(Target.getWIntType()); 1373 1374 // C++20 (proposed) 1375 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1376 1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1378 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1379 else // C99 1380 Char16Ty = getFromTargetType(Target.getChar16Type()); 1381 1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1383 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1384 else // C99 1385 Char32Ty = getFromTargetType(Target.getChar32Type()); 1386 1387 // Placeholder type for type-dependent expressions whose type is 1388 // completely unknown. No code should ever check a type against 1389 // DependentTy and users should never see it; however, it is here to 1390 // help diagnose failures to properly check for type-dependent 1391 // expressions. 1392 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1393 1394 // Placeholder type for functions. 1395 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1396 1397 // Placeholder type for bound members. 1398 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1399 1400 // Placeholder type for pseudo-objects. 1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1402 1403 // "any" type; useful for debugger-like clients. 1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1405 1406 // Placeholder type for unbridged ARC casts. 1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1408 1409 // Placeholder type for builtin functions. 1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1411 1412 // Placeholder type for OMP array sections. 1413 if (LangOpts.OpenMP) { 1414 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1417 } 1418 if (LangOpts.MatrixTypes) 1419 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1420 1421 // Builtin types for 'id', 'Class', and 'SEL'. 1422 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1423 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1424 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1425 1426 if (LangOpts.OpenCL) { 1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1428 InitBuiltinType(SingletonId, BuiltinType::Id); 1429 #include "clang/Basic/OpenCLImageTypes.def" 1430 1431 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1432 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1433 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1434 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1435 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1436 1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1438 InitBuiltinType(Id##Ty, BuiltinType::Id); 1439 #include "clang/Basic/OpenCLExtensionTypes.def" 1440 } 1441 1442 if (Target.hasAArch64SVETypes()) { 1443 #define SVE_TYPE(Name, Id, SingletonId) \ 1444 InitBuiltinType(SingletonId, BuiltinType::Id); 1445 #include "clang/Basic/AArch64SVEACLETypes.def" 1446 } 1447 1448 if (Target.getTriple().isPPC64()) { 1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1450 InitBuiltinType(Id##Ty, BuiltinType::Id); 1451 #include "clang/Basic/PPCTypes.def" 1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1453 InitBuiltinType(Id##Ty, BuiltinType::Id); 1454 #include "clang/Basic/PPCTypes.def" 1455 } 1456 1457 if (Target.hasRISCVVTypes()) { 1458 #define RVV_TYPE(Name, Id, SingletonId) \ 1459 InitBuiltinType(SingletonId, BuiltinType::Id); 1460 #include "clang/Basic/RISCVVTypes.def" 1461 } 1462 1463 // Builtin type for __objc_yes and __objc_no 1464 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1465 SignedCharTy : BoolTy); 1466 1467 ObjCConstantStringType = QualType(); 1468 1469 ObjCSuperType = QualType(); 1470 1471 // void * type 1472 if (LangOpts.OpenCLGenericAddressSpace) { 1473 auto Q = VoidTy.getQualifiers(); 1474 Q.setAddressSpace(LangAS::opencl_generic); 1475 VoidPtrTy = getPointerType(getCanonicalType( 1476 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1477 } else { 1478 VoidPtrTy = getPointerType(VoidTy); 1479 } 1480 1481 // nullptr type (C++0x 2.14.7) 1482 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1483 1484 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1485 InitBuiltinType(HalfTy, BuiltinType::Half); 1486 1487 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1488 1489 // Builtin type used to help define __builtin_va_list. 1490 VaListTagDecl = nullptr; 1491 1492 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1493 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1494 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1495 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1496 } 1497 } 1498 1499 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1500 return SourceMgr.getDiagnostics(); 1501 } 1502 1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1504 AttrVec *&Result = DeclAttrs[D]; 1505 if (!Result) { 1506 void *Mem = Allocate(sizeof(AttrVec)); 1507 Result = new (Mem) AttrVec; 1508 } 1509 1510 return *Result; 1511 } 1512 1513 /// Erase the attributes corresponding to the given declaration. 1514 void ASTContext::eraseDeclAttrs(const Decl *D) { 1515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1516 if (Pos != DeclAttrs.end()) { 1517 Pos->second->~AttrVec(); 1518 DeclAttrs.erase(Pos); 1519 } 1520 } 1521 1522 // FIXME: Remove ? 1523 MemberSpecializationInfo * 1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1525 assert(Var->isStaticDataMember() && "Not a static data member"); 1526 return getTemplateOrSpecializationInfo(Var) 1527 .dyn_cast<MemberSpecializationInfo *>(); 1528 } 1529 1530 ASTContext::TemplateOrSpecializationInfo 1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1532 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1533 TemplateOrInstantiation.find(Var); 1534 if (Pos == TemplateOrInstantiation.end()) 1535 return {}; 1536 1537 return Pos->second; 1538 } 1539 1540 void 1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1542 TemplateSpecializationKind TSK, 1543 SourceLocation PointOfInstantiation) { 1544 assert(Inst->isStaticDataMember() && "Not a static data member"); 1545 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1546 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1547 Tmpl, TSK, PointOfInstantiation)); 1548 } 1549 1550 void 1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1552 TemplateOrSpecializationInfo TSI) { 1553 assert(!TemplateOrInstantiation[Inst] && 1554 "Already noted what the variable was instantiated from"); 1555 TemplateOrInstantiation[Inst] = TSI; 1556 } 1557 1558 NamedDecl * 1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1560 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1561 if (Pos == InstantiatedFromUsingDecl.end()) 1562 return nullptr; 1563 1564 return Pos->second; 1565 } 1566 1567 void 1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1569 assert((isa<UsingDecl>(Pattern) || 1570 isa<UnresolvedUsingValueDecl>(Pattern) || 1571 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1572 "pattern decl is not a using decl"); 1573 assert((isa<UsingDecl>(Inst) || 1574 isa<UnresolvedUsingValueDecl>(Inst) || 1575 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1576 "instantiation did not produce a using decl"); 1577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1578 InstantiatedFromUsingDecl[Inst] = Pattern; 1579 } 1580 1581 UsingEnumDecl * 1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1583 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1584 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1585 return nullptr; 1586 1587 return Pos->second; 1588 } 1589 1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1591 UsingEnumDecl *Pattern) { 1592 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1593 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1594 } 1595 1596 UsingShadowDecl * 1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1598 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1599 = InstantiatedFromUsingShadowDecl.find(Inst); 1600 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1601 return nullptr; 1602 1603 return Pos->second; 1604 } 1605 1606 void 1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1608 UsingShadowDecl *Pattern) { 1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1611 } 1612 1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1614 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1615 = InstantiatedFromUnnamedFieldDecl.find(Field); 1616 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1617 return nullptr; 1618 1619 return Pos->second; 1620 } 1621 1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1623 FieldDecl *Tmpl) { 1624 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1625 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1626 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1627 "Already noted what unnamed field was instantiated from"); 1628 1629 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1630 } 1631 1632 ASTContext::overridden_cxx_method_iterator 1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1634 return overridden_methods(Method).begin(); 1635 } 1636 1637 ASTContext::overridden_cxx_method_iterator 1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1639 return overridden_methods(Method).end(); 1640 } 1641 1642 unsigned 1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1644 auto Range = overridden_methods(Method); 1645 return Range.end() - Range.begin(); 1646 } 1647 1648 ASTContext::overridden_method_range 1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1650 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1651 OverriddenMethods.find(Method->getCanonicalDecl()); 1652 if (Pos == OverriddenMethods.end()) 1653 return overridden_method_range(nullptr, nullptr); 1654 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1655 } 1656 1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1658 const CXXMethodDecl *Overridden) { 1659 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1660 OverriddenMethods[Method].push_back(Overridden); 1661 } 1662 1663 void ASTContext::getOverriddenMethods( 1664 const NamedDecl *D, 1665 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1666 assert(D); 1667 1668 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1669 Overridden.append(overridden_methods_begin(CXXMethod), 1670 overridden_methods_end(CXXMethod)); 1671 return; 1672 } 1673 1674 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1675 if (!Method) 1676 return; 1677 1678 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1679 Method->getOverriddenMethods(OverDecls); 1680 Overridden.append(OverDecls.begin(), OverDecls.end()); 1681 } 1682 1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1684 assert(!Import->getNextLocalImport() && 1685 "Import declaration already in the chain"); 1686 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1687 if (!FirstLocalImport) { 1688 FirstLocalImport = Import; 1689 LastLocalImport = Import; 1690 return; 1691 } 1692 1693 LastLocalImport->setNextLocalImport(Import); 1694 LastLocalImport = Import; 1695 } 1696 1697 //===----------------------------------------------------------------------===// 1698 // Type Sizing and Analysis 1699 //===----------------------------------------------------------------------===// 1700 1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1702 /// scalar floating point type. 1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1704 switch (T->castAs<BuiltinType>()->getKind()) { 1705 default: 1706 llvm_unreachable("Not a floating point type!"); 1707 case BuiltinType::BFloat16: 1708 return Target->getBFloat16Format(); 1709 case BuiltinType::Float16: 1710 case BuiltinType::Half: 1711 return Target->getHalfFormat(); 1712 case BuiltinType::Float: return Target->getFloatFormat(); 1713 case BuiltinType::Double: return Target->getDoubleFormat(); 1714 case BuiltinType::Ibm128: 1715 return Target->getIbm128Format(); 1716 case BuiltinType::LongDouble: 1717 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1718 return AuxTarget->getLongDoubleFormat(); 1719 return Target->getLongDoubleFormat(); 1720 case BuiltinType::Float128: 1721 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1722 return AuxTarget->getFloat128Format(); 1723 return Target->getFloat128Format(); 1724 } 1725 } 1726 1727 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1728 unsigned Align = Target->getCharWidth(); 1729 1730 bool UseAlignAttrOnly = false; 1731 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1732 Align = AlignFromAttr; 1733 1734 // __attribute__((aligned)) can increase or decrease alignment 1735 // *except* on a struct or struct member, where it only increases 1736 // alignment unless 'packed' is also specified. 1737 // 1738 // It is an error for alignas to decrease alignment, so we can 1739 // ignore that possibility; Sema should diagnose it. 1740 if (isa<FieldDecl>(D)) { 1741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1743 } else { 1744 UseAlignAttrOnly = true; 1745 } 1746 } 1747 else if (isa<FieldDecl>(D)) 1748 UseAlignAttrOnly = 1749 D->hasAttr<PackedAttr>() || 1750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1751 1752 // If we're using the align attribute only, just ignore everything 1753 // else about the declaration and its type. 1754 if (UseAlignAttrOnly) { 1755 // do nothing 1756 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1757 QualType T = VD->getType(); 1758 if (const auto *RT = T->getAs<ReferenceType>()) { 1759 if (ForAlignof) 1760 T = RT->getPointeeType(); 1761 else 1762 T = getPointerType(RT->getPointeeType()); 1763 } 1764 QualType BaseT = getBaseElementType(T); 1765 if (T->isFunctionType()) 1766 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1767 else if (!BaseT->isIncompleteType()) { 1768 // Adjust alignments of declarations with array type by the 1769 // large-array alignment on the target. 1770 if (const ArrayType *arrayType = getAsArrayType(T)) { 1771 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1772 if (!ForAlignof && MinWidth) { 1773 if (isa<VariableArrayType>(arrayType)) 1774 Align = std::max(Align, Target->getLargeArrayAlign()); 1775 else if (isa<ConstantArrayType>(arrayType) && 1776 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1777 Align = std::max(Align, Target->getLargeArrayAlign()); 1778 } 1779 } 1780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1781 if (BaseT.getQualifiers().hasUnaligned()) 1782 Align = Target->getCharWidth(); 1783 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1784 if (VD->hasGlobalStorage() && !ForAlignof) { 1785 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1786 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1787 } 1788 } 1789 } 1790 1791 // Fields can be subject to extra alignment constraints, like if 1792 // the field is packed, the struct is packed, or the struct has a 1793 // a max-field-alignment constraint (#pragma pack). So calculate 1794 // the actual alignment of the field within the struct, and then 1795 // (as we're expected to) constrain that by the alignment of the type. 1796 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1797 const RecordDecl *Parent = Field->getParent(); 1798 // We can only produce a sensible answer if the record is valid. 1799 if (!Parent->isInvalidDecl()) { 1800 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1801 1802 // Start with the record's overall alignment. 1803 unsigned FieldAlign = toBits(Layout.getAlignment()); 1804 1805 // Use the GCD of that and the offset within the record. 1806 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1807 if (Offset > 0) { 1808 // Alignment is always a power of 2, so the GCD will be a power of 2, 1809 // which means we get to do this crazy thing instead of Euclid's. 1810 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1811 if (LowBitOfOffset < FieldAlign) 1812 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1813 } 1814 1815 Align = std::min(Align, FieldAlign); 1816 } 1817 } 1818 } 1819 1820 // Some targets have hard limitation on the maximum requestable alignment in 1821 // aligned attribute for static variables. 1822 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1823 const auto *VD = dyn_cast<VarDecl>(D); 1824 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1825 Align = std::min(Align, MaxAlignedAttr); 1826 1827 return toCharUnitsFromBits(Align); 1828 } 1829 1830 CharUnits ASTContext::getExnObjectAlignment() const { 1831 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1832 } 1833 1834 // getTypeInfoDataSizeInChars - Return the size of a type, in 1835 // chars. If the type is a record, its data size is returned. This is 1836 // the size of the memcpy that's performed when assigning this type 1837 // using a trivial copy/move assignment operator. 1838 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1839 TypeInfoChars Info = getTypeInfoInChars(T); 1840 1841 // In C++, objects can sometimes be allocated into the tail padding 1842 // of a base-class subobject. We decide whether that's possible 1843 // during class layout, so here we can just trust the layout results. 1844 if (getLangOpts().CPlusPlus) { 1845 if (const auto *RT = T->getAs<RecordType>()) { 1846 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1847 Info.Width = layout.getDataSize(); 1848 } 1849 } 1850 1851 return Info; 1852 } 1853 1854 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1855 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1856 TypeInfoChars 1857 static getConstantArrayInfoInChars(const ASTContext &Context, 1858 const ConstantArrayType *CAT) { 1859 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1860 uint64_t Size = CAT->getSize().getZExtValue(); 1861 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1862 (uint64_t)(-1)/Size) && 1863 "Overflow in array type char size evaluation"); 1864 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1865 unsigned Align = EltInfo.Align.getQuantity(); 1866 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1867 Context.getTargetInfo().getPointerWidth(0) == 64) 1868 Width = llvm::alignTo(Width, Align); 1869 return TypeInfoChars(CharUnits::fromQuantity(Width), 1870 CharUnits::fromQuantity(Align), 1871 EltInfo.AlignRequirement); 1872 } 1873 1874 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1875 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1876 return getConstantArrayInfoInChars(*this, CAT); 1877 TypeInfo Info = getTypeInfo(T); 1878 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1879 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1880 } 1881 1882 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1883 return getTypeInfoInChars(T.getTypePtr()); 1884 } 1885 1886 bool ASTContext::isAlignmentRequired(const Type *T) const { 1887 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1888 } 1889 1890 bool ASTContext::isAlignmentRequired(QualType T) const { 1891 return isAlignmentRequired(T.getTypePtr()); 1892 } 1893 1894 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1895 bool NeedsPreferredAlignment) const { 1896 // An alignment on a typedef overrides anything else. 1897 if (const auto *TT = T->getAs<TypedefType>()) 1898 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1899 return Align; 1900 1901 // If we have an (array of) complete type, we're done. 1902 T = getBaseElementType(T); 1903 if (!T->isIncompleteType()) 1904 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1905 1906 // If we had an array type, its element type might be a typedef 1907 // type with an alignment attribute. 1908 if (const auto *TT = T->getAs<TypedefType>()) 1909 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1910 return Align; 1911 1912 // Otherwise, see if the declaration of the type had an attribute. 1913 if (const auto *TT = T->getAs<TagType>()) 1914 return TT->getDecl()->getMaxAlignment(); 1915 1916 return 0; 1917 } 1918 1919 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1920 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1921 if (I != MemoizedTypeInfo.end()) 1922 return I->second; 1923 1924 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1925 TypeInfo TI = getTypeInfoImpl(T); 1926 MemoizedTypeInfo[T] = TI; 1927 return TI; 1928 } 1929 1930 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1931 /// method does not work on incomplete types. 1932 /// 1933 /// FIXME: Pointers into different addr spaces could have different sizes and 1934 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1935 /// should take a QualType, &c. 1936 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1937 uint64_t Width = 0; 1938 unsigned Align = 8; 1939 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1940 unsigned AS = 0; 1941 switch (T->getTypeClass()) { 1942 #define TYPE(Class, Base) 1943 #define ABSTRACT_TYPE(Class, Base) 1944 #define NON_CANONICAL_TYPE(Class, Base) 1945 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1947 case Type::Class: \ 1948 assert(!T->isDependentType() && "should not see dependent types here"); \ 1949 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1950 #include "clang/AST/TypeNodes.inc" 1951 llvm_unreachable("Should not see dependent types"); 1952 1953 case Type::FunctionNoProto: 1954 case Type::FunctionProto: 1955 // GCC extension: alignof(function) = 32 bits 1956 Width = 0; 1957 Align = 32; 1958 break; 1959 1960 case Type::IncompleteArray: 1961 case Type::VariableArray: 1962 case Type::ConstantArray: { 1963 // Model non-constant sized arrays as size zero, but track the alignment. 1964 uint64_t Size = 0; 1965 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1966 Size = CAT->getSize().getZExtValue(); 1967 1968 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1969 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1970 "Overflow in array type bit size evaluation"); 1971 Width = EltInfo.Width * Size; 1972 Align = EltInfo.Align; 1973 AlignRequirement = EltInfo.AlignRequirement; 1974 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1975 getTargetInfo().getPointerWidth(0) == 64) 1976 Width = llvm::alignTo(Width, Align); 1977 break; 1978 } 1979 1980 case Type::ExtVector: 1981 case Type::Vector: { 1982 const auto *VT = cast<VectorType>(T); 1983 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1984 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 1985 : EltInfo.Width * VT->getNumElements(); 1986 // Enforce at least byte alignment. 1987 Align = std::max<unsigned>(8, Width); 1988 1989 // If the alignment is not a power of 2, round up to the next power of 2. 1990 // This happens for non-power-of-2 length vectors. 1991 if (Align & (Align-1)) { 1992 Align = llvm::NextPowerOf2(Align); 1993 Width = llvm::alignTo(Width, Align); 1994 } 1995 // Adjust the alignment based on the target max. 1996 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1997 if (TargetVectorAlign && TargetVectorAlign < Align) 1998 Align = TargetVectorAlign; 1999 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 2000 // Adjust the alignment for fixed-length SVE vectors. This is important 2001 // for non-power-of-2 vector lengths. 2002 Align = 128; 2003 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2004 // Adjust the alignment for fixed-length SVE predicates. 2005 Align = 16; 2006 break; 2007 } 2008 2009 case Type::ConstantMatrix: { 2010 const auto *MT = cast<ConstantMatrixType>(T); 2011 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2012 // The internal layout of a matrix value is implementation defined. 2013 // Initially be ABI compatible with arrays with respect to alignment and 2014 // size. 2015 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2016 Align = ElementInfo.Align; 2017 break; 2018 } 2019 2020 case Type::Builtin: 2021 switch (cast<BuiltinType>(T)->getKind()) { 2022 default: llvm_unreachable("Unknown builtin type!"); 2023 case BuiltinType::Void: 2024 // GCC extension: alignof(void) = 8 bits. 2025 Width = 0; 2026 Align = 8; 2027 break; 2028 case BuiltinType::Bool: 2029 Width = Target->getBoolWidth(); 2030 Align = Target->getBoolAlign(); 2031 break; 2032 case BuiltinType::Char_S: 2033 case BuiltinType::Char_U: 2034 case BuiltinType::UChar: 2035 case BuiltinType::SChar: 2036 case BuiltinType::Char8: 2037 Width = Target->getCharWidth(); 2038 Align = Target->getCharAlign(); 2039 break; 2040 case BuiltinType::WChar_S: 2041 case BuiltinType::WChar_U: 2042 Width = Target->getWCharWidth(); 2043 Align = Target->getWCharAlign(); 2044 break; 2045 case BuiltinType::Char16: 2046 Width = Target->getChar16Width(); 2047 Align = Target->getChar16Align(); 2048 break; 2049 case BuiltinType::Char32: 2050 Width = Target->getChar32Width(); 2051 Align = Target->getChar32Align(); 2052 break; 2053 case BuiltinType::UShort: 2054 case BuiltinType::Short: 2055 Width = Target->getShortWidth(); 2056 Align = Target->getShortAlign(); 2057 break; 2058 case BuiltinType::UInt: 2059 case BuiltinType::Int: 2060 Width = Target->getIntWidth(); 2061 Align = Target->getIntAlign(); 2062 break; 2063 case BuiltinType::ULong: 2064 case BuiltinType::Long: 2065 Width = Target->getLongWidth(); 2066 Align = Target->getLongAlign(); 2067 break; 2068 case BuiltinType::ULongLong: 2069 case BuiltinType::LongLong: 2070 Width = Target->getLongLongWidth(); 2071 Align = Target->getLongLongAlign(); 2072 break; 2073 case BuiltinType::Int128: 2074 case BuiltinType::UInt128: 2075 Width = 128; 2076 Align = 128; // int128_t is 128-bit aligned on all targets. 2077 break; 2078 case BuiltinType::ShortAccum: 2079 case BuiltinType::UShortAccum: 2080 case BuiltinType::SatShortAccum: 2081 case BuiltinType::SatUShortAccum: 2082 Width = Target->getShortAccumWidth(); 2083 Align = Target->getShortAccumAlign(); 2084 break; 2085 case BuiltinType::Accum: 2086 case BuiltinType::UAccum: 2087 case BuiltinType::SatAccum: 2088 case BuiltinType::SatUAccum: 2089 Width = Target->getAccumWidth(); 2090 Align = Target->getAccumAlign(); 2091 break; 2092 case BuiltinType::LongAccum: 2093 case BuiltinType::ULongAccum: 2094 case BuiltinType::SatLongAccum: 2095 case BuiltinType::SatULongAccum: 2096 Width = Target->getLongAccumWidth(); 2097 Align = Target->getLongAccumAlign(); 2098 break; 2099 case BuiltinType::ShortFract: 2100 case BuiltinType::UShortFract: 2101 case BuiltinType::SatShortFract: 2102 case BuiltinType::SatUShortFract: 2103 Width = Target->getShortFractWidth(); 2104 Align = Target->getShortFractAlign(); 2105 break; 2106 case BuiltinType::Fract: 2107 case BuiltinType::UFract: 2108 case BuiltinType::SatFract: 2109 case BuiltinType::SatUFract: 2110 Width = Target->getFractWidth(); 2111 Align = Target->getFractAlign(); 2112 break; 2113 case BuiltinType::LongFract: 2114 case BuiltinType::ULongFract: 2115 case BuiltinType::SatLongFract: 2116 case BuiltinType::SatULongFract: 2117 Width = Target->getLongFractWidth(); 2118 Align = Target->getLongFractAlign(); 2119 break; 2120 case BuiltinType::BFloat16: 2121 if (Target->hasBFloat16Type()) { 2122 Width = Target->getBFloat16Width(); 2123 Align = Target->getBFloat16Align(); 2124 } 2125 break; 2126 case BuiltinType::Float16: 2127 case BuiltinType::Half: 2128 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2129 !getLangOpts().OpenMPIsDevice) { 2130 Width = Target->getHalfWidth(); 2131 Align = Target->getHalfAlign(); 2132 } else { 2133 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2134 "Expected OpenMP device compilation."); 2135 Width = AuxTarget->getHalfWidth(); 2136 Align = AuxTarget->getHalfAlign(); 2137 } 2138 break; 2139 case BuiltinType::Float: 2140 Width = Target->getFloatWidth(); 2141 Align = Target->getFloatAlign(); 2142 break; 2143 case BuiltinType::Double: 2144 Width = Target->getDoubleWidth(); 2145 Align = Target->getDoubleAlign(); 2146 break; 2147 case BuiltinType::Ibm128: 2148 Width = Target->getIbm128Width(); 2149 Align = Target->getIbm128Align(); 2150 break; 2151 case BuiltinType::LongDouble: 2152 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2153 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2154 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2155 Width = AuxTarget->getLongDoubleWidth(); 2156 Align = AuxTarget->getLongDoubleAlign(); 2157 } else { 2158 Width = Target->getLongDoubleWidth(); 2159 Align = Target->getLongDoubleAlign(); 2160 } 2161 break; 2162 case BuiltinType::Float128: 2163 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2164 !getLangOpts().OpenMPIsDevice) { 2165 Width = Target->getFloat128Width(); 2166 Align = Target->getFloat128Align(); 2167 } else { 2168 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2169 "Expected OpenMP device compilation."); 2170 Width = AuxTarget->getFloat128Width(); 2171 Align = AuxTarget->getFloat128Align(); 2172 } 2173 break; 2174 case BuiltinType::NullPtr: 2175 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2176 Align = Target->getPointerAlign(0); // == sizeof(void*) 2177 break; 2178 case BuiltinType::ObjCId: 2179 case BuiltinType::ObjCClass: 2180 case BuiltinType::ObjCSel: 2181 Width = Target->getPointerWidth(0); 2182 Align = Target->getPointerAlign(0); 2183 break; 2184 case BuiltinType::OCLSampler: 2185 case BuiltinType::OCLEvent: 2186 case BuiltinType::OCLClkEvent: 2187 case BuiltinType::OCLQueue: 2188 case BuiltinType::OCLReserveID: 2189 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2190 case BuiltinType::Id: 2191 #include "clang/Basic/OpenCLImageTypes.def" 2192 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2193 case BuiltinType::Id: 2194 #include "clang/Basic/OpenCLExtensionTypes.def" 2195 AS = getTargetAddressSpace( 2196 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2197 Width = Target->getPointerWidth(AS); 2198 Align = Target->getPointerAlign(AS); 2199 break; 2200 // The SVE types are effectively target-specific. The length of an 2201 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2202 // of 128 bits. There is one predicate bit for each vector byte, so the 2203 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2204 // 2205 // Because the length is only known at runtime, we use a dummy value 2206 // of 0 for the static length. The alignment values are those defined 2207 // by the Procedure Call Standard for the Arm Architecture. 2208 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2209 IsSigned, IsFP, IsBF) \ 2210 case BuiltinType::Id: \ 2211 Width = 0; \ 2212 Align = 128; \ 2213 break; 2214 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2215 case BuiltinType::Id: \ 2216 Width = 0; \ 2217 Align = 16; \ 2218 break; 2219 #include "clang/Basic/AArch64SVEACLETypes.def" 2220 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2221 case BuiltinType::Id: \ 2222 Width = Size; \ 2223 Align = Size; \ 2224 break; 2225 #include "clang/Basic/PPCTypes.def" 2226 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2227 IsFP) \ 2228 case BuiltinType::Id: \ 2229 Width = 0; \ 2230 Align = ElBits; \ 2231 break; 2232 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2233 case BuiltinType::Id: \ 2234 Width = 0; \ 2235 Align = 8; \ 2236 break; 2237 #include "clang/Basic/RISCVVTypes.def" 2238 } 2239 break; 2240 case Type::ObjCObjectPointer: 2241 Width = Target->getPointerWidth(0); 2242 Align = Target->getPointerAlign(0); 2243 break; 2244 case Type::BlockPointer: 2245 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2246 Width = Target->getPointerWidth(AS); 2247 Align = Target->getPointerAlign(AS); 2248 break; 2249 case Type::LValueReference: 2250 case Type::RValueReference: 2251 // alignof and sizeof should never enter this code path here, so we go 2252 // the pointer route. 2253 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2254 Width = Target->getPointerWidth(AS); 2255 Align = Target->getPointerAlign(AS); 2256 break; 2257 case Type::Pointer: 2258 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2259 Width = Target->getPointerWidth(AS); 2260 Align = Target->getPointerAlign(AS); 2261 break; 2262 case Type::MemberPointer: { 2263 const auto *MPT = cast<MemberPointerType>(T); 2264 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2265 Width = MPI.Width; 2266 Align = MPI.Align; 2267 break; 2268 } 2269 case Type::Complex: { 2270 // Complex types have the same alignment as their elements, but twice the 2271 // size. 2272 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2273 Width = EltInfo.Width * 2; 2274 Align = EltInfo.Align; 2275 break; 2276 } 2277 case Type::ObjCObject: 2278 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2279 case Type::Adjusted: 2280 case Type::Decayed: 2281 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2282 case Type::ObjCInterface: { 2283 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2284 if (ObjCI->getDecl()->isInvalidDecl()) { 2285 Width = 8; 2286 Align = 8; 2287 break; 2288 } 2289 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2290 Width = toBits(Layout.getSize()); 2291 Align = toBits(Layout.getAlignment()); 2292 break; 2293 } 2294 case Type::BitInt: { 2295 const auto *EIT = cast<BitIntType>(T); 2296 Align = 2297 std::min(static_cast<unsigned>(std::max( 2298 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2299 Target->getLongLongAlign()); 2300 Width = llvm::alignTo(EIT->getNumBits(), Align); 2301 break; 2302 } 2303 case Type::Record: 2304 case Type::Enum: { 2305 const auto *TT = cast<TagType>(T); 2306 2307 if (TT->getDecl()->isInvalidDecl()) { 2308 Width = 8; 2309 Align = 8; 2310 break; 2311 } 2312 2313 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2314 const EnumDecl *ED = ET->getDecl(); 2315 TypeInfo Info = 2316 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2317 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2318 Info.Align = AttrAlign; 2319 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2320 } 2321 return Info; 2322 } 2323 2324 const auto *RT = cast<RecordType>(TT); 2325 const RecordDecl *RD = RT->getDecl(); 2326 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2327 Width = toBits(Layout.getSize()); 2328 Align = toBits(Layout.getAlignment()); 2329 AlignRequirement = RD->hasAttr<AlignedAttr>() 2330 ? AlignRequirementKind::RequiredByRecord 2331 : AlignRequirementKind::None; 2332 break; 2333 } 2334 2335 case Type::SubstTemplateTypeParm: 2336 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2337 getReplacementType().getTypePtr()); 2338 2339 case Type::Auto: 2340 case Type::DeducedTemplateSpecialization: { 2341 const auto *A = cast<DeducedType>(T); 2342 assert(!A->getDeducedType().isNull() && 2343 "cannot request the size of an undeduced or dependent auto type"); 2344 return getTypeInfo(A->getDeducedType().getTypePtr()); 2345 } 2346 2347 case Type::Paren: 2348 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2349 2350 case Type::MacroQualified: 2351 return getTypeInfo( 2352 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2353 2354 case Type::ObjCTypeParam: 2355 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2356 2357 case Type::Using: 2358 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2359 2360 case Type::Typedef: { 2361 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2362 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2363 // If the typedef has an aligned attribute on it, it overrides any computed 2364 // alignment we have. This violates the GCC documentation (which says that 2365 // attribute(aligned) can only round up) but matches its implementation. 2366 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2367 Align = AttrAlign; 2368 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2369 } else { 2370 Align = Info.Align; 2371 AlignRequirement = Info.AlignRequirement; 2372 } 2373 Width = Info.Width; 2374 break; 2375 } 2376 2377 case Type::Elaborated: 2378 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2379 2380 case Type::Attributed: 2381 return getTypeInfo( 2382 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2383 2384 case Type::BTFTagAttributed: 2385 return getTypeInfo( 2386 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr()); 2387 2388 case Type::Atomic: { 2389 // Start with the base type information. 2390 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2391 Width = Info.Width; 2392 Align = Info.Align; 2393 2394 if (!Width) { 2395 // An otherwise zero-sized type should still generate an 2396 // atomic operation. 2397 Width = Target->getCharWidth(); 2398 assert(Align); 2399 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2400 // If the size of the type doesn't exceed the platform's max 2401 // atomic promotion width, make the size and alignment more 2402 // favorable to atomic operations: 2403 2404 // Round the size up to a power of 2. 2405 if (!llvm::isPowerOf2_64(Width)) 2406 Width = llvm::NextPowerOf2(Width); 2407 2408 // Set the alignment equal to the size. 2409 Align = static_cast<unsigned>(Width); 2410 } 2411 } 2412 break; 2413 2414 case Type::Pipe: 2415 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2416 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2417 break; 2418 } 2419 2420 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2421 return TypeInfo(Width, Align, AlignRequirement); 2422 } 2423 2424 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2425 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2426 if (I != MemoizedUnadjustedAlign.end()) 2427 return I->second; 2428 2429 unsigned UnadjustedAlign; 2430 if (const auto *RT = T->getAs<RecordType>()) { 2431 const RecordDecl *RD = RT->getDecl(); 2432 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2433 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2434 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2435 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2436 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2437 } else { 2438 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2439 } 2440 2441 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2442 return UnadjustedAlign; 2443 } 2444 2445 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2446 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2447 return SimdAlign; 2448 } 2449 2450 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2451 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2452 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2453 } 2454 2455 /// toBits - Convert a size in characters to a size in characters. 2456 int64_t ASTContext::toBits(CharUnits CharSize) const { 2457 return CharSize.getQuantity() * getCharWidth(); 2458 } 2459 2460 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2461 /// This method does not work on incomplete types. 2462 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2463 return getTypeInfoInChars(T).Width; 2464 } 2465 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2466 return getTypeInfoInChars(T).Width; 2467 } 2468 2469 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2470 /// characters. This method does not work on incomplete types. 2471 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2472 return toCharUnitsFromBits(getTypeAlign(T)); 2473 } 2474 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2475 return toCharUnitsFromBits(getTypeAlign(T)); 2476 } 2477 2478 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2479 /// type, in characters, before alignment adustments. This method does 2480 /// not work on incomplete types. 2481 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2482 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2483 } 2484 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2485 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2486 } 2487 2488 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2489 /// type for the current target in bits. This can be different than the ABI 2490 /// alignment in cases where it is beneficial for performance or backwards 2491 /// compatibility preserving to overalign a data type. (Note: despite the name, 2492 /// the preferred alignment is ABI-impacting, and not an optimization.) 2493 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2494 TypeInfo TI = getTypeInfo(T); 2495 unsigned ABIAlign = TI.Align; 2496 2497 T = T->getBaseElementTypeUnsafe(); 2498 2499 // The preferred alignment of member pointers is that of a pointer. 2500 if (T->isMemberPointerType()) 2501 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2502 2503 if (!Target->allowsLargerPreferedTypeAlignment()) 2504 return ABIAlign; 2505 2506 if (const auto *RT = T->getAs<RecordType>()) { 2507 const RecordDecl *RD = RT->getDecl(); 2508 2509 // When used as part of a typedef, or together with a 'packed' attribute, 2510 // the 'aligned' attribute can be used to decrease alignment. Note that the 2511 // 'packed' case is already taken into consideration when computing the 2512 // alignment, we only need to handle the typedef case here. 2513 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2514 RD->isInvalidDecl()) 2515 return ABIAlign; 2516 2517 unsigned PreferredAlign = static_cast<unsigned>( 2518 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2519 assert(PreferredAlign >= ABIAlign && 2520 "PreferredAlign should be at least as large as ABIAlign."); 2521 return PreferredAlign; 2522 } 2523 2524 // Double (and, for targets supporting AIX `power` alignment, long double) and 2525 // long long should be naturally aligned (despite requiring less alignment) if 2526 // possible. 2527 if (const auto *CT = T->getAs<ComplexType>()) 2528 T = CT->getElementType().getTypePtr(); 2529 if (const auto *ET = T->getAs<EnumType>()) 2530 T = ET->getDecl()->getIntegerType().getTypePtr(); 2531 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2532 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2533 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2534 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2535 Target->defaultsToAIXPowerAlignment())) 2536 // Don't increase the alignment if an alignment attribute was specified on a 2537 // typedef declaration. 2538 if (!TI.isAlignRequired()) 2539 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2540 2541 return ABIAlign; 2542 } 2543 2544 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2545 /// for __attribute__((aligned)) on this target, to be used if no alignment 2546 /// value is specified. 2547 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2548 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2549 } 2550 2551 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2552 /// to a global variable of the specified type. 2553 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2554 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2555 return std::max(getPreferredTypeAlign(T), 2556 getTargetInfo().getMinGlobalAlign(TypeSize)); 2557 } 2558 2559 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2560 /// should be given to a global variable of the specified type. 2561 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2562 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2563 } 2564 2565 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2566 CharUnits Offset = CharUnits::Zero(); 2567 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2568 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2569 Offset += Layout->getBaseClassOffset(Base); 2570 Layout = &getASTRecordLayout(Base); 2571 } 2572 return Offset; 2573 } 2574 2575 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2576 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2577 CharUnits ThisAdjustment = CharUnits::Zero(); 2578 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2579 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2580 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2581 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2582 const CXXRecordDecl *Base = RD; 2583 const CXXRecordDecl *Derived = Path[I]; 2584 if (DerivedMember) 2585 std::swap(Base, Derived); 2586 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2587 RD = Path[I]; 2588 } 2589 if (DerivedMember) 2590 ThisAdjustment = -ThisAdjustment; 2591 return ThisAdjustment; 2592 } 2593 2594 /// DeepCollectObjCIvars - 2595 /// This routine first collects all declared, but not synthesized, ivars in 2596 /// super class and then collects all ivars, including those synthesized for 2597 /// current class. This routine is used for implementation of current class 2598 /// when all ivars, declared and synthesized are known. 2599 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2600 bool leafClass, 2601 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2602 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2603 DeepCollectObjCIvars(SuperClass, false, Ivars); 2604 if (!leafClass) { 2605 llvm::append_range(Ivars, OI->ivars()); 2606 } else { 2607 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2608 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2609 Iv= Iv->getNextIvar()) 2610 Ivars.push_back(Iv); 2611 } 2612 } 2613 2614 /// CollectInheritedProtocols - Collect all protocols in current class and 2615 /// those inherited by it. 2616 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2617 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2618 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2619 // We can use protocol_iterator here instead of 2620 // all_referenced_protocol_iterator since we are walking all categories. 2621 for (auto *Proto : OI->all_referenced_protocols()) { 2622 CollectInheritedProtocols(Proto, Protocols); 2623 } 2624 2625 // Categories of this Interface. 2626 for (const auto *Cat : OI->visible_categories()) 2627 CollectInheritedProtocols(Cat, Protocols); 2628 2629 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2630 while (SD) { 2631 CollectInheritedProtocols(SD, Protocols); 2632 SD = SD->getSuperClass(); 2633 } 2634 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2635 for (auto *Proto : OC->protocols()) { 2636 CollectInheritedProtocols(Proto, Protocols); 2637 } 2638 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2639 // Insert the protocol. 2640 if (!Protocols.insert( 2641 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2642 return; 2643 2644 for (auto *Proto : OP->protocols()) 2645 CollectInheritedProtocols(Proto, Protocols); 2646 } 2647 } 2648 2649 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2650 const RecordDecl *RD) { 2651 assert(RD->isUnion() && "Must be union type"); 2652 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2653 2654 for (const auto *Field : RD->fields()) { 2655 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2656 return false; 2657 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2658 if (FieldSize != UnionSize) 2659 return false; 2660 } 2661 return !RD->field_empty(); 2662 } 2663 2664 static int64_t getSubobjectOffset(const FieldDecl *Field, 2665 const ASTContext &Context, 2666 const clang::ASTRecordLayout & /*Layout*/) { 2667 return Context.getFieldOffset(Field); 2668 } 2669 2670 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2671 const ASTContext &Context, 2672 const clang::ASTRecordLayout &Layout) { 2673 return Context.toBits(Layout.getBaseClassOffset(RD)); 2674 } 2675 2676 static llvm::Optional<int64_t> 2677 structHasUniqueObjectRepresentations(const ASTContext &Context, 2678 const RecordDecl *RD); 2679 2680 static llvm::Optional<int64_t> 2681 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2682 if (Field->getType()->isRecordType()) { 2683 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2684 if (!RD->isUnion()) 2685 return structHasUniqueObjectRepresentations(Context, RD); 2686 } 2687 if (!Field->getType()->isReferenceType() && 2688 !Context.hasUniqueObjectRepresentations(Field->getType())) 2689 return llvm::None; 2690 2691 int64_t FieldSizeInBits = 2692 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2693 if (Field->isBitField()) { 2694 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2695 if (BitfieldSize > FieldSizeInBits) 2696 return llvm::None; 2697 FieldSizeInBits = BitfieldSize; 2698 } 2699 return FieldSizeInBits; 2700 } 2701 2702 static llvm::Optional<int64_t> 2703 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2704 return structHasUniqueObjectRepresentations(Context, RD); 2705 } 2706 2707 template <typename RangeT> 2708 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2709 const RangeT &Subobjects, int64_t CurOffsetInBits, 2710 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2711 for (const auto *Subobject : Subobjects) { 2712 llvm::Optional<int64_t> SizeInBits = 2713 getSubobjectSizeInBits(Subobject, Context); 2714 if (!SizeInBits) 2715 return llvm::None; 2716 if (*SizeInBits != 0) { 2717 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2718 if (Offset != CurOffsetInBits) 2719 return llvm::None; 2720 CurOffsetInBits += *SizeInBits; 2721 } 2722 } 2723 return CurOffsetInBits; 2724 } 2725 2726 static llvm::Optional<int64_t> 2727 structHasUniqueObjectRepresentations(const ASTContext &Context, 2728 const RecordDecl *RD) { 2729 assert(!RD->isUnion() && "Must be struct/class type"); 2730 const auto &Layout = Context.getASTRecordLayout(RD); 2731 2732 int64_t CurOffsetInBits = 0; 2733 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2734 if (ClassDecl->isDynamicClass()) 2735 return llvm::None; 2736 2737 SmallVector<CXXRecordDecl *, 4> Bases; 2738 for (const auto &Base : ClassDecl->bases()) { 2739 // Empty types can be inherited from, and non-empty types can potentially 2740 // have tail padding, so just make sure there isn't an error. 2741 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2742 } 2743 2744 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2745 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2746 }); 2747 2748 llvm::Optional<int64_t> OffsetAfterBases = 2749 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2750 Context, Layout); 2751 if (!OffsetAfterBases) 2752 return llvm::None; 2753 CurOffsetInBits = *OffsetAfterBases; 2754 } 2755 2756 llvm::Optional<int64_t> OffsetAfterFields = 2757 structSubobjectsHaveUniqueObjectRepresentations( 2758 RD->fields(), CurOffsetInBits, Context, Layout); 2759 if (!OffsetAfterFields) 2760 return llvm::None; 2761 CurOffsetInBits = *OffsetAfterFields; 2762 2763 return CurOffsetInBits; 2764 } 2765 2766 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2767 // C++17 [meta.unary.prop]: 2768 // The predicate condition for a template specialization 2769 // has_unique_object_representations<T> shall be 2770 // satisfied if and only if: 2771 // (9.1) - T is trivially copyable, and 2772 // (9.2) - any two objects of type T with the same value have the same 2773 // object representation, where two objects 2774 // of array or non-union class type are considered to have the same value 2775 // if their respective sequences of 2776 // direct subobjects have the same values, and two objects of union type 2777 // are considered to have the same 2778 // value if they have the same active member and the corresponding members 2779 // have the same value. 2780 // The set of scalar types for which this condition holds is 2781 // implementation-defined. [ Note: If a type has padding 2782 // bits, the condition does not hold; otherwise, the condition holds true 2783 // for unsigned integral types. -- end note ] 2784 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2785 2786 // Arrays are unique only if their element type is unique. 2787 if (Ty->isArrayType()) 2788 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2789 2790 // (9.1) - T is trivially copyable... 2791 if (!Ty.isTriviallyCopyableType(*this)) 2792 return false; 2793 2794 // All integrals and enums are unique. 2795 if (Ty->isIntegralOrEnumerationType()) 2796 return true; 2797 2798 // All other pointers are unique. 2799 if (Ty->isPointerType()) 2800 return true; 2801 2802 if (Ty->isMemberPointerType()) { 2803 const auto *MPT = Ty->getAs<MemberPointerType>(); 2804 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2805 } 2806 2807 if (Ty->isRecordType()) { 2808 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2809 2810 if (Record->isInvalidDecl()) 2811 return false; 2812 2813 if (Record->isUnion()) 2814 return unionHasUniqueObjectRepresentations(*this, Record); 2815 2816 Optional<int64_t> StructSize = 2817 structHasUniqueObjectRepresentations(*this, Record); 2818 2819 return StructSize && 2820 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2821 } 2822 2823 // FIXME: More cases to handle here (list by rsmith): 2824 // vectors (careful about, eg, vector of 3 foo) 2825 // _Complex int and friends 2826 // _Atomic T 2827 // Obj-C block pointers 2828 // Obj-C object pointers 2829 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2830 // clk_event_t, queue_t, reserve_id_t) 2831 // There're also Obj-C class types and the Obj-C selector type, but I think it 2832 // makes sense for those to return false here. 2833 2834 return false; 2835 } 2836 2837 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2838 unsigned count = 0; 2839 // Count ivars declared in class extension. 2840 for (const auto *Ext : OI->known_extensions()) 2841 count += Ext->ivar_size(); 2842 2843 // Count ivar defined in this class's implementation. This 2844 // includes synthesized ivars. 2845 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2846 count += ImplDecl->ivar_size(); 2847 2848 return count; 2849 } 2850 2851 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2852 if (!E) 2853 return false; 2854 2855 // nullptr_t is always treated as null. 2856 if (E->getType()->isNullPtrType()) return true; 2857 2858 if (E->getType()->isAnyPointerType() && 2859 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2860 Expr::NPC_ValueDependentIsNull)) 2861 return true; 2862 2863 // Unfortunately, __null has type 'int'. 2864 if (isa<GNUNullExpr>(E)) return true; 2865 2866 return false; 2867 } 2868 2869 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2870 /// exists. 2871 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2872 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2873 I = ObjCImpls.find(D); 2874 if (I != ObjCImpls.end()) 2875 return cast<ObjCImplementationDecl>(I->second); 2876 return nullptr; 2877 } 2878 2879 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2880 /// exists. 2881 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2882 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2883 I = ObjCImpls.find(D); 2884 if (I != ObjCImpls.end()) 2885 return cast<ObjCCategoryImplDecl>(I->second); 2886 return nullptr; 2887 } 2888 2889 /// Set the implementation of ObjCInterfaceDecl. 2890 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2891 ObjCImplementationDecl *ImplD) { 2892 assert(IFaceD && ImplD && "Passed null params"); 2893 ObjCImpls[IFaceD] = ImplD; 2894 } 2895 2896 /// Set the implementation of ObjCCategoryDecl. 2897 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2898 ObjCCategoryImplDecl *ImplD) { 2899 assert(CatD && ImplD && "Passed null params"); 2900 ObjCImpls[CatD] = ImplD; 2901 } 2902 2903 const ObjCMethodDecl * 2904 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2905 return ObjCMethodRedecls.lookup(MD); 2906 } 2907 2908 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2909 const ObjCMethodDecl *Redecl) { 2910 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2911 ObjCMethodRedecls[MD] = Redecl; 2912 } 2913 2914 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2915 const NamedDecl *ND) const { 2916 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2917 return ID; 2918 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2919 return CD->getClassInterface(); 2920 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2921 return IMD->getClassInterface(); 2922 2923 return nullptr; 2924 } 2925 2926 /// Get the copy initialization expression of VarDecl, or nullptr if 2927 /// none exists. 2928 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2929 assert(VD && "Passed null params"); 2930 assert(VD->hasAttr<BlocksAttr>() && 2931 "getBlockVarCopyInits - not __block var"); 2932 auto I = BlockVarCopyInits.find(VD); 2933 if (I != BlockVarCopyInits.end()) 2934 return I->second; 2935 return {nullptr, false}; 2936 } 2937 2938 /// Set the copy initialization expression of a block var decl. 2939 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2940 bool CanThrow) { 2941 assert(VD && CopyExpr && "Passed null params"); 2942 assert(VD->hasAttr<BlocksAttr>() && 2943 "setBlockVarCopyInits - not __block var"); 2944 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2945 } 2946 2947 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2948 unsigned DataSize) const { 2949 if (!DataSize) 2950 DataSize = TypeLoc::getFullDataSizeForType(T); 2951 else 2952 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2953 "incorrect data size provided to CreateTypeSourceInfo!"); 2954 2955 auto *TInfo = 2956 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2957 new (TInfo) TypeSourceInfo(T); 2958 return TInfo; 2959 } 2960 2961 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2962 SourceLocation L) const { 2963 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2964 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2965 return DI; 2966 } 2967 2968 const ASTRecordLayout & 2969 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2970 return getObjCLayout(D, nullptr); 2971 } 2972 2973 const ASTRecordLayout & 2974 ASTContext::getASTObjCImplementationLayout( 2975 const ObjCImplementationDecl *D) const { 2976 return getObjCLayout(D->getClassInterface(), D); 2977 } 2978 2979 //===----------------------------------------------------------------------===// 2980 // Type creation/memoization methods 2981 //===----------------------------------------------------------------------===// 2982 2983 QualType 2984 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2985 unsigned fastQuals = quals.getFastQualifiers(); 2986 quals.removeFastQualifiers(); 2987 2988 // Check if we've already instantiated this type. 2989 llvm::FoldingSetNodeID ID; 2990 ExtQuals::Profile(ID, baseType, quals); 2991 void *insertPos = nullptr; 2992 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2993 assert(eq->getQualifiers() == quals); 2994 return QualType(eq, fastQuals); 2995 } 2996 2997 // If the base type is not canonical, make the appropriate canonical type. 2998 QualType canon; 2999 if (!baseType->isCanonicalUnqualified()) { 3000 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 3001 canonSplit.Quals.addConsistentQualifiers(quals); 3002 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 3003 3004 // Re-find the insert position. 3005 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3006 } 3007 3008 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3009 ExtQualNodes.InsertNode(eq, insertPos); 3010 return QualType(eq, fastQuals); 3011 } 3012 3013 QualType ASTContext::getAddrSpaceQualType(QualType T, 3014 LangAS AddressSpace) const { 3015 QualType CanT = getCanonicalType(T); 3016 if (CanT.getAddressSpace() == AddressSpace) 3017 return T; 3018 3019 // If we are composing extended qualifiers together, merge together 3020 // into one ExtQuals node. 3021 QualifierCollector Quals; 3022 const Type *TypeNode = Quals.strip(T); 3023 3024 // If this type already has an address space specified, it cannot get 3025 // another one. 3026 assert(!Quals.hasAddressSpace() && 3027 "Type cannot be in multiple addr spaces!"); 3028 Quals.addAddressSpace(AddressSpace); 3029 3030 return getExtQualType(TypeNode, Quals); 3031 } 3032 3033 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3034 // If the type is not qualified with an address space, just return it 3035 // immediately. 3036 if (!T.hasAddressSpace()) 3037 return T; 3038 3039 // If we are composing extended qualifiers together, merge together 3040 // into one ExtQuals node. 3041 QualifierCollector Quals; 3042 const Type *TypeNode; 3043 3044 while (T.hasAddressSpace()) { 3045 TypeNode = Quals.strip(T); 3046 3047 // If the type no longer has an address space after stripping qualifiers, 3048 // jump out. 3049 if (!QualType(TypeNode, 0).hasAddressSpace()) 3050 break; 3051 3052 // There might be sugar in the way. Strip it and try again. 3053 T = T.getSingleStepDesugaredType(*this); 3054 } 3055 3056 Quals.removeAddressSpace(); 3057 3058 // Removal of the address space can mean there are no longer any 3059 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3060 // or required. 3061 if (Quals.hasNonFastQualifiers()) 3062 return getExtQualType(TypeNode, Quals); 3063 else 3064 return QualType(TypeNode, Quals.getFastQualifiers()); 3065 } 3066 3067 QualType ASTContext::getObjCGCQualType(QualType T, 3068 Qualifiers::GC GCAttr) const { 3069 QualType CanT = getCanonicalType(T); 3070 if (CanT.getObjCGCAttr() == GCAttr) 3071 return T; 3072 3073 if (const auto *ptr = T->getAs<PointerType>()) { 3074 QualType Pointee = ptr->getPointeeType(); 3075 if (Pointee->isAnyPointerType()) { 3076 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3077 return getPointerType(ResultType); 3078 } 3079 } 3080 3081 // If we are composing extended qualifiers together, merge together 3082 // into one ExtQuals node. 3083 QualifierCollector Quals; 3084 const Type *TypeNode = Quals.strip(T); 3085 3086 // If this type already has an ObjCGC specified, it cannot get 3087 // another one. 3088 assert(!Quals.hasObjCGCAttr() && 3089 "Type cannot have multiple ObjCGCs!"); 3090 Quals.addObjCGCAttr(GCAttr); 3091 3092 return getExtQualType(TypeNode, Quals); 3093 } 3094 3095 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3096 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3097 QualType Pointee = Ptr->getPointeeType(); 3098 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3099 return getPointerType(removeAddrSpaceQualType(Pointee)); 3100 } 3101 } 3102 return T; 3103 } 3104 3105 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3106 FunctionType::ExtInfo Info) { 3107 if (T->getExtInfo() == Info) 3108 return T; 3109 3110 QualType Result; 3111 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3112 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3113 } else { 3114 const auto *FPT = cast<FunctionProtoType>(T); 3115 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3116 EPI.ExtInfo = Info; 3117 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3118 } 3119 3120 return cast<FunctionType>(Result.getTypePtr()); 3121 } 3122 3123 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3124 QualType ResultType) { 3125 FD = FD->getMostRecentDecl(); 3126 while (true) { 3127 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3128 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3129 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3130 if (FunctionDecl *Next = FD->getPreviousDecl()) 3131 FD = Next; 3132 else 3133 break; 3134 } 3135 if (ASTMutationListener *L = getASTMutationListener()) 3136 L->DeducedReturnType(FD, ResultType); 3137 } 3138 3139 /// Get a function type and produce the equivalent function type with the 3140 /// specified exception specification. Type sugar that can be present on a 3141 /// declaration of a function with an exception specification is permitted 3142 /// and preserved. Other type sugar (for instance, typedefs) is not. 3143 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3144 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3145 // Might have some parens. 3146 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3147 return getParenType( 3148 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3149 3150 // Might be wrapped in a macro qualified type. 3151 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3152 return getMacroQualifiedType( 3153 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3154 MQT->getMacroIdentifier()); 3155 3156 // Might have a calling-convention attribute. 3157 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3158 return getAttributedType( 3159 AT->getAttrKind(), 3160 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3161 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3162 3163 // Anything else must be a function type. Rebuild it with the new exception 3164 // specification. 3165 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3166 return getFunctionType( 3167 Proto->getReturnType(), Proto->getParamTypes(), 3168 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3169 } 3170 3171 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3172 QualType U) { 3173 return hasSameType(T, U) || 3174 (getLangOpts().CPlusPlus17 && 3175 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3176 getFunctionTypeWithExceptionSpec(U, EST_None))); 3177 } 3178 3179 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3180 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3181 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3182 SmallVector<QualType, 16> Args(Proto->param_types()); 3183 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3184 Args[i] = removePtrSizeAddrSpace(Args[i]); 3185 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3186 } 3187 3188 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3189 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3190 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3191 } 3192 3193 return T; 3194 } 3195 3196 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3197 return hasSameType(T, U) || 3198 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3199 getFunctionTypeWithoutPtrSizes(U)); 3200 } 3201 3202 void ASTContext::adjustExceptionSpec( 3203 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3204 bool AsWritten) { 3205 // Update the type. 3206 QualType Updated = 3207 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3208 FD->setType(Updated); 3209 3210 if (!AsWritten) 3211 return; 3212 3213 // Update the type in the type source information too. 3214 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3215 // If the type and the type-as-written differ, we may need to update 3216 // the type-as-written too. 3217 if (TSInfo->getType() != FD->getType()) 3218 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3219 3220 // FIXME: When we get proper type location information for exceptions, 3221 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3222 // up the TypeSourceInfo; 3223 assert(TypeLoc::getFullDataSizeForType(Updated) == 3224 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3225 "TypeLoc size mismatch from updating exception specification"); 3226 TSInfo->overrideType(Updated); 3227 } 3228 } 3229 3230 /// getComplexType - Return the uniqued reference to the type for a complex 3231 /// number with the specified element type. 3232 QualType ASTContext::getComplexType(QualType T) const { 3233 // Unique pointers, to guarantee there is only one pointer of a particular 3234 // structure. 3235 llvm::FoldingSetNodeID ID; 3236 ComplexType::Profile(ID, T); 3237 3238 void *InsertPos = nullptr; 3239 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3240 return QualType(CT, 0); 3241 3242 // If the pointee type isn't canonical, this won't be a canonical type either, 3243 // so fill in the canonical type field. 3244 QualType Canonical; 3245 if (!T.isCanonical()) { 3246 Canonical = getComplexType(getCanonicalType(T)); 3247 3248 // Get the new insert position for the node we care about. 3249 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3250 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3251 } 3252 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3253 Types.push_back(New); 3254 ComplexTypes.InsertNode(New, InsertPos); 3255 return QualType(New, 0); 3256 } 3257 3258 /// getPointerType - Return the uniqued reference to the type for a pointer to 3259 /// the specified type. 3260 QualType ASTContext::getPointerType(QualType T) const { 3261 // Unique pointers, to guarantee there is only one pointer of a particular 3262 // structure. 3263 llvm::FoldingSetNodeID ID; 3264 PointerType::Profile(ID, T); 3265 3266 void *InsertPos = nullptr; 3267 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3268 return QualType(PT, 0); 3269 3270 // If the pointee type isn't canonical, this won't be a canonical type either, 3271 // so fill in the canonical type field. 3272 QualType Canonical; 3273 if (!T.isCanonical()) { 3274 Canonical = getPointerType(getCanonicalType(T)); 3275 3276 // Get the new insert position for the node we care about. 3277 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3278 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3279 } 3280 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3281 Types.push_back(New); 3282 PointerTypes.InsertNode(New, InsertPos); 3283 return QualType(New, 0); 3284 } 3285 3286 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3287 llvm::FoldingSetNodeID ID; 3288 AdjustedType::Profile(ID, Orig, New); 3289 void *InsertPos = nullptr; 3290 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3291 if (AT) 3292 return QualType(AT, 0); 3293 3294 QualType Canonical = getCanonicalType(New); 3295 3296 // Get the new insert position for the node we care about. 3297 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3298 assert(!AT && "Shouldn't be in the map!"); 3299 3300 AT = new (*this, TypeAlignment) 3301 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3302 Types.push_back(AT); 3303 AdjustedTypes.InsertNode(AT, InsertPos); 3304 return QualType(AT, 0); 3305 } 3306 3307 QualType ASTContext::getDecayedType(QualType T) const { 3308 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3309 3310 QualType Decayed; 3311 3312 // C99 6.7.5.3p7: 3313 // A declaration of a parameter as "array of type" shall be 3314 // adjusted to "qualified pointer to type", where the type 3315 // qualifiers (if any) are those specified within the [ and ] of 3316 // the array type derivation. 3317 if (T->isArrayType()) 3318 Decayed = getArrayDecayedType(T); 3319 3320 // C99 6.7.5.3p8: 3321 // A declaration of a parameter as "function returning type" 3322 // shall be adjusted to "pointer to function returning type", as 3323 // in 6.3.2.1. 3324 if (T->isFunctionType()) 3325 Decayed = getPointerType(T); 3326 3327 llvm::FoldingSetNodeID ID; 3328 AdjustedType::Profile(ID, T, Decayed); 3329 void *InsertPos = nullptr; 3330 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3331 if (AT) 3332 return QualType(AT, 0); 3333 3334 QualType Canonical = getCanonicalType(Decayed); 3335 3336 // Get the new insert position for the node we care about. 3337 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3338 assert(!AT && "Shouldn't be in the map!"); 3339 3340 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3341 Types.push_back(AT); 3342 AdjustedTypes.InsertNode(AT, InsertPos); 3343 return QualType(AT, 0); 3344 } 3345 3346 /// getBlockPointerType - Return the uniqued reference to the type for 3347 /// a pointer to the specified block. 3348 QualType ASTContext::getBlockPointerType(QualType T) const { 3349 assert(T->isFunctionType() && "block of function types only"); 3350 // Unique pointers, to guarantee there is only one block of a particular 3351 // structure. 3352 llvm::FoldingSetNodeID ID; 3353 BlockPointerType::Profile(ID, T); 3354 3355 void *InsertPos = nullptr; 3356 if (BlockPointerType *PT = 3357 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3358 return QualType(PT, 0); 3359 3360 // If the block pointee type isn't canonical, this won't be a canonical 3361 // type either so fill in the canonical type field. 3362 QualType Canonical; 3363 if (!T.isCanonical()) { 3364 Canonical = getBlockPointerType(getCanonicalType(T)); 3365 3366 // Get the new insert position for the node we care about. 3367 BlockPointerType *NewIP = 3368 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3369 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3370 } 3371 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3372 Types.push_back(New); 3373 BlockPointerTypes.InsertNode(New, InsertPos); 3374 return QualType(New, 0); 3375 } 3376 3377 /// getLValueReferenceType - Return the uniqued reference to the type for an 3378 /// lvalue reference to the specified type. 3379 QualType 3380 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3381 assert((!T->isPlaceholderType() || 3382 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3383 "Unresolved placeholder type"); 3384 3385 // Unique pointers, to guarantee there is only one pointer of a particular 3386 // structure. 3387 llvm::FoldingSetNodeID ID; 3388 ReferenceType::Profile(ID, T, SpelledAsLValue); 3389 3390 void *InsertPos = nullptr; 3391 if (LValueReferenceType *RT = 3392 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3393 return QualType(RT, 0); 3394 3395 const auto *InnerRef = T->getAs<ReferenceType>(); 3396 3397 // If the referencee type isn't canonical, this won't be a canonical type 3398 // either, so fill in the canonical type field. 3399 QualType Canonical; 3400 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3401 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3402 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3403 3404 // Get the new insert position for the node we care about. 3405 LValueReferenceType *NewIP = 3406 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3407 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3408 } 3409 3410 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3411 SpelledAsLValue); 3412 Types.push_back(New); 3413 LValueReferenceTypes.InsertNode(New, InsertPos); 3414 3415 return QualType(New, 0); 3416 } 3417 3418 /// getRValueReferenceType - Return the uniqued reference to the type for an 3419 /// rvalue reference to the specified type. 3420 QualType ASTContext::getRValueReferenceType(QualType T) const { 3421 assert((!T->isPlaceholderType() || 3422 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3423 "Unresolved placeholder type"); 3424 3425 // Unique pointers, to guarantee there is only one pointer of a particular 3426 // structure. 3427 llvm::FoldingSetNodeID ID; 3428 ReferenceType::Profile(ID, T, false); 3429 3430 void *InsertPos = nullptr; 3431 if (RValueReferenceType *RT = 3432 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3433 return QualType(RT, 0); 3434 3435 const auto *InnerRef = T->getAs<ReferenceType>(); 3436 3437 // If the referencee type isn't canonical, this won't be a canonical type 3438 // either, so fill in the canonical type field. 3439 QualType Canonical; 3440 if (InnerRef || !T.isCanonical()) { 3441 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3442 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3443 3444 // Get the new insert position for the node we care about. 3445 RValueReferenceType *NewIP = 3446 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3447 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3448 } 3449 3450 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3451 Types.push_back(New); 3452 RValueReferenceTypes.InsertNode(New, InsertPos); 3453 return QualType(New, 0); 3454 } 3455 3456 /// getMemberPointerType - Return the uniqued reference to the type for a 3457 /// member pointer to the specified type, in the specified class. 3458 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3459 // Unique pointers, to guarantee there is only one pointer of a particular 3460 // structure. 3461 llvm::FoldingSetNodeID ID; 3462 MemberPointerType::Profile(ID, T, Cls); 3463 3464 void *InsertPos = nullptr; 3465 if (MemberPointerType *PT = 3466 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3467 return QualType(PT, 0); 3468 3469 // If the pointee or class type isn't canonical, this won't be a canonical 3470 // type either, so fill in the canonical type field. 3471 QualType Canonical; 3472 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3473 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3474 3475 // Get the new insert position for the node we care about. 3476 MemberPointerType *NewIP = 3477 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3478 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3479 } 3480 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3481 Types.push_back(New); 3482 MemberPointerTypes.InsertNode(New, InsertPos); 3483 return QualType(New, 0); 3484 } 3485 3486 /// getConstantArrayType - Return the unique reference to the type for an 3487 /// array of the specified element type. 3488 QualType ASTContext::getConstantArrayType(QualType EltTy, 3489 const llvm::APInt &ArySizeIn, 3490 const Expr *SizeExpr, 3491 ArrayType::ArraySizeModifier ASM, 3492 unsigned IndexTypeQuals) const { 3493 assert((EltTy->isDependentType() || 3494 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3495 "Constant array of VLAs is illegal!"); 3496 3497 // We only need the size as part of the type if it's instantiation-dependent. 3498 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3499 SizeExpr = nullptr; 3500 3501 // Convert the array size into a canonical width matching the pointer size for 3502 // the target. 3503 llvm::APInt ArySize(ArySizeIn); 3504 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3505 3506 llvm::FoldingSetNodeID ID; 3507 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3508 IndexTypeQuals); 3509 3510 void *InsertPos = nullptr; 3511 if (ConstantArrayType *ATP = 3512 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3513 return QualType(ATP, 0); 3514 3515 // If the element type isn't canonical or has qualifiers, or the array bound 3516 // is instantiation-dependent, this won't be a canonical type either, so fill 3517 // in the canonical type field. 3518 QualType Canon; 3519 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3520 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3521 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3522 ASM, IndexTypeQuals); 3523 Canon = getQualifiedType(Canon, canonSplit.Quals); 3524 3525 // Get the new insert position for the node we care about. 3526 ConstantArrayType *NewIP = 3527 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3528 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3529 } 3530 3531 void *Mem = Allocate( 3532 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3533 TypeAlignment); 3534 auto *New = new (Mem) 3535 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3536 ConstantArrayTypes.InsertNode(New, InsertPos); 3537 Types.push_back(New); 3538 return QualType(New, 0); 3539 } 3540 3541 /// getVariableArrayDecayedType - Turns the given type, which may be 3542 /// variably-modified, into the corresponding type with all the known 3543 /// sizes replaced with [*]. 3544 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3545 // Vastly most common case. 3546 if (!type->isVariablyModifiedType()) return type; 3547 3548 QualType result; 3549 3550 SplitQualType split = type.getSplitDesugaredType(); 3551 const Type *ty = split.Ty; 3552 switch (ty->getTypeClass()) { 3553 #define TYPE(Class, Base) 3554 #define ABSTRACT_TYPE(Class, Base) 3555 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3556 #include "clang/AST/TypeNodes.inc" 3557 llvm_unreachable("didn't desugar past all non-canonical types?"); 3558 3559 // These types should never be variably-modified. 3560 case Type::Builtin: 3561 case Type::Complex: 3562 case Type::Vector: 3563 case Type::DependentVector: 3564 case Type::ExtVector: 3565 case Type::DependentSizedExtVector: 3566 case Type::ConstantMatrix: 3567 case Type::DependentSizedMatrix: 3568 case Type::DependentAddressSpace: 3569 case Type::ObjCObject: 3570 case Type::ObjCInterface: 3571 case Type::ObjCObjectPointer: 3572 case Type::Record: 3573 case Type::Enum: 3574 case Type::UnresolvedUsing: 3575 case Type::TypeOfExpr: 3576 case Type::TypeOf: 3577 case Type::Decltype: 3578 case Type::UnaryTransform: 3579 case Type::DependentName: 3580 case Type::InjectedClassName: 3581 case Type::TemplateSpecialization: 3582 case Type::DependentTemplateSpecialization: 3583 case Type::TemplateTypeParm: 3584 case Type::SubstTemplateTypeParmPack: 3585 case Type::Auto: 3586 case Type::DeducedTemplateSpecialization: 3587 case Type::PackExpansion: 3588 case Type::BitInt: 3589 case Type::DependentBitInt: 3590 llvm_unreachable("type should never be variably-modified"); 3591 3592 // These types can be variably-modified but should never need to 3593 // further decay. 3594 case Type::FunctionNoProto: 3595 case Type::FunctionProto: 3596 case Type::BlockPointer: 3597 case Type::MemberPointer: 3598 case Type::Pipe: 3599 return type; 3600 3601 // These types can be variably-modified. All these modifications 3602 // preserve structure except as noted by comments. 3603 // TODO: if we ever care about optimizing VLAs, there are no-op 3604 // optimizations available here. 3605 case Type::Pointer: 3606 result = getPointerType(getVariableArrayDecayedType( 3607 cast<PointerType>(ty)->getPointeeType())); 3608 break; 3609 3610 case Type::LValueReference: { 3611 const auto *lv = cast<LValueReferenceType>(ty); 3612 result = getLValueReferenceType( 3613 getVariableArrayDecayedType(lv->getPointeeType()), 3614 lv->isSpelledAsLValue()); 3615 break; 3616 } 3617 3618 case Type::RValueReference: { 3619 const auto *lv = cast<RValueReferenceType>(ty); 3620 result = getRValueReferenceType( 3621 getVariableArrayDecayedType(lv->getPointeeType())); 3622 break; 3623 } 3624 3625 case Type::Atomic: { 3626 const auto *at = cast<AtomicType>(ty); 3627 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3628 break; 3629 } 3630 3631 case Type::ConstantArray: { 3632 const auto *cat = cast<ConstantArrayType>(ty); 3633 result = getConstantArrayType( 3634 getVariableArrayDecayedType(cat->getElementType()), 3635 cat->getSize(), 3636 cat->getSizeExpr(), 3637 cat->getSizeModifier(), 3638 cat->getIndexTypeCVRQualifiers()); 3639 break; 3640 } 3641 3642 case Type::DependentSizedArray: { 3643 const auto *dat = cast<DependentSizedArrayType>(ty); 3644 result = getDependentSizedArrayType( 3645 getVariableArrayDecayedType(dat->getElementType()), 3646 dat->getSizeExpr(), 3647 dat->getSizeModifier(), 3648 dat->getIndexTypeCVRQualifiers(), 3649 dat->getBracketsRange()); 3650 break; 3651 } 3652 3653 // Turn incomplete types into [*] types. 3654 case Type::IncompleteArray: { 3655 const auto *iat = cast<IncompleteArrayType>(ty); 3656 result = getVariableArrayType( 3657 getVariableArrayDecayedType(iat->getElementType()), 3658 /*size*/ nullptr, 3659 ArrayType::Normal, 3660 iat->getIndexTypeCVRQualifiers(), 3661 SourceRange()); 3662 break; 3663 } 3664 3665 // Turn VLA types into [*] types. 3666 case Type::VariableArray: { 3667 const auto *vat = cast<VariableArrayType>(ty); 3668 result = getVariableArrayType( 3669 getVariableArrayDecayedType(vat->getElementType()), 3670 /*size*/ nullptr, 3671 ArrayType::Star, 3672 vat->getIndexTypeCVRQualifiers(), 3673 vat->getBracketsRange()); 3674 break; 3675 } 3676 } 3677 3678 // Apply the top-level qualifiers from the original. 3679 return getQualifiedType(result, split.Quals); 3680 } 3681 3682 /// getVariableArrayType - Returns a non-unique reference to the type for a 3683 /// variable array of the specified element type. 3684 QualType ASTContext::getVariableArrayType(QualType EltTy, 3685 Expr *NumElts, 3686 ArrayType::ArraySizeModifier ASM, 3687 unsigned IndexTypeQuals, 3688 SourceRange Brackets) const { 3689 // Since we don't unique expressions, it isn't possible to unique VLA's 3690 // that have an expression provided for their size. 3691 QualType Canon; 3692 3693 // Be sure to pull qualifiers off the element type. 3694 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3695 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3696 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3697 IndexTypeQuals, Brackets); 3698 Canon = getQualifiedType(Canon, canonSplit.Quals); 3699 } 3700 3701 auto *New = new (*this, TypeAlignment) 3702 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3703 3704 VariableArrayTypes.push_back(New); 3705 Types.push_back(New); 3706 return QualType(New, 0); 3707 } 3708 3709 /// getDependentSizedArrayType - Returns a non-unique reference to 3710 /// the type for a dependently-sized array of the specified element 3711 /// type. 3712 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3713 Expr *numElements, 3714 ArrayType::ArraySizeModifier ASM, 3715 unsigned elementTypeQuals, 3716 SourceRange brackets) const { 3717 assert((!numElements || numElements->isTypeDependent() || 3718 numElements->isValueDependent()) && 3719 "Size must be type- or value-dependent!"); 3720 3721 // Dependently-sized array types that do not have a specified number 3722 // of elements will have their sizes deduced from a dependent 3723 // initializer. We do no canonicalization here at all, which is okay 3724 // because they can't be used in most locations. 3725 if (!numElements) { 3726 auto *newType 3727 = new (*this, TypeAlignment) 3728 DependentSizedArrayType(*this, elementType, QualType(), 3729 numElements, ASM, elementTypeQuals, 3730 brackets); 3731 Types.push_back(newType); 3732 return QualType(newType, 0); 3733 } 3734 3735 // Otherwise, we actually build a new type every time, but we 3736 // also build a canonical type. 3737 3738 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3739 3740 void *insertPos = nullptr; 3741 llvm::FoldingSetNodeID ID; 3742 DependentSizedArrayType::Profile(ID, *this, 3743 QualType(canonElementType.Ty, 0), 3744 ASM, elementTypeQuals, numElements); 3745 3746 // Look for an existing type with these properties. 3747 DependentSizedArrayType *canonTy = 3748 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3749 3750 // If we don't have one, build one. 3751 if (!canonTy) { 3752 canonTy = new (*this, TypeAlignment) 3753 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3754 QualType(), numElements, ASM, elementTypeQuals, 3755 brackets); 3756 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3757 Types.push_back(canonTy); 3758 } 3759 3760 // Apply qualifiers from the element type to the array. 3761 QualType canon = getQualifiedType(QualType(canonTy,0), 3762 canonElementType.Quals); 3763 3764 // If we didn't need extra canonicalization for the element type or the size 3765 // expression, then just use that as our result. 3766 if (QualType(canonElementType.Ty, 0) == elementType && 3767 canonTy->getSizeExpr() == numElements) 3768 return canon; 3769 3770 // Otherwise, we need to build a type which follows the spelling 3771 // of the element type. 3772 auto *sugaredType 3773 = new (*this, TypeAlignment) 3774 DependentSizedArrayType(*this, elementType, canon, numElements, 3775 ASM, elementTypeQuals, brackets); 3776 Types.push_back(sugaredType); 3777 return QualType(sugaredType, 0); 3778 } 3779 3780 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3781 ArrayType::ArraySizeModifier ASM, 3782 unsigned elementTypeQuals) const { 3783 llvm::FoldingSetNodeID ID; 3784 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3785 3786 void *insertPos = nullptr; 3787 if (IncompleteArrayType *iat = 3788 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3789 return QualType(iat, 0); 3790 3791 // If the element type isn't canonical, this won't be a canonical type 3792 // either, so fill in the canonical type field. We also have to pull 3793 // qualifiers off the element type. 3794 QualType canon; 3795 3796 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3797 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3798 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3799 ASM, elementTypeQuals); 3800 canon = getQualifiedType(canon, canonSplit.Quals); 3801 3802 // Get the new insert position for the node we care about. 3803 IncompleteArrayType *existing = 3804 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3805 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3806 } 3807 3808 auto *newType = new (*this, TypeAlignment) 3809 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3810 3811 IncompleteArrayTypes.InsertNode(newType, insertPos); 3812 Types.push_back(newType); 3813 return QualType(newType, 0); 3814 } 3815 3816 ASTContext::BuiltinVectorTypeInfo 3817 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3818 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3819 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3820 NUMVECTORS}; 3821 3822 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3823 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3824 3825 switch (Ty->getKind()) { 3826 default: 3827 llvm_unreachable("Unsupported builtin vector type"); 3828 case BuiltinType::SveInt8: 3829 return SVE_INT_ELTTY(8, 16, true, 1); 3830 case BuiltinType::SveUint8: 3831 return SVE_INT_ELTTY(8, 16, false, 1); 3832 case BuiltinType::SveInt8x2: 3833 return SVE_INT_ELTTY(8, 16, true, 2); 3834 case BuiltinType::SveUint8x2: 3835 return SVE_INT_ELTTY(8, 16, false, 2); 3836 case BuiltinType::SveInt8x3: 3837 return SVE_INT_ELTTY(8, 16, true, 3); 3838 case BuiltinType::SveUint8x3: 3839 return SVE_INT_ELTTY(8, 16, false, 3); 3840 case BuiltinType::SveInt8x4: 3841 return SVE_INT_ELTTY(8, 16, true, 4); 3842 case BuiltinType::SveUint8x4: 3843 return SVE_INT_ELTTY(8, 16, false, 4); 3844 case BuiltinType::SveInt16: 3845 return SVE_INT_ELTTY(16, 8, true, 1); 3846 case BuiltinType::SveUint16: 3847 return SVE_INT_ELTTY(16, 8, false, 1); 3848 case BuiltinType::SveInt16x2: 3849 return SVE_INT_ELTTY(16, 8, true, 2); 3850 case BuiltinType::SveUint16x2: 3851 return SVE_INT_ELTTY(16, 8, false, 2); 3852 case BuiltinType::SveInt16x3: 3853 return SVE_INT_ELTTY(16, 8, true, 3); 3854 case BuiltinType::SveUint16x3: 3855 return SVE_INT_ELTTY(16, 8, false, 3); 3856 case BuiltinType::SveInt16x4: 3857 return SVE_INT_ELTTY(16, 8, true, 4); 3858 case BuiltinType::SveUint16x4: 3859 return SVE_INT_ELTTY(16, 8, false, 4); 3860 case BuiltinType::SveInt32: 3861 return SVE_INT_ELTTY(32, 4, true, 1); 3862 case BuiltinType::SveUint32: 3863 return SVE_INT_ELTTY(32, 4, false, 1); 3864 case BuiltinType::SveInt32x2: 3865 return SVE_INT_ELTTY(32, 4, true, 2); 3866 case BuiltinType::SveUint32x2: 3867 return SVE_INT_ELTTY(32, 4, false, 2); 3868 case BuiltinType::SveInt32x3: 3869 return SVE_INT_ELTTY(32, 4, true, 3); 3870 case BuiltinType::SveUint32x3: 3871 return SVE_INT_ELTTY(32, 4, false, 3); 3872 case BuiltinType::SveInt32x4: 3873 return SVE_INT_ELTTY(32, 4, true, 4); 3874 case BuiltinType::SveUint32x4: 3875 return SVE_INT_ELTTY(32, 4, false, 4); 3876 case BuiltinType::SveInt64: 3877 return SVE_INT_ELTTY(64, 2, true, 1); 3878 case BuiltinType::SveUint64: 3879 return SVE_INT_ELTTY(64, 2, false, 1); 3880 case BuiltinType::SveInt64x2: 3881 return SVE_INT_ELTTY(64, 2, true, 2); 3882 case BuiltinType::SveUint64x2: 3883 return SVE_INT_ELTTY(64, 2, false, 2); 3884 case BuiltinType::SveInt64x3: 3885 return SVE_INT_ELTTY(64, 2, true, 3); 3886 case BuiltinType::SveUint64x3: 3887 return SVE_INT_ELTTY(64, 2, false, 3); 3888 case BuiltinType::SveInt64x4: 3889 return SVE_INT_ELTTY(64, 2, true, 4); 3890 case BuiltinType::SveUint64x4: 3891 return SVE_INT_ELTTY(64, 2, false, 4); 3892 case BuiltinType::SveBool: 3893 return SVE_ELTTY(BoolTy, 16, 1); 3894 case BuiltinType::SveFloat16: 3895 return SVE_ELTTY(HalfTy, 8, 1); 3896 case BuiltinType::SveFloat16x2: 3897 return SVE_ELTTY(HalfTy, 8, 2); 3898 case BuiltinType::SveFloat16x3: 3899 return SVE_ELTTY(HalfTy, 8, 3); 3900 case BuiltinType::SveFloat16x4: 3901 return SVE_ELTTY(HalfTy, 8, 4); 3902 case BuiltinType::SveFloat32: 3903 return SVE_ELTTY(FloatTy, 4, 1); 3904 case BuiltinType::SveFloat32x2: 3905 return SVE_ELTTY(FloatTy, 4, 2); 3906 case BuiltinType::SveFloat32x3: 3907 return SVE_ELTTY(FloatTy, 4, 3); 3908 case BuiltinType::SveFloat32x4: 3909 return SVE_ELTTY(FloatTy, 4, 4); 3910 case BuiltinType::SveFloat64: 3911 return SVE_ELTTY(DoubleTy, 2, 1); 3912 case BuiltinType::SveFloat64x2: 3913 return SVE_ELTTY(DoubleTy, 2, 2); 3914 case BuiltinType::SveFloat64x3: 3915 return SVE_ELTTY(DoubleTy, 2, 3); 3916 case BuiltinType::SveFloat64x4: 3917 return SVE_ELTTY(DoubleTy, 2, 4); 3918 case BuiltinType::SveBFloat16: 3919 return SVE_ELTTY(BFloat16Ty, 8, 1); 3920 case BuiltinType::SveBFloat16x2: 3921 return SVE_ELTTY(BFloat16Ty, 8, 2); 3922 case BuiltinType::SveBFloat16x3: 3923 return SVE_ELTTY(BFloat16Ty, 8, 3); 3924 case BuiltinType::SveBFloat16x4: 3925 return SVE_ELTTY(BFloat16Ty, 8, 4); 3926 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3927 IsSigned) \ 3928 case BuiltinType::Id: \ 3929 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3930 llvm::ElementCount::getScalable(NumEls), NF}; 3931 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3932 case BuiltinType::Id: \ 3933 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3934 llvm::ElementCount::getScalable(NumEls), NF}; 3935 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3936 case BuiltinType::Id: \ 3937 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3938 #include "clang/Basic/RISCVVTypes.def" 3939 } 3940 } 3941 3942 /// getScalableVectorType - Return the unique reference to a scalable vector 3943 /// type of the specified element type and size. VectorType must be a built-in 3944 /// type. 3945 QualType ASTContext::getScalableVectorType(QualType EltTy, 3946 unsigned NumElts) const { 3947 if (Target->hasAArch64SVETypes()) { 3948 uint64_t EltTySize = getTypeSize(EltTy); 3949 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3950 IsSigned, IsFP, IsBF) \ 3951 if (!EltTy->isBooleanType() && \ 3952 ((EltTy->hasIntegerRepresentation() && \ 3953 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3954 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3955 IsFP && !IsBF) || \ 3956 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3957 IsBF && !IsFP)) && \ 3958 EltTySize == ElBits && NumElts == NumEls) { \ 3959 return SingletonId; \ 3960 } 3961 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3962 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3963 return SingletonId; 3964 #include "clang/Basic/AArch64SVEACLETypes.def" 3965 } else if (Target->hasRISCVVTypes()) { 3966 uint64_t EltTySize = getTypeSize(EltTy); 3967 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3968 IsFP) \ 3969 if (!EltTy->isBooleanType() && \ 3970 ((EltTy->hasIntegerRepresentation() && \ 3971 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3972 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3973 EltTySize == ElBits && NumElts == NumEls) \ 3974 return SingletonId; 3975 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3976 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3977 return SingletonId; 3978 #include "clang/Basic/RISCVVTypes.def" 3979 } 3980 return QualType(); 3981 } 3982 3983 /// getVectorType - Return the unique reference to a vector type of 3984 /// the specified element type and size. VectorType must be a built-in type. 3985 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3986 VectorType::VectorKind VecKind) const { 3987 assert(vecType->isBuiltinType()); 3988 3989 // Check if we've already instantiated a vector of this type. 3990 llvm::FoldingSetNodeID ID; 3991 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3992 3993 void *InsertPos = nullptr; 3994 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3995 return QualType(VTP, 0); 3996 3997 // If the element type isn't canonical, this won't be a canonical type either, 3998 // so fill in the canonical type field. 3999 QualType Canonical; 4000 if (!vecType.isCanonical()) { 4001 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 4002 4003 // Get the new insert position for the node we care about. 4004 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4005 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4006 } 4007 auto *New = new (*this, TypeAlignment) 4008 VectorType(vecType, NumElts, Canonical, VecKind); 4009 VectorTypes.InsertNode(New, InsertPos); 4010 Types.push_back(New); 4011 return QualType(New, 0); 4012 } 4013 4014 QualType 4015 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4016 SourceLocation AttrLoc, 4017 VectorType::VectorKind VecKind) const { 4018 llvm::FoldingSetNodeID ID; 4019 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4020 VecKind); 4021 void *InsertPos = nullptr; 4022 DependentVectorType *Canon = 4023 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4024 DependentVectorType *New; 4025 4026 if (Canon) { 4027 New = new (*this, TypeAlignment) DependentVectorType( 4028 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4029 } else { 4030 QualType CanonVecTy = getCanonicalType(VecType); 4031 if (CanonVecTy == VecType) { 4032 New = new (*this, TypeAlignment) DependentVectorType( 4033 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4034 4035 DependentVectorType *CanonCheck = 4036 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4037 assert(!CanonCheck && 4038 "Dependent-sized vector_size canonical type broken"); 4039 (void)CanonCheck; 4040 DependentVectorTypes.InsertNode(New, InsertPos); 4041 } else { 4042 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4043 SourceLocation(), VecKind); 4044 New = new (*this, TypeAlignment) DependentVectorType( 4045 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4046 } 4047 } 4048 4049 Types.push_back(New); 4050 return QualType(New, 0); 4051 } 4052 4053 /// getExtVectorType - Return the unique reference to an extended vector type of 4054 /// the specified element type and size. VectorType must be a built-in type. 4055 QualType 4056 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4057 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4058 4059 // Check if we've already instantiated a vector of this type. 4060 llvm::FoldingSetNodeID ID; 4061 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4062 VectorType::GenericVector); 4063 void *InsertPos = nullptr; 4064 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4065 return QualType(VTP, 0); 4066 4067 // If the element type isn't canonical, this won't be a canonical type either, 4068 // so fill in the canonical type field. 4069 QualType Canonical; 4070 if (!vecType.isCanonical()) { 4071 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4072 4073 // Get the new insert position for the node we care about. 4074 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4075 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4076 } 4077 auto *New = new (*this, TypeAlignment) 4078 ExtVectorType(vecType, NumElts, Canonical); 4079 VectorTypes.InsertNode(New, InsertPos); 4080 Types.push_back(New); 4081 return QualType(New, 0); 4082 } 4083 4084 QualType 4085 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4086 Expr *SizeExpr, 4087 SourceLocation AttrLoc) const { 4088 llvm::FoldingSetNodeID ID; 4089 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4090 SizeExpr); 4091 4092 void *InsertPos = nullptr; 4093 DependentSizedExtVectorType *Canon 4094 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4095 DependentSizedExtVectorType *New; 4096 if (Canon) { 4097 // We already have a canonical version of this array type; use it as 4098 // the canonical type for a newly-built type. 4099 New = new (*this, TypeAlignment) 4100 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4101 SizeExpr, AttrLoc); 4102 } else { 4103 QualType CanonVecTy = getCanonicalType(vecType); 4104 if (CanonVecTy == vecType) { 4105 New = new (*this, TypeAlignment) 4106 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4107 AttrLoc); 4108 4109 DependentSizedExtVectorType *CanonCheck 4110 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4111 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4112 (void)CanonCheck; 4113 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4114 } else { 4115 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4116 SourceLocation()); 4117 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4118 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4119 } 4120 } 4121 4122 Types.push_back(New); 4123 return QualType(New, 0); 4124 } 4125 4126 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4127 unsigned NumColumns) const { 4128 llvm::FoldingSetNodeID ID; 4129 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4130 Type::ConstantMatrix); 4131 4132 assert(MatrixType::isValidElementType(ElementTy) && 4133 "need a valid element type"); 4134 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4135 ConstantMatrixType::isDimensionValid(NumColumns) && 4136 "need valid matrix dimensions"); 4137 void *InsertPos = nullptr; 4138 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4139 return QualType(MTP, 0); 4140 4141 QualType Canonical; 4142 if (!ElementTy.isCanonical()) { 4143 Canonical = 4144 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4145 4146 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4147 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4148 (void)NewIP; 4149 } 4150 4151 auto *New = new (*this, TypeAlignment) 4152 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4153 MatrixTypes.InsertNode(New, InsertPos); 4154 Types.push_back(New); 4155 return QualType(New, 0); 4156 } 4157 4158 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4159 Expr *RowExpr, 4160 Expr *ColumnExpr, 4161 SourceLocation AttrLoc) const { 4162 QualType CanonElementTy = getCanonicalType(ElementTy); 4163 llvm::FoldingSetNodeID ID; 4164 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4165 ColumnExpr); 4166 4167 void *InsertPos = nullptr; 4168 DependentSizedMatrixType *Canon = 4169 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4170 4171 if (!Canon) { 4172 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4173 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4174 #ifndef NDEBUG 4175 DependentSizedMatrixType *CanonCheck = 4176 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4177 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4178 #endif 4179 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4180 Types.push_back(Canon); 4181 } 4182 4183 // Already have a canonical version of the matrix type 4184 // 4185 // If it exactly matches the requested type, use it directly. 4186 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4187 Canon->getRowExpr() == ColumnExpr) 4188 return QualType(Canon, 0); 4189 4190 // Use Canon as the canonical type for newly-built type. 4191 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4192 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4193 ColumnExpr, AttrLoc); 4194 Types.push_back(New); 4195 return QualType(New, 0); 4196 } 4197 4198 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4199 Expr *AddrSpaceExpr, 4200 SourceLocation AttrLoc) const { 4201 assert(AddrSpaceExpr->isInstantiationDependent()); 4202 4203 QualType canonPointeeType = getCanonicalType(PointeeType); 4204 4205 void *insertPos = nullptr; 4206 llvm::FoldingSetNodeID ID; 4207 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4208 AddrSpaceExpr); 4209 4210 DependentAddressSpaceType *canonTy = 4211 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4212 4213 if (!canonTy) { 4214 canonTy = new (*this, TypeAlignment) 4215 DependentAddressSpaceType(*this, canonPointeeType, 4216 QualType(), AddrSpaceExpr, AttrLoc); 4217 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4218 Types.push_back(canonTy); 4219 } 4220 4221 if (canonPointeeType == PointeeType && 4222 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4223 return QualType(canonTy, 0); 4224 4225 auto *sugaredType 4226 = new (*this, TypeAlignment) 4227 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4228 AddrSpaceExpr, AttrLoc); 4229 Types.push_back(sugaredType); 4230 return QualType(sugaredType, 0); 4231 } 4232 4233 /// Determine whether \p T is canonical as the result type of a function. 4234 static bool isCanonicalResultType(QualType T) { 4235 return T.isCanonical() && 4236 (T.getObjCLifetime() == Qualifiers::OCL_None || 4237 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4238 } 4239 4240 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4241 QualType 4242 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4243 const FunctionType::ExtInfo &Info) const { 4244 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter 4245 // functionality creates a function without a prototype regardless of 4246 // language mode (so it makes them even in C++). Once the rewriter has been 4247 // fixed, this assertion can be enabled again. 4248 //assert(!LangOpts.requiresStrictPrototypes() && 4249 // "strict prototypes are disabled"); 4250 4251 // Unique functions, to guarantee there is only one function of a particular 4252 // structure. 4253 llvm::FoldingSetNodeID ID; 4254 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4255 4256 void *InsertPos = nullptr; 4257 if (FunctionNoProtoType *FT = 4258 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4259 return QualType(FT, 0); 4260 4261 QualType Canonical; 4262 if (!isCanonicalResultType(ResultTy)) { 4263 Canonical = 4264 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4265 4266 // Get the new insert position for the node we care about. 4267 FunctionNoProtoType *NewIP = 4268 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4269 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4270 } 4271 4272 auto *New = new (*this, TypeAlignment) 4273 FunctionNoProtoType(ResultTy, Canonical, Info); 4274 Types.push_back(New); 4275 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4276 return QualType(New, 0); 4277 } 4278 4279 CanQualType 4280 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4281 CanQualType CanResultType = getCanonicalType(ResultType); 4282 4283 // Canonical result types do not have ARC lifetime qualifiers. 4284 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4285 Qualifiers Qs = CanResultType.getQualifiers(); 4286 Qs.removeObjCLifetime(); 4287 return CanQualType::CreateUnsafe( 4288 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4289 } 4290 4291 return CanResultType; 4292 } 4293 4294 static bool isCanonicalExceptionSpecification( 4295 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4296 if (ESI.Type == EST_None) 4297 return true; 4298 if (!NoexceptInType) 4299 return false; 4300 4301 // C++17 onwards: exception specification is part of the type, as a simple 4302 // boolean "can this function type throw". 4303 if (ESI.Type == EST_BasicNoexcept) 4304 return true; 4305 4306 // A noexcept(expr) specification is (possibly) canonical if expr is 4307 // value-dependent. 4308 if (ESI.Type == EST_DependentNoexcept) 4309 return true; 4310 4311 // A dynamic exception specification is canonical if it only contains pack 4312 // expansions (so we can't tell whether it's non-throwing) and all its 4313 // contained types are canonical. 4314 if (ESI.Type == EST_Dynamic) { 4315 bool AnyPackExpansions = false; 4316 for (QualType ET : ESI.Exceptions) { 4317 if (!ET.isCanonical()) 4318 return false; 4319 if (ET->getAs<PackExpansionType>()) 4320 AnyPackExpansions = true; 4321 } 4322 return AnyPackExpansions; 4323 } 4324 4325 return false; 4326 } 4327 4328 QualType ASTContext::getFunctionTypeInternal( 4329 QualType ResultTy, ArrayRef<QualType> ArgArray, 4330 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4331 size_t NumArgs = ArgArray.size(); 4332 4333 // Unique functions, to guarantee there is only one function of a particular 4334 // structure. 4335 llvm::FoldingSetNodeID ID; 4336 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4337 *this, true); 4338 4339 QualType Canonical; 4340 bool Unique = false; 4341 4342 void *InsertPos = nullptr; 4343 if (FunctionProtoType *FPT = 4344 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4345 QualType Existing = QualType(FPT, 0); 4346 4347 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4348 // it so long as our exception specification doesn't contain a dependent 4349 // noexcept expression, or we're just looking for a canonical type. 4350 // Otherwise, we're going to need to create a type 4351 // sugar node to hold the concrete expression. 4352 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4353 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4354 return Existing; 4355 4356 // We need a new type sugar node for this one, to hold the new noexcept 4357 // expression. We do no canonicalization here, but that's OK since we don't 4358 // expect to see the same noexcept expression much more than once. 4359 Canonical = getCanonicalType(Existing); 4360 Unique = true; 4361 } 4362 4363 bool NoexceptInType = getLangOpts().CPlusPlus17; 4364 bool IsCanonicalExceptionSpec = 4365 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4366 4367 // Determine whether the type being created is already canonical or not. 4368 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4369 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4370 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4371 if (!ArgArray[i].isCanonicalAsParam()) 4372 isCanonical = false; 4373 4374 if (OnlyWantCanonical) 4375 assert(isCanonical && 4376 "given non-canonical parameters constructing canonical type"); 4377 4378 // If this type isn't canonical, get the canonical version of it if we don't 4379 // already have it. The exception spec is only partially part of the 4380 // canonical type, and only in C++17 onwards. 4381 if (!isCanonical && Canonical.isNull()) { 4382 SmallVector<QualType, 16> CanonicalArgs; 4383 CanonicalArgs.reserve(NumArgs); 4384 for (unsigned i = 0; i != NumArgs; ++i) 4385 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4386 4387 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4388 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4389 CanonicalEPI.HasTrailingReturn = false; 4390 4391 if (IsCanonicalExceptionSpec) { 4392 // Exception spec is already OK. 4393 } else if (NoexceptInType) { 4394 switch (EPI.ExceptionSpec.Type) { 4395 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4396 // We don't know yet. It shouldn't matter what we pick here; no-one 4397 // should ever look at this. 4398 LLVM_FALLTHROUGH; 4399 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4400 CanonicalEPI.ExceptionSpec.Type = EST_None; 4401 break; 4402 4403 // A dynamic exception specification is almost always "not noexcept", 4404 // with the exception that a pack expansion might expand to no types. 4405 case EST_Dynamic: { 4406 bool AnyPacks = false; 4407 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4408 if (ET->getAs<PackExpansionType>()) 4409 AnyPacks = true; 4410 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4411 } 4412 if (!AnyPacks) 4413 CanonicalEPI.ExceptionSpec.Type = EST_None; 4414 else { 4415 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4416 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4417 } 4418 break; 4419 } 4420 4421 case EST_DynamicNone: 4422 case EST_BasicNoexcept: 4423 case EST_NoexceptTrue: 4424 case EST_NoThrow: 4425 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4426 break; 4427 4428 case EST_DependentNoexcept: 4429 llvm_unreachable("dependent noexcept is already canonical"); 4430 } 4431 } else { 4432 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4433 } 4434 4435 // Adjust the canonical function result type. 4436 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4437 Canonical = 4438 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4439 4440 // Get the new insert position for the node we care about. 4441 FunctionProtoType *NewIP = 4442 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4443 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4444 } 4445 4446 // Compute the needed size to hold this FunctionProtoType and the 4447 // various trailing objects. 4448 auto ESH = FunctionProtoType::getExceptionSpecSize( 4449 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4450 size_t Size = FunctionProtoType::totalSizeToAlloc< 4451 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4452 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4453 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4454 NumArgs, EPI.Variadic, 4455 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4456 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4457 EPI.ExtParameterInfos ? NumArgs : 0, 4458 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4459 4460 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4461 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4462 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4463 Types.push_back(FTP); 4464 if (!Unique) 4465 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4466 return QualType(FTP, 0); 4467 } 4468 4469 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4470 llvm::FoldingSetNodeID ID; 4471 PipeType::Profile(ID, T, ReadOnly); 4472 4473 void *InsertPos = nullptr; 4474 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4475 return QualType(PT, 0); 4476 4477 // If the pipe element type isn't canonical, this won't be a canonical type 4478 // either, so fill in the canonical type field. 4479 QualType Canonical; 4480 if (!T.isCanonical()) { 4481 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4482 4483 // Get the new insert position for the node we care about. 4484 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4485 assert(!NewIP && "Shouldn't be in the map!"); 4486 (void)NewIP; 4487 } 4488 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4489 Types.push_back(New); 4490 PipeTypes.InsertNode(New, InsertPos); 4491 return QualType(New, 0); 4492 } 4493 4494 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4495 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4496 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4497 : Ty; 4498 } 4499 4500 QualType ASTContext::getReadPipeType(QualType T) const { 4501 return getPipeType(T, true); 4502 } 4503 4504 QualType ASTContext::getWritePipeType(QualType T) const { 4505 return getPipeType(T, false); 4506 } 4507 4508 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4509 llvm::FoldingSetNodeID ID; 4510 BitIntType::Profile(ID, IsUnsigned, NumBits); 4511 4512 void *InsertPos = nullptr; 4513 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4514 return QualType(EIT, 0); 4515 4516 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4517 BitIntTypes.InsertNode(New, InsertPos); 4518 Types.push_back(New); 4519 return QualType(New, 0); 4520 } 4521 4522 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4523 Expr *NumBitsExpr) const { 4524 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4525 llvm::FoldingSetNodeID ID; 4526 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4527 4528 void *InsertPos = nullptr; 4529 if (DependentBitIntType *Existing = 4530 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4531 return QualType(Existing, 0); 4532 4533 auto *New = new (*this, TypeAlignment) 4534 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4535 DependentBitIntTypes.InsertNode(New, InsertPos); 4536 4537 Types.push_back(New); 4538 return QualType(New, 0); 4539 } 4540 4541 #ifndef NDEBUG 4542 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4543 if (!isa<CXXRecordDecl>(D)) return false; 4544 const auto *RD = cast<CXXRecordDecl>(D); 4545 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4546 return true; 4547 if (RD->getDescribedClassTemplate() && 4548 !isa<ClassTemplateSpecializationDecl>(RD)) 4549 return true; 4550 return false; 4551 } 4552 #endif 4553 4554 /// getInjectedClassNameType - Return the unique reference to the 4555 /// injected class name type for the specified templated declaration. 4556 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4557 QualType TST) const { 4558 assert(NeedsInjectedClassNameType(Decl)); 4559 if (Decl->TypeForDecl) { 4560 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4561 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4562 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4563 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4564 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4565 } else { 4566 Type *newType = 4567 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4568 Decl->TypeForDecl = newType; 4569 Types.push_back(newType); 4570 } 4571 return QualType(Decl->TypeForDecl, 0); 4572 } 4573 4574 /// getTypeDeclType - Return the unique reference to the type for the 4575 /// specified type declaration. 4576 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4577 assert(Decl && "Passed null for Decl param"); 4578 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4579 4580 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4581 return getTypedefType(Typedef); 4582 4583 assert(!isa<TemplateTypeParmDecl>(Decl) && 4584 "Template type parameter types are always available."); 4585 4586 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4587 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4588 assert(!NeedsInjectedClassNameType(Record)); 4589 return getRecordType(Record); 4590 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4591 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4592 return getEnumType(Enum); 4593 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4594 return getUnresolvedUsingType(Using); 4595 } else 4596 llvm_unreachable("TypeDecl without a type?"); 4597 4598 return QualType(Decl->TypeForDecl, 0); 4599 } 4600 4601 /// getTypedefType - Return the unique reference to the type for the 4602 /// specified typedef name decl. 4603 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4604 QualType Underlying) const { 4605 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4606 4607 if (Underlying.isNull()) 4608 Underlying = Decl->getUnderlyingType(); 4609 QualType Canonical = getCanonicalType(Underlying); 4610 auto *newType = new (*this, TypeAlignment) 4611 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4612 Decl->TypeForDecl = newType; 4613 Types.push_back(newType); 4614 return QualType(newType, 0); 4615 } 4616 4617 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4618 QualType Underlying) const { 4619 llvm::FoldingSetNodeID ID; 4620 UsingType::Profile(ID, Found); 4621 4622 void *InsertPos = nullptr; 4623 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4624 if (T) 4625 return QualType(T, 0); 4626 4627 assert(!Underlying.hasLocalQualifiers()); 4628 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4629 QualType Canon = Underlying.getCanonicalType(); 4630 4631 UsingType *NewType = 4632 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4633 Types.push_back(NewType); 4634 UsingTypes.InsertNode(NewType, InsertPos); 4635 return QualType(NewType, 0); 4636 } 4637 4638 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4639 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4640 4641 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4642 if (PrevDecl->TypeForDecl) 4643 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4644 4645 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4646 Decl->TypeForDecl = newType; 4647 Types.push_back(newType); 4648 return QualType(newType, 0); 4649 } 4650 4651 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4652 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4653 4654 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4655 if (PrevDecl->TypeForDecl) 4656 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4657 4658 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4659 Decl->TypeForDecl = newType; 4660 Types.push_back(newType); 4661 return QualType(newType, 0); 4662 } 4663 4664 QualType ASTContext::getUnresolvedUsingType( 4665 const UnresolvedUsingTypenameDecl *Decl) const { 4666 if (Decl->TypeForDecl) 4667 return QualType(Decl->TypeForDecl, 0); 4668 4669 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4670 Decl->getCanonicalDecl()) 4671 if (CanonicalDecl->TypeForDecl) 4672 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4673 4674 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4675 Decl->TypeForDecl = newType; 4676 Types.push_back(newType); 4677 return QualType(newType, 0); 4678 } 4679 4680 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4681 QualType modifiedType, 4682 QualType equivalentType) { 4683 llvm::FoldingSetNodeID id; 4684 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4685 4686 void *insertPos = nullptr; 4687 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4688 if (type) return QualType(type, 0); 4689 4690 QualType canon = getCanonicalType(equivalentType); 4691 type = new (*this, TypeAlignment) 4692 AttributedType(canon, attrKind, modifiedType, equivalentType); 4693 4694 Types.push_back(type); 4695 AttributedTypes.InsertNode(type, insertPos); 4696 4697 return QualType(type, 0); 4698 } 4699 4700 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 4701 QualType Wrapped) { 4702 llvm::FoldingSetNodeID ID; 4703 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr); 4704 4705 void *InsertPos = nullptr; 4706 BTFTagAttributedType *Ty = 4707 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos); 4708 if (Ty) 4709 return QualType(Ty, 0); 4710 4711 QualType Canon = getCanonicalType(Wrapped); 4712 Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr); 4713 4714 Types.push_back(Ty); 4715 BTFTagAttributedTypes.InsertNode(Ty, InsertPos); 4716 4717 return QualType(Ty, 0); 4718 } 4719 4720 /// Retrieve a substitution-result type. 4721 QualType 4722 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4723 QualType Replacement) const { 4724 assert(Replacement.isCanonical() 4725 && "replacement types must always be canonical"); 4726 4727 llvm::FoldingSetNodeID ID; 4728 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4729 void *InsertPos = nullptr; 4730 SubstTemplateTypeParmType *SubstParm 4731 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4732 4733 if (!SubstParm) { 4734 SubstParm = new (*this, TypeAlignment) 4735 SubstTemplateTypeParmType(Parm, Replacement); 4736 Types.push_back(SubstParm); 4737 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4738 } 4739 4740 return QualType(SubstParm, 0); 4741 } 4742 4743 /// Retrieve a 4744 QualType ASTContext::getSubstTemplateTypeParmPackType( 4745 const TemplateTypeParmType *Parm, 4746 const TemplateArgument &ArgPack) { 4747 #ifndef NDEBUG 4748 for (const auto &P : ArgPack.pack_elements()) { 4749 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4750 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4751 } 4752 #endif 4753 4754 llvm::FoldingSetNodeID ID; 4755 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4756 void *InsertPos = nullptr; 4757 if (SubstTemplateTypeParmPackType *SubstParm 4758 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4759 return QualType(SubstParm, 0); 4760 4761 QualType Canon; 4762 if (!Parm->isCanonicalUnqualified()) { 4763 Canon = getCanonicalType(QualType(Parm, 0)); 4764 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4765 ArgPack); 4766 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4767 } 4768 4769 auto *SubstParm 4770 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4771 ArgPack); 4772 Types.push_back(SubstParm); 4773 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4774 return QualType(SubstParm, 0); 4775 } 4776 4777 /// Retrieve the template type parameter type for a template 4778 /// parameter or parameter pack with the given depth, index, and (optionally) 4779 /// name. 4780 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4781 bool ParameterPack, 4782 TemplateTypeParmDecl *TTPDecl) const { 4783 llvm::FoldingSetNodeID ID; 4784 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4785 void *InsertPos = nullptr; 4786 TemplateTypeParmType *TypeParm 4787 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4788 4789 if (TypeParm) 4790 return QualType(TypeParm, 0); 4791 4792 if (TTPDecl) { 4793 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4794 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4795 4796 TemplateTypeParmType *TypeCheck 4797 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4798 assert(!TypeCheck && "Template type parameter canonical type broken"); 4799 (void)TypeCheck; 4800 } else 4801 TypeParm = new (*this, TypeAlignment) 4802 TemplateTypeParmType(Depth, Index, ParameterPack); 4803 4804 Types.push_back(TypeParm); 4805 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4806 4807 return QualType(TypeParm, 0); 4808 } 4809 4810 TypeSourceInfo * 4811 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4812 SourceLocation NameLoc, 4813 const TemplateArgumentListInfo &Args, 4814 QualType Underlying) const { 4815 assert(!Name.getAsDependentTemplateName() && 4816 "No dependent template names here!"); 4817 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4818 4819 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4820 TemplateSpecializationTypeLoc TL = 4821 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4822 TL.setTemplateKeywordLoc(SourceLocation()); 4823 TL.setTemplateNameLoc(NameLoc); 4824 TL.setLAngleLoc(Args.getLAngleLoc()); 4825 TL.setRAngleLoc(Args.getRAngleLoc()); 4826 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4827 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4828 return DI; 4829 } 4830 4831 QualType 4832 ASTContext::getTemplateSpecializationType(TemplateName Template, 4833 const TemplateArgumentListInfo &Args, 4834 QualType Underlying) const { 4835 assert(!Template.getAsDependentTemplateName() && 4836 "No dependent template names here!"); 4837 4838 SmallVector<TemplateArgument, 4> ArgVec; 4839 ArgVec.reserve(Args.size()); 4840 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4841 ArgVec.push_back(Arg.getArgument()); 4842 4843 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4844 } 4845 4846 #ifndef NDEBUG 4847 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4848 for (const TemplateArgument &Arg : Args) 4849 if (Arg.isPackExpansion()) 4850 return true; 4851 4852 return true; 4853 } 4854 #endif 4855 4856 QualType 4857 ASTContext::getTemplateSpecializationType(TemplateName Template, 4858 ArrayRef<TemplateArgument> Args, 4859 QualType Underlying) const { 4860 assert(!Template.getAsDependentTemplateName() && 4861 "No dependent template names here!"); 4862 // Look through qualified template names. 4863 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4864 Template = QTN->getUnderlyingTemplate(); 4865 4866 bool IsTypeAlias = 4867 isa_and_nonnull<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4868 QualType CanonType; 4869 if (!Underlying.isNull()) 4870 CanonType = getCanonicalType(Underlying); 4871 else { 4872 // We can get here with an alias template when the specialization contains 4873 // a pack expansion that does not match up with a parameter pack. 4874 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4875 "Caller must compute aliased type"); 4876 IsTypeAlias = false; 4877 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4878 } 4879 4880 // Allocate the (non-canonical) template specialization type, but don't 4881 // try to unique it: these types typically have location information that 4882 // we don't unique and don't want to lose. 4883 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4884 sizeof(TemplateArgument) * Args.size() + 4885 (IsTypeAlias? sizeof(QualType) : 0), 4886 TypeAlignment); 4887 auto *Spec 4888 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4889 IsTypeAlias ? Underlying : QualType()); 4890 4891 Types.push_back(Spec); 4892 return QualType(Spec, 0); 4893 } 4894 4895 static bool 4896 getCanonicalTemplateArguments(const ASTContext &C, 4897 ArrayRef<TemplateArgument> OrigArgs, 4898 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4899 bool AnyNonCanonArgs = false; 4900 unsigned NumArgs = OrigArgs.size(); 4901 CanonArgs.resize(NumArgs); 4902 for (unsigned I = 0; I != NumArgs; ++I) { 4903 const TemplateArgument &OrigArg = OrigArgs[I]; 4904 TemplateArgument &CanonArg = CanonArgs[I]; 4905 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4906 if (!CanonArg.structurallyEquals(OrigArg)) 4907 AnyNonCanonArgs = true; 4908 } 4909 return AnyNonCanonArgs; 4910 } 4911 4912 QualType ASTContext::getCanonicalTemplateSpecializationType( 4913 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4914 assert(!Template.getAsDependentTemplateName() && 4915 "No dependent template names here!"); 4916 4917 // Look through qualified template names. 4918 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4919 Template = TemplateName(QTN->getUnderlyingTemplate()); 4920 4921 // Build the canonical template specialization type. 4922 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4923 SmallVector<TemplateArgument, 4> CanonArgs; 4924 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4925 4926 // Determine whether this canonical template specialization type already 4927 // exists. 4928 llvm::FoldingSetNodeID ID; 4929 TemplateSpecializationType::Profile(ID, CanonTemplate, 4930 CanonArgs, *this); 4931 4932 void *InsertPos = nullptr; 4933 TemplateSpecializationType *Spec 4934 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4935 4936 if (!Spec) { 4937 // Allocate a new canonical template specialization type. 4938 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4939 sizeof(TemplateArgument) * CanonArgs.size()), 4940 TypeAlignment); 4941 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4942 CanonArgs, 4943 QualType(), QualType()); 4944 Types.push_back(Spec); 4945 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4946 } 4947 4948 assert(Spec->isDependentType() && 4949 "Non-dependent template-id type must have a canonical type"); 4950 return QualType(Spec, 0); 4951 } 4952 4953 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4954 NestedNameSpecifier *NNS, 4955 QualType NamedType, 4956 TagDecl *OwnedTagDecl) const { 4957 llvm::FoldingSetNodeID ID; 4958 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4959 4960 void *InsertPos = nullptr; 4961 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4962 if (T) 4963 return QualType(T, 0); 4964 4965 QualType Canon = NamedType; 4966 if (!Canon.isCanonical()) { 4967 Canon = getCanonicalType(NamedType); 4968 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4969 assert(!CheckT && "Elaborated canonical type broken"); 4970 (void)CheckT; 4971 } 4972 4973 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4974 TypeAlignment); 4975 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4976 4977 Types.push_back(T); 4978 ElaboratedTypes.InsertNode(T, InsertPos); 4979 return QualType(T, 0); 4980 } 4981 4982 QualType 4983 ASTContext::getParenType(QualType InnerType) const { 4984 llvm::FoldingSetNodeID ID; 4985 ParenType::Profile(ID, InnerType); 4986 4987 void *InsertPos = nullptr; 4988 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4989 if (T) 4990 return QualType(T, 0); 4991 4992 QualType Canon = InnerType; 4993 if (!Canon.isCanonical()) { 4994 Canon = getCanonicalType(InnerType); 4995 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4996 assert(!CheckT && "Paren canonical type broken"); 4997 (void)CheckT; 4998 } 4999 5000 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 5001 Types.push_back(T); 5002 ParenTypes.InsertNode(T, InsertPos); 5003 return QualType(T, 0); 5004 } 5005 5006 QualType 5007 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 5008 const IdentifierInfo *MacroII) const { 5009 QualType Canon = UnderlyingTy; 5010 if (!Canon.isCanonical()) 5011 Canon = getCanonicalType(UnderlyingTy); 5012 5013 auto *newType = new (*this, TypeAlignment) 5014 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 5015 Types.push_back(newType); 5016 return QualType(newType, 0); 5017 } 5018 5019 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 5020 NestedNameSpecifier *NNS, 5021 const IdentifierInfo *Name, 5022 QualType Canon) const { 5023 if (Canon.isNull()) { 5024 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5025 if (CanonNNS != NNS) 5026 Canon = getDependentNameType(Keyword, CanonNNS, Name); 5027 } 5028 5029 llvm::FoldingSetNodeID ID; 5030 DependentNameType::Profile(ID, Keyword, NNS, Name); 5031 5032 void *InsertPos = nullptr; 5033 DependentNameType *T 5034 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5035 if (T) 5036 return QualType(T, 0); 5037 5038 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5039 Types.push_back(T); 5040 DependentNameTypes.InsertNode(T, InsertPos); 5041 return QualType(T, 0); 5042 } 5043 5044 QualType 5045 ASTContext::getDependentTemplateSpecializationType( 5046 ElaboratedTypeKeyword Keyword, 5047 NestedNameSpecifier *NNS, 5048 const IdentifierInfo *Name, 5049 const TemplateArgumentListInfo &Args) const { 5050 // TODO: avoid this copy 5051 SmallVector<TemplateArgument, 16> ArgCopy; 5052 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5053 ArgCopy.push_back(Args[I].getArgument()); 5054 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5055 } 5056 5057 QualType 5058 ASTContext::getDependentTemplateSpecializationType( 5059 ElaboratedTypeKeyword Keyword, 5060 NestedNameSpecifier *NNS, 5061 const IdentifierInfo *Name, 5062 ArrayRef<TemplateArgument> Args) const { 5063 assert((!NNS || NNS->isDependent()) && 5064 "nested-name-specifier must be dependent"); 5065 5066 llvm::FoldingSetNodeID ID; 5067 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5068 Name, Args); 5069 5070 void *InsertPos = nullptr; 5071 DependentTemplateSpecializationType *T 5072 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5073 if (T) 5074 return QualType(T, 0); 5075 5076 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5077 5078 ElaboratedTypeKeyword CanonKeyword = Keyword; 5079 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5080 5081 SmallVector<TemplateArgument, 16> CanonArgs; 5082 bool AnyNonCanonArgs = 5083 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5084 5085 QualType Canon; 5086 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5087 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5088 Name, 5089 CanonArgs); 5090 5091 // Find the insert position again. 5092 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5093 } 5094 5095 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5096 sizeof(TemplateArgument) * Args.size()), 5097 TypeAlignment); 5098 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5099 Name, Args, Canon); 5100 Types.push_back(T); 5101 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5102 return QualType(T, 0); 5103 } 5104 5105 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5106 TemplateArgument Arg; 5107 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5108 QualType ArgType = getTypeDeclType(TTP); 5109 if (TTP->isParameterPack()) 5110 ArgType = getPackExpansionType(ArgType, None); 5111 5112 Arg = TemplateArgument(ArgType); 5113 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5114 QualType T = 5115 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5116 // For class NTTPs, ensure we include the 'const' so the type matches that 5117 // of a real template argument. 5118 // FIXME: It would be more faithful to model this as something like an 5119 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5120 if (T->isRecordType()) 5121 T.addConst(); 5122 Expr *E = new (*this) DeclRefExpr( 5123 *this, NTTP, /*enclosing*/ false, T, 5124 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5125 5126 if (NTTP->isParameterPack()) 5127 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5128 None); 5129 Arg = TemplateArgument(E); 5130 } else { 5131 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5132 if (TTP->isParameterPack()) 5133 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5134 else 5135 Arg = TemplateArgument(TemplateName(TTP)); 5136 } 5137 5138 if (Param->isTemplateParameterPack()) 5139 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5140 5141 return Arg; 5142 } 5143 5144 void 5145 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5146 SmallVectorImpl<TemplateArgument> &Args) { 5147 Args.reserve(Args.size() + Params->size()); 5148 5149 for (NamedDecl *Param : *Params) 5150 Args.push_back(getInjectedTemplateArg(Param)); 5151 } 5152 5153 QualType ASTContext::getPackExpansionType(QualType Pattern, 5154 Optional<unsigned> NumExpansions, 5155 bool ExpectPackInType) { 5156 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5157 "Pack expansions must expand one or more parameter packs"); 5158 5159 llvm::FoldingSetNodeID ID; 5160 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5161 5162 void *InsertPos = nullptr; 5163 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5164 if (T) 5165 return QualType(T, 0); 5166 5167 QualType Canon; 5168 if (!Pattern.isCanonical()) { 5169 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5170 /*ExpectPackInType=*/false); 5171 5172 // Find the insert position again, in case we inserted an element into 5173 // PackExpansionTypes and invalidated our insert position. 5174 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5175 } 5176 5177 T = new (*this, TypeAlignment) 5178 PackExpansionType(Pattern, Canon, NumExpansions); 5179 Types.push_back(T); 5180 PackExpansionTypes.InsertNode(T, InsertPos); 5181 return QualType(T, 0); 5182 } 5183 5184 /// CmpProtocolNames - Comparison predicate for sorting protocols 5185 /// alphabetically. 5186 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5187 ObjCProtocolDecl *const *RHS) { 5188 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5189 } 5190 5191 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5192 if (Protocols.empty()) return true; 5193 5194 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5195 return false; 5196 5197 for (unsigned i = 1; i != Protocols.size(); ++i) 5198 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5199 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5200 return false; 5201 return true; 5202 } 5203 5204 static void 5205 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5206 // Sort protocols, keyed by name. 5207 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5208 5209 // Canonicalize. 5210 for (ObjCProtocolDecl *&P : Protocols) 5211 P = P->getCanonicalDecl(); 5212 5213 // Remove duplicates. 5214 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5215 Protocols.erase(ProtocolsEnd, Protocols.end()); 5216 } 5217 5218 QualType ASTContext::getObjCObjectType(QualType BaseType, 5219 ObjCProtocolDecl * const *Protocols, 5220 unsigned NumProtocols) const { 5221 return getObjCObjectType(BaseType, {}, 5222 llvm::makeArrayRef(Protocols, NumProtocols), 5223 /*isKindOf=*/false); 5224 } 5225 5226 QualType ASTContext::getObjCObjectType( 5227 QualType baseType, 5228 ArrayRef<QualType> typeArgs, 5229 ArrayRef<ObjCProtocolDecl *> protocols, 5230 bool isKindOf) const { 5231 // If the base type is an interface and there aren't any protocols or 5232 // type arguments to add, then the interface type will do just fine. 5233 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5234 isa<ObjCInterfaceType>(baseType)) 5235 return baseType; 5236 5237 // Look in the folding set for an existing type. 5238 llvm::FoldingSetNodeID ID; 5239 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5240 void *InsertPos = nullptr; 5241 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5242 return QualType(QT, 0); 5243 5244 // Determine the type arguments to be used for canonicalization, 5245 // which may be explicitly specified here or written on the base 5246 // type. 5247 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5248 if (effectiveTypeArgs.empty()) { 5249 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5250 effectiveTypeArgs = baseObject->getTypeArgs(); 5251 } 5252 5253 // Build the canonical type, which has the canonical base type and a 5254 // sorted-and-uniqued list of protocols and the type arguments 5255 // canonicalized. 5256 QualType canonical; 5257 bool typeArgsAreCanonical = llvm::all_of( 5258 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5259 bool protocolsSorted = areSortedAndUniqued(protocols); 5260 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5261 // Determine the canonical type arguments. 5262 ArrayRef<QualType> canonTypeArgs; 5263 SmallVector<QualType, 4> canonTypeArgsVec; 5264 if (!typeArgsAreCanonical) { 5265 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5266 for (auto typeArg : effectiveTypeArgs) 5267 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5268 canonTypeArgs = canonTypeArgsVec; 5269 } else { 5270 canonTypeArgs = effectiveTypeArgs; 5271 } 5272 5273 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5274 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5275 if (!protocolsSorted) { 5276 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5277 SortAndUniqueProtocols(canonProtocolsVec); 5278 canonProtocols = canonProtocolsVec; 5279 } else { 5280 canonProtocols = protocols; 5281 } 5282 5283 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5284 canonProtocols, isKindOf); 5285 5286 // Regenerate InsertPos. 5287 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5288 } 5289 5290 unsigned size = sizeof(ObjCObjectTypeImpl); 5291 size += typeArgs.size() * sizeof(QualType); 5292 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5293 void *mem = Allocate(size, TypeAlignment); 5294 auto *T = 5295 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5296 isKindOf); 5297 5298 Types.push_back(T); 5299 ObjCObjectTypes.InsertNode(T, InsertPos); 5300 return QualType(T, 0); 5301 } 5302 5303 /// Apply Objective-C protocol qualifiers to the given type. 5304 /// If this is for the canonical type of a type parameter, we can apply 5305 /// protocol qualifiers on the ObjCObjectPointerType. 5306 QualType 5307 ASTContext::applyObjCProtocolQualifiers(QualType type, 5308 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5309 bool allowOnPointerType) const { 5310 hasError = false; 5311 5312 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5313 return getObjCTypeParamType(objT->getDecl(), protocols); 5314 } 5315 5316 // Apply protocol qualifiers to ObjCObjectPointerType. 5317 if (allowOnPointerType) { 5318 if (const auto *objPtr = 5319 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5320 const ObjCObjectType *objT = objPtr->getObjectType(); 5321 // Merge protocol lists and construct ObjCObjectType. 5322 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5323 protocolsVec.append(objT->qual_begin(), 5324 objT->qual_end()); 5325 protocolsVec.append(protocols.begin(), protocols.end()); 5326 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5327 type = getObjCObjectType( 5328 objT->getBaseType(), 5329 objT->getTypeArgsAsWritten(), 5330 protocols, 5331 objT->isKindOfTypeAsWritten()); 5332 return getObjCObjectPointerType(type); 5333 } 5334 } 5335 5336 // Apply protocol qualifiers to ObjCObjectType. 5337 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5338 // FIXME: Check for protocols to which the class type is already 5339 // known to conform. 5340 5341 return getObjCObjectType(objT->getBaseType(), 5342 objT->getTypeArgsAsWritten(), 5343 protocols, 5344 objT->isKindOfTypeAsWritten()); 5345 } 5346 5347 // If the canonical type is ObjCObjectType, ... 5348 if (type->isObjCObjectType()) { 5349 // Silently overwrite any existing protocol qualifiers. 5350 // TODO: determine whether that's the right thing to do. 5351 5352 // FIXME: Check for protocols to which the class type is already 5353 // known to conform. 5354 return getObjCObjectType(type, {}, protocols, false); 5355 } 5356 5357 // id<protocol-list> 5358 if (type->isObjCIdType()) { 5359 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5360 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5361 objPtr->isKindOfType()); 5362 return getObjCObjectPointerType(type); 5363 } 5364 5365 // Class<protocol-list> 5366 if (type->isObjCClassType()) { 5367 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5368 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5369 objPtr->isKindOfType()); 5370 return getObjCObjectPointerType(type); 5371 } 5372 5373 hasError = true; 5374 return type; 5375 } 5376 5377 QualType 5378 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5379 ArrayRef<ObjCProtocolDecl *> protocols) const { 5380 // Look in the folding set for an existing type. 5381 llvm::FoldingSetNodeID ID; 5382 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5383 void *InsertPos = nullptr; 5384 if (ObjCTypeParamType *TypeParam = 5385 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5386 return QualType(TypeParam, 0); 5387 5388 // We canonicalize to the underlying type. 5389 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5390 if (!protocols.empty()) { 5391 // Apply the protocol qualifers. 5392 bool hasError; 5393 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5394 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5395 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5396 } 5397 5398 unsigned size = sizeof(ObjCTypeParamType); 5399 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5400 void *mem = Allocate(size, TypeAlignment); 5401 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5402 5403 Types.push_back(newType); 5404 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5405 return QualType(newType, 0); 5406 } 5407 5408 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5409 ObjCTypeParamDecl *New) const { 5410 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5411 // Update TypeForDecl after updating TypeSourceInfo. 5412 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5413 SmallVector<ObjCProtocolDecl *, 8> protocols; 5414 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5415 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5416 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5417 } 5418 5419 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5420 /// protocol list adopt all protocols in QT's qualified-id protocol 5421 /// list. 5422 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5423 ObjCInterfaceDecl *IC) { 5424 if (!QT->isObjCQualifiedIdType()) 5425 return false; 5426 5427 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5428 // If both the right and left sides have qualifiers. 5429 for (auto *Proto : OPT->quals()) { 5430 if (!IC->ClassImplementsProtocol(Proto, false)) 5431 return false; 5432 } 5433 return true; 5434 } 5435 return false; 5436 } 5437 5438 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5439 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5440 /// of protocols. 5441 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5442 ObjCInterfaceDecl *IDecl) { 5443 if (!QT->isObjCQualifiedIdType()) 5444 return false; 5445 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5446 if (!OPT) 5447 return false; 5448 if (!IDecl->hasDefinition()) 5449 return false; 5450 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5451 CollectInheritedProtocols(IDecl, InheritedProtocols); 5452 if (InheritedProtocols.empty()) 5453 return false; 5454 // Check that if every protocol in list of id<plist> conforms to a protocol 5455 // of IDecl's, then bridge casting is ok. 5456 bool Conforms = false; 5457 for (auto *Proto : OPT->quals()) { 5458 Conforms = false; 5459 for (auto *PI : InheritedProtocols) { 5460 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5461 Conforms = true; 5462 break; 5463 } 5464 } 5465 if (!Conforms) 5466 break; 5467 } 5468 if (Conforms) 5469 return true; 5470 5471 for (auto *PI : InheritedProtocols) { 5472 // If both the right and left sides have qualifiers. 5473 bool Adopts = false; 5474 for (auto *Proto : OPT->quals()) { 5475 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5476 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5477 break; 5478 } 5479 if (!Adopts) 5480 return false; 5481 } 5482 return true; 5483 } 5484 5485 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5486 /// the given object type. 5487 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5488 llvm::FoldingSetNodeID ID; 5489 ObjCObjectPointerType::Profile(ID, ObjectT); 5490 5491 void *InsertPos = nullptr; 5492 if (ObjCObjectPointerType *QT = 5493 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5494 return QualType(QT, 0); 5495 5496 // Find the canonical object type. 5497 QualType Canonical; 5498 if (!ObjectT.isCanonical()) { 5499 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5500 5501 // Regenerate InsertPos. 5502 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5503 } 5504 5505 // No match. 5506 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5507 auto *QType = 5508 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5509 5510 Types.push_back(QType); 5511 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5512 return QualType(QType, 0); 5513 } 5514 5515 /// getObjCInterfaceType - Return the unique reference to the type for the 5516 /// specified ObjC interface decl. The list of protocols is optional. 5517 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5518 ObjCInterfaceDecl *PrevDecl) const { 5519 if (Decl->TypeForDecl) 5520 return QualType(Decl->TypeForDecl, 0); 5521 5522 if (PrevDecl) { 5523 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5524 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5525 return QualType(PrevDecl->TypeForDecl, 0); 5526 } 5527 5528 // Prefer the definition, if there is one. 5529 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5530 Decl = Def; 5531 5532 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5533 auto *T = new (Mem) ObjCInterfaceType(Decl); 5534 Decl->TypeForDecl = T; 5535 Types.push_back(T); 5536 return QualType(T, 0); 5537 } 5538 5539 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5540 /// TypeOfExprType AST's (since expression's are never shared). For example, 5541 /// multiple declarations that refer to "typeof(x)" all contain different 5542 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5543 /// on canonical type's (which are always unique). 5544 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5545 TypeOfExprType *toe; 5546 if (tofExpr->isTypeDependent()) { 5547 llvm::FoldingSetNodeID ID; 5548 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5549 5550 void *InsertPos = nullptr; 5551 DependentTypeOfExprType *Canon 5552 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5553 if (Canon) { 5554 // We already have a "canonical" version of an identical, dependent 5555 // typeof(expr) type. Use that as our canonical type. 5556 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5557 QualType((TypeOfExprType*)Canon, 0)); 5558 } else { 5559 // Build a new, canonical typeof(expr) type. 5560 Canon 5561 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5562 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5563 toe = Canon; 5564 } 5565 } else { 5566 QualType Canonical = getCanonicalType(tofExpr->getType()); 5567 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5568 } 5569 Types.push_back(toe); 5570 return QualType(toe, 0); 5571 } 5572 5573 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5574 /// TypeOfType nodes. The only motivation to unique these nodes would be 5575 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5576 /// an issue. This doesn't affect the type checker, since it operates 5577 /// on canonical types (which are always unique). 5578 QualType ASTContext::getTypeOfType(QualType tofType) const { 5579 QualType Canonical = getCanonicalType(tofType); 5580 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5581 Types.push_back(tot); 5582 return QualType(tot, 0); 5583 } 5584 5585 /// getReferenceQualifiedType - Given an expr, will return the type for 5586 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5587 /// and class member access into account. 5588 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5589 // C++11 [dcl.type.simple]p4: 5590 // [...] 5591 QualType T = E->getType(); 5592 switch (E->getValueKind()) { 5593 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5594 // type of e; 5595 case VK_XValue: 5596 return getRValueReferenceType(T); 5597 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5598 // type of e; 5599 case VK_LValue: 5600 return getLValueReferenceType(T); 5601 // - otherwise, decltype(e) is the type of e. 5602 case VK_PRValue: 5603 return T; 5604 } 5605 llvm_unreachable("Unknown value kind"); 5606 } 5607 5608 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5609 /// nodes. This would never be helpful, since each such type has its own 5610 /// expression, and would not give a significant memory saving, since there 5611 /// is an Expr tree under each such type. 5612 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5613 DecltypeType *dt; 5614 5615 // C++11 [temp.type]p2: 5616 // If an expression e involves a template parameter, decltype(e) denotes a 5617 // unique dependent type. Two such decltype-specifiers refer to the same 5618 // type only if their expressions are equivalent (14.5.6.1). 5619 if (e->isInstantiationDependent()) { 5620 llvm::FoldingSetNodeID ID; 5621 DependentDecltypeType::Profile(ID, *this, e); 5622 5623 void *InsertPos = nullptr; 5624 DependentDecltypeType *Canon 5625 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5626 if (!Canon) { 5627 // Build a new, canonical decltype(expr) type. 5628 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5629 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5630 } 5631 dt = new (*this, TypeAlignment) 5632 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5633 } else { 5634 dt = new (*this, TypeAlignment) 5635 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5636 } 5637 Types.push_back(dt); 5638 return QualType(dt, 0); 5639 } 5640 5641 /// getUnaryTransformationType - We don't unique these, since the memory 5642 /// savings are minimal and these are rare. 5643 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5644 QualType UnderlyingType, 5645 UnaryTransformType::UTTKind Kind) 5646 const { 5647 UnaryTransformType *ut = nullptr; 5648 5649 if (BaseType->isDependentType()) { 5650 // Look in the folding set for an existing type. 5651 llvm::FoldingSetNodeID ID; 5652 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5653 5654 void *InsertPos = nullptr; 5655 DependentUnaryTransformType *Canon 5656 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5657 5658 if (!Canon) { 5659 // Build a new, canonical __underlying_type(type) type. 5660 Canon = new (*this, TypeAlignment) 5661 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5662 Kind); 5663 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5664 } 5665 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5666 QualType(), Kind, 5667 QualType(Canon, 0)); 5668 } else { 5669 QualType CanonType = getCanonicalType(UnderlyingType); 5670 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5671 UnderlyingType, Kind, 5672 CanonType); 5673 } 5674 Types.push_back(ut); 5675 return QualType(ut, 0); 5676 } 5677 5678 QualType ASTContext::getAutoTypeInternal( 5679 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5680 bool IsPack, ConceptDecl *TypeConstraintConcept, 5681 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5682 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5683 !TypeConstraintConcept && !IsDependent) 5684 return getAutoDeductType(); 5685 5686 // Look in the folding set for an existing type. 5687 void *InsertPos = nullptr; 5688 llvm::FoldingSetNodeID ID; 5689 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5690 TypeConstraintConcept, TypeConstraintArgs); 5691 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5692 return QualType(AT, 0); 5693 5694 QualType Canon; 5695 if (!IsCanon) { 5696 if (DeducedType.isNull()) { 5697 SmallVector<TemplateArgument, 4> CanonArgs; 5698 bool AnyNonCanonArgs = 5699 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5700 if (AnyNonCanonArgs) { 5701 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5702 TypeConstraintConcept, CanonArgs, true); 5703 // Find the insert position again. 5704 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5705 } 5706 } else { 5707 Canon = DeducedType.getCanonicalType(); 5708 } 5709 } 5710 5711 void *Mem = Allocate(sizeof(AutoType) + 5712 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5713 TypeAlignment); 5714 auto *AT = new (Mem) AutoType( 5715 DeducedType, Keyword, 5716 (IsDependent ? TypeDependence::DependentInstantiation 5717 : TypeDependence::None) | 5718 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5719 Canon, TypeConstraintConcept, TypeConstraintArgs); 5720 Types.push_back(AT); 5721 AutoTypes.InsertNode(AT, InsertPos); 5722 return QualType(AT, 0); 5723 } 5724 5725 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5726 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5727 /// canonical deduced-but-dependent 'auto' type. 5728 QualType 5729 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5730 bool IsDependent, bool IsPack, 5731 ConceptDecl *TypeConstraintConcept, 5732 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5733 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5734 assert((!IsDependent || DeducedType.isNull()) && 5735 "A dependent auto should be undeduced"); 5736 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5737 TypeConstraintConcept, TypeConstraintArgs); 5738 } 5739 5740 /// Return the uniqued reference to the deduced template specialization type 5741 /// which has been deduced to the given type, or to the canonical undeduced 5742 /// such type, or the canonical deduced-but-dependent such type. 5743 QualType ASTContext::getDeducedTemplateSpecializationType( 5744 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5745 // Look in the folding set for an existing type. 5746 void *InsertPos = nullptr; 5747 llvm::FoldingSetNodeID ID; 5748 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5749 IsDependent); 5750 if (DeducedTemplateSpecializationType *DTST = 5751 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5752 return QualType(DTST, 0); 5753 5754 auto *DTST = new (*this, TypeAlignment) 5755 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5756 llvm::FoldingSetNodeID TempID; 5757 DTST->Profile(TempID); 5758 assert(ID == TempID && "ID does not match"); 5759 Types.push_back(DTST); 5760 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5761 return QualType(DTST, 0); 5762 } 5763 5764 /// getAtomicType - Return the uniqued reference to the atomic type for 5765 /// the given value type. 5766 QualType ASTContext::getAtomicType(QualType T) const { 5767 // Unique pointers, to guarantee there is only one pointer of a particular 5768 // structure. 5769 llvm::FoldingSetNodeID ID; 5770 AtomicType::Profile(ID, T); 5771 5772 void *InsertPos = nullptr; 5773 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5774 return QualType(AT, 0); 5775 5776 // If the atomic value type isn't canonical, this won't be a canonical type 5777 // either, so fill in the canonical type field. 5778 QualType Canonical; 5779 if (!T.isCanonical()) { 5780 Canonical = getAtomicType(getCanonicalType(T)); 5781 5782 // Get the new insert position for the node we care about. 5783 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5784 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5785 } 5786 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5787 Types.push_back(New); 5788 AtomicTypes.InsertNode(New, InsertPos); 5789 return QualType(New, 0); 5790 } 5791 5792 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5793 QualType ASTContext::getAutoDeductType() const { 5794 if (AutoDeductTy.isNull()) 5795 AutoDeductTy = QualType(new (*this, TypeAlignment) 5796 AutoType(QualType(), AutoTypeKeyword::Auto, 5797 TypeDependence::None, QualType(), 5798 /*concept*/ nullptr, /*args*/ {}), 5799 0); 5800 return AutoDeductTy; 5801 } 5802 5803 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5804 QualType ASTContext::getAutoRRefDeductType() const { 5805 if (AutoRRefDeductTy.isNull()) 5806 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5807 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5808 return AutoRRefDeductTy; 5809 } 5810 5811 /// getTagDeclType - Return the unique reference to the type for the 5812 /// specified TagDecl (struct/union/class/enum) decl. 5813 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5814 assert(Decl); 5815 // FIXME: What is the design on getTagDeclType when it requires casting 5816 // away const? mutable? 5817 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5818 } 5819 5820 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5821 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5822 /// needs to agree with the definition in <stddef.h>. 5823 CanQualType ASTContext::getSizeType() const { 5824 return getFromTargetType(Target->getSizeType()); 5825 } 5826 5827 /// Return the unique signed counterpart of the integer type 5828 /// corresponding to size_t. 5829 CanQualType ASTContext::getSignedSizeType() const { 5830 return getFromTargetType(Target->getSignedSizeType()); 5831 } 5832 5833 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5834 CanQualType ASTContext::getIntMaxType() const { 5835 return getFromTargetType(Target->getIntMaxType()); 5836 } 5837 5838 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5839 CanQualType ASTContext::getUIntMaxType() const { 5840 return getFromTargetType(Target->getUIntMaxType()); 5841 } 5842 5843 /// getSignedWCharType - Return the type of "signed wchar_t". 5844 /// Used when in C++, as a GCC extension. 5845 QualType ASTContext::getSignedWCharType() const { 5846 // FIXME: derive from "Target" ? 5847 return WCharTy; 5848 } 5849 5850 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5851 /// Used when in C++, as a GCC extension. 5852 QualType ASTContext::getUnsignedWCharType() const { 5853 // FIXME: derive from "Target" ? 5854 return UnsignedIntTy; 5855 } 5856 5857 QualType ASTContext::getIntPtrType() const { 5858 return getFromTargetType(Target->getIntPtrType()); 5859 } 5860 5861 QualType ASTContext::getUIntPtrType() const { 5862 return getCorrespondingUnsignedType(getIntPtrType()); 5863 } 5864 5865 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5866 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5867 QualType ASTContext::getPointerDiffType() const { 5868 return getFromTargetType(Target->getPtrDiffType(0)); 5869 } 5870 5871 /// Return the unique unsigned counterpart of "ptrdiff_t" 5872 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5873 /// in the definition of %tu format specifier. 5874 QualType ASTContext::getUnsignedPointerDiffType() const { 5875 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5876 } 5877 5878 /// Return the unique type for "pid_t" defined in 5879 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5880 QualType ASTContext::getProcessIDType() const { 5881 return getFromTargetType(Target->getProcessIDType()); 5882 } 5883 5884 //===----------------------------------------------------------------------===// 5885 // Type Operators 5886 //===----------------------------------------------------------------------===// 5887 5888 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5889 // Push qualifiers into arrays, and then discard any remaining 5890 // qualifiers. 5891 T = getCanonicalType(T); 5892 T = getVariableArrayDecayedType(T); 5893 const Type *Ty = T.getTypePtr(); 5894 QualType Result; 5895 if (isa<ArrayType>(Ty)) { 5896 Result = getArrayDecayedType(QualType(Ty,0)); 5897 } else if (isa<FunctionType>(Ty)) { 5898 Result = getPointerType(QualType(Ty, 0)); 5899 } else { 5900 Result = QualType(Ty, 0); 5901 } 5902 5903 return CanQualType::CreateUnsafe(Result); 5904 } 5905 5906 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5907 Qualifiers &quals) { 5908 SplitQualType splitType = type.getSplitUnqualifiedType(); 5909 5910 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5911 // the unqualified desugared type and then drops it on the floor. 5912 // We then have to strip that sugar back off with 5913 // getUnqualifiedDesugaredType(), which is silly. 5914 const auto *AT = 5915 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5916 5917 // If we don't have an array, just use the results in splitType. 5918 if (!AT) { 5919 quals = splitType.Quals; 5920 return QualType(splitType.Ty, 0); 5921 } 5922 5923 // Otherwise, recurse on the array's element type. 5924 QualType elementType = AT->getElementType(); 5925 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5926 5927 // If that didn't change the element type, AT has no qualifiers, so we 5928 // can just use the results in splitType. 5929 if (elementType == unqualElementType) { 5930 assert(quals.empty()); // from the recursive call 5931 quals = splitType.Quals; 5932 return QualType(splitType.Ty, 0); 5933 } 5934 5935 // Otherwise, add in the qualifiers from the outermost type, then 5936 // build the type back up. 5937 quals.addConsistentQualifiers(splitType.Quals); 5938 5939 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5940 return getConstantArrayType(unqualElementType, CAT->getSize(), 5941 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5942 } 5943 5944 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5945 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5946 } 5947 5948 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5949 return getVariableArrayType(unqualElementType, 5950 VAT->getSizeExpr(), 5951 VAT->getSizeModifier(), 5952 VAT->getIndexTypeCVRQualifiers(), 5953 VAT->getBracketsRange()); 5954 } 5955 5956 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5957 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5958 DSAT->getSizeModifier(), 0, 5959 SourceRange()); 5960 } 5961 5962 /// Attempt to unwrap two types that may both be array types with the same bound 5963 /// (or both be array types of unknown bound) for the purpose of comparing the 5964 /// cv-decomposition of two types per C++ [conv.qual]. 5965 /// 5966 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5967 /// C++20 [conv.qual], if permitted by the current language mode. 5968 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5969 bool AllowPiMismatch) { 5970 while (true) { 5971 auto *AT1 = getAsArrayType(T1); 5972 if (!AT1) 5973 return; 5974 5975 auto *AT2 = getAsArrayType(T2); 5976 if (!AT2) 5977 return; 5978 5979 // If we don't have two array types with the same constant bound nor two 5980 // incomplete array types, we've unwrapped everything we can. 5981 // C++20 also permits one type to be a constant array type and the other 5982 // to be an incomplete array type. 5983 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5984 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5985 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5986 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 5987 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5988 isa<IncompleteArrayType>(AT2)))) 5989 return; 5990 } else if (isa<IncompleteArrayType>(AT1)) { 5991 if (!(isa<IncompleteArrayType>(AT2) || 5992 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5993 isa<ConstantArrayType>(AT2)))) 5994 return; 5995 } else { 5996 return; 5997 } 5998 5999 T1 = AT1->getElementType(); 6000 T2 = AT2->getElementType(); 6001 } 6002 } 6003 6004 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 6005 /// 6006 /// If T1 and T2 are both pointer types of the same kind, or both array types 6007 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 6008 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 6009 /// 6010 /// This function will typically be called in a loop that successively 6011 /// "unwraps" pointer and pointer-to-member types to compare them at each 6012 /// level. 6013 /// 6014 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 6015 /// C++20 [conv.qual], if permitted by the current language mode. 6016 /// 6017 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 6018 /// pair of types that can't be unwrapped further. 6019 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 6020 bool AllowPiMismatch) { 6021 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 6022 6023 const auto *T1PtrType = T1->getAs<PointerType>(); 6024 const auto *T2PtrType = T2->getAs<PointerType>(); 6025 if (T1PtrType && T2PtrType) { 6026 T1 = T1PtrType->getPointeeType(); 6027 T2 = T2PtrType->getPointeeType(); 6028 return true; 6029 } 6030 6031 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6032 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6033 if (T1MPType && T2MPType && 6034 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6035 QualType(T2MPType->getClass(), 0))) { 6036 T1 = T1MPType->getPointeeType(); 6037 T2 = T2MPType->getPointeeType(); 6038 return true; 6039 } 6040 6041 if (getLangOpts().ObjC) { 6042 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6043 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6044 if (T1OPType && T2OPType) { 6045 T1 = T1OPType->getPointeeType(); 6046 T2 = T2OPType->getPointeeType(); 6047 return true; 6048 } 6049 } 6050 6051 // FIXME: Block pointers, too? 6052 6053 return false; 6054 } 6055 6056 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6057 while (true) { 6058 Qualifiers Quals; 6059 T1 = getUnqualifiedArrayType(T1, Quals); 6060 T2 = getUnqualifiedArrayType(T2, Quals); 6061 if (hasSameType(T1, T2)) 6062 return true; 6063 if (!UnwrapSimilarTypes(T1, T2)) 6064 return false; 6065 } 6066 } 6067 6068 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6069 while (true) { 6070 Qualifiers Quals1, Quals2; 6071 T1 = getUnqualifiedArrayType(T1, Quals1); 6072 T2 = getUnqualifiedArrayType(T2, Quals2); 6073 6074 Quals1.removeCVRQualifiers(); 6075 Quals2.removeCVRQualifiers(); 6076 if (Quals1 != Quals2) 6077 return false; 6078 6079 if (hasSameType(T1, T2)) 6080 return true; 6081 6082 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6083 return false; 6084 } 6085 } 6086 6087 DeclarationNameInfo 6088 ASTContext::getNameForTemplate(TemplateName Name, 6089 SourceLocation NameLoc) const { 6090 switch (Name.getKind()) { 6091 case TemplateName::QualifiedTemplate: 6092 case TemplateName::Template: 6093 // DNInfo work in progress: CHECKME: what about DNLoc? 6094 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6095 NameLoc); 6096 6097 case TemplateName::OverloadedTemplate: { 6098 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6099 // DNInfo work in progress: CHECKME: what about DNLoc? 6100 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6101 } 6102 6103 case TemplateName::AssumedTemplate: { 6104 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6105 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6106 } 6107 6108 case TemplateName::DependentTemplate: { 6109 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6110 DeclarationName DName; 6111 if (DTN->isIdentifier()) { 6112 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6113 return DeclarationNameInfo(DName, NameLoc); 6114 } else { 6115 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6116 // DNInfo work in progress: FIXME: source locations? 6117 DeclarationNameLoc DNLoc = 6118 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6119 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6120 } 6121 } 6122 6123 case TemplateName::SubstTemplateTemplateParm: { 6124 SubstTemplateTemplateParmStorage *subst 6125 = Name.getAsSubstTemplateTemplateParm(); 6126 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6127 NameLoc); 6128 } 6129 6130 case TemplateName::SubstTemplateTemplateParmPack: { 6131 SubstTemplateTemplateParmPackStorage *subst 6132 = Name.getAsSubstTemplateTemplateParmPack(); 6133 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6134 NameLoc); 6135 } 6136 case TemplateName::UsingTemplate: 6137 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(), 6138 NameLoc); 6139 } 6140 6141 llvm_unreachable("bad template name kind!"); 6142 } 6143 6144 TemplateName 6145 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6146 switch (Name.getKind()) { 6147 case TemplateName::UsingTemplate: 6148 case TemplateName::QualifiedTemplate: 6149 case TemplateName::Template: { 6150 TemplateDecl *Template = Name.getAsTemplateDecl(); 6151 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6152 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6153 6154 // The canonical template name is the canonical template declaration. 6155 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6156 } 6157 6158 case TemplateName::OverloadedTemplate: 6159 case TemplateName::AssumedTemplate: 6160 llvm_unreachable("cannot canonicalize unresolved template"); 6161 6162 case TemplateName::DependentTemplate: { 6163 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6164 assert(DTN && "Non-dependent template names must refer to template decls."); 6165 return DTN->CanonicalTemplateName; 6166 } 6167 6168 case TemplateName::SubstTemplateTemplateParm: { 6169 SubstTemplateTemplateParmStorage *subst 6170 = Name.getAsSubstTemplateTemplateParm(); 6171 return getCanonicalTemplateName(subst->getReplacement()); 6172 } 6173 6174 case TemplateName::SubstTemplateTemplateParmPack: { 6175 SubstTemplateTemplateParmPackStorage *subst 6176 = Name.getAsSubstTemplateTemplateParmPack(); 6177 TemplateTemplateParmDecl *canonParameter 6178 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6179 TemplateArgument canonArgPack 6180 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6181 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6182 } 6183 } 6184 6185 llvm_unreachable("bad template name!"); 6186 } 6187 6188 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6189 const TemplateName &Y) const { 6190 return getCanonicalTemplateName(X).getAsVoidPointer() == 6191 getCanonicalTemplateName(Y).getAsVoidPointer(); 6192 } 6193 6194 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6195 const NamedDecl *Y) { 6196 if (X->getKind() != Y->getKind()) 6197 return false; 6198 6199 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6200 auto *TY = cast<TemplateTypeParmDecl>(Y); 6201 if (TX->isParameterPack() != TY->isParameterPack()) 6202 return false; 6203 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6204 return false; 6205 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6206 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6207 if (!TXTC != !TYTC) 6208 return false; 6209 if (TXTC && TYTC) { 6210 auto *NCX = TXTC->getNamedConcept(); 6211 auto *NCY = TYTC->getNamedConcept(); 6212 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6213 return false; 6214 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6215 return false; 6216 if (TXTC->hasExplicitTemplateArgs()) { 6217 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6218 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6219 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6220 return false; 6221 llvm::FoldingSetNodeID XID, YID; 6222 for (auto &ArgLoc : TXTCArgs->arguments()) 6223 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6224 for (auto &ArgLoc : TYTCArgs->arguments()) 6225 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6226 if (XID != YID) 6227 return false; 6228 } 6229 } 6230 return true; 6231 } 6232 6233 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6234 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6235 return TX->isParameterPack() == TY->isParameterPack() && 6236 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6237 } 6238 6239 auto *TX = cast<TemplateTemplateParmDecl>(X); 6240 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6241 return TX->isParameterPack() == TY->isParameterPack() && 6242 isSameTemplateParameterList(TX->getTemplateParameters(), 6243 TY->getTemplateParameters()); 6244 } 6245 6246 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6247 const TemplateParameterList *Y) { 6248 if (X->size() != Y->size()) 6249 return false; 6250 6251 for (unsigned I = 0, N = X->size(); I != N; ++I) 6252 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6253 return false; 6254 6255 const Expr *XRC = X->getRequiresClause(); 6256 const Expr *YRC = Y->getRequiresClause(); 6257 if (!XRC != !YRC) 6258 return false; 6259 if (XRC) { 6260 llvm::FoldingSetNodeID XRCID, YRCID; 6261 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6262 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6263 if (XRCID != YRCID) 6264 return false; 6265 } 6266 6267 return true; 6268 } 6269 6270 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6271 if (auto *NS = X->getAsNamespace()) 6272 return NS; 6273 if (auto *NAS = X->getAsNamespaceAlias()) 6274 return NAS->getNamespace(); 6275 return nullptr; 6276 } 6277 6278 static bool isSameQualifier(const NestedNameSpecifier *X, 6279 const NestedNameSpecifier *Y) { 6280 if (auto *NSX = getNamespace(X)) { 6281 auto *NSY = getNamespace(Y); 6282 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6283 return false; 6284 } else if (X->getKind() != Y->getKind()) 6285 return false; 6286 6287 // FIXME: For namespaces and types, we're permitted to check that the entity 6288 // is named via the same tokens. We should probably do so. 6289 switch (X->getKind()) { 6290 case NestedNameSpecifier::Identifier: 6291 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6292 return false; 6293 break; 6294 case NestedNameSpecifier::Namespace: 6295 case NestedNameSpecifier::NamespaceAlias: 6296 // We've already checked that we named the same namespace. 6297 break; 6298 case NestedNameSpecifier::TypeSpec: 6299 case NestedNameSpecifier::TypeSpecWithTemplate: 6300 if (X->getAsType()->getCanonicalTypeInternal() != 6301 Y->getAsType()->getCanonicalTypeInternal()) 6302 return false; 6303 break; 6304 case NestedNameSpecifier::Global: 6305 case NestedNameSpecifier::Super: 6306 return true; 6307 } 6308 6309 // Recurse into earlier portion of NNS, if any. 6310 auto *PX = X->getPrefix(); 6311 auto *PY = Y->getPrefix(); 6312 if (PX && PY) 6313 return isSameQualifier(PX, PY); 6314 return !PX && !PY; 6315 } 6316 6317 /// Determine whether the attributes we can overload on are identical for A and 6318 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6319 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6320 const FunctionDecl *B) { 6321 // Note that pass_object_size attributes are represented in the function's 6322 // ExtParameterInfo, so we don't need to check them here. 6323 6324 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6325 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6326 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6327 6328 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6329 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6330 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6331 6332 // Return false if the number of enable_if attributes is different. 6333 if (!Cand1A || !Cand2A) 6334 return false; 6335 6336 Cand1ID.clear(); 6337 Cand2ID.clear(); 6338 6339 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6340 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6341 6342 // Return false if any of the enable_if expressions of A and B are 6343 // different. 6344 if (Cand1ID != Cand2ID) 6345 return false; 6346 } 6347 return true; 6348 } 6349 6350 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6351 if (X == Y) 6352 return true; 6353 6354 if (X->getDeclName() != Y->getDeclName()) 6355 return false; 6356 6357 // Must be in the same context. 6358 // 6359 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6360 // could be two different declarations of the same function. (We will fix the 6361 // semantic DC to refer to the primary definition after merging.) 6362 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6363 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6364 return false; 6365 6366 // Two typedefs refer to the same entity if they have the same underlying 6367 // type. 6368 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6369 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6370 return hasSameType(TypedefX->getUnderlyingType(), 6371 TypedefY->getUnderlyingType()); 6372 6373 // Must have the same kind. 6374 if (X->getKind() != Y->getKind()) 6375 return false; 6376 6377 // Objective-C classes and protocols with the same name always match. 6378 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6379 return true; 6380 6381 if (isa<ClassTemplateSpecializationDecl>(X)) { 6382 // No need to handle these here: we merge them when adding them to the 6383 // template. 6384 return false; 6385 } 6386 6387 // Compatible tags match. 6388 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6389 const auto *TagY = cast<TagDecl>(Y); 6390 return (TagX->getTagKind() == TagY->getTagKind()) || 6391 ((TagX->getTagKind() == TTK_Struct || 6392 TagX->getTagKind() == TTK_Class || 6393 TagX->getTagKind() == TTK_Interface) && 6394 (TagY->getTagKind() == TTK_Struct || 6395 TagY->getTagKind() == TTK_Class || 6396 TagY->getTagKind() == TTK_Interface)); 6397 } 6398 6399 // Functions with the same type and linkage match. 6400 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6401 // functions, etc. 6402 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6403 const auto *FuncY = cast<FunctionDecl>(Y); 6404 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6405 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6406 if (CtorX->getInheritedConstructor() && 6407 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6408 CtorY->getInheritedConstructor().getConstructor())) 6409 return false; 6410 } 6411 6412 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6413 return false; 6414 6415 // Multiversioned functions with different feature strings are represented 6416 // as separate declarations. 6417 if (FuncX->isMultiVersion()) { 6418 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6419 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6420 assert(TAX && TAY && "Multiversion Function without target attribute"); 6421 6422 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6423 return false; 6424 } 6425 6426 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6427 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6428 if (!XRC != !YRC) 6429 return false; 6430 if (XRC) { 6431 llvm::FoldingSetNodeID XRCID, YRCID; 6432 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6433 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6434 if (XRCID != YRCID) 6435 return false; 6436 } 6437 6438 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6439 // Map to the first declaration that we've already merged into this one. 6440 // The TSI of redeclarations might not match (due to calling conventions 6441 // being inherited onto the type but not the TSI), but the TSI type of 6442 // the first declaration of the function should match across modules. 6443 FD = FD->getCanonicalDecl(); 6444 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6445 : FD->getType(); 6446 }; 6447 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6448 if (!hasSameType(XT, YT)) { 6449 // We can get functions with different types on the redecl chain in C++17 6450 // if they have differing exception specifications and at least one of 6451 // the excpetion specs is unresolved. 6452 auto *XFPT = XT->getAs<FunctionProtoType>(); 6453 auto *YFPT = YT->getAs<FunctionProtoType>(); 6454 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6455 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6456 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6457 // FIXME: We could make isSameEntity const after we make 6458 // hasSameFunctionTypeIgnoringExceptionSpec const. 6459 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6460 return true; 6461 return false; 6462 } 6463 6464 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6465 hasSameOverloadableAttrs(FuncX, FuncY); 6466 } 6467 6468 // Variables with the same type and linkage match. 6469 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6470 const auto *VarY = cast<VarDecl>(Y); 6471 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6472 if (hasSameType(VarX->getType(), VarY->getType())) 6473 return true; 6474 6475 // We can get decls with different types on the redecl chain. Eg. 6476 // template <typename T> struct S { static T Var[]; }; // #1 6477 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6478 // Only? happens when completing an incomplete array type. In this case 6479 // when comparing #1 and #2 we should go through their element type. 6480 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6481 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6482 if (!VarXTy || !VarYTy) 6483 return false; 6484 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6485 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6486 } 6487 return false; 6488 } 6489 6490 // Namespaces with the same name and inlinedness match. 6491 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6492 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6493 return NamespaceX->isInline() == NamespaceY->isInline(); 6494 } 6495 6496 // Identical template names and kinds match if their template parameter lists 6497 // and patterns match. 6498 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6499 const auto *TemplateY = cast<TemplateDecl>(Y); 6500 return isSameEntity(TemplateX->getTemplatedDecl(), 6501 TemplateY->getTemplatedDecl()) && 6502 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6503 TemplateY->getTemplateParameters()); 6504 } 6505 6506 // Fields with the same name and the same type match. 6507 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6508 const auto *FDY = cast<FieldDecl>(Y); 6509 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6510 return hasSameType(FDX->getType(), FDY->getType()); 6511 } 6512 6513 // Indirect fields with the same target field match. 6514 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6515 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6516 return IFDX->getAnonField()->getCanonicalDecl() == 6517 IFDY->getAnonField()->getCanonicalDecl(); 6518 } 6519 6520 // Enumerators with the same name match. 6521 if (isa<EnumConstantDecl>(X)) 6522 // FIXME: Also check the value is odr-equivalent. 6523 return true; 6524 6525 // Using shadow declarations with the same target match. 6526 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6527 const auto *USY = cast<UsingShadowDecl>(Y); 6528 return USX->getTargetDecl() == USY->getTargetDecl(); 6529 } 6530 6531 // Using declarations with the same qualifier match. (We already know that 6532 // the name matches.) 6533 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6534 const auto *UY = cast<UsingDecl>(Y); 6535 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6536 UX->hasTypename() == UY->hasTypename() && 6537 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6538 } 6539 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6540 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6541 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6542 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6543 } 6544 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6545 return isSameQualifier( 6546 UX->getQualifier(), 6547 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6548 } 6549 6550 // Using-pack declarations are only created by instantiation, and match if 6551 // they're instantiated from matching UnresolvedUsing...Decls. 6552 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6553 return declaresSameEntity( 6554 UX->getInstantiatedFromUsingDecl(), 6555 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6556 } 6557 6558 // Namespace alias definitions with the same target match. 6559 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6560 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6561 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6562 } 6563 6564 return false; 6565 } 6566 6567 TemplateArgument 6568 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6569 switch (Arg.getKind()) { 6570 case TemplateArgument::Null: 6571 return Arg; 6572 6573 case TemplateArgument::Expression: 6574 return Arg; 6575 6576 case TemplateArgument::Declaration: { 6577 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6578 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6579 } 6580 6581 case TemplateArgument::NullPtr: 6582 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6583 /*isNullPtr*/true); 6584 6585 case TemplateArgument::Template: 6586 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6587 6588 case TemplateArgument::TemplateExpansion: 6589 return TemplateArgument(getCanonicalTemplateName( 6590 Arg.getAsTemplateOrTemplatePattern()), 6591 Arg.getNumTemplateExpansions()); 6592 6593 case TemplateArgument::Integral: 6594 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6595 6596 case TemplateArgument::Type: 6597 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6598 6599 case TemplateArgument::Pack: { 6600 if (Arg.pack_size() == 0) 6601 return Arg; 6602 6603 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6604 unsigned Idx = 0; 6605 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6606 AEnd = Arg.pack_end(); 6607 A != AEnd; (void)++A, ++Idx) 6608 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6609 6610 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6611 } 6612 } 6613 6614 // Silence GCC warning 6615 llvm_unreachable("Unhandled template argument kind"); 6616 } 6617 6618 NestedNameSpecifier * 6619 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6620 if (!NNS) 6621 return nullptr; 6622 6623 switch (NNS->getKind()) { 6624 case NestedNameSpecifier::Identifier: 6625 // Canonicalize the prefix but keep the identifier the same. 6626 return NestedNameSpecifier::Create(*this, 6627 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6628 NNS->getAsIdentifier()); 6629 6630 case NestedNameSpecifier::Namespace: 6631 // A namespace is canonical; build a nested-name-specifier with 6632 // this namespace and no prefix. 6633 return NestedNameSpecifier::Create(*this, nullptr, 6634 NNS->getAsNamespace()->getOriginalNamespace()); 6635 6636 case NestedNameSpecifier::NamespaceAlias: 6637 // A namespace is canonical; build a nested-name-specifier with 6638 // this namespace and no prefix. 6639 return NestedNameSpecifier::Create(*this, nullptr, 6640 NNS->getAsNamespaceAlias()->getNamespace() 6641 ->getOriginalNamespace()); 6642 6643 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6644 // latter will have the 'template' keyword when printed. 6645 case NestedNameSpecifier::TypeSpec: 6646 case NestedNameSpecifier::TypeSpecWithTemplate: { 6647 const Type *T = getCanonicalType(NNS->getAsType()); 6648 6649 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6650 // break it apart into its prefix and identifier, then reconsititute those 6651 // as the canonical nested-name-specifier. This is required to canonicalize 6652 // a dependent nested-name-specifier involving typedefs of dependent-name 6653 // types, e.g., 6654 // typedef typename T::type T1; 6655 // typedef typename T1::type T2; 6656 if (const auto *DNT = T->getAs<DependentNameType>()) 6657 return NestedNameSpecifier::Create( 6658 *this, DNT->getQualifier(), 6659 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6660 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6661 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6662 const_cast<Type *>(T)); 6663 6664 // TODO: Set 'Template' parameter to true for other template types. 6665 return NestedNameSpecifier::Create(*this, nullptr, false, 6666 const_cast<Type *>(T)); 6667 } 6668 6669 case NestedNameSpecifier::Global: 6670 case NestedNameSpecifier::Super: 6671 // The global specifier and __super specifer are canonical and unique. 6672 return NNS; 6673 } 6674 6675 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6676 } 6677 6678 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6679 // Handle the non-qualified case efficiently. 6680 if (!T.hasLocalQualifiers()) { 6681 // Handle the common positive case fast. 6682 if (const auto *AT = dyn_cast<ArrayType>(T)) 6683 return AT; 6684 } 6685 6686 // Handle the common negative case fast. 6687 if (!isa<ArrayType>(T.getCanonicalType())) 6688 return nullptr; 6689 6690 // Apply any qualifiers from the array type to the element type. This 6691 // implements C99 6.7.3p8: "If the specification of an array type includes 6692 // any type qualifiers, the element type is so qualified, not the array type." 6693 6694 // If we get here, we either have type qualifiers on the type, or we have 6695 // sugar such as a typedef in the way. If we have type qualifiers on the type 6696 // we must propagate them down into the element type. 6697 6698 SplitQualType split = T.getSplitDesugaredType(); 6699 Qualifiers qs = split.Quals; 6700 6701 // If we have a simple case, just return now. 6702 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6703 if (!ATy || qs.empty()) 6704 return ATy; 6705 6706 // Otherwise, we have an array and we have qualifiers on it. Push the 6707 // qualifiers into the array element type and return a new array type. 6708 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6709 6710 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6711 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6712 CAT->getSizeExpr(), 6713 CAT->getSizeModifier(), 6714 CAT->getIndexTypeCVRQualifiers())); 6715 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6716 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6717 IAT->getSizeModifier(), 6718 IAT->getIndexTypeCVRQualifiers())); 6719 6720 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6721 return cast<ArrayType>( 6722 getDependentSizedArrayType(NewEltTy, 6723 DSAT->getSizeExpr(), 6724 DSAT->getSizeModifier(), 6725 DSAT->getIndexTypeCVRQualifiers(), 6726 DSAT->getBracketsRange())); 6727 6728 const auto *VAT = cast<VariableArrayType>(ATy); 6729 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6730 VAT->getSizeExpr(), 6731 VAT->getSizeModifier(), 6732 VAT->getIndexTypeCVRQualifiers(), 6733 VAT->getBracketsRange())); 6734 } 6735 6736 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6737 if (T->isArrayType() || T->isFunctionType()) 6738 return getDecayedType(T); 6739 return T; 6740 } 6741 6742 QualType ASTContext::getSignatureParameterType(QualType T) const { 6743 T = getVariableArrayDecayedType(T); 6744 T = getAdjustedParameterType(T); 6745 return T.getUnqualifiedType(); 6746 } 6747 6748 QualType ASTContext::getExceptionObjectType(QualType T) const { 6749 // C++ [except.throw]p3: 6750 // A throw-expression initializes a temporary object, called the exception 6751 // object, the type of which is determined by removing any top-level 6752 // cv-qualifiers from the static type of the operand of throw and adjusting 6753 // the type from "array of T" or "function returning T" to "pointer to T" 6754 // or "pointer to function returning T", [...] 6755 T = getVariableArrayDecayedType(T); 6756 if (T->isArrayType() || T->isFunctionType()) 6757 T = getDecayedType(T); 6758 return T.getUnqualifiedType(); 6759 } 6760 6761 /// getArrayDecayedType - Return the properly qualified result of decaying the 6762 /// specified array type to a pointer. This operation is non-trivial when 6763 /// handling typedefs etc. The canonical type of "T" must be an array type, 6764 /// this returns a pointer to a properly qualified element of the array. 6765 /// 6766 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6767 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6768 // Get the element type with 'getAsArrayType' so that we don't lose any 6769 // typedefs in the element type of the array. This also handles propagation 6770 // of type qualifiers from the array type into the element type if present 6771 // (C99 6.7.3p8). 6772 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6773 assert(PrettyArrayType && "Not an array type!"); 6774 6775 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6776 6777 // int x[restrict 4] -> int *restrict 6778 QualType Result = getQualifiedType(PtrTy, 6779 PrettyArrayType->getIndexTypeQualifiers()); 6780 6781 // int x[_Nullable] -> int * _Nullable 6782 if (auto Nullability = Ty->getNullability(*this)) { 6783 Result = const_cast<ASTContext *>(this)->getAttributedType( 6784 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6785 } 6786 return Result; 6787 } 6788 6789 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6790 return getBaseElementType(array->getElementType()); 6791 } 6792 6793 QualType ASTContext::getBaseElementType(QualType type) const { 6794 Qualifiers qs; 6795 while (true) { 6796 SplitQualType split = type.getSplitDesugaredType(); 6797 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6798 if (!array) break; 6799 6800 type = array->getElementType(); 6801 qs.addConsistentQualifiers(split.Quals); 6802 } 6803 6804 return getQualifiedType(type, qs); 6805 } 6806 6807 /// getConstantArrayElementCount - Returns number of constant array elements. 6808 uint64_t 6809 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6810 uint64_t ElementCount = 1; 6811 do { 6812 ElementCount *= CA->getSize().getZExtValue(); 6813 CA = dyn_cast_or_null<ConstantArrayType>( 6814 CA->getElementType()->getAsArrayTypeUnsafe()); 6815 } while (CA); 6816 return ElementCount; 6817 } 6818 6819 /// getFloatingRank - Return a relative rank for floating point types. 6820 /// This routine will assert if passed a built-in type that isn't a float. 6821 static FloatingRank getFloatingRank(QualType T) { 6822 if (const auto *CT = T->getAs<ComplexType>()) 6823 return getFloatingRank(CT->getElementType()); 6824 6825 switch (T->castAs<BuiltinType>()->getKind()) { 6826 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6827 case BuiltinType::Float16: return Float16Rank; 6828 case BuiltinType::Half: return HalfRank; 6829 case BuiltinType::Float: return FloatRank; 6830 case BuiltinType::Double: return DoubleRank; 6831 case BuiltinType::LongDouble: return LongDoubleRank; 6832 case BuiltinType::Float128: return Float128Rank; 6833 case BuiltinType::BFloat16: return BFloat16Rank; 6834 case BuiltinType::Ibm128: return Ibm128Rank; 6835 } 6836 } 6837 6838 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6839 /// point types, ignoring the domain of the type (i.e. 'double' == 6840 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6841 /// LHS < RHS, return -1. 6842 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6843 FloatingRank LHSR = getFloatingRank(LHS); 6844 FloatingRank RHSR = getFloatingRank(RHS); 6845 6846 if (LHSR == RHSR) 6847 return 0; 6848 if (LHSR > RHSR) 6849 return 1; 6850 return -1; 6851 } 6852 6853 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6854 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6855 return 0; 6856 return getFloatingTypeOrder(LHS, RHS); 6857 } 6858 6859 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6860 /// routine will assert if passed a built-in type that isn't an integer or enum, 6861 /// or if it is not canonicalized. 6862 unsigned ASTContext::getIntegerRank(const Type *T) const { 6863 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6864 6865 // Results in this 'losing' to any type of the same size, but winning if 6866 // larger. 6867 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6868 return 0 + (EIT->getNumBits() << 3); 6869 6870 switch (cast<BuiltinType>(T)->getKind()) { 6871 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6872 case BuiltinType::Bool: 6873 return 1 + (getIntWidth(BoolTy) << 3); 6874 case BuiltinType::Char_S: 6875 case BuiltinType::Char_U: 6876 case BuiltinType::SChar: 6877 case BuiltinType::UChar: 6878 return 2 + (getIntWidth(CharTy) << 3); 6879 case BuiltinType::Short: 6880 case BuiltinType::UShort: 6881 return 3 + (getIntWidth(ShortTy) << 3); 6882 case BuiltinType::Int: 6883 case BuiltinType::UInt: 6884 return 4 + (getIntWidth(IntTy) << 3); 6885 case BuiltinType::Long: 6886 case BuiltinType::ULong: 6887 return 5 + (getIntWidth(LongTy) << 3); 6888 case BuiltinType::LongLong: 6889 case BuiltinType::ULongLong: 6890 return 6 + (getIntWidth(LongLongTy) << 3); 6891 case BuiltinType::Int128: 6892 case BuiltinType::UInt128: 6893 return 7 + (getIntWidth(Int128Ty) << 3); 6894 } 6895 } 6896 6897 /// Whether this is a promotable bitfield reference according 6898 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6899 /// 6900 /// \returns the type this bit-field will promote to, or NULL if no 6901 /// promotion occurs. 6902 QualType ASTContext::isPromotableBitField(Expr *E) const { 6903 if (E->isTypeDependent() || E->isValueDependent()) 6904 return {}; 6905 6906 // C++ [conv.prom]p5: 6907 // If the bit-field has an enumerated type, it is treated as any other 6908 // value of that type for promotion purposes. 6909 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6910 return {}; 6911 6912 // FIXME: We should not do this unless E->refersToBitField() is true. This 6913 // matters in C where getSourceBitField() will find bit-fields for various 6914 // cases where the source expression is not a bit-field designator. 6915 6916 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6917 if (!Field) 6918 return {}; 6919 6920 QualType FT = Field->getType(); 6921 6922 uint64_t BitWidth = Field->getBitWidthValue(*this); 6923 uint64_t IntSize = getTypeSize(IntTy); 6924 // C++ [conv.prom]p5: 6925 // A prvalue for an integral bit-field can be converted to a prvalue of type 6926 // int if int can represent all the values of the bit-field; otherwise, it 6927 // can be converted to unsigned int if unsigned int can represent all the 6928 // values of the bit-field. If the bit-field is larger yet, no integral 6929 // promotion applies to it. 6930 // C11 6.3.1.1/2: 6931 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6932 // If an int can represent all values of the original type (as restricted by 6933 // the width, for a bit-field), the value is converted to an int; otherwise, 6934 // it is converted to an unsigned int. 6935 // 6936 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6937 // We perform that promotion here to match GCC and C++. 6938 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6939 // greater than that of 'int'. We perform that promotion to match GCC. 6940 if (BitWidth < IntSize) 6941 return IntTy; 6942 6943 if (BitWidth == IntSize) 6944 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6945 6946 // Bit-fields wider than int are not subject to promotions, and therefore act 6947 // like the base type. GCC has some weird bugs in this area that we 6948 // deliberately do not follow (GCC follows a pre-standard resolution to 6949 // C's DR315 which treats bit-width as being part of the type, and this leaks 6950 // into their semantics in some cases). 6951 return {}; 6952 } 6953 6954 /// getPromotedIntegerType - Returns the type that Promotable will 6955 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6956 /// integer type. 6957 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6958 assert(!Promotable.isNull()); 6959 assert(Promotable->isPromotableIntegerType()); 6960 if (const auto *ET = Promotable->getAs<EnumType>()) 6961 return ET->getDecl()->getPromotionType(); 6962 6963 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6964 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6965 // (3.9.1) can be converted to a prvalue of the first of the following 6966 // types that can represent all the values of its underlying type: 6967 // int, unsigned int, long int, unsigned long int, long long int, or 6968 // unsigned long long int [...] 6969 // FIXME: Is there some better way to compute this? 6970 if (BT->getKind() == BuiltinType::WChar_S || 6971 BT->getKind() == BuiltinType::WChar_U || 6972 BT->getKind() == BuiltinType::Char8 || 6973 BT->getKind() == BuiltinType::Char16 || 6974 BT->getKind() == BuiltinType::Char32) { 6975 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6976 uint64_t FromSize = getTypeSize(BT); 6977 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6978 LongLongTy, UnsignedLongLongTy }; 6979 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6980 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6981 if (FromSize < ToSize || 6982 (FromSize == ToSize && 6983 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6984 return PromoteTypes[Idx]; 6985 } 6986 llvm_unreachable("char type should fit into long long"); 6987 } 6988 } 6989 6990 // At this point, we should have a signed or unsigned integer type. 6991 if (Promotable->isSignedIntegerType()) 6992 return IntTy; 6993 uint64_t PromotableSize = getIntWidth(Promotable); 6994 uint64_t IntSize = getIntWidth(IntTy); 6995 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6996 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6997 } 6998 6999 /// Recurses in pointer/array types until it finds an objc retainable 7000 /// type and returns its ownership. 7001 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 7002 while (!T.isNull()) { 7003 if (T.getObjCLifetime() != Qualifiers::OCL_None) 7004 return T.getObjCLifetime(); 7005 if (T->isArrayType()) 7006 T = getBaseElementType(T); 7007 else if (const auto *PT = T->getAs<PointerType>()) 7008 T = PT->getPointeeType(); 7009 else if (const auto *RT = T->getAs<ReferenceType>()) 7010 T = RT->getPointeeType(); 7011 else 7012 break; 7013 } 7014 7015 return Qualifiers::OCL_None; 7016 } 7017 7018 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 7019 // Incomplete enum types are not treated as integer types. 7020 // FIXME: In C++, enum types are never integer types. 7021 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 7022 return ET->getDecl()->getIntegerType().getTypePtr(); 7023 return nullptr; 7024 } 7025 7026 /// getIntegerTypeOrder - Returns the highest ranked integer type: 7027 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 7028 /// LHS < RHS, return -1. 7029 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 7030 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 7031 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 7032 7033 // Unwrap enums to their underlying type. 7034 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 7035 LHSC = getIntegerTypeForEnum(ET); 7036 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7037 RHSC = getIntegerTypeForEnum(ET); 7038 7039 if (LHSC == RHSC) return 0; 7040 7041 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7042 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7043 7044 unsigned LHSRank = getIntegerRank(LHSC); 7045 unsigned RHSRank = getIntegerRank(RHSC); 7046 7047 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7048 if (LHSRank == RHSRank) return 0; 7049 return LHSRank > RHSRank ? 1 : -1; 7050 } 7051 7052 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7053 if (LHSUnsigned) { 7054 // If the unsigned [LHS] type is larger, return it. 7055 if (LHSRank >= RHSRank) 7056 return 1; 7057 7058 // If the signed type can represent all values of the unsigned type, it 7059 // wins. Because we are dealing with 2's complement and types that are 7060 // powers of two larger than each other, this is always safe. 7061 return -1; 7062 } 7063 7064 // If the unsigned [RHS] type is larger, return it. 7065 if (RHSRank >= LHSRank) 7066 return -1; 7067 7068 // If the signed type can represent all values of the unsigned type, it 7069 // wins. Because we are dealing with 2's complement and types that are 7070 // powers of two larger than each other, this is always safe. 7071 return 1; 7072 } 7073 7074 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7075 if (CFConstantStringTypeDecl) 7076 return CFConstantStringTypeDecl; 7077 7078 assert(!CFConstantStringTagDecl && 7079 "tag and typedef should be initialized together"); 7080 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7081 CFConstantStringTagDecl->startDefinition(); 7082 7083 struct { 7084 QualType Type; 7085 const char *Name; 7086 } Fields[5]; 7087 unsigned Count = 0; 7088 7089 /// Objective-C ABI 7090 /// 7091 /// typedef struct __NSConstantString_tag { 7092 /// const int *isa; 7093 /// int flags; 7094 /// const char *str; 7095 /// long length; 7096 /// } __NSConstantString; 7097 /// 7098 /// Swift ABI (4.1, 4.2) 7099 /// 7100 /// typedef struct __NSConstantString_tag { 7101 /// uintptr_t _cfisa; 7102 /// uintptr_t _swift_rc; 7103 /// _Atomic(uint64_t) _cfinfoa; 7104 /// const char *_ptr; 7105 /// uint32_t _length; 7106 /// } __NSConstantString; 7107 /// 7108 /// Swift ABI (5.0) 7109 /// 7110 /// typedef struct __NSConstantString_tag { 7111 /// uintptr_t _cfisa; 7112 /// uintptr_t _swift_rc; 7113 /// _Atomic(uint64_t) _cfinfoa; 7114 /// const char *_ptr; 7115 /// uintptr_t _length; 7116 /// } __NSConstantString; 7117 7118 const auto CFRuntime = getLangOpts().CFRuntime; 7119 if (static_cast<unsigned>(CFRuntime) < 7120 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7121 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7122 Fields[Count++] = { IntTy, "flags" }; 7123 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7124 Fields[Count++] = { LongTy, "length" }; 7125 } else { 7126 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7127 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7128 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7129 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7130 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7131 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7132 Fields[Count++] = { IntTy, "_ptr" }; 7133 else 7134 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7135 } 7136 7137 // Create fields 7138 for (unsigned i = 0; i < Count; ++i) { 7139 FieldDecl *Field = 7140 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7141 SourceLocation(), &Idents.get(Fields[i].Name), 7142 Fields[i].Type, /*TInfo=*/nullptr, 7143 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7144 Field->setAccess(AS_public); 7145 CFConstantStringTagDecl->addDecl(Field); 7146 } 7147 7148 CFConstantStringTagDecl->completeDefinition(); 7149 // This type is designed to be compatible with NSConstantString, but cannot 7150 // use the same name, since NSConstantString is an interface. 7151 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7152 CFConstantStringTypeDecl = 7153 buildImplicitTypedef(tagType, "__NSConstantString"); 7154 7155 return CFConstantStringTypeDecl; 7156 } 7157 7158 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7159 if (!CFConstantStringTagDecl) 7160 getCFConstantStringDecl(); // Build the tag and the typedef. 7161 return CFConstantStringTagDecl; 7162 } 7163 7164 // getCFConstantStringType - Return the type used for constant CFStrings. 7165 QualType ASTContext::getCFConstantStringType() const { 7166 return getTypedefType(getCFConstantStringDecl()); 7167 } 7168 7169 QualType ASTContext::getObjCSuperType() const { 7170 if (ObjCSuperType.isNull()) { 7171 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7172 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7173 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7174 } 7175 return ObjCSuperType; 7176 } 7177 7178 void ASTContext::setCFConstantStringType(QualType T) { 7179 const auto *TD = T->castAs<TypedefType>(); 7180 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7181 const auto *TagType = 7182 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7183 CFConstantStringTagDecl = TagType->getDecl(); 7184 } 7185 7186 QualType ASTContext::getBlockDescriptorType() const { 7187 if (BlockDescriptorType) 7188 return getTagDeclType(BlockDescriptorType); 7189 7190 RecordDecl *RD; 7191 // FIXME: Needs the FlagAppleBlock bit. 7192 RD = buildImplicitRecord("__block_descriptor"); 7193 RD->startDefinition(); 7194 7195 QualType FieldTypes[] = { 7196 UnsignedLongTy, 7197 UnsignedLongTy, 7198 }; 7199 7200 static const char *const FieldNames[] = { 7201 "reserved", 7202 "Size" 7203 }; 7204 7205 for (size_t i = 0; i < 2; ++i) { 7206 FieldDecl *Field = FieldDecl::Create( 7207 *this, RD, SourceLocation(), SourceLocation(), 7208 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7209 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7210 Field->setAccess(AS_public); 7211 RD->addDecl(Field); 7212 } 7213 7214 RD->completeDefinition(); 7215 7216 BlockDescriptorType = RD; 7217 7218 return getTagDeclType(BlockDescriptorType); 7219 } 7220 7221 QualType ASTContext::getBlockDescriptorExtendedType() const { 7222 if (BlockDescriptorExtendedType) 7223 return getTagDeclType(BlockDescriptorExtendedType); 7224 7225 RecordDecl *RD; 7226 // FIXME: Needs the FlagAppleBlock bit. 7227 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7228 RD->startDefinition(); 7229 7230 QualType FieldTypes[] = { 7231 UnsignedLongTy, 7232 UnsignedLongTy, 7233 getPointerType(VoidPtrTy), 7234 getPointerType(VoidPtrTy) 7235 }; 7236 7237 static const char *const FieldNames[] = { 7238 "reserved", 7239 "Size", 7240 "CopyFuncPtr", 7241 "DestroyFuncPtr" 7242 }; 7243 7244 for (size_t i = 0; i < 4; ++i) { 7245 FieldDecl *Field = FieldDecl::Create( 7246 *this, RD, SourceLocation(), SourceLocation(), 7247 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7248 /*BitWidth=*/nullptr, 7249 /*Mutable=*/false, ICIS_NoInit); 7250 Field->setAccess(AS_public); 7251 RD->addDecl(Field); 7252 } 7253 7254 RD->completeDefinition(); 7255 7256 BlockDescriptorExtendedType = RD; 7257 return getTagDeclType(BlockDescriptorExtendedType); 7258 } 7259 7260 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7261 const auto *BT = dyn_cast<BuiltinType>(T); 7262 7263 if (!BT) { 7264 if (isa<PipeType>(T)) 7265 return OCLTK_Pipe; 7266 7267 return OCLTK_Default; 7268 } 7269 7270 switch (BT->getKind()) { 7271 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7272 case BuiltinType::Id: \ 7273 return OCLTK_Image; 7274 #include "clang/Basic/OpenCLImageTypes.def" 7275 7276 case BuiltinType::OCLClkEvent: 7277 return OCLTK_ClkEvent; 7278 7279 case BuiltinType::OCLEvent: 7280 return OCLTK_Event; 7281 7282 case BuiltinType::OCLQueue: 7283 return OCLTK_Queue; 7284 7285 case BuiltinType::OCLReserveID: 7286 return OCLTK_ReserveID; 7287 7288 case BuiltinType::OCLSampler: 7289 return OCLTK_Sampler; 7290 7291 default: 7292 return OCLTK_Default; 7293 } 7294 } 7295 7296 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7297 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7298 } 7299 7300 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7301 /// requires copy/dispose. Note that this must match the logic 7302 /// in buildByrefHelpers. 7303 bool ASTContext::BlockRequiresCopying(QualType Ty, 7304 const VarDecl *D) { 7305 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7306 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7307 if (!copyExpr && record->hasTrivialDestructor()) return false; 7308 7309 return true; 7310 } 7311 7312 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7313 // move or destroy. 7314 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7315 return true; 7316 7317 if (!Ty->isObjCRetainableType()) return false; 7318 7319 Qualifiers qs = Ty.getQualifiers(); 7320 7321 // If we have lifetime, that dominates. 7322 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7323 switch (lifetime) { 7324 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7325 7326 // These are just bits as far as the runtime is concerned. 7327 case Qualifiers::OCL_ExplicitNone: 7328 case Qualifiers::OCL_Autoreleasing: 7329 return false; 7330 7331 // These cases should have been taken care of when checking the type's 7332 // non-triviality. 7333 case Qualifiers::OCL_Weak: 7334 case Qualifiers::OCL_Strong: 7335 llvm_unreachable("impossible"); 7336 } 7337 llvm_unreachable("fell out of lifetime switch!"); 7338 } 7339 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7340 Ty->isObjCObjectPointerType()); 7341 } 7342 7343 bool ASTContext::getByrefLifetime(QualType Ty, 7344 Qualifiers::ObjCLifetime &LifeTime, 7345 bool &HasByrefExtendedLayout) const { 7346 if (!getLangOpts().ObjC || 7347 getLangOpts().getGC() != LangOptions::NonGC) 7348 return false; 7349 7350 HasByrefExtendedLayout = false; 7351 if (Ty->isRecordType()) { 7352 HasByrefExtendedLayout = true; 7353 LifeTime = Qualifiers::OCL_None; 7354 } else if ((LifeTime = Ty.getObjCLifetime())) { 7355 // Honor the ARC qualifiers. 7356 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7357 // The MRR rule. 7358 LifeTime = Qualifiers::OCL_ExplicitNone; 7359 } else { 7360 LifeTime = Qualifiers::OCL_None; 7361 } 7362 return true; 7363 } 7364 7365 CanQualType ASTContext::getNSUIntegerType() const { 7366 assert(Target && "Expected target to be initialized"); 7367 const llvm::Triple &T = Target->getTriple(); 7368 // Windows is LLP64 rather than LP64 7369 if (T.isOSWindows() && T.isArch64Bit()) 7370 return UnsignedLongLongTy; 7371 return UnsignedLongTy; 7372 } 7373 7374 CanQualType ASTContext::getNSIntegerType() const { 7375 assert(Target && "Expected target to be initialized"); 7376 const llvm::Triple &T = Target->getTriple(); 7377 // Windows is LLP64 rather than LP64 7378 if (T.isOSWindows() && T.isArch64Bit()) 7379 return LongLongTy; 7380 return LongTy; 7381 } 7382 7383 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7384 if (!ObjCInstanceTypeDecl) 7385 ObjCInstanceTypeDecl = 7386 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7387 return ObjCInstanceTypeDecl; 7388 } 7389 7390 // This returns true if a type has been typedefed to BOOL: 7391 // typedef <type> BOOL; 7392 static bool isTypeTypedefedAsBOOL(QualType T) { 7393 if (const auto *TT = dyn_cast<TypedefType>(T)) 7394 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7395 return II->isStr("BOOL"); 7396 7397 return false; 7398 } 7399 7400 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7401 /// purpose. 7402 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7403 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7404 return CharUnits::Zero(); 7405 7406 CharUnits sz = getTypeSizeInChars(type); 7407 7408 // Make all integer and enum types at least as large as an int 7409 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7410 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7411 // Treat arrays as pointers, since that's how they're passed in. 7412 else if (type->isArrayType()) 7413 sz = getTypeSizeInChars(VoidPtrTy); 7414 return sz; 7415 } 7416 7417 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7418 return getTargetInfo().getCXXABI().isMicrosoft() && 7419 VD->isStaticDataMember() && 7420 VD->getType()->isIntegralOrEnumerationType() && 7421 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7422 } 7423 7424 ASTContext::InlineVariableDefinitionKind 7425 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7426 if (!VD->isInline()) 7427 return InlineVariableDefinitionKind::None; 7428 7429 // In almost all cases, it's a weak definition. 7430 auto *First = VD->getFirstDecl(); 7431 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7432 return InlineVariableDefinitionKind::Weak; 7433 7434 // If there's a file-context declaration in this translation unit, it's a 7435 // non-discardable definition. 7436 for (auto *D : VD->redecls()) 7437 if (D->getLexicalDeclContext()->isFileContext() && 7438 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7439 return InlineVariableDefinitionKind::Strong; 7440 7441 // If we've not seen one yet, we don't know. 7442 return InlineVariableDefinitionKind::WeakUnknown; 7443 } 7444 7445 static std::string charUnitsToString(const CharUnits &CU) { 7446 return llvm::itostr(CU.getQuantity()); 7447 } 7448 7449 /// getObjCEncodingForBlock - Return the encoded type for this block 7450 /// declaration. 7451 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7452 std::string S; 7453 7454 const BlockDecl *Decl = Expr->getBlockDecl(); 7455 QualType BlockTy = 7456 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7457 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7458 // Encode result type. 7459 if (getLangOpts().EncodeExtendedBlockSig) 7460 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7461 true /*Extended*/); 7462 else 7463 getObjCEncodingForType(BlockReturnTy, S); 7464 // Compute size of all parameters. 7465 // Start with computing size of a pointer in number of bytes. 7466 // FIXME: There might(should) be a better way of doing this computation! 7467 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7468 CharUnits ParmOffset = PtrSize; 7469 for (auto PI : Decl->parameters()) { 7470 QualType PType = PI->getType(); 7471 CharUnits sz = getObjCEncodingTypeSize(PType); 7472 if (sz.isZero()) 7473 continue; 7474 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7475 ParmOffset += sz; 7476 } 7477 // Size of the argument frame 7478 S += charUnitsToString(ParmOffset); 7479 // Block pointer and offset. 7480 S += "@?0"; 7481 7482 // Argument types. 7483 ParmOffset = PtrSize; 7484 for (auto PVDecl : Decl->parameters()) { 7485 QualType PType = PVDecl->getOriginalType(); 7486 if (const auto *AT = 7487 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7488 // Use array's original type only if it has known number of 7489 // elements. 7490 if (!isa<ConstantArrayType>(AT)) 7491 PType = PVDecl->getType(); 7492 } else if (PType->isFunctionType()) 7493 PType = PVDecl->getType(); 7494 if (getLangOpts().EncodeExtendedBlockSig) 7495 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7496 S, true /*Extended*/); 7497 else 7498 getObjCEncodingForType(PType, S); 7499 S += charUnitsToString(ParmOffset); 7500 ParmOffset += getObjCEncodingTypeSize(PType); 7501 } 7502 7503 return S; 7504 } 7505 7506 std::string 7507 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7508 std::string S; 7509 // Encode result type. 7510 getObjCEncodingForType(Decl->getReturnType(), S); 7511 CharUnits ParmOffset; 7512 // Compute size of all parameters. 7513 for (auto PI : Decl->parameters()) { 7514 QualType PType = PI->getType(); 7515 CharUnits sz = getObjCEncodingTypeSize(PType); 7516 if (sz.isZero()) 7517 continue; 7518 7519 assert(sz.isPositive() && 7520 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7521 ParmOffset += sz; 7522 } 7523 S += charUnitsToString(ParmOffset); 7524 ParmOffset = CharUnits::Zero(); 7525 7526 // Argument types. 7527 for (auto PVDecl : Decl->parameters()) { 7528 QualType PType = PVDecl->getOriginalType(); 7529 if (const auto *AT = 7530 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7531 // Use array's original type only if it has known number of 7532 // elements. 7533 if (!isa<ConstantArrayType>(AT)) 7534 PType = PVDecl->getType(); 7535 } else if (PType->isFunctionType()) 7536 PType = PVDecl->getType(); 7537 getObjCEncodingForType(PType, S); 7538 S += charUnitsToString(ParmOffset); 7539 ParmOffset += getObjCEncodingTypeSize(PType); 7540 } 7541 7542 return S; 7543 } 7544 7545 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7546 /// method parameter or return type. If Extended, include class names and 7547 /// block object types. 7548 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7549 QualType T, std::string& S, 7550 bool Extended) const { 7551 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7552 getObjCEncodingForTypeQualifier(QT, S); 7553 // Encode parameter type. 7554 ObjCEncOptions Options = ObjCEncOptions() 7555 .setExpandPointedToStructures() 7556 .setExpandStructures() 7557 .setIsOutermostType(); 7558 if (Extended) 7559 Options.setEncodeBlockParameters().setEncodeClassNames(); 7560 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7561 } 7562 7563 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7564 /// declaration. 7565 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7566 bool Extended) const { 7567 // FIXME: This is not very efficient. 7568 // Encode return type. 7569 std::string S; 7570 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7571 Decl->getReturnType(), S, Extended); 7572 // Compute size of all parameters. 7573 // Start with computing size of a pointer in number of bytes. 7574 // FIXME: There might(should) be a better way of doing this computation! 7575 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7576 // The first two arguments (self and _cmd) are pointers; account for 7577 // their size. 7578 CharUnits ParmOffset = 2 * PtrSize; 7579 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7580 E = Decl->sel_param_end(); PI != E; ++PI) { 7581 QualType PType = (*PI)->getType(); 7582 CharUnits sz = getObjCEncodingTypeSize(PType); 7583 if (sz.isZero()) 7584 continue; 7585 7586 assert(sz.isPositive() && 7587 "getObjCEncodingForMethodDecl - Incomplete param type"); 7588 ParmOffset += sz; 7589 } 7590 S += charUnitsToString(ParmOffset); 7591 S += "@0:"; 7592 S += charUnitsToString(PtrSize); 7593 7594 // Argument types. 7595 ParmOffset = 2 * PtrSize; 7596 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7597 E = Decl->sel_param_end(); PI != E; ++PI) { 7598 const ParmVarDecl *PVDecl = *PI; 7599 QualType PType = PVDecl->getOriginalType(); 7600 if (const auto *AT = 7601 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7602 // Use array's original type only if it has known number of 7603 // elements. 7604 if (!isa<ConstantArrayType>(AT)) 7605 PType = PVDecl->getType(); 7606 } else if (PType->isFunctionType()) 7607 PType = PVDecl->getType(); 7608 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7609 PType, S, Extended); 7610 S += charUnitsToString(ParmOffset); 7611 ParmOffset += getObjCEncodingTypeSize(PType); 7612 } 7613 7614 return S; 7615 } 7616 7617 ObjCPropertyImplDecl * 7618 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7619 const ObjCPropertyDecl *PD, 7620 const Decl *Container) const { 7621 if (!Container) 7622 return nullptr; 7623 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7624 for (auto *PID : CID->property_impls()) 7625 if (PID->getPropertyDecl() == PD) 7626 return PID; 7627 } else { 7628 const auto *OID = cast<ObjCImplementationDecl>(Container); 7629 for (auto *PID : OID->property_impls()) 7630 if (PID->getPropertyDecl() == PD) 7631 return PID; 7632 } 7633 return nullptr; 7634 } 7635 7636 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7637 /// property declaration. If non-NULL, Container must be either an 7638 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7639 /// NULL when getting encodings for protocol properties. 7640 /// Property attributes are stored as a comma-delimited C string. The simple 7641 /// attributes readonly and bycopy are encoded as single characters. The 7642 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7643 /// encoded as single characters, followed by an identifier. Property types 7644 /// are also encoded as a parametrized attribute. The characters used to encode 7645 /// these attributes are defined by the following enumeration: 7646 /// @code 7647 /// enum PropertyAttributes { 7648 /// kPropertyReadOnly = 'R', // property is read-only. 7649 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7650 /// kPropertyByref = '&', // property is a reference to the value last assigned 7651 /// kPropertyDynamic = 'D', // property is dynamic 7652 /// kPropertyGetter = 'G', // followed by getter selector name 7653 /// kPropertySetter = 'S', // followed by setter selector name 7654 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7655 /// kPropertyType = 'T' // followed by old-style type encoding. 7656 /// kPropertyWeak = 'W' // 'weak' property 7657 /// kPropertyStrong = 'P' // property GC'able 7658 /// kPropertyNonAtomic = 'N' // property non-atomic 7659 /// }; 7660 /// @endcode 7661 std::string 7662 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7663 const Decl *Container) const { 7664 // Collect information from the property implementation decl(s). 7665 bool Dynamic = false; 7666 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7667 7668 if (ObjCPropertyImplDecl *PropertyImpDecl = 7669 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7670 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7671 Dynamic = true; 7672 else 7673 SynthesizePID = PropertyImpDecl; 7674 } 7675 7676 // FIXME: This is not very efficient. 7677 std::string S = "T"; 7678 7679 // Encode result type. 7680 // GCC has some special rules regarding encoding of properties which 7681 // closely resembles encoding of ivars. 7682 getObjCEncodingForPropertyType(PD->getType(), S); 7683 7684 if (PD->isReadOnly()) { 7685 S += ",R"; 7686 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7687 S += ",C"; 7688 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7689 S += ",&"; 7690 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7691 S += ",W"; 7692 } else { 7693 switch (PD->getSetterKind()) { 7694 case ObjCPropertyDecl::Assign: break; 7695 case ObjCPropertyDecl::Copy: S += ",C"; break; 7696 case ObjCPropertyDecl::Retain: S += ",&"; break; 7697 case ObjCPropertyDecl::Weak: S += ",W"; break; 7698 } 7699 } 7700 7701 // It really isn't clear at all what this means, since properties 7702 // are "dynamic by default". 7703 if (Dynamic) 7704 S += ",D"; 7705 7706 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7707 S += ",N"; 7708 7709 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7710 S += ",G"; 7711 S += PD->getGetterName().getAsString(); 7712 } 7713 7714 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7715 S += ",S"; 7716 S += PD->getSetterName().getAsString(); 7717 } 7718 7719 if (SynthesizePID) { 7720 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7721 S += ",V"; 7722 S += OID->getNameAsString(); 7723 } 7724 7725 // FIXME: OBJCGC: weak & strong 7726 return S; 7727 } 7728 7729 /// getLegacyIntegralTypeEncoding - 7730 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7731 /// 'l' or 'L' , but not always. For typedefs, we need to use 7732 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7733 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7734 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7735 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7736 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7737 PointeeTy = UnsignedIntTy; 7738 else 7739 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7740 PointeeTy = IntTy; 7741 } 7742 } 7743 } 7744 7745 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7746 const FieldDecl *Field, 7747 QualType *NotEncodedT) const { 7748 // We follow the behavior of gcc, expanding structures which are 7749 // directly pointed to, and expanding embedded structures. Note that 7750 // these rules are sufficient to prevent recursive encoding of the 7751 // same type. 7752 getObjCEncodingForTypeImpl(T, S, 7753 ObjCEncOptions() 7754 .setExpandPointedToStructures() 7755 .setExpandStructures() 7756 .setIsOutermostType(), 7757 Field, NotEncodedT); 7758 } 7759 7760 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7761 std::string& S) const { 7762 // Encode result type. 7763 // GCC has some special rules regarding encoding of properties which 7764 // closely resembles encoding of ivars. 7765 getObjCEncodingForTypeImpl(T, S, 7766 ObjCEncOptions() 7767 .setExpandPointedToStructures() 7768 .setExpandStructures() 7769 .setIsOutermostType() 7770 .setEncodingProperty(), 7771 /*Field=*/nullptr); 7772 } 7773 7774 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7775 const BuiltinType *BT) { 7776 BuiltinType::Kind kind = BT->getKind(); 7777 switch (kind) { 7778 case BuiltinType::Void: return 'v'; 7779 case BuiltinType::Bool: return 'B'; 7780 case BuiltinType::Char8: 7781 case BuiltinType::Char_U: 7782 case BuiltinType::UChar: return 'C'; 7783 case BuiltinType::Char16: 7784 case BuiltinType::UShort: return 'S'; 7785 case BuiltinType::Char32: 7786 case BuiltinType::UInt: return 'I'; 7787 case BuiltinType::ULong: 7788 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7789 case BuiltinType::UInt128: return 'T'; 7790 case BuiltinType::ULongLong: return 'Q'; 7791 case BuiltinType::Char_S: 7792 case BuiltinType::SChar: return 'c'; 7793 case BuiltinType::Short: return 's'; 7794 case BuiltinType::WChar_S: 7795 case BuiltinType::WChar_U: 7796 case BuiltinType::Int: return 'i'; 7797 case BuiltinType::Long: 7798 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7799 case BuiltinType::LongLong: return 'q'; 7800 case BuiltinType::Int128: return 't'; 7801 case BuiltinType::Float: return 'f'; 7802 case BuiltinType::Double: return 'd'; 7803 case BuiltinType::LongDouble: return 'D'; 7804 case BuiltinType::NullPtr: return '*'; // like char* 7805 7806 case BuiltinType::BFloat16: 7807 case BuiltinType::Float16: 7808 case BuiltinType::Float128: 7809 case BuiltinType::Ibm128: 7810 case BuiltinType::Half: 7811 case BuiltinType::ShortAccum: 7812 case BuiltinType::Accum: 7813 case BuiltinType::LongAccum: 7814 case BuiltinType::UShortAccum: 7815 case BuiltinType::UAccum: 7816 case BuiltinType::ULongAccum: 7817 case BuiltinType::ShortFract: 7818 case BuiltinType::Fract: 7819 case BuiltinType::LongFract: 7820 case BuiltinType::UShortFract: 7821 case BuiltinType::UFract: 7822 case BuiltinType::ULongFract: 7823 case BuiltinType::SatShortAccum: 7824 case BuiltinType::SatAccum: 7825 case BuiltinType::SatLongAccum: 7826 case BuiltinType::SatUShortAccum: 7827 case BuiltinType::SatUAccum: 7828 case BuiltinType::SatULongAccum: 7829 case BuiltinType::SatShortFract: 7830 case BuiltinType::SatFract: 7831 case BuiltinType::SatLongFract: 7832 case BuiltinType::SatUShortFract: 7833 case BuiltinType::SatUFract: 7834 case BuiltinType::SatULongFract: 7835 // FIXME: potentially need @encodes for these! 7836 return ' '; 7837 7838 #define SVE_TYPE(Name, Id, SingletonId) \ 7839 case BuiltinType::Id: 7840 #include "clang/Basic/AArch64SVEACLETypes.def" 7841 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7842 #include "clang/Basic/RISCVVTypes.def" 7843 { 7844 DiagnosticsEngine &Diags = C->getDiagnostics(); 7845 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7846 "cannot yet @encode type %0"); 7847 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7848 return ' '; 7849 } 7850 7851 case BuiltinType::ObjCId: 7852 case BuiltinType::ObjCClass: 7853 case BuiltinType::ObjCSel: 7854 llvm_unreachable("@encoding ObjC primitive type"); 7855 7856 // OpenCL and placeholder types don't need @encodings. 7857 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7858 case BuiltinType::Id: 7859 #include "clang/Basic/OpenCLImageTypes.def" 7860 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7861 case BuiltinType::Id: 7862 #include "clang/Basic/OpenCLExtensionTypes.def" 7863 case BuiltinType::OCLEvent: 7864 case BuiltinType::OCLClkEvent: 7865 case BuiltinType::OCLQueue: 7866 case BuiltinType::OCLReserveID: 7867 case BuiltinType::OCLSampler: 7868 case BuiltinType::Dependent: 7869 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7870 case BuiltinType::Id: 7871 #include "clang/Basic/PPCTypes.def" 7872 #define BUILTIN_TYPE(KIND, ID) 7873 #define PLACEHOLDER_TYPE(KIND, ID) \ 7874 case BuiltinType::KIND: 7875 #include "clang/AST/BuiltinTypes.def" 7876 llvm_unreachable("invalid builtin type for @encode"); 7877 } 7878 llvm_unreachable("invalid BuiltinType::Kind value"); 7879 } 7880 7881 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7882 EnumDecl *Enum = ET->getDecl(); 7883 7884 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7885 if (!Enum->isFixed()) 7886 return 'i'; 7887 7888 // The encoding of a fixed enum type matches its fixed underlying type. 7889 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7890 return getObjCEncodingForPrimitiveType(C, BT); 7891 } 7892 7893 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7894 QualType T, const FieldDecl *FD) { 7895 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7896 S += 'b'; 7897 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7898 // The GNU runtime requires more information; bitfields are encoded as b, 7899 // then the offset (in bits) of the first element, then the type of the 7900 // bitfield, then the size in bits. For example, in this structure: 7901 // 7902 // struct 7903 // { 7904 // int integer; 7905 // int flags:2; 7906 // }; 7907 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7908 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7909 // information is not especially sensible, but we're stuck with it for 7910 // compatibility with GCC, although providing it breaks anything that 7911 // actually uses runtime introspection and wants to work on both runtimes... 7912 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7913 uint64_t Offset; 7914 7915 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7916 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7917 IVD); 7918 } else { 7919 const RecordDecl *RD = FD->getParent(); 7920 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7921 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7922 } 7923 7924 S += llvm::utostr(Offset); 7925 7926 if (const auto *ET = T->getAs<EnumType>()) 7927 S += ObjCEncodingForEnumType(Ctx, ET); 7928 else { 7929 const auto *BT = T->castAs<BuiltinType>(); 7930 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7931 } 7932 } 7933 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7934 } 7935 7936 // Helper function for determining whether the encoded type string would include 7937 // a template specialization type. 7938 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7939 bool VisitBasesAndFields) { 7940 T = T->getBaseElementTypeUnsafe(); 7941 7942 if (auto *PT = T->getAs<PointerType>()) 7943 return hasTemplateSpecializationInEncodedString( 7944 PT->getPointeeType().getTypePtr(), false); 7945 7946 auto *CXXRD = T->getAsCXXRecordDecl(); 7947 7948 if (!CXXRD) 7949 return false; 7950 7951 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7952 return true; 7953 7954 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7955 return false; 7956 7957 for (auto B : CXXRD->bases()) 7958 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7959 true)) 7960 return true; 7961 7962 for (auto *FD : CXXRD->fields()) 7963 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7964 true)) 7965 return true; 7966 7967 return false; 7968 } 7969 7970 // FIXME: Use SmallString for accumulating string. 7971 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7972 const ObjCEncOptions Options, 7973 const FieldDecl *FD, 7974 QualType *NotEncodedT) const { 7975 CanQualType CT = getCanonicalType(T); 7976 switch (CT->getTypeClass()) { 7977 case Type::Builtin: 7978 case Type::Enum: 7979 if (FD && FD->isBitField()) 7980 return EncodeBitField(this, S, T, FD); 7981 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7982 S += getObjCEncodingForPrimitiveType(this, BT); 7983 else 7984 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7985 return; 7986 7987 case Type::Complex: 7988 S += 'j'; 7989 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7990 ObjCEncOptions(), 7991 /*Field=*/nullptr); 7992 return; 7993 7994 case Type::Atomic: 7995 S += 'A'; 7996 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7997 ObjCEncOptions(), 7998 /*Field=*/nullptr); 7999 return; 8000 8001 // encoding for pointer or reference types. 8002 case Type::Pointer: 8003 case Type::LValueReference: 8004 case Type::RValueReference: { 8005 QualType PointeeTy; 8006 if (isa<PointerType>(CT)) { 8007 const auto *PT = T->castAs<PointerType>(); 8008 if (PT->isObjCSelType()) { 8009 S += ':'; 8010 return; 8011 } 8012 PointeeTy = PT->getPointeeType(); 8013 } else { 8014 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 8015 } 8016 8017 bool isReadOnly = false; 8018 // For historical/compatibility reasons, the read-only qualifier of the 8019 // pointee gets emitted _before_ the '^'. The read-only qualifier of 8020 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 8021 // Also, do not emit the 'r' for anything but the outermost type! 8022 if (isa<TypedefType>(T.getTypePtr())) { 8023 if (Options.IsOutermostType() && T.isConstQualified()) { 8024 isReadOnly = true; 8025 S += 'r'; 8026 } 8027 } else if (Options.IsOutermostType()) { 8028 QualType P = PointeeTy; 8029 while (auto PT = P->getAs<PointerType>()) 8030 P = PT->getPointeeType(); 8031 if (P.isConstQualified()) { 8032 isReadOnly = true; 8033 S += 'r'; 8034 } 8035 } 8036 if (isReadOnly) { 8037 // Another legacy compatibility encoding. Some ObjC qualifier and type 8038 // combinations need to be rearranged. 8039 // Rewrite "in const" from "nr" to "rn" 8040 if (StringRef(S).endswith("nr")) 8041 S.replace(S.end()-2, S.end(), "rn"); 8042 } 8043 8044 if (PointeeTy->isCharType()) { 8045 // char pointer types should be encoded as '*' unless it is a 8046 // type that has been typedef'd to 'BOOL'. 8047 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8048 S += '*'; 8049 return; 8050 } 8051 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8052 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8053 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8054 S += '#'; 8055 return; 8056 } 8057 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8058 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8059 S += '@'; 8060 return; 8061 } 8062 // If the encoded string for the class includes template names, just emit 8063 // "^v" for pointers to the class. 8064 if (getLangOpts().CPlusPlus && 8065 (!getLangOpts().EncodeCXXClassTemplateSpec && 8066 hasTemplateSpecializationInEncodedString( 8067 RTy, Options.ExpandPointedToStructures()))) { 8068 S += "^v"; 8069 return; 8070 } 8071 // fall through... 8072 } 8073 S += '^'; 8074 getLegacyIntegralTypeEncoding(PointeeTy); 8075 8076 ObjCEncOptions NewOptions; 8077 if (Options.ExpandPointedToStructures()) 8078 NewOptions.setExpandStructures(); 8079 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8080 /*Field=*/nullptr, NotEncodedT); 8081 return; 8082 } 8083 8084 case Type::ConstantArray: 8085 case Type::IncompleteArray: 8086 case Type::VariableArray: { 8087 const auto *AT = cast<ArrayType>(CT); 8088 8089 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8090 // Incomplete arrays are encoded as a pointer to the array element. 8091 S += '^'; 8092 8093 getObjCEncodingForTypeImpl( 8094 AT->getElementType(), S, 8095 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8096 } else { 8097 S += '['; 8098 8099 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8100 S += llvm::utostr(CAT->getSize().getZExtValue()); 8101 else { 8102 //Variable length arrays are encoded as a regular array with 0 elements. 8103 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8104 "Unknown array type!"); 8105 S += '0'; 8106 } 8107 8108 getObjCEncodingForTypeImpl( 8109 AT->getElementType(), S, 8110 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8111 NotEncodedT); 8112 S += ']'; 8113 } 8114 return; 8115 } 8116 8117 case Type::FunctionNoProto: 8118 case Type::FunctionProto: 8119 S += '?'; 8120 return; 8121 8122 case Type::Record: { 8123 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8124 S += RDecl->isUnion() ? '(' : '{'; 8125 // Anonymous structures print as '?' 8126 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8127 S += II->getName(); 8128 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8129 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8130 llvm::raw_string_ostream OS(S); 8131 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8132 getPrintingPolicy()); 8133 } 8134 } else { 8135 S += '?'; 8136 } 8137 if (Options.ExpandStructures()) { 8138 S += '='; 8139 if (!RDecl->isUnion()) { 8140 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8141 } else { 8142 for (const auto *Field : RDecl->fields()) { 8143 if (FD) { 8144 S += '"'; 8145 S += Field->getNameAsString(); 8146 S += '"'; 8147 } 8148 8149 // Special case bit-fields. 8150 if (Field->isBitField()) { 8151 getObjCEncodingForTypeImpl(Field->getType(), S, 8152 ObjCEncOptions().setExpandStructures(), 8153 Field); 8154 } else { 8155 QualType qt = Field->getType(); 8156 getLegacyIntegralTypeEncoding(qt); 8157 getObjCEncodingForTypeImpl( 8158 qt, S, 8159 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8160 NotEncodedT); 8161 } 8162 } 8163 } 8164 } 8165 S += RDecl->isUnion() ? ')' : '}'; 8166 return; 8167 } 8168 8169 case Type::BlockPointer: { 8170 const auto *BT = T->castAs<BlockPointerType>(); 8171 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8172 if (Options.EncodeBlockParameters()) { 8173 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8174 8175 S += '<'; 8176 // Block return type 8177 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8178 Options.forComponentType(), FD, NotEncodedT); 8179 // Block self 8180 S += "@?"; 8181 // Block parameters 8182 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8183 for (const auto &I : FPT->param_types()) 8184 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8185 NotEncodedT); 8186 } 8187 S += '>'; 8188 } 8189 return; 8190 } 8191 8192 case Type::ObjCObject: { 8193 // hack to match legacy encoding of *id and *Class 8194 QualType Ty = getObjCObjectPointerType(CT); 8195 if (Ty->isObjCIdType()) { 8196 S += "{objc_object=}"; 8197 return; 8198 } 8199 else if (Ty->isObjCClassType()) { 8200 S += "{objc_class=}"; 8201 return; 8202 } 8203 // TODO: Double check to make sure this intentionally falls through. 8204 LLVM_FALLTHROUGH; 8205 } 8206 8207 case Type::ObjCInterface: { 8208 // Ignore protocol qualifiers when mangling at this level. 8209 // @encode(class_name) 8210 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8211 S += '{'; 8212 S += OI->getObjCRuntimeNameAsString(); 8213 if (Options.ExpandStructures()) { 8214 S += '='; 8215 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8216 DeepCollectObjCIvars(OI, true, Ivars); 8217 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8218 const FieldDecl *Field = Ivars[i]; 8219 if (Field->isBitField()) 8220 getObjCEncodingForTypeImpl(Field->getType(), S, 8221 ObjCEncOptions().setExpandStructures(), 8222 Field); 8223 else 8224 getObjCEncodingForTypeImpl(Field->getType(), S, 8225 ObjCEncOptions().setExpandStructures(), FD, 8226 NotEncodedT); 8227 } 8228 } 8229 S += '}'; 8230 return; 8231 } 8232 8233 case Type::ObjCObjectPointer: { 8234 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8235 if (OPT->isObjCIdType()) { 8236 S += '@'; 8237 return; 8238 } 8239 8240 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8241 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8242 // Since this is a binary compatibility issue, need to consult with 8243 // runtime folks. Fortunately, this is a *very* obscure construct. 8244 S += '#'; 8245 return; 8246 } 8247 8248 if (OPT->isObjCQualifiedIdType()) { 8249 getObjCEncodingForTypeImpl( 8250 getObjCIdType(), S, 8251 Options.keepingOnly(ObjCEncOptions() 8252 .setExpandPointedToStructures() 8253 .setExpandStructures()), 8254 FD); 8255 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8256 // Note that we do extended encoding of protocol qualifier list 8257 // Only when doing ivar or property encoding. 8258 S += '"'; 8259 for (const auto *I : OPT->quals()) { 8260 S += '<'; 8261 S += I->getObjCRuntimeNameAsString(); 8262 S += '>'; 8263 } 8264 S += '"'; 8265 } 8266 return; 8267 } 8268 8269 S += '@'; 8270 if (OPT->getInterfaceDecl() && 8271 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8272 S += '"'; 8273 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8274 for (const auto *I : OPT->quals()) { 8275 S += '<'; 8276 S += I->getObjCRuntimeNameAsString(); 8277 S += '>'; 8278 } 8279 S += '"'; 8280 } 8281 return; 8282 } 8283 8284 // gcc just blithely ignores member pointers. 8285 // FIXME: we should do better than that. 'M' is available. 8286 case Type::MemberPointer: 8287 // This matches gcc's encoding, even though technically it is insufficient. 8288 //FIXME. We should do a better job than gcc. 8289 case Type::Vector: 8290 case Type::ExtVector: 8291 // Until we have a coherent encoding of these three types, issue warning. 8292 if (NotEncodedT) 8293 *NotEncodedT = T; 8294 return; 8295 8296 case Type::ConstantMatrix: 8297 if (NotEncodedT) 8298 *NotEncodedT = T; 8299 return; 8300 8301 case Type::BitInt: 8302 if (NotEncodedT) 8303 *NotEncodedT = T; 8304 return; 8305 8306 // We could see an undeduced auto type here during error recovery. 8307 // Just ignore it. 8308 case Type::Auto: 8309 case Type::DeducedTemplateSpecialization: 8310 return; 8311 8312 case Type::Pipe: 8313 #define ABSTRACT_TYPE(KIND, BASE) 8314 #define TYPE(KIND, BASE) 8315 #define DEPENDENT_TYPE(KIND, BASE) \ 8316 case Type::KIND: 8317 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8318 case Type::KIND: 8319 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8320 case Type::KIND: 8321 #include "clang/AST/TypeNodes.inc" 8322 llvm_unreachable("@encode for dependent type!"); 8323 } 8324 llvm_unreachable("bad type kind!"); 8325 } 8326 8327 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8328 std::string &S, 8329 const FieldDecl *FD, 8330 bool includeVBases, 8331 QualType *NotEncodedT) const { 8332 assert(RDecl && "Expected non-null RecordDecl"); 8333 assert(!RDecl->isUnion() && "Should not be called for unions"); 8334 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8335 return; 8336 8337 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8338 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8339 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8340 8341 if (CXXRec) { 8342 for (const auto &BI : CXXRec->bases()) { 8343 if (!BI.isVirtual()) { 8344 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8345 if (base->isEmpty()) 8346 continue; 8347 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8348 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8349 std::make_pair(offs, base)); 8350 } 8351 } 8352 } 8353 8354 unsigned i = 0; 8355 for (FieldDecl *Field : RDecl->fields()) { 8356 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8357 continue; 8358 uint64_t offs = layout.getFieldOffset(i); 8359 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8360 std::make_pair(offs, Field)); 8361 ++i; 8362 } 8363 8364 if (CXXRec && includeVBases) { 8365 for (const auto &BI : CXXRec->vbases()) { 8366 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8367 if (base->isEmpty()) 8368 continue; 8369 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8370 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8371 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8372 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8373 std::make_pair(offs, base)); 8374 } 8375 } 8376 8377 CharUnits size; 8378 if (CXXRec) { 8379 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8380 } else { 8381 size = layout.getSize(); 8382 } 8383 8384 #ifndef NDEBUG 8385 uint64_t CurOffs = 0; 8386 #endif 8387 std::multimap<uint64_t, NamedDecl *>::iterator 8388 CurLayObj = FieldOrBaseOffsets.begin(); 8389 8390 if (CXXRec && CXXRec->isDynamicClass() && 8391 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8392 if (FD) { 8393 S += "\"_vptr$"; 8394 std::string recname = CXXRec->getNameAsString(); 8395 if (recname.empty()) recname = "?"; 8396 S += recname; 8397 S += '"'; 8398 } 8399 S += "^^?"; 8400 #ifndef NDEBUG 8401 CurOffs += getTypeSize(VoidPtrTy); 8402 #endif 8403 } 8404 8405 if (!RDecl->hasFlexibleArrayMember()) { 8406 // Mark the end of the structure. 8407 uint64_t offs = toBits(size); 8408 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8409 std::make_pair(offs, nullptr)); 8410 } 8411 8412 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8413 #ifndef NDEBUG 8414 assert(CurOffs <= CurLayObj->first); 8415 if (CurOffs < CurLayObj->first) { 8416 uint64_t padding = CurLayObj->first - CurOffs; 8417 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8418 // packing/alignment of members is different that normal, in which case 8419 // the encoding will be out-of-sync with the real layout. 8420 // If the runtime switches to just consider the size of types without 8421 // taking into account alignment, we could make padding explicit in the 8422 // encoding (e.g. using arrays of chars). The encoding strings would be 8423 // longer then though. 8424 CurOffs += padding; 8425 } 8426 #endif 8427 8428 NamedDecl *dcl = CurLayObj->second; 8429 if (!dcl) 8430 break; // reached end of structure. 8431 8432 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8433 // We expand the bases without their virtual bases since those are going 8434 // in the initial structure. Note that this differs from gcc which 8435 // expands virtual bases each time one is encountered in the hierarchy, 8436 // making the encoding type bigger than it really is. 8437 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8438 NotEncodedT); 8439 assert(!base->isEmpty()); 8440 #ifndef NDEBUG 8441 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8442 #endif 8443 } else { 8444 const auto *field = cast<FieldDecl>(dcl); 8445 if (FD) { 8446 S += '"'; 8447 S += field->getNameAsString(); 8448 S += '"'; 8449 } 8450 8451 if (field->isBitField()) { 8452 EncodeBitField(this, S, field->getType(), field); 8453 #ifndef NDEBUG 8454 CurOffs += field->getBitWidthValue(*this); 8455 #endif 8456 } else { 8457 QualType qt = field->getType(); 8458 getLegacyIntegralTypeEncoding(qt); 8459 getObjCEncodingForTypeImpl( 8460 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8461 FD, NotEncodedT); 8462 #ifndef NDEBUG 8463 CurOffs += getTypeSize(field->getType()); 8464 #endif 8465 } 8466 } 8467 } 8468 } 8469 8470 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8471 std::string& S) const { 8472 if (QT & Decl::OBJC_TQ_In) 8473 S += 'n'; 8474 if (QT & Decl::OBJC_TQ_Inout) 8475 S += 'N'; 8476 if (QT & Decl::OBJC_TQ_Out) 8477 S += 'o'; 8478 if (QT & Decl::OBJC_TQ_Bycopy) 8479 S += 'O'; 8480 if (QT & Decl::OBJC_TQ_Byref) 8481 S += 'R'; 8482 if (QT & Decl::OBJC_TQ_Oneway) 8483 S += 'V'; 8484 } 8485 8486 TypedefDecl *ASTContext::getObjCIdDecl() const { 8487 if (!ObjCIdDecl) { 8488 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8489 T = getObjCObjectPointerType(T); 8490 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8491 } 8492 return ObjCIdDecl; 8493 } 8494 8495 TypedefDecl *ASTContext::getObjCSelDecl() const { 8496 if (!ObjCSelDecl) { 8497 QualType T = getPointerType(ObjCBuiltinSelTy); 8498 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8499 } 8500 return ObjCSelDecl; 8501 } 8502 8503 TypedefDecl *ASTContext::getObjCClassDecl() const { 8504 if (!ObjCClassDecl) { 8505 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8506 T = getObjCObjectPointerType(T); 8507 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8508 } 8509 return ObjCClassDecl; 8510 } 8511 8512 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8513 if (!ObjCProtocolClassDecl) { 8514 ObjCProtocolClassDecl 8515 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8516 SourceLocation(), 8517 &Idents.get("Protocol"), 8518 /*typeParamList=*/nullptr, 8519 /*PrevDecl=*/nullptr, 8520 SourceLocation(), true); 8521 } 8522 8523 return ObjCProtocolClassDecl; 8524 } 8525 8526 //===----------------------------------------------------------------------===// 8527 // __builtin_va_list Construction Functions 8528 //===----------------------------------------------------------------------===// 8529 8530 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8531 StringRef Name) { 8532 // typedef char* __builtin[_ms]_va_list; 8533 QualType T = Context->getPointerType(Context->CharTy); 8534 return Context->buildImplicitTypedef(T, Name); 8535 } 8536 8537 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8538 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8539 } 8540 8541 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8542 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8543 } 8544 8545 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8546 // typedef void* __builtin_va_list; 8547 QualType T = Context->getPointerType(Context->VoidTy); 8548 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8549 } 8550 8551 static TypedefDecl * 8552 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8553 // struct __va_list 8554 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8555 if (Context->getLangOpts().CPlusPlus) { 8556 // namespace std { struct __va_list { 8557 auto *NS = NamespaceDecl::Create( 8558 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8559 /*Inline*/ false, SourceLocation(), SourceLocation(), 8560 &Context->Idents.get("std"), 8561 /*PrevDecl*/ nullptr); 8562 NS->setImplicit(); 8563 VaListTagDecl->setDeclContext(NS); 8564 } 8565 8566 VaListTagDecl->startDefinition(); 8567 8568 const size_t NumFields = 5; 8569 QualType FieldTypes[NumFields]; 8570 const char *FieldNames[NumFields]; 8571 8572 // void *__stack; 8573 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8574 FieldNames[0] = "__stack"; 8575 8576 // void *__gr_top; 8577 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8578 FieldNames[1] = "__gr_top"; 8579 8580 // void *__vr_top; 8581 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8582 FieldNames[2] = "__vr_top"; 8583 8584 // int __gr_offs; 8585 FieldTypes[3] = Context->IntTy; 8586 FieldNames[3] = "__gr_offs"; 8587 8588 // int __vr_offs; 8589 FieldTypes[4] = Context->IntTy; 8590 FieldNames[4] = "__vr_offs"; 8591 8592 // Create fields 8593 for (unsigned i = 0; i < NumFields; ++i) { 8594 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8595 VaListTagDecl, 8596 SourceLocation(), 8597 SourceLocation(), 8598 &Context->Idents.get(FieldNames[i]), 8599 FieldTypes[i], /*TInfo=*/nullptr, 8600 /*BitWidth=*/nullptr, 8601 /*Mutable=*/false, 8602 ICIS_NoInit); 8603 Field->setAccess(AS_public); 8604 VaListTagDecl->addDecl(Field); 8605 } 8606 VaListTagDecl->completeDefinition(); 8607 Context->VaListTagDecl = VaListTagDecl; 8608 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8609 8610 // } __builtin_va_list; 8611 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8612 } 8613 8614 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8615 // typedef struct __va_list_tag { 8616 RecordDecl *VaListTagDecl; 8617 8618 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8619 VaListTagDecl->startDefinition(); 8620 8621 const size_t NumFields = 5; 8622 QualType FieldTypes[NumFields]; 8623 const char *FieldNames[NumFields]; 8624 8625 // unsigned char gpr; 8626 FieldTypes[0] = Context->UnsignedCharTy; 8627 FieldNames[0] = "gpr"; 8628 8629 // unsigned char fpr; 8630 FieldTypes[1] = Context->UnsignedCharTy; 8631 FieldNames[1] = "fpr"; 8632 8633 // unsigned short reserved; 8634 FieldTypes[2] = Context->UnsignedShortTy; 8635 FieldNames[2] = "reserved"; 8636 8637 // void* overflow_arg_area; 8638 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8639 FieldNames[3] = "overflow_arg_area"; 8640 8641 // void* reg_save_area; 8642 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8643 FieldNames[4] = "reg_save_area"; 8644 8645 // Create fields 8646 for (unsigned i = 0; i < NumFields; ++i) { 8647 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8648 SourceLocation(), 8649 SourceLocation(), 8650 &Context->Idents.get(FieldNames[i]), 8651 FieldTypes[i], /*TInfo=*/nullptr, 8652 /*BitWidth=*/nullptr, 8653 /*Mutable=*/false, 8654 ICIS_NoInit); 8655 Field->setAccess(AS_public); 8656 VaListTagDecl->addDecl(Field); 8657 } 8658 VaListTagDecl->completeDefinition(); 8659 Context->VaListTagDecl = VaListTagDecl; 8660 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8661 8662 // } __va_list_tag; 8663 TypedefDecl *VaListTagTypedefDecl = 8664 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8665 8666 QualType VaListTagTypedefType = 8667 Context->getTypedefType(VaListTagTypedefDecl); 8668 8669 // typedef __va_list_tag __builtin_va_list[1]; 8670 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8671 QualType VaListTagArrayType 8672 = Context->getConstantArrayType(VaListTagTypedefType, 8673 Size, nullptr, ArrayType::Normal, 0); 8674 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8675 } 8676 8677 static TypedefDecl * 8678 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8679 // struct __va_list_tag { 8680 RecordDecl *VaListTagDecl; 8681 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8682 VaListTagDecl->startDefinition(); 8683 8684 const size_t NumFields = 4; 8685 QualType FieldTypes[NumFields]; 8686 const char *FieldNames[NumFields]; 8687 8688 // unsigned gp_offset; 8689 FieldTypes[0] = Context->UnsignedIntTy; 8690 FieldNames[0] = "gp_offset"; 8691 8692 // unsigned fp_offset; 8693 FieldTypes[1] = Context->UnsignedIntTy; 8694 FieldNames[1] = "fp_offset"; 8695 8696 // void* overflow_arg_area; 8697 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8698 FieldNames[2] = "overflow_arg_area"; 8699 8700 // void* reg_save_area; 8701 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8702 FieldNames[3] = "reg_save_area"; 8703 8704 // Create fields 8705 for (unsigned i = 0; i < NumFields; ++i) { 8706 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8707 VaListTagDecl, 8708 SourceLocation(), 8709 SourceLocation(), 8710 &Context->Idents.get(FieldNames[i]), 8711 FieldTypes[i], /*TInfo=*/nullptr, 8712 /*BitWidth=*/nullptr, 8713 /*Mutable=*/false, 8714 ICIS_NoInit); 8715 Field->setAccess(AS_public); 8716 VaListTagDecl->addDecl(Field); 8717 } 8718 VaListTagDecl->completeDefinition(); 8719 Context->VaListTagDecl = VaListTagDecl; 8720 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8721 8722 // }; 8723 8724 // typedef struct __va_list_tag __builtin_va_list[1]; 8725 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8726 QualType VaListTagArrayType = Context->getConstantArrayType( 8727 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8728 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8729 } 8730 8731 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8732 // typedef int __builtin_va_list[4]; 8733 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8734 QualType IntArrayType = Context->getConstantArrayType( 8735 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8736 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8737 } 8738 8739 static TypedefDecl * 8740 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8741 // struct __va_list 8742 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8743 if (Context->getLangOpts().CPlusPlus) { 8744 // namespace std { struct __va_list { 8745 NamespaceDecl *NS; 8746 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8747 Context->getTranslationUnitDecl(), 8748 /*Inline*/false, SourceLocation(), 8749 SourceLocation(), &Context->Idents.get("std"), 8750 /*PrevDecl*/ nullptr); 8751 NS->setImplicit(); 8752 VaListDecl->setDeclContext(NS); 8753 } 8754 8755 VaListDecl->startDefinition(); 8756 8757 // void * __ap; 8758 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8759 VaListDecl, 8760 SourceLocation(), 8761 SourceLocation(), 8762 &Context->Idents.get("__ap"), 8763 Context->getPointerType(Context->VoidTy), 8764 /*TInfo=*/nullptr, 8765 /*BitWidth=*/nullptr, 8766 /*Mutable=*/false, 8767 ICIS_NoInit); 8768 Field->setAccess(AS_public); 8769 VaListDecl->addDecl(Field); 8770 8771 // }; 8772 VaListDecl->completeDefinition(); 8773 Context->VaListTagDecl = VaListDecl; 8774 8775 // typedef struct __va_list __builtin_va_list; 8776 QualType T = Context->getRecordType(VaListDecl); 8777 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8778 } 8779 8780 static TypedefDecl * 8781 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8782 // struct __va_list_tag { 8783 RecordDecl *VaListTagDecl; 8784 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8785 VaListTagDecl->startDefinition(); 8786 8787 const size_t NumFields = 4; 8788 QualType FieldTypes[NumFields]; 8789 const char *FieldNames[NumFields]; 8790 8791 // long __gpr; 8792 FieldTypes[0] = Context->LongTy; 8793 FieldNames[0] = "__gpr"; 8794 8795 // long __fpr; 8796 FieldTypes[1] = Context->LongTy; 8797 FieldNames[1] = "__fpr"; 8798 8799 // void *__overflow_arg_area; 8800 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8801 FieldNames[2] = "__overflow_arg_area"; 8802 8803 // void *__reg_save_area; 8804 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8805 FieldNames[3] = "__reg_save_area"; 8806 8807 // Create fields 8808 for (unsigned i = 0; i < NumFields; ++i) { 8809 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8810 VaListTagDecl, 8811 SourceLocation(), 8812 SourceLocation(), 8813 &Context->Idents.get(FieldNames[i]), 8814 FieldTypes[i], /*TInfo=*/nullptr, 8815 /*BitWidth=*/nullptr, 8816 /*Mutable=*/false, 8817 ICIS_NoInit); 8818 Field->setAccess(AS_public); 8819 VaListTagDecl->addDecl(Field); 8820 } 8821 VaListTagDecl->completeDefinition(); 8822 Context->VaListTagDecl = VaListTagDecl; 8823 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8824 8825 // }; 8826 8827 // typedef __va_list_tag __builtin_va_list[1]; 8828 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8829 QualType VaListTagArrayType = Context->getConstantArrayType( 8830 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8831 8832 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8833 } 8834 8835 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8836 // typedef struct __va_list_tag { 8837 RecordDecl *VaListTagDecl; 8838 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8839 VaListTagDecl->startDefinition(); 8840 8841 const size_t NumFields = 3; 8842 QualType FieldTypes[NumFields]; 8843 const char *FieldNames[NumFields]; 8844 8845 // void *CurrentSavedRegisterArea; 8846 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8847 FieldNames[0] = "__current_saved_reg_area_pointer"; 8848 8849 // void *SavedRegAreaEnd; 8850 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8851 FieldNames[1] = "__saved_reg_area_end_pointer"; 8852 8853 // void *OverflowArea; 8854 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8855 FieldNames[2] = "__overflow_area_pointer"; 8856 8857 // Create fields 8858 for (unsigned i = 0; i < NumFields; ++i) { 8859 FieldDecl *Field = FieldDecl::Create( 8860 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8861 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8862 /*TInfo=*/nullptr, 8863 /*BitWidth=*/nullptr, 8864 /*Mutable=*/false, ICIS_NoInit); 8865 Field->setAccess(AS_public); 8866 VaListTagDecl->addDecl(Field); 8867 } 8868 VaListTagDecl->completeDefinition(); 8869 Context->VaListTagDecl = VaListTagDecl; 8870 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8871 8872 // } __va_list_tag; 8873 TypedefDecl *VaListTagTypedefDecl = 8874 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8875 8876 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8877 8878 // typedef __va_list_tag __builtin_va_list[1]; 8879 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8880 QualType VaListTagArrayType = Context->getConstantArrayType( 8881 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8882 8883 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8884 } 8885 8886 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8887 TargetInfo::BuiltinVaListKind Kind) { 8888 switch (Kind) { 8889 case TargetInfo::CharPtrBuiltinVaList: 8890 return CreateCharPtrBuiltinVaListDecl(Context); 8891 case TargetInfo::VoidPtrBuiltinVaList: 8892 return CreateVoidPtrBuiltinVaListDecl(Context); 8893 case TargetInfo::AArch64ABIBuiltinVaList: 8894 return CreateAArch64ABIBuiltinVaListDecl(Context); 8895 case TargetInfo::PowerABIBuiltinVaList: 8896 return CreatePowerABIBuiltinVaListDecl(Context); 8897 case TargetInfo::X86_64ABIBuiltinVaList: 8898 return CreateX86_64ABIBuiltinVaListDecl(Context); 8899 case TargetInfo::PNaClABIBuiltinVaList: 8900 return CreatePNaClABIBuiltinVaListDecl(Context); 8901 case TargetInfo::AAPCSABIBuiltinVaList: 8902 return CreateAAPCSABIBuiltinVaListDecl(Context); 8903 case TargetInfo::SystemZBuiltinVaList: 8904 return CreateSystemZBuiltinVaListDecl(Context); 8905 case TargetInfo::HexagonBuiltinVaList: 8906 return CreateHexagonBuiltinVaListDecl(Context); 8907 } 8908 8909 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8910 } 8911 8912 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8913 if (!BuiltinVaListDecl) { 8914 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8915 assert(BuiltinVaListDecl->isImplicit()); 8916 } 8917 8918 return BuiltinVaListDecl; 8919 } 8920 8921 Decl *ASTContext::getVaListTagDecl() const { 8922 // Force the creation of VaListTagDecl by building the __builtin_va_list 8923 // declaration. 8924 if (!VaListTagDecl) 8925 (void)getBuiltinVaListDecl(); 8926 8927 return VaListTagDecl; 8928 } 8929 8930 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8931 if (!BuiltinMSVaListDecl) 8932 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8933 8934 return BuiltinMSVaListDecl; 8935 } 8936 8937 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8938 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8939 } 8940 8941 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8942 assert(ObjCConstantStringType.isNull() && 8943 "'NSConstantString' type already set!"); 8944 8945 ObjCConstantStringType = getObjCInterfaceType(Decl); 8946 } 8947 8948 /// Retrieve the template name that corresponds to a non-empty 8949 /// lookup. 8950 TemplateName 8951 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8952 UnresolvedSetIterator End) const { 8953 unsigned size = End - Begin; 8954 assert(size > 1 && "set is not overloaded!"); 8955 8956 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8957 size * sizeof(FunctionTemplateDecl*)); 8958 auto *OT = new (memory) OverloadedTemplateStorage(size); 8959 8960 NamedDecl **Storage = OT->getStorage(); 8961 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8962 NamedDecl *D = *I; 8963 assert(isa<FunctionTemplateDecl>(D) || 8964 isa<UnresolvedUsingValueDecl>(D) || 8965 (isa<UsingShadowDecl>(D) && 8966 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8967 *Storage++ = D; 8968 } 8969 8970 return TemplateName(OT); 8971 } 8972 8973 /// Retrieve a template name representing an unqualified-id that has been 8974 /// assumed to name a template for ADL purposes. 8975 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8976 auto *OT = new (*this) AssumedTemplateStorage(Name); 8977 return TemplateName(OT); 8978 } 8979 8980 /// Retrieve the template name that represents a qualified 8981 /// template name such as \c std::vector. 8982 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8983 bool TemplateKeyword, 8984 TemplateName Template) const { 8985 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8986 8987 // FIXME: Canonicalization? 8988 llvm::FoldingSetNodeID ID; 8989 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8990 8991 void *InsertPos = nullptr; 8992 QualifiedTemplateName *QTN = 8993 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8994 if (!QTN) { 8995 QTN = new (*this, alignof(QualifiedTemplateName)) 8996 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8997 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8998 } 8999 9000 return TemplateName(QTN); 9001 } 9002 9003 /// Retrieve the template name that represents a dependent 9004 /// template name such as \c MetaFun::template apply. 9005 TemplateName 9006 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9007 const IdentifierInfo *Name) const { 9008 assert((!NNS || NNS->isDependent()) && 9009 "Nested name specifier must be dependent"); 9010 9011 llvm::FoldingSetNodeID ID; 9012 DependentTemplateName::Profile(ID, NNS, Name); 9013 9014 void *InsertPos = nullptr; 9015 DependentTemplateName *QTN = 9016 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9017 9018 if (QTN) 9019 return TemplateName(QTN); 9020 9021 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9022 if (CanonNNS == NNS) { 9023 QTN = new (*this, alignof(DependentTemplateName)) 9024 DependentTemplateName(NNS, Name); 9025 } else { 9026 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 9027 QTN = new (*this, alignof(DependentTemplateName)) 9028 DependentTemplateName(NNS, Name, Canon); 9029 DependentTemplateName *CheckQTN = 9030 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9031 assert(!CheckQTN && "Dependent type name canonicalization broken"); 9032 (void)CheckQTN; 9033 } 9034 9035 DependentTemplateNames.InsertNode(QTN, InsertPos); 9036 return TemplateName(QTN); 9037 } 9038 9039 /// Retrieve the template name that represents a dependent 9040 /// template name such as \c MetaFun::template operator+. 9041 TemplateName 9042 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9043 OverloadedOperatorKind Operator) const { 9044 assert((!NNS || NNS->isDependent()) && 9045 "Nested name specifier must be dependent"); 9046 9047 llvm::FoldingSetNodeID ID; 9048 DependentTemplateName::Profile(ID, NNS, Operator); 9049 9050 void *InsertPos = nullptr; 9051 DependentTemplateName *QTN 9052 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9053 9054 if (QTN) 9055 return TemplateName(QTN); 9056 9057 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9058 if (CanonNNS == NNS) { 9059 QTN = new (*this, alignof(DependentTemplateName)) 9060 DependentTemplateName(NNS, Operator); 9061 } else { 9062 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9063 QTN = new (*this, alignof(DependentTemplateName)) 9064 DependentTemplateName(NNS, Operator, Canon); 9065 9066 DependentTemplateName *CheckQTN 9067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9068 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9069 (void)CheckQTN; 9070 } 9071 9072 DependentTemplateNames.InsertNode(QTN, InsertPos); 9073 return TemplateName(QTN); 9074 } 9075 9076 TemplateName 9077 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9078 TemplateName replacement) const { 9079 llvm::FoldingSetNodeID ID; 9080 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9081 9082 void *insertPos = nullptr; 9083 SubstTemplateTemplateParmStorage *subst 9084 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9085 9086 if (!subst) { 9087 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9088 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9089 } 9090 9091 return TemplateName(subst); 9092 } 9093 9094 TemplateName 9095 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9096 const TemplateArgument &ArgPack) const { 9097 auto &Self = const_cast<ASTContext &>(*this); 9098 llvm::FoldingSetNodeID ID; 9099 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9100 9101 void *InsertPos = nullptr; 9102 SubstTemplateTemplateParmPackStorage *Subst 9103 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9104 9105 if (!Subst) { 9106 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9107 ArgPack.pack_size(), 9108 ArgPack.pack_begin()); 9109 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9110 } 9111 9112 return TemplateName(Subst); 9113 } 9114 9115 /// getFromTargetType - Given one of the integer types provided by 9116 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9117 /// is actually a value of type @c TargetInfo::IntType. 9118 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9119 switch (Type) { 9120 case TargetInfo::NoInt: return {}; 9121 case TargetInfo::SignedChar: return SignedCharTy; 9122 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9123 case TargetInfo::SignedShort: return ShortTy; 9124 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9125 case TargetInfo::SignedInt: return IntTy; 9126 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9127 case TargetInfo::SignedLong: return LongTy; 9128 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9129 case TargetInfo::SignedLongLong: return LongLongTy; 9130 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9131 } 9132 9133 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9134 } 9135 9136 //===----------------------------------------------------------------------===// 9137 // Type Predicates. 9138 //===----------------------------------------------------------------------===// 9139 9140 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9141 /// garbage collection attribute. 9142 /// 9143 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9144 if (getLangOpts().getGC() == LangOptions::NonGC) 9145 return Qualifiers::GCNone; 9146 9147 assert(getLangOpts().ObjC); 9148 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9149 9150 // Default behaviour under objective-C's gc is for ObjC pointers 9151 // (or pointers to them) be treated as though they were declared 9152 // as __strong. 9153 if (GCAttrs == Qualifiers::GCNone) { 9154 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9155 return Qualifiers::Strong; 9156 else if (Ty->isPointerType()) 9157 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9158 } else { 9159 // It's not valid to set GC attributes on anything that isn't a 9160 // pointer. 9161 #ifndef NDEBUG 9162 QualType CT = Ty->getCanonicalTypeInternal(); 9163 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9164 CT = AT->getElementType(); 9165 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9166 #endif 9167 } 9168 return GCAttrs; 9169 } 9170 9171 //===----------------------------------------------------------------------===// 9172 // Type Compatibility Testing 9173 //===----------------------------------------------------------------------===// 9174 9175 /// areCompatVectorTypes - Return true if the two specified vector types are 9176 /// compatible. 9177 static bool areCompatVectorTypes(const VectorType *LHS, 9178 const VectorType *RHS) { 9179 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9180 return LHS->getElementType() == RHS->getElementType() && 9181 LHS->getNumElements() == RHS->getNumElements(); 9182 } 9183 9184 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9185 /// compatible. 9186 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9187 const ConstantMatrixType *RHS) { 9188 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9189 return LHS->getElementType() == RHS->getElementType() && 9190 LHS->getNumRows() == RHS->getNumRows() && 9191 LHS->getNumColumns() == RHS->getNumColumns(); 9192 } 9193 9194 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9195 QualType SecondVec) { 9196 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9197 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9198 9199 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9200 return true; 9201 9202 // Treat Neon vector types and most AltiVec vector types as if they are the 9203 // equivalent GCC vector types. 9204 const auto *First = FirstVec->castAs<VectorType>(); 9205 const auto *Second = SecondVec->castAs<VectorType>(); 9206 if (First->getNumElements() == Second->getNumElements() && 9207 hasSameType(First->getElementType(), Second->getElementType()) && 9208 First->getVectorKind() != VectorType::AltiVecPixel && 9209 First->getVectorKind() != VectorType::AltiVecBool && 9210 Second->getVectorKind() != VectorType::AltiVecPixel && 9211 Second->getVectorKind() != VectorType::AltiVecBool && 9212 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9213 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9214 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9215 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9216 return true; 9217 9218 return false; 9219 } 9220 9221 /// getSVETypeSize - Return SVE vector or predicate register size. 9222 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9223 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9224 return Ty->getKind() == BuiltinType::SveBool 9225 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9226 : Context.getLangOpts().VScaleMin * 128; 9227 } 9228 9229 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9230 QualType SecondType) { 9231 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9232 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9233 "Expected SVE builtin type and vector type!"); 9234 9235 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9236 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9237 if (const auto *VT = SecondType->getAs<VectorType>()) { 9238 // Predicates have the same representation as uint8 so we also have to 9239 // check the kind to make these types incompatible. 9240 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9241 return BT->getKind() == BuiltinType::SveBool; 9242 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9243 return VT->getElementType().getCanonicalType() == 9244 FirstType->getSveEltType(*this); 9245 else if (VT->getVectorKind() == VectorType::GenericVector) 9246 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9247 hasSameType(VT->getElementType(), 9248 getBuiltinVectorTypeInfo(BT).ElementType); 9249 } 9250 } 9251 return false; 9252 }; 9253 9254 return IsValidCast(FirstType, SecondType) || 9255 IsValidCast(SecondType, FirstType); 9256 } 9257 9258 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9259 QualType SecondType) { 9260 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9261 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9262 "Expected SVE builtin type and vector type!"); 9263 9264 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9265 const auto *BT = FirstType->getAs<BuiltinType>(); 9266 if (!BT) 9267 return false; 9268 9269 const auto *VecTy = SecondType->getAs<VectorType>(); 9270 if (VecTy && 9271 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9272 VecTy->getVectorKind() == VectorType::GenericVector)) { 9273 const LangOptions::LaxVectorConversionKind LVCKind = 9274 getLangOpts().getLaxVectorConversions(); 9275 9276 // Can not convert between sve predicates and sve vectors because of 9277 // different size. 9278 if (BT->getKind() == BuiltinType::SveBool && 9279 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9280 return false; 9281 9282 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9283 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9284 // converts to VLAT and VLAT implicitly converts to GNUT." 9285 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9286 // predicates. 9287 if (VecTy->getVectorKind() == VectorType::GenericVector && 9288 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9289 return false; 9290 9291 // If -flax-vector-conversions=all is specified, the types are 9292 // certainly compatible. 9293 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9294 return true; 9295 9296 // If -flax-vector-conversions=integer is specified, the types are 9297 // compatible if the elements are integer types. 9298 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9299 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9300 FirstType->getSveEltType(*this)->isIntegerType(); 9301 } 9302 9303 return false; 9304 }; 9305 9306 return IsLaxCompatible(FirstType, SecondType) || 9307 IsLaxCompatible(SecondType, FirstType); 9308 } 9309 9310 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9311 while (true) { 9312 // __strong id 9313 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9314 if (Attr->getAttrKind() == attr::ObjCOwnership) 9315 return true; 9316 9317 Ty = Attr->getModifiedType(); 9318 9319 // X *__strong (...) 9320 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9321 Ty = Paren->getInnerType(); 9322 9323 // We do not want to look through typedefs, typeof(expr), 9324 // typeof(type), or any other way that the type is somehow 9325 // abstracted. 9326 } else { 9327 return false; 9328 } 9329 } 9330 } 9331 9332 //===----------------------------------------------------------------------===// 9333 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9334 //===----------------------------------------------------------------------===// 9335 9336 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9337 /// inheritance hierarchy of 'rProto'. 9338 bool 9339 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9340 ObjCProtocolDecl *rProto) const { 9341 if (declaresSameEntity(lProto, rProto)) 9342 return true; 9343 for (auto *PI : rProto->protocols()) 9344 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9345 return true; 9346 return false; 9347 } 9348 9349 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9350 /// Class<pr1, ...>. 9351 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9352 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9353 for (auto *lhsProto : lhs->quals()) { 9354 bool match = false; 9355 for (auto *rhsProto : rhs->quals()) { 9356 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9357 match = true; 9358 break; 9359 } 9360 } 9361 if (!match) 9362 return false; 9363 } 9364 return true; 9365 } 9366 9367 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9368 /// ObjCQualifiedIDType. 9369 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9370 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9371 bool compare) { 9372 // Allow id<P..> and an 'id' in all cases. 9373 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9374 return true; 9375 9376 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9377 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9378 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9379 return false; 9380 9381 if (lhs->isObjCQualifiedIdType()) { 9382 if (rhs->qual_empty()) { 9383 // If the RHS is a unqualified interface pointer "NSString*", 9384 // make sure we check the class hierarchy. 9385 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9386 for (auto *I : lhs->quals()) { 9387 // when comparing an id<P> on lhs with a static type on rhs, 9388 // see if static class implements all of id's protocols, directly or 9389 // through its super class and categories. 9390 if (!rhsID->ClassImplementsProtocol(I, true)) 9391 return false; 9392 } 9393 } 9394 // If there are no qualifiers and no interface, we have an 'id'. 9395 return true; 9396 } 9397 // Both the right and left sides have qualifiers. 9398 for (auto *lhsProto : lhs->quals()) { 9399 bool match = false; 9400 9401 // when comparing an id<P> on lhs with a static type on rhs, 9402 // see if static class implements all of id's protocols, directly or 9403 // through its super class and categories. 9404 for (auto *rhsProto : rhs->quals()) { 9405 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9406 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9407 match = true; 9408 break; 9409 } 9410 } 9411 // If the RHS is a qualified interface pointer "NSString<P>*", 9412 // make sure we check the class hierarchy. 9413 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9414 for (auto *I : lhs->quals()) { 9415 // when comparing an id<P> on lhs with a static type on rhs, 9416 // see if static class implements all of id's protocols, directly or 9417 // through its super class and categories. 9418 if (rhsID->ClassImplementsProtocol(I, true)) { 9419 match = true; 9420 break; 9421 } 9422 } 9423 } 9424 if (!match) 9425 return false; 9426 } 9427 9428 return true; 9429 } 9430 9431 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9432 9433 if (lhs->getInterfaceType()) { 9434 // If both the right and left sides have qualifiers. 9435 for (auto *lhsProto : lhs->quals()) { 9436 bool match = false; 9437 9438 // when comparing an id<P> on rhs with a static type on lhs, 9439 // see if static class implements all of id's protocols, directly or 9440 // through its super class and categories. 9441 // First, lhs protocols in the qualifier list must be found, direct 9442 // or indirect in rhs's qualifier list or it is a mismatch. 9443 for (auto *rhsProto : rhs->quals()) { 9444 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9445 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9446 match = true; 9447 break; 9448 } 9449 } 9450 if (!match) 9451 return false; 9452 } 9453 9454 // Static class's protocols, or its super class or category protocols 9455 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9456 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9458 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9459 // This is rather dubious but matches gcc's behavior. If lhs has 9460 // no type qualifier and its class has no static protocol(s) 9461 // assume that it is mismatch. 9462 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9463 return false; 9464 for (auto *lhsProto : LHSInheritedProtocols) { 9465 bool match = false; 9466 for (auto *rhsProto : rhs->quals()) { 9467 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9468 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9469 match = true; 9470 break; 9471 } 9472 } 9473 if (!match) 9474 return false; 9475 } 9476 } 9477 return true; 9478 } 9479 return false; 9480 } 9481 9482 /// canAssignObjCInterfaces - Return true if the two interface types are 9483 /// compatible for assignment from RHS to LHS. This handles validation of any 9484 /// protocol qualifiers on the LHS or RHS. 9485 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9486 const ObjCObjectPointerType *RHSOPT) { 9487 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9488 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9489 9490 // If either type represents the built-in 'id' type, return true. 9491 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9492 return true; 9493 9494 // Function object that propagates a successful result or handles 9495 // __kindof types. 9496 auto finish = [&](bool succeeded) -> bool { 9497 if (succeeded) 9498 return true; 9499 9500 if (!RHS->isKindOfType()) 9501 return false; 9502 9503 // Strip off __kindof and protocol qualifiers, then check whether 9504 // we can assign the other way. 9505 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9506 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9507 }; 9508 9509 // Casts from or to id<P> are allowed when the other side has compatible 9510 // protocols. 9511 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9512 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9513 } 9514 9515 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9516 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9517 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9518 } 9519 9520 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9521 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9522 return true; 9523 } 9524 9525 // If we have 2 user-defined types, fall into that path. 9526 if (LHS->getInterface() && RHS->getInterface()) { 9527 return finish(canAssignObjCInterfaces(LHS, RHS)); 9528 } 9529 9530 return false; 9531 } 9532 9533 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9534 /// for providing type-safety for objective-c pointers used to pass/return 9535 /// arguments in block literals. When passed as arguments, passing 'A*' where 9536 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9537 /// not OK. For the return type, the opposite is not OK. 9538 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9539 const ObjCObjectPointerType *LHSOPT, 9540 const ObjCObjectPointerType *RHSOPT, 9541 bool BlockReturnType) { 9542 9543 // Function object that propagates a successful result or handles 9544 // __kindof types. 9545 auto finish = [&](bool succeeded) -> bool { 9546 if (succeeded) 9547 return true; 9548 9549 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9550 if (!Expected->isKindOfType()) 9551 return false; 9552 9553 // Strip off __kindof and protocol qualifiers, then check whether 9554 // we can assign the other way. 9555 return canAssignObjCInterfacesInBlockPointer( 9556 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9557 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9558 BlockReturnType); 9559 }; 9560 9561 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9562 return true; 9563 9564 if (LHSOPT->isObjCBuiltinType()) { 9565 return finish(RHSOPT->isObjCBuiltinType() || 9566 RHSOPT->isObjCQualifiedIdType()); 9567 } 9568 9569 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9570 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9571 // Use for block parameters previous type checking for compatibility. 9572 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9573 // Or corrected type checking as in non-compat mode. 9574 (!BlockReturnType && 9575 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9576 else 9577 return finish(ObjCQualifiedIdTypesAreCompatible( 9578 (BlockReturnType ? LHSOPT : RHSOPT), 9579 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9580 } 9581 9582 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9583 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9584 if (LHS && RHS) { // We have 2 user-defined types. 9585 if (LHS != RHS) { 9586 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9587 return finish(BlockReturnType); 9588 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9589 return finish(!BlockReturnType); 9590 } 9591 else 9592 return true; 9593 } 9594 return false; 9595 } 9596 9597 /// Comparison routine for Objective-C protocols to be used with 9598 /// llvm::array_pod_sort. 9599 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9600 ObjCProtocolDecl * const *rhs) { 9601 return (*lhs)->getName().compare((*rhs)->getName()); 9602 } 9603 9604 /// getIntersectionOfProtocols - This routine finds the intersection of set 9605 /// of protocols inherited from two distinct objective-c pointer objects with 9606 /// the given common base. 9607 /// It is used to build composite qualifier list of the composite type of 9608 /// the conditional expression involving two objective-c pointer objects. 9609 static 9610 void getIntersectionOfProtocols(ASTContext &Context, 9611 const ObjCInterfaceDecl *CommonBase, 9612 const ObjCObjectPointerType *LHSOPT, 9613 const ObjCObjectPointerType *RHSOPT, 9614 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9615 9616 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9617 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9618 assert(LHS->getInterface() && "LHS must have an interface base"); 9619 assert(RHS->getInterface() && "RHS must have an interface base"); 9620 9621 // Add all of the protocols for the LHS. 9622 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9623 9624 // Start with the protocol qualifiers. 9625 for (auto proto : LHS->quals()) { 9626 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9627 } 9628 9629 // Also add the protocols associated with the LHS interface. 9630 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9631 9632 // Add all of the protocols for the RHS. 9633 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9634 9635 // Start with the protocol qualifiers. 9636 for (auto proto : RHS->quals()) { 9637 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9638 } 9639 9640 // Also add the protocols associated with the RHS interface. 9641 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9642 9643 // Compute the intersection of the collected protocol sets. 9644 for (auto proto : LHSProtocolSet) { 9645 if (RHSProtocolSet.count(proto)) 9646 IntersectionSet.push_back(proto); 9647 } 9648 9649 // Compute the set of protocols that is implied by either the common type or 9650 // the protocols within the intersection. 9651 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9652 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9653 9654 // Remove any implied protocols from the list of inherited protocols. 9655 if (!ImpliedProtocols.empty()) { 9656 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9657 return ImpliedProtocols.contains(proto); 9658 }); 9659 } 9660 9661 // Sort the remaining protocols by name. 9662 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9663 compareObjCProtocolsByName); 9664 } 9665 9666 /// Determine whether the first type is a subtype of the second. 9667 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9668 QualType rhs) { 9669 // Common case: two object pointers. 9670 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9671 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9672 if (lhsOPT && rhsOPT) 9673 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9674 9675 // Two block pointers. 9676 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9677 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9678 if (lhsBlock && rhsBlock) 9679 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9680 9681 // If either is an unqualified 'id' and the other is a block, it's 9682 // acceptable. 9683 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9684 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9685 return true; 9686 9687 return false; 9688 } 9689 9690 // Check that the given Objective-C type argument lists are equivalent. 9691 static bool sameObjCTypeArgs(ASTContext &ctx, 9692 const ObjCInterfaceDecl *iface, 9693 ArrayRef<QualType> lhsArgs, 9694 ArrayRef<QualType> rhsArgs, 9695 bool stripKindOf) { 9696 if (lhsArgs.size() != rhsArgs.size()) 9697 return false; 9698 9699 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9700 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9701 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9702 continue; 9703 9704 switch (typeParams->begin()[i]->getVariance()) { 9705 case ObjCTypeParamVariance::Invariant: 9706 if (!stripKindOf || 9707 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9708 rhsArgs[i].stripObjCKindOfType(ctx))) { 9709 return false; 9710 } 9711 break; 9712 9713 case ObjCTypeParamVariance::Covariant: 9714 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9715 return false; 9716 break; 9717 9718 case ObjCTypeParamVariance::Contravariant: 9719 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9720 return false; 9721 break; 9722 } 9723 } 9724 9725 return true; 9726 } 9727 9728 QualType ASTContext::areCommonBaseCompatible( 9729 const ObjCObjectPointerType *Lptr, 9730 const ObjCObjectPointerType *Rptr) { 9731 const ObjCObjectType *LHS = Lptr->getObjectType(); 9732 const ObjCObjectType *RHS = Rptr->getObjectType(); 9733 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9734 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9735 9736 if (!LDecl || !RDecl) 9737 return {}; 9738 9739 // When either LHS or RHS is a kindof type, we should return a kindof type. 9740 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9741 // kindof(A). 9742 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9743 9744 // Follow the left-hand side up the class hierarchy until we either hit a 9745 // root or find the RHS. Record the ancestors in case we don't find it. 9746 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9747 LHSAncestors; 9748 while (true) { 9749 // Record this ancestor. We'll need this if the common type isn't in the 9750 // path from the LHS to the root. 9751 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9752 9753 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9754 // Get the type arguments. 9755 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9756 bool anyChanges = false; 9757 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9758 // Both have type arguments, compare them. 9759 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9760 LHS->getTypeArgs(), RHS->getTypeArgs(), 9761 /*stripKindOf=*/true)) 9762 return {}; 9763 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9764 // If only one has type arguments, the result will not have type 9765 // arguments. 9766 LHSTypeArgs = {}; 9767 anyChanges = true; 9768 } 9769 9770 // Compute the intersection of protocols. 9771 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9772 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9773 Protocols); 9774 if (!Protocols.empty()) 9775 anyChanges = true; 9776 9777 // If anything in the LHS will have changed, build a new result type. 9778 // If we need to return a kindof type but LHS is not a kindof type, we 9779 // build a new result type. 9780 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9781 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9782 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9783 anyKindOf || LHS->isKindOfType()); 9784 return getObjCObjectPointerType(Result); 9785 } 9786 9787 return getObjCObjectPointerType(QualType(LHS, 0)); 9788 } 9789 9790 // Find the superclass. 9791 QualType LHSSuperType = LHS->getSuperClassType(); 9792 if (LHSSuperType.isNull()) 9793 break; 9794 9795 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9796 } 9797 9798 // We didn't find anything by following the LHS to its root; now check 9799 // the RHS against the cached set of ancestors. 9800 while (true) { 9801 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9802 if (KnownLHS != LHSAncestors.end()) { 9803 LHS = KnownLHS->second; 9804 9805 // Get the type arguments. 9806 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9807 bool anyChanges = false; 9808 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9809 // Both have type arguments, compare them. 9810 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9811 LHS->getTypeArgs(), RHS->getTypeArgs(), 9812 /*stripKindOf=*/true)) 9813 return {}; 9814 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9815 // If only one has type arguments, the result will not have type 9816 // arguments. 9817 RHSTypeArgs = {}; 9818 anyChanges = true; 9819 } 9820 9821 // Compute the intersection of protocols. 9822 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9823 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9824 Protocols); 9825 if (!Protocols.empty()) 9826 anyChanges = true; 9827 9828 // If we need to return a kindof type but RHS is not a kindof type, we 9829 // build a new result type. 9830 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9831 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9832 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9833 anyKindOf || RHS->isKindOfType()); 9834 return getObjCObjectPointerType(Result); 9835 } 9836 9837 return getObjCObjectPointerType(QualType(RHS, 0)); 9838 } 9839 9840 // Find the superclass of the RHS. 9841 QualType RHSSuperType = RHS->getSuperClassType(); 9842 if (RHSSuperType.isNull()) 9843 break; 9844 9845 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9846 } 9847 9848 return {}; 9849 } 9850 9851 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9852 const ObjCObjectType *RHS) { 9853 assert(LHS->getInterface() && "LHS is not an interface type"); 9854 assert(RHS->getInterface() && "RHS is not an interface type"); 9855 9856 // Verify that the base decls are compatible: the RHS must be a subclass of 9857 // the LHS. 9858 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9859 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9860 if (!IsSuperClass) 9861 return false; 9862 9863 // If the LHS has protocol qualifiers, determine whether all of them are 9864 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9865 // LHS). 9866 if (LHS->getNumProtocols() > 0) { 9867 // OK if conversion of LHS to SuperClass results in narrowing of types 9868 // ; i.e., SuperClass may implement at least one of the protocols 9869 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9870 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9871 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9872 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9873 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9874 // qualifiers. 9875 for (auto *RHSPI : RHS->quals()) 9876 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9877 // If there is no protocols associated with RHS, it is not a match. 9878 if (SuperClassInheritedProtocols.empty()) 9879 return false; 9880 9881 for (const auto *LHSProto : LHS->quals()) { 9882 bool SuperImplementsProtocol = false; 9883 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9884 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9885 SuperImplementsProtocol = true; 9886 break; 9887 } 9888 if (!SuperImplementsProtocol) 9889 return false; 9890 } 9891 } 9892 9893 // If the LHS is specialized, we may need to check type arguments. 9894 if (LHS->isSpecialized()) { 9895 // Follow the superclass chain until we've matched the LHS class in the 9896 // hierarchy. This substitutes type arguments through. 9897 const ObjCObjectType *RHSSuper = RHS; 9898 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9899 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9900 9901 // If the RHS is specializd, compare type arguments. 9902 if (RHSSuper->isSpecialized() && 9903 !sameObjCTypeArgs(*this, LHS->getInterface(), 9904 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9905 /*stripKindOf=*/true)) { 9906 return false; 9907 } 9908 } 9909 9910 return true; 9911 } 9912 9913 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9914 // get the "pointed to" types 9915 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9916 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9917 9918 if (!LHSOPT || !RHSOPT) 9919 return false; 9920 9921 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9922 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9923 } 9924 9925 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9926 return canAssignObjCInterfaces( 9927 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9928 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9929 } 9930 9931 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9932 /// both shall have the identically qualified version of a compatible type. 9933 /// C99 6.2.7p1: Two types have compatible types if their types are the 9934 /// same. See 6.7.[2,3,5] for additional rules. 9935 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9936 bool CompareUnqualified) { 9937 if (getLangOpts().CPlusPlus) 9938 return hasSameType(LHS, RHS); 9939 9940 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9941 } 9942 9943 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9944 return typesAreCompatible(LHS, RHS); 9945 } 9946 9947 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9948 return !mergeTypes(LHS, RHS, true).isNull(); 9949 } 9950 9951 /// mergeTransparentUnionType - if T is a transparent union type and a member 9952 /// of T is compatible with SubType, return the merged type, else return 9953 /// QualType() 9954 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9955 bool OfBlockPointer, 9956 bool Unqualified) { 9957 if (const RecordType *UT = T->getAsUnionType()) { 9958 RecordDecl *UD = UT->getDecl(); 9959 if (UD->hasAttr<TransparentUnionAttr>()) { 9960 for (const auto *I : UD->fields()) { 9961 QualType ET = I->getType().getUnqualifiedType(); 9962 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9963 if (!MT.isNull()) 9964 return MT; 9965 } 9966 } 9967 } 9968 9969 return {}; 9970 } 9971 9972 /// mergeFunctionParameterTypes - merge two types which appear as function 9973 /// parameter types 9974 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9975 bool OfBlockPointer, 9976 bool Unqualified) { 9977 // GNU extension: two types are compatible if they appear as a function 9978 // argument, one of the types is a transparent union type and the other 9979 // type is compatible with a union member 9980 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9981 Unqualified); 9982 if (!lmerge.isNull()) 9983 return lmerge; 9984 9985 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9986 Unqualified); 9987 if (!rmerge.isNull()) 9988 return rmerge; 9989 9990 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9991 } 9992 9993 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9994 bool OfBlockPointer, bool Unqualified, 9995 bool AllowCXX) { 9996 const auto *lbase = lhs->castAs<FunctionType>(); 9997 const auto *rbase = rhs->castAs<FunctionType>(); 9998 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9999 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 10000 bool allLTypes = true; 10001 bool allRTypes = true; 10002 10003 // Check return type 10004 QualType retType; 10005 if (OfBlockPointer) { 10006 QualType RHS = rbase->getReturnType(); 10007 QualType LHS = lbase->getReturnType(); 10008 bool UnqualifiedResult = Unqualified; 10009 if (!UnqualifiedResult) 10010 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 10011 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 10012 } 10013 else 10014 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 10015 Unqualified); 10016 if (retType.isNull()) 10017 return {}; 10018 10019 if (Unqualified) 10020 retType = retType.getUnqualifiedType(); 10021 10022 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 10023 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 10024 if (Unqualified) { 10025 LRetType = LRetType.getUnqualifiedType(); 10026 RRetType = RRetType.getUnqualifiedType(); 10027 } 10028 10029 if (getCanonicalType(retType) != LRetType) 10030 allLTypes = false; 10031 if (getCanonicalType(retType) != RRetType) 10032 allRTypes = false; 10033 10034 // FIXME: double check this 10035 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10036 // rbase->getRegParmAttr() != 0 && 10037 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10038 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10039 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10040 10041 // Compatible functions must have compatible calling conventions 10042 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10043 return {}; 10044 10045 // Regparm is part of the calling convention. 10046 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10047 return {}; 10048 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10049 return {}; 10050 10051 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10052 return {}; 10053 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10054 return {}; 10055 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10056 return {}; 10057 10058 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10059 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10060 10061 if (lbaseInfo.getNoReturn() != NoReturn) 10062 allLTypes = false; 10063 if (rbaseInfo.getNoReturn() != NoReturn) 10064 allRTypes = false; 10065 10066 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10067 10068 if (lproto && rproto) { // two C99 style function prototypes 10069 assert((AllowCXX || 10070 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10071 "C++ shouldn't be here"); 10072 // Compatible functions must have the same number of parameters 10073 if (lproto->getNumParams() != rproto->getNumParams()) 10074 return {}; 10075 10076 // Variadic and non-variadic functions aren't compatible 10077 if (lproto->isVariadic() != rproto->isVariadic()) 10078 return {}; 10079 10080 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10081 return {}; 10082 10083 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10084 bool canUseLeft, canUseRight; 10085 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10086 newParamInfos)) 10087 return {}; 10088 10089 if (!canUseLeft) 10090 allLTypes = false; 10091 if (!canUseRight) 10092 allRTypes = false; 10093 10094 // Check parameter type compatibility 10095 SmallVector<QualType, 10> types; 10096 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10097 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10098 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10099 QualType paramType = mergeFunctionParameterTypes( 10100 lParamType, rParamType, OfBlockPointer, Unqualified); 10101 if (paramType.isNull()) 10102 return {}; 10103 10104 if (Unqualified) 10105 paramType = paramType.getUnqualifiedType(); 10106 10107 types.push_back(paramType); 10108 if (Unqualified) { 10109 lParamType = lParamType.getUnqualifiedType(); 10110 rParamType = rParamType.getUnqualifiedType(); 10111 } 10112 10113 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10114 allLTypes = false; 10115 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10116 allRTypes = false; 10117 } 10118 10119 if (allLTypes) return lhs; 10120 if (allRTypes) return rhs; 10121 10122 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10123 EPI.ExtInfo = einfo; 10124 EPI.ExtParameterInfos = 10125 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10126 return getFunctionType(retType, types, EPI); 10127 } 10128 10129 if (lproto) allRTypes = false; 10130 if (rproto) allLTypes = false; 10131 10132 const FunctionProtoType *proto = lproto ? lproto : rproto; 10133 if (proto) { 10134 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10135 if (proto->isVariadic()) 10136 return {}; 10137 // Check that the types are compatible with the types that 10138 // would result from default argument promotions (C99 6.7.5.3p15). 10139 // The only types actually affected are promotable integer 10140 // types and floats, which would be passed as a different 10141 // type depending on whether the prototype is visible. 10142 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10143 QualType paramTy = proto->getParamType(i); 10144 10145 // Look at the converted type of enum types, since that is the type used 10146 // to pass enum values. 10147 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10148 paramTy = Enum->getDecl()->getIntegerType(); 10149 if (paramTy.isNull()) 10150 return {}; 10151 } 10152 10153 if (paramTy->isPromotableIntegerType() || 10154 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10155 return {}; 10156 } 10157 10158 if (allLTypes) return lhs; 10159 if (allRTypes) return rhs; 10160 10161 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10162 EPI.ExtInfo = einfo; 10163 return getFunctionType(retType, proto->getParamTypes(), EPI); 10164 } 10165 10166 if (allLTypes) return lhs; 10167 if (allRTypes) return rhs; 10168 return getFunctionNoProtoType(retType, einfo); 10169 } 10170 10171 /// Given that we have an enum type and a non-enum type, try to merge them. 10172 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10173 QualType other, bool isBlockReturnType) { 10174 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10175 // a signed integer type, or an unsigned integer type. 10176 // Compatibility is based on the underlying type, not the promotion 10177 // type. 10178 QualType underlyingType = ET->getDecl()->getIntegerType(); 10179 if (underlyingType.isNull()) 10180 return {}; 10181 if (Context.hasSameType(underlyingType, other)) 10182 return other; 10183 10184 // In block return types, we're more permissive and accept any 10185 // integral type of the same size. 10186 if (isBlockReturnType && other->isIntegerType() && 10187 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10188 return other; 10189 10190 return {}; 10191 } 10192 10193 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10194 bool OfBlockPointer, 10195 bool Unqualified, bool BlockReturnType) { 10196 // For C++ we will not reach this code with reference types (see below), 10197 // for OpenMP variant call overloading we might. 10198 // 10199 // C++ [expr]: If an expression initially has the type "reference to T", the 10200 // type is adjusted to "T" prior to any further analysis, the expression 10201 // designates the object or function denoted by the reference, and the 10202 // expression is an lvalue unless the reference is an rvalue reference and 10203 // the expression is a function call (possibly inside parentheses). 10204 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10205 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10206 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10207 LHS->getTypeClass() == RHS->getTypeClass()) 10208 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10209 OfBlockPointer, Unqualified, BlockReturnType); 10210 if (LHSRefTy || RHSRefTy) 10211 return {}; 10212 10213 if (Unqualified) { 10214 LHS = LHS.getUnqualifiedType(); 10215 RHS = RHS.getUnqualifiedType(); 10216 } 10217 10218 QualType LHSCan = getCanonicalType(LHS), 10219 RHSCan = getCanonicalType(RHS); 10220 10221 // If two types are identical, they are compatible. 10222 if (LHSCan == RHSCan) 10223 return LHS; 10224 10225 // If the qualifiers are different, the types aren't compatible... mostly. 10226 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10227 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10228 if (LQuals != RQuals) { 10229 // If any of these qualifiers are different, we have a type 10230 // mismatch. 10231 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10232 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10233 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10234 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10235 return {}; 10236 10237 // Exactly one GC qualifier difference is allowed: __strong is 10238 // okay if the other type has no GC qualifier but is an Objective 10239 // C object pointer (i.e. implicitly strong by default). We fix 10240 // this by pretending that the unqualified type was actually 10241 // qualified __strong. 10242 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10243 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10244 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10245 10246 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10247 return {}; 10248 10249 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10250 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10251 } 10252 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10253 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10254 } 10255 return {}; 10256 } 10257 10258 // Okay, qualifiers are equal. 10259 10260 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10261 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10262 10263 // We want to consider the two function types to be the same for these 10264 // comparisons, just force one to the other. 10265 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10266 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10267 10268 // Same as above for arrays 10269 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10270 LHSClass = Type::ConstantArray; 10271 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10272 RHSClass = Type::ConstantArray; 10273 10274 // ObjCInterfaces are just specialized ObjCObjects. 10275 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10276 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10277 10278 // Canonicalize ExtVector -> Vector. 10279 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10280 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10281 10282 // If the canonical type classes don't match. 10283 if (LHSClass != RHSClass) { 10284 // Note that we only have special rules for turning block enum 10285 // returns into block int returns, not vice-versa. 10286 if (const auto *ETy = LHS->getAs<EnumType>()) { 10287 return mergeEnumWithInteger(*this, ETy, RHS, false); 10288 } 10289 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10290 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10291 } 10292 // allow block pointer type to match an 'id' type. 10293 if (OfBlockPointer && !BlockReturnType) { 10294 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10295 return LHS; 10296 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10297 return RHS; 10298 } 10299 // Allow __auto_type to match anything; it merges to the type with more 10300 // information. 10301 if (const auto *AT = LHS->getAs<AutoType>()) { 10302 if (AT->isGNUAutoType()) 10303 return RHS; 10304 } 10305 if (const auto *AT = RHS->getAs<AutoType>()) { 10306 if (AT->isGNUAutoType()) 10307 return LHS; 10308 } 10309 return {}; 10310 } 10311 10312 // The canonical type classes match. 10313 switch (LHSClass) { 10314 #define TYPE(Class, Base) 10315 #define ABSTRACT_TYPE(Class, Base) 10316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10317 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10318 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10319 #include "clang/AST/TypeNodes.inc" 10320 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10321 10322 case Type::Auto: 10323 case Type::DeducedTemplateSpecialization: 10324 case Type::LValueReference: 10325 case Type::RValueReference: 10326 case Type::MemberPointer: 10327 llvm_unreachable("C++ should never be in mergeTypes"); 10328 10329 case Type::ObjCInterface: 10330 case Type::IncompleteArray: 10331 case Type::VariableArray: 10332 case Type::FunctionProto: 10333 case Type::ExtVector: 10334 llvm_unreachable("Types are eliminated above"); 10335 10336 case Type::Pointer: 10337 { 10338 // Merge two pointer types, while trying to preserve typedef info 10339 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10340 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10341 if (Unqualified) { 10342 LHSPointee = LHSPointee.getUnqualifiedType(); 10343 RHSPointee = RHSPointee.getUnqualifiedType(); 10344 } 10345 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10346 Unqualified); 10347 if (ResultType.isNull()) 10348 return {}; 10349 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10350 return LHS; 10351 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10352 return RHS; 10353 return getPointerType(ResultType); 10354 } 10355 case Type::BlockPointer: 10356 { 10357 // Merge two block pointer types, while trying to preserve typedef info 10358 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10359 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10360 if (Unqualified) { 10361 LHSPointee = LHSPointee.getUnqualifiedType(); 10362 RHSPointee = RHSPointee.getUnqualifiedType(); 10363 } 10364 if (getLangOpts().OpenCL) { 10365 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10366 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10367 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10368 // 6.12.5) thus the following check is asymmetric. 10369 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10370 return {}; 10371 LHSPteeQual.removeAddressSpace(); 10372 RHSPteeQual.removeAddressSpace(); 10373 LHSPointee = 10374 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10375 RHSPointee = 10376 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10377 } 10378 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10379 Unqualified); 10380 if (ResultType.isNull()) 10381 return {}; 10382 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10383 return LHS; 10384 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10385 return RHS; 10386 return getBlockPointerType(ResultType); 10387 } 10388 case Type::Atomic: 10389 { 10390 // Merge two pointer types, while trying to preserve typedef info 10391 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10392 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10393 if (Unqualified) { 10394 LHSValue = LHSValue.getUnqualifiedType(); 10395 RHSValue = RHSValue.getUnqualifiedType(); 10396 } 10397 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10398 Unqualified); 10399 if (ResultType.isNull()) 10400 return {}; 10401 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10402 return LHS; 10403 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10404 return RHS; 10405 return getAtomicType(ResultType); 10406 } 10407 case Type::ConstantArray: 10408 { 10409 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10410 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10411 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10412 return {}; 10413 10414 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10415 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10416 if (Unqualified) { 10417 LHSElem = LHSElem.getUnqualifiedType(); 10418 RHSElem = RHSElem.getUnqualifiedType(); 10419 } 10420 10421 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10422 if (ResultType.isNull()) 10423 return {}; 10424 10425 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10426 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10427 10428 // If either side is a variable array, and both are complete, check whether 10429 // the current dimension is definite. 10430 if (LVAT || RVAT) { 10431 auto SizeFetch = [this](const VariableArrayType* VAT, 10432 const ConstantArrayType* CAT) 10433 -> std::pair<bool,llvm::APInt> { 10434 if (VAT) { 10435 Optional<llvm::APSInt> TheInt; 10436 Expr *E = VAT->getSizeExpr(); 10437 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10438 return std::make_pair(true, *TheInt); 10439 return std::make_pair(false, llvm::APSInt()); 10440 } 10441 if (CAT) 10442 return std::make_pair(true, CAT->getSize()); 10443 return std::make_pair(false, llvm::APInt()); 10444 }; 10445 10446 bool HaveLSize, HaveRSize; 10447 llvm::APInt LSize, RSize; 10448 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10449 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10450 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10451 return {}; // Definite, but unequal, array dimension 10452 } 10453 10454 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10455 return LHS; 10456 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10457 return RHS; 10458 if (LCAT) 10459 return getConstantArrayType(ResultType, LCAT->getSize(), 10460 LCAT->getSizeExpr(), 10461 ArrayType::ArraySizeModifier(), 0); 10462 if (RCAT) 10463 return getConstantArrayType(ResultType, RCAT->getSize(), 10464 RCAT->getSizeExpr(), 10465 ArrayType::ArraySizeModifier(), 0); 10466 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10467 return LHS; 10468 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10469 return RHS; 10470 if (LVAT) { 10471 // FIXME: This isn't correct! But tricky to implement because 10472 // the array's size has to be the size of LHS, but the type 10473 // has to be different. 10474 return LHS; 10475 } 10476 if (RVAT) { 10477 // FIXME: This isn't correct! But tricky to implement because 10478 // the array's size has to be the size of RHS, but the type 10479 // has to be different. 10480 return RHS; 10481 } 10482 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10483 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10484 return getIncompleteArrayType(ResultType, 10485 ArrayType::ArraySizeModifier(), 0); 10486 } 10487 case Type::FunctionNoProto: 10488 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10489 case Type::Record: 10490 case Type::Enum: 10491 return {}; 10492 case Type::Builtin: 10493 // Only exactly equal builtin types are compatible, which is tested above. 10494 return {}; 10495 case Type::Complex: 10496 // Distinct complex types are incompatible. 10497 return {}; 10498 case Type::Vector: 10499 // FIXME: The merged type should be an ExtVector! 10500 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10501 RHSCan->castAs<VectorType>())) 10502 return LHS; 10503 return {}; 10504 case Type::ConstantMatrix: 10505 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10506 RHSCan->castAs<ConstantMatrixType>())) 10507 return LHS; 10508 return {}; 10509 case Type::ObjCObject: { 10510 // Check if the types are assignment compatible. 10511 // FIXME: This should be type compatibility, e.g. whether 10512 // "LHS x; RHS x;" at global scope is legal. 10513 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10514 RHS->castAs<ObjCObjectType>())) 10515 return LHS; 10516 return {}; 10517 } 10518 case Type::ObjCObjectPointer: 10519 if (OfBlockPointer) { 10520 if (canAssignObjCInterfacesInBlockPointer( 10521 LHS->castAs<ObjCObjectPointerType>(), 10522 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10523 return LHS; 10524 return {}; 10525 } 10526 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10527 RHS->castAs<ObjCObjectPointerType>())) 10528 return LHS; 10529 return {}; 10530 case Type::Pipe: 10531 assert(LHS != RHS && 10532 "Equivalent pipe types should have already been handled!"); 10533 return {}; 10534 case Type::BitInt: { 10535 // Merge two bit-precise int types, while trying to preserve typedef info. 10536 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10537 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10538 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10539 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10540 10541 // Like unsigned/int, shouldn't have a type if they don't match. 10542 if (LHSUnsigned != RHSUnsigned) 10543 return {}; 10544 10545 if (LHSBits != RHSBits) 10546 return {}; 10547 return LHS; 10548 } 10549 } 10550 10551 llvm_unreachable("Invalid Type::Class!"); 10552 } 10553 10554 bool ASTContext::mergeExtParameterInfo( 10555 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10556 bool &CanUseFirst, bool &CanUseSecond, 10557 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10558 assert(NewParamInfos.empty() && "param info list not empty"); 10559 CanUseFirst = CanUseSecond = true; 10560 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10561 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10562 10563 // Fast path: if the first type doesn't have ext parameter infos, 10564 // we match if and only if the second type also doesn't have them. 10565 if (!FirstHasInfo && !SecondHasInfo) 10566 return true; 10567 10568 bool NeedParamInfo = false; 10569 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10570 : SecondFnType->getExtParameterInfos().size(); 10571 10572 for (size_t I = 0; I < E; ++I) { 10573 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10574 if (FirstHasInfo) 10575 FirstParam = FirstFnType->getExtParameterInfo(I); 10576 if (SecondHasInfo) 10577 SecondParam = SecondFnType->getExtParameterInfo(I); 10578 10579 // Cannot merge unless everything except the noescape flag matches. 10580 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10581 return false; 10582 10583 bool FirstNoEscape = FirstParam.isNoEscape(); 10584 bool SecondNoEscape = SecondParam.isNoEscape(); 10585 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10586 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10587 if (NewParamInfos.back().getOpaqueValue()) 10588 NeedParamInfo = true; 10589 if (FirstNoEscape != IsNoEscape) 10590 CanUseFirst = false; 10591 if (SecondNoEscape != IsNoEscape) 10592 CanUseSecond = false; 10593 } 10594 10595 if (!NeedParamInfo) 10596 NewParamInfos.clear(); 10597 10598 return true; 10599 } 10600 10601 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10602 ObjCLayouts[CD] = nullptr; 10603 } 10604 10605 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10606 /// 'RHS' attributes and returns the merged version; including for function 10607 /// return types. 10608 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10609 QualType LHSCan = getCanonicalType(LHS), 10610 RHSCan = getCanonicalType(RHS); 10611 // If two types are identical, they are compatible. 10612 if (LHSCan == RHSCan) 10613 return LHS; 10614 if (RHSCan->isFunctionType()) { 10615 if (!LHSCan->isFunctionType()) 10616 return {}; 10617 QualType OldReturnType = 10618 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10619 QualType NewReturnType = 10620 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10621 QualType ResReturnType = 10622 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10623 if (ResReturnType.isNull()) 10624 return {}; 10625 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10626 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10627 // In either case, use OldReturnType to build the new function type. 10628 const auto *F = LHS->castAs<FunctionType>(); 10629 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10630 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10631 EPI.ExtInfo = getFunctionExtInfo(LHS); 10632 QualType ResultType = 10633 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10634 return ResultType; 10635 } 10636 } 10637 return {}; 10638 } 10639 10640 // If the qualifiers are different, the types can still be merged. 10641 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10642 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10643 if (LQuals != RQuals) { 10644 // If any of these qualifiers are different, we have a type mismatch. 10645 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10646 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10647 return {}; 10648 10649 // Exactly one GC qualifier difference is allowed: __strong is 10650 // okay if the other type has no GC qualifier but is an Objective 10651 // C object pointer (i.e. implicitly strong by default). We fix 10652 // this by pretending that the unqualified type was actually 10653 // qualified __strong. 10654 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10655 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10656 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10657 10658 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10659 return {}; 10660 10661 if (GC_L == Qualifiers::Strong) 10662 return LHS; 10663 if (GC_R == Qualifiers::Strong) 10664 return RHS; 10665 return {}; 10666 } 10667 10668 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10669 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10670 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10671 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10672 if (ResQT == LHSBaseQT) 10673 return LHS; 10674 if (ResQT == RHSBaseQT) 10675 return RHS; 10676 } 10677 return {}; 10678 } 10679 10680 //===----------------------------------------------------------------------===// 10681 // Integer Predicates 10682 //===----------------------------------------------------------------------===// 10683 10684 unsigned ASTContext::getIntWidth(QualType T) const { 10685 if (const auto *ET = T->getAs<EnumType>()) 10686 T = ET->getDecl()->getIntegerType(); 10687 if (T->isBooleanType()) 10688 return 1; 10689 if (const auto *EIT = T->getAs<BitIntType>()) 10690 return EIT->getNumBits(); 10691 // For builtin types, just use the standard type sizing method 10692 return (unsigned)getTypeSize(T); 10693 } 10694 10695 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10696 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10697 "Unexpected type"); 10698 10699 // Turn <4 x signed int> -> <4 x unsigned int> 10700 if (const auto *VTy = T->getAs<VectorType>()) 10701 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10702 VTy->getNumElements(), VTy->getVectorKind()); 10703 10704 // For _BitInt, return an unsigned _BitInt with same width. 10705 if (const auto *EITy = T->getAs<BitIntType>()) 10706 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10707 10708 // For enums, get the underlying integer type of the enum, and let the general 10709 // integer type signchanging code handle it. 10710 if (const auto *ETy = T->getAs<EnumType>()) 10711 T = ETy->getDecl()->getIntegerType(); 10712 10713 switch (T->castAs<BuiltinType>()->getKind()) { 10714 case BuiltinType::Char_S: 10715 case BuiltinType::SChar: 10716 return UnsignedCharTy; 10717 case BuiltinType::Short: 10718 return UnsignedShortTy; 10719 case BuiltinType::Int: 10720 return UnsignedIntTy; 10721 case BuiltinType::Long: 10722 return UnsignedLongTy; 10723 case BuiltinType::LongLong: 10724 return UnsignedLongLongTy; 10725 case BuiltinType::Int128: 10726 return UnsignedInt128Ty; 10727 // wchar_t is special. It is either signed or not, but when it's signed, 10728 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10729 // version of it's underlying type instead. 10730 case BuiltinType::WChar_S: 10731 return getUnsignedWCharType(); 10732 10733 case BuiltinType::ShortAccum: 10734 return UnsignedShortAccumTy; 10735 case BuiltinType::Accum: 10736 return UnsignedAccumTy; 10737 case BuiltinType::LongAccum: 10738 return UnsignedLongAccumTy; 10739 case BuiltinType::SatShortAccum: 10740 return SatUnsignedShortAccumTy; 10741 case BuiltinType::SatAccum: 10742 return SatUnsignedAccumTy; 10743 case BuiltinType::SatLongAccum: 10744 return SatUnsignedLongAccumTy; 10745 case BuiltinType::ShortFract: 10746 return UnsignedShortFractTy; 10747 case BuiltinType::Fract: 10748 return UnsignedFractTy; 10749 case BuiltinType::LongFract: 10750 return UnsignedLongFractTy; 10751 case BuiltinType::SatShortFract: 10752 return SatUnsignedShortFractTy; 10753 case BuiltinType::SatFract: 10754 return SatUnsignedFractTy; 10755 case BuiltinType::SatLongFract: 10756 return SatUnsignedLongFractTy; 10757 default: 10758 llvm_unreachable("Unexpected signed integer or fixed point type"); 10759 } 10760 } 10761 10762 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10763 assert((T->hasUnsignedIntegerRepresentation() || 10764 T->isUnsignedFixedPointType()) && 10765 "Unexpected type"); 10766 10767 // Turn <4 x unsigned int> -> <4 x signed int> 10768 if (const auto *VTy = T->getAs<VectorType>()) 10769 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10770 VTy->getNumElements(), VTy->getVectorKind()); 10771 10772 // For _BitInt, return a signed _BitInt with same width. 10773 if (const auto *EITy = T->getAs<BitIntType>()) 10774 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10775 10776 // For enums, get the underlying integer type of the enum, and let the general 10777 // integer type signchanging code handle it. 10778 if (const auto *ETy = T->getAs<EnumType>()) 10779 T = ETy->getDecl()->getIntegerType(); 10780 10781 switch (T->castAs<BuiltinType>()->getKind()) { 10782 case BuiltinType::Char_U: 10783 case BuiltinType::UChar: 10784 return SignedCharTy; 10785 case BuiltinType::UShort: 10786 return ShortTy; 10787 case BuiltinType::UInt: 10788 return IntTy; 10789 case BuiltinType::ULong: 10790 return LongTy; 10791 case BuiltinType::ULongLong: 10792 return LongLongTy; 10793 case BuiltinType::UInt128: 10794 return Int128Ty; 10795 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10796 // there's no matching "signed wchar_t". Therefore we return the signed 10797 // version of it's underlying type instead. 10798 case BuiltinType::WChar_U: 10799 return getSignedWCharType(); 10800 10801 case BuiltinType::UShortAccum: 10802 return ShortAccumTy; 10803 case BuiltinType::UAccum: 10804 return AccumTy; 10805 case BuiltinType::ULongAccum: 10806 return LongAccumTy; 10807 case BuiltinType::SatUShortAccum: 10808 return SatShortAccumTy; 10809 case BuiltinType::SatUAccum: 10810 return SatAccumTy; 10811 case BuiltinType::SatULongAccum: 10812 return SatLongAccumTy; 10813 case BuiltinType::UShortFract: 10814 return ShortFractTy; 10815 case BuiltinType::UFract: 10816 return FractTy; 10817 case BuiltinType::ULongFract: 10818 return LongFractTy; 10819 case BuiltinType::SatUShortFract: 10820 return SatShortFractTy; 10821 case BuiltinType::SatUFract: 10822 return SatFractTy; 10823 case BuiltinType::SatULongFract: 10824 return SatLongFractTy; 10825 default: 10826 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10827 } 10828 } 10829 10830 ASTMutationListener::~ASTMutationListener() = default; 10831 10832 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10833 QualType ReturnType) {} 10834 10835 //===----------------------------------------------------------------------===// 10836 // Builtin Type Computation 10837 //===----------------------------------------------------------------------===// 10838 10839 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10840 /// pointer over the consumed characters. This returns the resultant type. If 10841 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10842 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10843 /// a vector of "i*". 10844 /// 10845 /// RequiresICE is filled in on return to indicate whether the value is required 10846 /// to be an Integer Constant Expression. 10847 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10848 ASTContext::GetBuiltinTypeError &Error, 10849 bool &RequiresICE, 10850 bool AllowTypeModifiers) { 10851 // Modifiers. 10852 int HowLong = 0; 10853 bool Signed = false, Unsigned = false; 10854 RequiresICE = false; 10855 10856 // Read the prefixed modifiers first. 10857 bool Done = false; 10858 #ifndef NDEBUG 10859 bool IsSpecial = false; 10860 #endif 10861 while (!Done) { 10862 switch (*Str++) { 10863 default: Done = true; --Str; break; 10864 case 'I': 10865 RequiresICE = true; 10866 break; 10867 case 'S': 10868 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10869 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10870 Signed = true; 10871 break; 10872 case 'U': 10873 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10874 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10875 Unsigned = true; 10876 break; 10877 case 'L': 10878 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10879 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10880 ++HowLong; 10881 break; 10882 case 'N': 10883 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10884 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10885 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10886 #ifndef NDEBUG 10887 IsSpecial = true; 10888 #endif 10889 if (Context.getTargetInfo().getLongWidth() == 32) 10890 ++HowLong; 10891 break; 10892 case 'W': 10893 // This modifier represents int64 type. 10894 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10895 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10896 #ifndef NDEBUG 10897 IsSpecial = true; 10898 #endif 10899 switch (Context.getTargetInfo().getInt64Type()) { 10900 default: 10901 llvm_unreachable("Unexpected integer type"); 10902 case TargetInfo::SignedLong: 10903 HowLong = 1; 10904 break; 10905 case TargetInfo::SignedLongLong: 10906 HowLong = 2; 10907 break; 10908 } 10909 break; 10910 case 'Z': 10911 // This modifier represents int32 type. 10912 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10913 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10914 #ifndef NDEBUG 10915 IsSpecial = true; 10916 #endif 10917 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10918 default: 10919 llvm_unreachable("Unexpected integer type"); 10920 case TargetInfo::SignedInt: 10921 HowLong = 0; 10922 break; 10923 case TargetInfo::SignedLong: 10924 HowLong = 1; 10925 break; 10926 case TargetInfo::SignedLongLong: 10927 HowLong = 2; 10928 break; 10929 } 10930 break; 10931 case 'O': 10932 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10933 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10934 #ifndef NDEBUG 10935 IsSpecial = true; 10936 #endif 10937 if (Context.getLangOpts().OpenCL) 10938 HowLong = 1; 10939 else 10940 HowLong = 2; 10941 break; 10942 } 10943 } 10944 10945 QualType Type; 10946 10947 // Read the base type. 10948 switch (*Str++) { 10949 default: llvm_unreachable("Unknown builtin type letter!"); 10950 case 'x': 10951 assert(HowLong == 0 && !Signed && !Unsigned && 10952 "Bad modifiers used with 'x'!"); 10953 Type = Context.Float16Ty; 10954 break; 10955 case 'y': 10956 assert(HowLong == 0 && !Signed && !Unsigned && 10957 "Bad modifiers used with 'y'!"); 10958 Type = Context.BFloat16Ty; 10959 break; 10960 case 'v': 10961 assert(HowLong == 0 && !Signed && !Unsigned && 10962 "Bad modifiers used with 'v'!"); 10963 Type = Context.VoidTy; 10964 break; 10965 case 'h': 10966 assert(HowLong == 0 && !Signed && !Unsigned && 10967 "Bad modifiers used with 'h'!"); 10968 Type = Context.HalfTy; 10969 break; 10970 case 'f': 10971 assert(HowLong == 0 && !Signed && !Unsigned && 10972 "Bad modifiers used with 'f'!"); 10973 Type = Context.FloatTy; 10974 break; 10975 case 'd': 10976 assert(HowLong < 3 && !Signed && !Unsigned && 10977 "Bad modifiers used with 'd'!"); 10978 if (HowLong == 1) 10979 Type = Context.LongDoubleTy; 10980 else if (HowLong == 2) 10981 Type = Context.Float128Ty; 10982 else 10983 Type = Context.DoubleTy; 10984 break; 10985 case 's': 10986 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10987 if (Unsigned) 10988 Type = Context.UnsignedShortTy; 10989 else 10990 Type = Context.ShortTy; 10991 break; 10992 case 'i': 10993 if (HowLong == 3) 10994 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10995 else if (HowLong == 2) 10996 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10997 else if (HowLong == 1) 10998 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10999 else 11000 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 11001 break; 11002 case 'c': 11003 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 11004 if (Signed) 11005 Type = Context.SignedCharTy; 11006 else if (Unsigned) 11007 Type = Context.UnsignedCharTy; 11008 else 11009 Type = Context.CharTy; 11010 break; 11011 case 'b': // boolean 11012 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 11013 Type = Context.BoolTy; 11014 break; 11015 case 'z': // size_t. 11016 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 11017 Type = Context.getSizeType(); 11018 break; 11019 case 'w': // wchar_t. 11020 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 11021 Type = Context.getWideCharType(); 11022 break; 11023 case 'F': 11024 Type = Context.getCFConstantStringType(); 11025 break; 11026 case 'G': 11027 Type = Context.getObjCIdType(); 11028 break; 11029 case 'H': 11030 Type = Context.getObjCSelType(); 11031 break; 11032 case 'M': 11033 Type = Context.getObjCSuperType(); 11034 break; 11035 case 'a': 11036 Type = Context.getBuiltinVaListType(); 11037 assert(!Type.isNull() && "builtin va list type not initialized!"); 11038 break; 11039 case 'A': 11040 // This is a "reference" to a va_list; however, what exactly 11041 // this means depends on how va_list is defined. There are two 11042 // different kinds of va_list: ones passed by value, and ones 11043 // passed by reference. An example of a by-value va_list is 11044 // x86, where va_list is a char*. An example of by-ref va_list 11045 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11046 // we want this argument to be a char*&; for x86-64, we want 11047 // it to be a __va_list_tag*. 11048 Type = Context.getBuiltinVaListType(); 11049 assert(!Type.isNull() && "builtin va list type not initialized!"); 11050 if (Type->isArrayType()) 11051 Type = Context.getArrayDecayedType(Type); 11052 else 11053 Type = Context.getLValueReferenceType(Type); 11054 break; 11055 case 'q': { 11056 char *End; 11057 unsigned NumElements = strtoul(Str, &End, 10); 11058 assert(End != Str && "Missing vector size"); 11059 Str = End; 11060 11061 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11062 RequiresICE, false); 11063 assert(!RequiresICE && "Can't require vector ICE"); 11064 11065 Type = Context.getScalableVectorType(ElementType, NumElements); 11066 break; 11067 } 11068 case 'V': { 11069 char *End; 11070 unsigned NumElements = strtoul(Str, &End, 10); 11071 assert(End != Str && "Missing vector size"); 11072 Str = End; 11073 11074 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11075 RequiresICE, false); 11076 assert(!RequiresICE && "Can't require vector ICE"); 11077 11078 // TODO: No way to make AltiVec vectors in builtins yet. 11079 Type = Context.getVectorType(ElementType, NumElements, 11080 VectorType::GenericVector); 11081 break; 11082 } 11083 case 'E': { 11084 char *End; 11085 11086 unsigned NumElements = strtoul(Str, &End, 10); 11087 assert(End != Str && "Missing vector size"); 11088 11089 Str = End; 11090 11091 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11092 false); 11093 Type = Context.getExtVectorType(ElementType, NumElements); 11094 break; 11095 } 11096 case 'X': { 11097 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11098 false); 11099 assert(!RequiresICE && "Can't require complex ICE"); 11100 Type = Context.getComplexType(ElementType); 11101 break; 11102 } 11103 case 'Y': 11104 Type = Context.getPointerDiffType(); 11105 break; 11106 case 'P': 11107 Type = Context.getFILEType(); 11108 if (Type.isNull()) { 11109 Error = ASTContext::GE_Missing_stdio; 11110 return {}; 11111 } 11112 break; 11113 case 'J': 11114 if (Signed) 11115 Type = Context.getsigjmp_bufType(); 11116 else 11117 Type = Context.getjmp_bufType(); 11118 11119 if (Type.isNull()) { 11120 Error = ASTContext::GE_Missing_setjmp; 11121 return {}; 11122 } 11123 break; 11124 case 'K': 11125 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11126 Type = Context.getucontext_tType(); 11127 11128 if (Type.isNull()) { 11129 Error = ASTContext::GE_Missing_ucontext; 11130 return {}; 11131 } 11132 break; 11133 case 'p': 11134 Type = Context.getProcessIDType(); 11135 break; 11136 } 11137 11138 // If there are modifiers and if we're allowed to parse them, go for it. 11139 Done = !AllowTypeModifiers; 11140 while (!Done) { 11141 switch (char c = *Str++) { 11142 default: Done = true; --Str; break; 11143 case '*': 11144 case '&': { 11145 // Both pointers and references can have their pointee types 11146 // qualified with an address space. 11147 char *End; 11148 unsigned AddrSpace = strtoul(Str, &End, 10); 11149 if (End != Str) { 11150 // Note AddrSpace == 0 is not the same as an unspecified address space. 11151 Type = Context.getAddrSpaceQualType( 11152 Type, 11153 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11154 Str = End; 11155 } 11156 if (c == '*') 11157 Type = Context.getPointerType(Type); 11158 else 11159 Type = Context.getLValueReferenceType(Type); 11160 break; 11161 } 11162 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11163 case 'C': 11164 Type = Type.withConst(); 11165 break; 11166 case 'D': 11167 Type = Context.getVolatileType(Type); 11168 break; 11169 case 'R': 11170 Type = Type.withRestrict(); 11171 break; 11172 } 11173 } 11174 11175 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11176 "Integer constant 'I' type must be an integer"); 11177 11178 return Type; 11179 } 11180 11181 // On some targets such as PowerPC, some of the builtins are defined with custom 11182 // type descriptors for target-dependent types. These descriptors are decoded in 11183 // other functions, but it may be useful to be able to fall back to default 11184 // descriptor decoding to define builtins mixing target-dependent and target- 11185 // independent types. This function allows decoding one type descriptor with 11186 // default decoding. 11187 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11188 GetBuiltinTypeError &Error, bool &RequireICE, 11189 bool AllowTypeModifiers) const { 11190 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11191 } 11192 11193 /// GetBuiltinType - Return the type for the specified builtin. 11194 QualType ASTContext::GetBuiltinType(unsigned Id, 11195 GetBuiltinTypeError &Error, 11196 unsigned *IntegerConstantArgs) const { 11197 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11198 if (TypeStr[0] == '\0') { 11199 Error = GE_Missing_type; 11200 return {}; 11201 } 11202 11203 SmallVector<QualType, 8> ArgTypes; 11204 11205 bool RequiresICE = false; 11206 Error = GE_None; 11207 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11208 RequiresICE, true); 11209 if (Error != GE_None) 11210 return {}; 11211 11212 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11213 11214 while (TypeStr[0] && TypeStr[0] != '.') { 11215 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11216 if (Error != GE_None) 11217 return {}; 11218 11219 // If this argument is required to be an IntegerConstantExpression and the 11220 // caller cares, fill in the bitmask we return. 11221 if (RequiresICE && IntegerConstantArgs) 11222 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11223 11224 // Do array -> pointer decay. The builtin should use the decayed type. 11225 if (Ty->isArrayType()) 11226 Ty = getArrayDecayedType(Ty); 11227 11228 ArgTypes.push_back(Ty); 11229 } 11230 11231 if (Id == Builtin::BI__GetExceptionInfo) 11232 return {}; 11233 11234 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11235 "'.' should only occur at end of builtin type list!"); 11236 11237 bool Variadic = (TypeStr[0] == '.'); 11238 11239 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11240 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11241 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11242 11243 11244 // We really shouldn't be making a no-proto type here. 11245 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes()) 11246 return getFunctionNoProtoType(ResType, EI); 11247 11248 FunctionProtoType::ExtProtoInfo EPI; 11249 EPI.ExtInfo = EI; 11250 EPI.Variadic = Variadic; 11251 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11252 EPI.ExceptionSpec.Type = 11253 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11254 11255 return getFunctionType(ResType, ArgTypes, EPI); 11256 } 11257 11258 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11259 const FunctionDecl *FD) { 11260 if (!FD->isExternallyVisible()) 11261 return GVA_Internal; 11262 11263 // Non-user-provided functions get emitted as weak definitions with every 11264 // use, no matter whether they've been explicitly instantiated etc. 11265 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11266 if (!MD->isUserProvided()) 11267 return GVA_DiscardableODR; 11268 11269 GVALinkage External; 11270 switch (FD->getTemplateSpecializationKind()) { 11271 case TSK_Undeclared: 11272 case TSK_ExplicitSpecialization: 11273 External = GVA_StrongExternal; 11274 break; 11275 11276 case TSK_ExplicitInstantiationDefinition: 11277 return GVA_StrongODR; 11278 11279 // C++11 [temp.explicit]p10: 11280 // [ Note: The intent is that an inline function that is the subject of 11281 // an explicit instantiation declaration will still be implicitly 11282 // instantiated when used so that the body can be considered for 11283 // inlining, but that no out-of-line copy of the inline function would be 11284 // generated in the translation unit. -- end note ] 11285 case TSK_ExplicitInstantiationDeclaration: 11286 return GVA_AvailableExternally; 11287 11288 case TSK_ImplicitInstantiation: 11289 External = GVA_DiscardableODR; 11290 break; 11291 } 11292 11293 if (!FD->isInlined()) 11294 return External; 11295 11296 if ((!Context.getLangOpts().CPlusPlus && 11297 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11298 !FD->hasAttr<DLLExportAttr>()) || 11299 FD->hasAttr<GNUInlineAttr>()) { 11300 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11301 11302 // GNU or C99 inline semantics. Determine whether this symbol should be 11303 // externally visible. 11304 if (FD->isInlineDefinitionExternallyVisible()) 11305 return External; 11306 11307 // C99 inline semantics, where the symbol is not externally visible. 11308 return GVA_AvailableExternally; 11309 } 11310 11311 // Functions specified with extern and inline in -fms-compatibility mode 11312 // forcibly get emitted. While the body of the function cannot be later 11313 // replaced, the function definition cannot be discarded. 11314 if (FD->isMSExternInline()) 11315 return GVA_StrongODR; 11316 11317 return GVA_DiscardableODR; 11318 } 11319 11320 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11321 const Decl *D, GVALinkage L) { 11322 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11323 // dllexport/dllimport on inline functions. 11324 if (D->hasAttr<DLLImportAttr>()) { 11325 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11326 return GVA_AvailableExternally; 11327 } else if (D->hasAttr<DLLExportAttr>()) { 11328 if (L == GVA_DiscardableODR) 11329 return GVA_StrongODR; 11330 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11331 // Device-side functions with __global__ attribute must always be 11332 // visible externally so they can be launched from host. 11333 if (D->hasAttr<CUDAGlobalAttr>() && 11334 (L == GVA_DiscardableODR || L == GVA_Internal)) 11335 return GVA_StrongODR; 11336 // Single source offloading languages like CUDA/HIP need to be able to 11337 // access static device variables from host code of the same compilation 11338 // unit. This is done by externalizing the static variable with a shared 11339 // name between the host and device compilation which is the same for the 11340 // same compilation unit whereas different among different compilation 11341 // units. 11342 if (Context.shouldExternalize(D)) 11343 return GVA_StrongExternal; 11344 } 11345 return L; 11346 } 11347 11348 /// Adjust the GVALinkage for a declaration based on what an external AST source 11349 /// knows about whether there can be other definitions of this declaration. 11350 static GVALinkage 11351 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11352 GVALinkage L) { 11353 ExternalASTSource *Source = Ctx.getExternalSource(); 11354 if (!Source) 11355 return L; 11356 11357 switch (Source->hasExternalDefinitions(D)) { 11358 case ExternalASTSource::EK_Never: 11359 // Other translation units rely on us to provide the definition. 11360 if (L == GVA_DiscardableODR) 11361 return GVA_StrongODR; 11362 break; 11363 11364 case ExternalASTSource::EK_Always: 11365 return GVA_AvailableExternally; 11366 11367 case ExternalASTSource::EK_ReplyHazy: 11368 break; 11369 } 11370 return L; 11371 } 11372 11373 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11374 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11375 adjustGVALinkageForAttributes(*this, FD, 11376 basicGVALinkageForFunction(*this, FD))); 11377 } 11378 11379 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11380 const VarDecl *VD) { 11381 if (!VD->isExternallyVisible()) 11382 return GVA_Internal; 11383 11384 if (VD->isStaticLocal()) { 11385 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11386 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11387 LexicalContext = LexicalContext->getLexicalParent(); 11388 11389 // ObjC Blocks can create local variables that don't have a FunctionDecl 11390 // LexicalContext. 11391 if (!LexicalContext) 11392 return GVA_DiscardableODR; 11393 11394 // Otherwise, let the static local variable inherit its linkage from the 11395 // nearest enclosing function. 11396 auto StaticLocalLinkage = 11397 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11398 11399 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11400 // be emitted in any object with references to the symbol for the object it 11401 // contains, whether inline or out-of-line." 11402 // Similar behavior is observed with MSVC. An alternative ABI could use 11403 // StrongODR/AvailableExternally to match the function, but none are 11404 // known/supported currently. 11405 if (StaticLocalLinkage == GVA_StrongODR || 11406 StaticLocalLinkage == GVA_AvailableExternally) 11407 return GVA_DiscardableODR; 11408 return StaticLocalLinkage; 11409 } 11410 11411 // MSVC treats in-class initialized static data members as definitions. 11412 // By giving them non-strong linkage, out-of-line definitions won't 11413 // cause link errors. 11414 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11415 return GVA_DiscardableODR; 11416 11417 // Most non-template variables have strong linkage; inline variables are 11418 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11419 GVALinkage StrongLinkage; 11420 switch (Context.getInlineVariableDefinitionKind(VD)) { 11421 case ASTContext::InlineVariableDefinitionKind::None: 11422 StrongLinkage = GVA_StrongExternal; 11423 break; 11424 case ASTContext::InlineVariableDefinitionKind::Weak: 11425 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11426 StrongLinkage = GVA_DiscardableODR; 11427 break; 11428 case ASTContext::InlineVariableDefinitionKind::Strong: 11429 StrongLinkage = GVA_StrongODR; 11430 break; 11431 } 11432 11433 switch (VD->getTemplateSpecializationKind()) { 11434 case TSK_Undeclared: 11435 return StrongLinkage; 11436 11437 case TSK_ExplicitSpecialization: 11438 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11439 VD->isStaticDataMember() 11440 ? GVA_StrongODR 11441 : StrongLinkage; 11442 11443 case TSK_ExplicitInstantiationDefinition: 11444 return GVA_StrongODR; 11445 11446 case TSK_ExplicitInstantiationDeclaration: 11447 return GVA_AvailableExternally; 11448 11449 case TSK_ImplicitInstantiation: 11450 return GVA_DiscardableODR; 11451 } 11452 11453 llvm_unreachable("Invalid Linkage!"); 11454 } 11455 11456 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11457 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11458 adjustGVALinkageForAttributes(*this, VD, 11459 basicGVALinkageForVariable(*this, VD))); 11460 } 11461 11462 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11463 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11464 if (!VD->isFileVarDecl()) 11465 return false; 11466 // Global named register variables (GNU extension) are never emitted. 11467 if (VD->getStorageClass() == SC_Register) 11468 return false; 11469 if (VD->getDescribedVarTemplate() || 11470 isa<VarTemplatePartialSpecializationDecl>(VD)) 11471 return false; 11472 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11473 // We never need to emit an uninstantiated function template. 11474 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11475 return false; 11476 } else if (isa<PragmaCommentDecl>(D)) 11477 return true; 11478 else if (isa<PragmaDetectMismatchDecl>(D)) 11479 return true; 11480 else if (isa<OMPRequiresDecl>(D)) 11481 return true; 11482 else if (isa<OMPThreadPrivateDecl>(D)) 11483 return !D->getDeclContext()->isDependentContext(); 11484 else if (isa<OMPAllocateDecl>(D)) 11485 return !D->getDeclContext()->isDependentContext(); 11486 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11487 return !D->getDeclContext()->isDependentContext(); 11488 else if (isa<ImportDecl>(D)) 11489 return true; 11490 else 11491 return false; 11492 11493 // If this is a member of a class template, we do not need to emit it. 11494 if (D->getDeclContext()->isDependentContext()) 11495 return false; 11496 11497 // Weak references don't produce any output by themselves. 11498 if (D->hasAttr<WeakRefAttr>()) 11499 return false; 11500 11501 // Aliases and used decls are required. 11502 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11503 return true; 11504 11505 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11506 // Forward declarations aren't required. 11507 if (!FD->doesThisDeclarationHaveABody()) 11508 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11509 11510 // Constructors and destructors are required. 11511 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11512 return true; 11513 11514 // The key function for a class is required. This rule only comes 11515 // into play when inline functions can be key functions, though. 11516 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11517 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11518 const CXXRecordDecl *RD = MD->getParent(); 11519 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11520 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11521 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11522 return true; 11523 } 11524 } 11525 } 11526 11527 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11528 11529 // static, static inline, always_inline, and extern inline functions can 11530 // always be deferred. Normal inline functions can be deferred in C99/C++. 11531 // Implicit template instantiations can also be deferred in C++. 11532 return !isDiscardableGVALinkage(Linkage); 11533 } 11534 11535 const auto *VD = cast<VarDecl>(D); 11536 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11537 11538 // If the decl is marked as `declare target to`, it should be emitted for the 11539 // host and for the device. 11540 if (LangOpts.OpenMP && 11541 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11542 return true; 11543 11544 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11545 !isMSStaticDataMemberInlineDefinition(VD)) 11546 return false; 11547 11548 // Variables that can be needed in other TUs are required. 11549 auto Linkage = GetGVALinkageForVariable(VD); 11550 if (!isDiscardableGVALinkage(Linkage)) 11551 return true; 11552 11553 // We never need to emit a variable that is available in another TU. 11554 if (Linkage == GVA_AvailableExternally) 11555 return false; 11556 11557 // Variables that have destruction with side-effects are required. 11558 if (VD->needsDestruction(*this)) 11559 return true; 11560 11561 // Variables that have initialization with side-effects are required. 11562 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11563 // We can get a value-dependent initializer during error recovery. 11564 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11565 return true; 11566 11567 // Likewise, variables with tuple-like bindings are required if their 11568 // bindings have side-effects. 11569 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11570 for (const auto *BD : DD->bindings()) 11571 if (const auto *BindingVD = BD->getHoldingVar()) 11572 if (DeclMustBeEmitted(BindingVD)) 11573 return true; 11574 11575 return false; 11576 } 11577 11578 void ASTContext::forEachMultiversionedFunctionVersion( 11579 const FunctionDecl *FD, 11580 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11581 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11582 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11583 FD = FD->getMostRecentDecl(); 11584 // FIXME: The order of traversal here matters and depends on the order of 11585 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11586 // shouldn't rely on that. 11587 for (auto *CurDecl : 11588 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11589 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11590 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11591 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11592 SeenDecls.insert(CurFD); 11593 Pred(CurFD); 11594 } 11595 } 11596 } 11597 11598 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11599 bool IsCXXMethod, 11600 bool IsBuiltin) const { 11601 // Pass through to the C++ ABI object 11602 if (IsCXXMethod) 11603 return ABI->getDefaultMethodCallConv(IsVariadic); 11604 11605 // Builtins ignore user-specified default calling convention and remain the 11606 // Target's default calling convention. 11607 if (!IsBuiltin) { 11608 switch (LangOpts.getDefaultCallingConv()) { 11609 case LangOptions::DCC_None: 11610 break; 11611 case LangOptions::DCC_CDecl: 11612 return CC_C; 11613 case LangOptions::DCC_FastCall: 11614 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11615 return CC_X86FastCall; 11616 break; 11617 case LangOptions::DCC_StdCall: 11618 if (!IsVariadic) 11619 return CC_X86StdCall; 11620 break; 11621 case LangOptions::DCC_VectorCall: 11622 // __vectorcall cannot be applied to variadic functions. 11623 if (!IsVariadic) 11624 return CC_X86VectorCall; 11625 break; 11626 case LangOptions::DCC_RegCall: 11627 // __regcall cannot be applied to variadic functions. 11628 if (!IsVariadic) 11629 return CC_X86RegCall; 11630 break; 11631 } 11632 } 11633 return Target->getDefaultCallingConv(); 11634 } 11635 11636 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11637 // Pass through to the C++ ABI object 11638 return ABI->isNearlyEmpty(RD); 11639 } 11640 11641 VTableContextBase *ASTContext::getVTableContext() { 11642 if (!VTContext.get()) { 11643 auto ABI = Target->getCXXABI(); 11644 if (ABI.isMicrosoft()) 11645 VTContext.reset(new MicrosoftVTableContext(*this)); 11646 else { 11647 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11648 ? ItaniumVTableContext::Relative 11649 : ItaniumVTableContext::Pointer; 11650 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11651 } 11652 } 11653 return VTContext.get(); 11654 } 11655 11656 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11657 if (!T) 11658 T = Target; 11659 switch (T->getCXXABI().getKind()) { 11660 case TargetCXXABI::AppleARM64: 11661 case TargetCXXABI::Fuchsia: 11662 case TargetCXXABI::GenericAArch64: 11663 case TargetCXXABI::GenericItanium: 11664 case TargetCXXABI::GenericARM: 11665 case TargetCXXABI::GenericMIPS: 11666 case TargetCXXABI::iOS: 11667 case TargetCXXABI::WebAssembly: 11668 case TargetCXXABI::WatchOS: 11669 case TargetCXXABI::XL: 11670 return ItaniumMangleContext::create(*this, getDiagnostics()); 11671 case TargetCXXABI::Microsoft: 11672 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11673 } 11674 llvm_unreachable("Unsupported ABI"); 11675 } 11676 11677 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11678 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11679 "Device mangle context does not support Microsoft mangling."); 11680 switch (T.getCXXABI().getKind()) { 11681 case TargetCXXABI::AppleARM64: 11682 case TargetCXXABI::Fuchsia: 11683 case TargetCXXABI::GenericAArch64: 11684 case TargetCXXABI::GenericItanium: 11685 case TargetCXXABI::GenericARM: 11686 case TargetCXXABI::GenericMIPS: 11687 case TargetCXXABI::iOS: 11688 case TargetCXXABI::WebAssembly: 11689 case TargetCXXABI::WatchOS: 11690 case TargetCXXABI::XL: 11691 return ItaniumMangleContext::create( 11692 *this, getDiagnostics(), 11693 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11694 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11695 return RD->getDeviceLambdaManglingNumber(); 11696 return llvm::None; 11697 }, 11698 /*IsAux=*/true); 11699 case TargetCXXABI::Microsoft: 11700 return MicrosoftMangleContext::create(*this, getDiagnostics(), 11701 /*IsAux=*/true); 11702 } 11703 llvm_unreachable("Unsupported ABI"); 11704 } 11705 11706 CXXABI::~CXXABI() = default; 11707 11708 size_t ASTContext::getSideTableAllocatedMemory() const { 11709 return ASTRecordLayouts.getMemorySize() + 11710 llvm::capacity_in_bytes(ObjCLayouts) + 11711 llvm::capacity_in_bytes(KeyFunctions) + 11712 llvm::capacity_in_bytes(ObjCImpls) + 11713 llvm::capacity_in_bytes(BlockVarCopyInits) + 11714 llvm::capacity_in_bytes(DeclAttrs) + 11715 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11716 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11717 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11718 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11719 llvm::capacity_in_bytes(OverriddenMethods) + 11720 llvm::capacity_in_bytes(Types) + 11721 llvm::capacity_in_bytes(VariableArrayTypes); 11722 } 11723 11724 /// getIntTypeForBitwidth - 11725 /// sets integer QualTy according to specified details: 11726 /// bitwidth, signed/unsigned. 11727 /// Returns empty type if there is no appropriate target types. 11728 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11729 unsigned Signed) const { 11730 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11731 CanQualType QualTy = getFromTargetType(Ty); 11732 if (!QualTy && DestWidth == 128) 11733 return Signed ? Int128Ty : UnsignedInt128Ty; 11734 return QualTy; 11735 } 11736 11737 /// getRealTypeForBitwidth - 11738 /// sets floating point QualTy according to specified bitwidth. 11739 /// Returns empty type if there is no appropriate target types. 11740 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11741 FloatModeKind ExplicitType) const { 11742 FloatModeKind Ty = 11743 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11744 switch (Ty) { 11745 case FloatModeKind::Float: 11746 return FloatTy; 11747 case FloatModeKind::Double: 11748 return DoubleTy; 11749 case FloatModeKind::LongDouble: 11750 return LongDoubleTy; 11751 case FloatModeKind::Float128: 11752 return Float128Ty; 11753 case FloatModeKind::Ibm128: 11754 return Ibm128Ty; 11755 case FloatModeKind::NoFloat: 11756 return {}; 11757 } 11758 11759 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11760 } 11761 11762 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11763 if (Number > 1) 11764 MangleNumbers[ND] = Number; 11765 } 11766 11767 unsigned ASTContext::getManglingNumber(const NamedDecl *ND, 11768 bool ForAuxTarget) const { 11769 auto I = MangleNumbers.find(ND); 11770 unsigned Res = I != MangleNumbers.end() ? I->second : 1; 11771 // CUDA/HIP host compilation encodes host and device mangling numbers 11772 // as lower and upper half of 32 bit integer. 11773 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) { 11774 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF; 11775 } else { 11776 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling " 11777 "number for aux target"); 11778 } 11779 return Res > 1 ? Res : 1; 11780 } 11781 11782 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11783 if (Number > 1) 11784 StaticLocalNumbers[VD] = Number; 11785 } 11786 11787 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11788 auto I = StaticLocalNumbers.find(VD); 11789 return I != StaticLocalNumbers.end() ? I->second : 1; 11790 } 11791 11792 MangleNumberingContext & 11793 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11794 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11795 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11796 if (!MCtx) 11797 MCtx = createMangleNumberingContext(); 11798 return *MCtx; 11799 } 11800 11801 MangleNumberingContext & 11802 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11803 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11804 std::unique_ptr<MangleNumberingContext> &MCtx = 11805 ExtraMangleNumberingContexts[D]; 11806 if (!MCtx) 11807 MCtx = createMangleNumberingContext(); 11808 return *MCtx; 11809 } 11810 11811 std::unique_ptr<MangleNumberingContext> 11812 ASTContext::createMangleNumberingContext() const { 11813 return ABI->createMangleNumberingContext(); 11814 } 11815 11816 const CXXConstructorDecl * 11817 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11818 return ABI->getCopyConstructorForExceptionObject( 11819 cast<CXXRecordDecl>(RD->getFirstDecl())); 11820 } 11821 11822 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11823 CXXConstructorDecl *CD) { 11824 return ABI->addCopyConstructorForExceptionObject( 11825 cast<CXXRecordDecl>(RD->getFirstDecl()), 11826 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11827 } 11828 11829 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11830 TypedefNameDecl *DD) { 11831 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11832 } 11833 11834 TypedefNameDecl * 11835 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11836 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11837 } 11838 11839 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11840 DeclaratorDecl *DD) { 11841 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11842 } 11843 11844 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11845 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11846 } 11847 11848 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11849 ParamIndices[D] = index; 11850 } 11851 11852 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11853 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11854 assert(I != ParamIndices.end() && 11855 "ParmIndices lacks entry set by ParmVarDecl"); 11856 return I->second; 11857 } 11858 11859 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11860 unsigned Length) const { 11861 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11862 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11863 EltTy = EltTy.withConst(); 11864 11865 EltTy = adjustStringLiteralBaseType(EltTy); 11866 11867 // Get an array type for the string, according to C99 6.4.5. This includes 11868 // the null terminator character. 11869 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11870 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11871 } 11872 11873 StringLiteral * 11874 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11875 StringLiteral *&Result = StringLiteralCache[Key]; 11876 if (!Result) 11877 Result = StringLiteral::Create( 11878 *this, Key, StringLiteral::Ascii, 11879 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11880 SourceLocation()); 11881 return Result; 11882 } 11883 11884 MSGuidDecl * 11885 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11886 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11887 11888 llvm::FoldingSetNodeID ID; 11889 MSGuidDecl::Profile(ID, Parts); 11890 11891 void *InsertPos; 11892 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11893 return Existing; 11894 11895 QualType GUIDType = getMSGuidType().withConst(); 11896 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11897 MSGuidDecls.InsertNode(New, InsertPos); 11898 return New; 11899 } 11900 11901 UnnamedGlobalConstantDecl * 11902 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty, 11903 const APValue &APVal) const { 11904 llvm::FoldingSetNodeID ID; 11905 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal); 11906 11907 void *InsertPos; 11908 if (UnnamedGlobalConstantDecl *Existing = 11909 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos)) 11910 return Existing; 11911 11912 UnnamedGlobalConstantDecl *New = 11913 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal); 11914 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos); 11915 return New; 11916 } 11917 11918 TemplateParamObjectDecl * 11919 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11920 assert(T->isRecordType() && "template param object of unexpected type"); 11921 11922 // C++ [temp.param]p8: 11923 // [...] a static storage duration object of type 'const T' [...] 11924 T.addConst(); 11925 11926 llvm::FoldingSetNodeID ID; 11927 TemplateParamObjectDecl::Profile(ID, T, V); 11928 11929 void *InsertPos; 11930 if (TemplateParamObjectDecl *Existing = 11931 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11932 return Existing; 11933 11934 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11935 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11936 return New; 11937 } 11938 11939 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11940 const llvm::Triple &T = getTargetInfo().getTriple(); 11941 if (!T.isOSDarwin()) 11942 return false; 11943 11944 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11945 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11946 return false; 11947 11948 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11949 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11950 uint64_t Size = sizeChars.getQuantity(); 11951 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11952 unsigned Align = alignChars.getQuantity(); 11953 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11954 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11955 } 11956 11957 bool 11958 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11959 const ObjCMethodDecl *MethodImpl) { 11960 // No point trying to match an unavailable/deprecated mothod. 11961 if (MethodDecl->hasAttr<UnavailableAttr>() 11962 || MethodDecl->hasAttr<DeprecatedAttr>()) 11963 return false; 11964 if (MethodDecl->getObjCDeclQualifier() != 11965 MethodImpl->getObjCDeclQualifier()) 11966 return false; 11967 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11968 return false; 11969 11970 if (MethodDecl->param_size() != MethodImpl->param_size()) 11971 return false; 11972 11973 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11974 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11975 EF = MethodDecl->param_end(); 11976 IM != EM && IF != EF; ++IM, ++IF) { 11977 const ParmVarDecl *DeclVar = (*IF); 11978 const ParmVarDecl *ImplVar = (*IM); 11979 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11980 return false; 11981 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11982 return false; 11983 } 11984 11985 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11986 } 11987 11988 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11989 LangAS AS; 11990 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11991 AS = LangAS::Default; 11992 else 11993 AS = QT->getPointeeType().getAddressSpace(); 11994 11995 return getTargetInfo().getNullPointerValue(AS); 11996 } 11997 11998 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11999 // Return the address space for the type. If the type is a 12000 // function type without an address space qualifier, the 12001 // program address space is used. Otherwise, the target picks 12002 // the best address space based on the type information 12003 return T->isFunctionType() && !T.hasAddressSpace() 12004 ? getTargetInfo().getProgramAddressSpace() 12005 : getTargetAddressSpace(T.getQualifiers()); 12006 } 12007 12008 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 12009 return getTargetAddressSpace(Q.getAddressSpace()); 12010 } 12011 12012 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 12013 if (isTargetAddressSpace(AS)) 12014 return toTargetAddressSpace(AS); 12015 else 12016 return (*AddrSpaceMap)[(unsigned)AS]; 12017 } 12018 12019 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 12020 assert(Ty->isFixedPointType()); 12021 12022 if (Ty->isSaturatedFixedPointType()) return Ty; 12023 12024 switch (Ty->castAs<BuiltinType>()->getKind()) { 12025 default: 12026 llvm_unreachable("Not a fixed point type!"); 12027 case BuiltinType::ShortAccum: 12028 return SatShortAccumTy; 12029 case BuiltinType::Accum: 12030 return SatAccumTy; 12031 case BuiltinType::LongAccum: 12032 return SatLongAccumTy; 12033 case BuiltinType::UShortAccum: 12034 return SatUnsignedShortAccumTy; 12035 case BuiltinType::UAccum: 12036 return SatUnsignedAccumTy; 12037 case BuiltinType::ULongAccum: 12038 return SatUnsignedLongAccumTy; 12039 case BuiltinType::ShortFract: 12040 return SatShortFractTy; 12041 case BuiltinType::Fract: 12042 return SatFractTy; 12043 case BuiltinType::LongFract: 12044 return SatLongFractTy; 12045 case BuiltinType::UShortFract: 12046 return SatUnsignedShortFractTy; 12047 case BuiltinType::UFract: 12048 return SatUnsignedFractTy; 12049 case BuiltinType::ULongFract: 12050 return SatUnsignedLongFractTy; 12051 } 12052 } 12053 12054 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 12055 if (LangOpts.OpenCL) 12056 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 12057 12058 if (LangOpts.CUDA) 12059 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 12060 12061 return getLangASFromTargetAS(AS); 12062 } 12063 12064 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 12065 // doesn't include ASTContext.h 12066 template 12067 clang::LazyGenerationalUpdatePtr< 12068 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 12069 clang::LazyGenerationalUpdatePtr< 12070 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12071 const clang::ASTContext &Ctx, Decl *Value); 12072 12073 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12074 assert(Ty->isFixedPointType()); 12075 12076 const TargetInfo &Target = getTargetInfo(); 12077 switch (Ty->castAs<BuiltinType>()->getKind()) { 12078 default: 12079 llvm_unreachable("Not a fixed point type!"); 12080 case BuiltinType::ShortAccum: 12081 case BuiltinType::SatShortAccum: 12082 return Target.getShortAccumScale(); 12083 case BuiltinType::Accum: 12084 case BuiltinType::SatAccum: 12085 return Target.getAccumScale(); 12086 case BuiltinType::LongAccum: 12087 case BuiltinType::SatLongAccum: 12088 return Target.getLongAccumScale(); 12089 case BuiltinType::UShortAccum: 12090 case BuiltinType::SatUShortAccum: 12091 return Target.getUnsignedShortAccumScale(); 12092 case BuiltinType::UAccum: 12093 case BuiltinType::SatUAccum: 12094 return Target.getUnsignedAccumScale(); 12095 case BuiltinType::ULongAccum: 12096 case BuiltinType::SatULongAccum: 12097 return Target.getUnsignedLongAccumScale(); 12098 case BuiltinType::ShortFract: 12099 case BuiltinType::SatShortFract: 12100 return Target.getShortFractScale(); 12101 case BuiltinType::Fract: 12102 case BuiltinType::SatFract: 12103 return Target.getFractScale(); 12104 case BuiltinType::LongFract: 12105 case BuiltinType::SatLongFract: 12106 return Target.getLongFractScale(); 12107 case BuiltinType::UShortFract: 12108 case BuiltinType::SatUShortFract: 12109 return Target.getUnsignedShortFractScale(); 12110 case BuiltinType::UFract: 12111 case BuiltinType::SatUFract: 12112 return Target.getUnsignedFractScale(); 12113 case BuiltinType::ULongFract: 12114 case BuiltinType::SatULongFract: 12115 return Target.getUnsignedLongFractScale(); 12116 } 12117 } 12118 12119 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12120 assert(Ty->isFixedPointType()); 12121 12122 const TargetInfo &Target = getTargetInfo(); 12123 switch (Ty->castAs<BuiltinType>()->getKind()) { 12124 default: 12125 llvm_unreachable("Not a fixed point type!"); 12126 case BuiltinType::ShortAccum: 12127 case BuiltinType::SatShortAccum: 12128 return Target.getShortAccumIBits(); 12129 case BuiltinType::Accum: 12130 case BuiltinType::SatAccum: 12131 return Target.getAccumIBits(); 12132 case BuiltinType::LongAccum: 12133 case BuiltinType::SatLongAccum: 12134 return Target.getLongAccumIBits(); 12135 case BuiltinType::UShortAccum: 12136 case BuiltinType::SatUShortAccum: 12137 return Target.getUnsignedShortAccumIBits(); 12138 case BuiltinType::UAccum: 12139 case BuiltinType::SatUAccum: 12140 return Target.getUnsignedAccumIBits(); 12141 case BuiltinType::ULongAccum: 12142 case BuiltinType::SatULongAccum: 12143 return Target.getUnsignedLongAccumIBits(); 12144 case BuiltinType::ShortFract: 12145 case BuiltinType::SatShortFract: 12146 case BuiltinType::Fract: 12147 case BuiltinType::SatFract: 12148 case BuiltinType::LongFract: 12149 case BuiltinType::SatLongFract: 12150 case BuiltinType::UShortFract: 12151 case BuiltinType::SatUShortFract: 12152 case BuiltinType::UFract: 12153 case BuiltinType::SatUFract: 12154 case BuiltinType::ULongFract: 12155 case BuiltinType::SatULongFract: 12156 return 0; 12157 } 12158 } 12159 12160 llvm::FixedPointSemantics 12161 ASTContext::getFixedPointSemantics(QualType Ty) const { 12162 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12163 "Can only get the fixed point semantics for a " 12164 "fixed point or integer type."); 12165 if (Ty->isIntegerType()) 12166 return llvm::FixedPointSemantics::GetIntegerSemantics( 12167 getIntWidth(Ty), Ty->isSignedIntegerType()); 12168 12169 bool isSigned = Ty->isSignedFixedPointType(); 12170 return llvm::FixedPointSemantics( 12171 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12172 Ty->isSaturatedFixedPointType(), 12173 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12174 } 12175 12176 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12177 assert(Ty->isFixedPointType()); 12178 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12179 } 12180 12181 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12182 assert(Ty->isFixedPointType()); 12183 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12184 } 12185 12186 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12187 assert(Ty->isUnsignedFixedPointType() && 12188 "Expected unsigned fixed point type"); 12189 12190 switch (Ty->castAs<BuiltinType>()->getKind()) { 12191 case BuiltinType::UShortAccum: 12192 return ShortAccumTy; 12193 case BuiltinType::UAccum: 12194 return AccumTy; 12195 case BuiltinType::ULongAccum: 12196 return LongAccumTy; 12197 case BuiltinType::SatUShortAccum: 12198 return SatShortAccumTy; 12199 case BuiltinType::SatUAccum: 12200 return SatAccumTy; 12201 case BuiltinType::SatULongAccum: 12202 return SatLongAccumTy; 12203 case BuiltinType::UShortFract: 12204 return ShortFractTy; 12205 case BuiltinType::UFract: 12206 return FractTy; 12207 case BuiltinType::ULongFract: 12208 return LongFractTy; 12209 case BuiltinType::SatUShortFract: 12210 return SatShortFractTy; 12211 case BuiltinType::SatUFract: 12212 return SatFractTy; 12213 case BuiltinType::SatULongFract: 12214 return SatLongFractTy; 12215 default: 12216 llvm_unreachable("Unexpected unsigned fixed point type"); 12217 } 12218 } 12219 12220 ParsedTargetAttr 12221 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12222 assert(TD != nullptr); 12223 ParsedTargetAttr ParsedAttr = TD->parse(); 12224 12225 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12226 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12227 }); 12228 return ParsedAttr; 12229 } 12230 12231 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12232 const FunctionDecl *FD) const { 12233 if (FD) 12234 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12235 else 12236 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12237 Target->getTargetOpts().CPU, 12238 Target->getTargetOpts().Features); 12239 } 12240 12241 // Fills in the supplied string map with the set of target features for the 12242 // passed in function. 12243 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12244 GlobalDecl GD) const { 12245 StringRef TargetCPU = Target->getTargetOpts().CPU; 12246 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12247 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12248 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12249 12250 // Make a copy of the features as passed on the command line into the 12251 // beginning of the additional features from the function to override. 12252 ParsedAttr.Features.insert( 12253 ParsedAttr.Features.begin(), 12254 Target->getTargetOpts().FeaturesAsWritten.begin(), 12255 Target->getTargetOpts().FeaturesAsWritten.end()); 12256 12257 if (ParsedAttr.Architecture != "" && 12258 Target->isValidCPUName(ParsedAttr.Architecture)) 12259 TargetCPU = ParsedAttr.Architecture; 12260 12261 // Now populate the feature map, first with the TargetCPU which is either 12262 // the default or a new one from the target attribute string. Then we'll use 12263 // the passed in features (FeaturesAsWritten) along with the new ones from 12264 // the attribute. 12265 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12266 ParsedAttr.Features); 12267 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12268 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12269 Target->getCPUSpecificCPUDispatchFeatures( 12270 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12271 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12272 Features.insert(Features.begin(), 12273 Target->getTargetOpts().FeaturesAsWritten.begin(), 12274 Target->getTargetOpts().FeaturesAsWritten.end()); 12275 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12276 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12277 std::vector<std::string> Features; 12278 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12279 if (VersionStr.startswith("arch=")) 12280 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12281 else if (VersionStr != "default") 12282 Features.push_back((StringRef{"+"} + VersionStr).str()); 12283 12284 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12285 } else { 12286 FeatureMap = Target->getTargetOpts().FeatureMap; 12287 } 12288 } 12289 12290 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12291 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12292 return *OMPTraitInfoVector.back(); 12293 } 12294 12295 const StreamingDiagnostic &clang:: 12296 operator<<(const StreamingDiagnostic &DB, 12297 const ASTContext::SectionInfo &Section) { 12298 if (Section.Decl) 12299 return DB << Section.Decl; 12300 return DB << "a prior #pragma section"; 12301 } 12302 12303 bool ASTContext::mayExternalize(const Decl *D) const { 12304 bool IsStaticVar = 12305 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12306 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12307 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12308 (D->hasAttr<CUDAConstantAttr>() && 12309 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12310 // CUDA/HIP: static managed variables need to be externalized since it is 12311 // a declaration in IR, therefore cannot have internal linkage. Kernels in 12312 // anonymous name space needs to be externalized to avoid duplicate symbols. 12313 return (IsStaticVar && 12314 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) || 12315 (D->hasAttr<CUDAGlobalAttr>() && 12316 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) == 12317 GVA_Internal); 12318 } 12319 12320 bool ASTContext::shouldExternalize(const Decl *D) const { 12321 return mayExternalize(D) && 12322 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() || 12323 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12324 } 12325 12326 StringRef ASTContext::getCUIDHash() const { 12327 if (!CUIDHash.empty()) 12328 return CUIDHash; 12329 if (LangOpts.CUID.empty()) 12330 return StringRef(); 12331 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12332 return CUIDHash; 12333 } 12334