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 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 743 NewConverted.push_back(Arg); 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 for (auto &Arg : OldConverted.drop_front(1)) 756 NewConverted.push_back(Arg); 757 } 758 Expr *NewIDC = ConceptSpecializationExpr::Create( 759 C, CSE->getNamedConcept(), NewConverted, nullptr, 760 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 761 762 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 763 NewIDC = new (C) CXXFoldExpr( 764 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 765 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 766 SourceLocation(), /*NumExpansions=*/None); 767 return NewIDC; 768 } 769 770 TemplateTemplateParmDecl * 771 ASTContext::getCanonicalTemplateTemplateParmDecl( 772 TemplateTemplateParmDecl *TTP) const { 773 // Check if we already have a canonical template template parameter. 774 llvm::FoldingSetNodeID ID; 775 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 776 void *InsertPos = nullptr; 777 CanonicalTemplateTemplateParm *Canonical 778 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 779 if (Canonical) 780 return Canonical->getParam(); 781 782 // Build a canonical template parameter list. 783 TemplateParameterList *Params = TTP->getTemplateParameters(); 784 SmallVector<NamedDecl *, 4> CanonParams; 785 CanonParams.reserve(Params->size()); 786 for (TemplateParameterList::const_iterator P = Params->begin(), 787 PEnd = Params->end(); 788 P != PEnd; ++P) { 789 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 790 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 791 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 792 TTP->getDepth(), TTP->getIndex(), nullptr, false, 793 TTP->isParameterPack(), TTP->hasTypeConstraint(), 794 TTP->isExpandedParameterPack() ? 795 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 796 if (const auto *TC = TTP->getTypeConstraint()) { 797 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 798 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 799 *this, TC->getImmediatelyDeclaredConstraint(), 800 ParamAsArgument); 801 TemplateArgumentListInfo CanonArgsAsWritten; 802 if (auto *Args = TC->getTemplateArgsAsWritten()) 803 for (const auto &ArgLoc : Args->arguments()) 804 CanonArgsAsWritten.addArgument( 805 TemplateArgumentLoc(ArgLoc.getArgument(), 806 TemplateArgumentLocInfo())); 807 NewTTP->setTypeConstraint( 808 NestedNameSpecifierLoc(), 809 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 810 SourceLocation()), /*FoundDecl=*/nullptr, 811 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 812 // simply omit the ArgsAsWritten 813 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 814 } 815 CanonParams.push_back(NewTTP); 816 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 817 QualType T = getCanonicalType(NTTP->getType()); 818 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 819 NonTypeTemplateParmDecl *Param; 820 if (NTTP->isExpandedParameterPack()) { 821 SmallVector<QualType, 2> ExpandedTypes; 822 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 823 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 824 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 825 ExpandedTInfos.push_back( 826 getTrivialTypeSourceInfo(ExpandedTypes.back())); 827 } 828 829 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 830 SourceLocation(), 831 SourceLocation(), 832 NTTP->getDepth(), 833 NTTP->getPosition(), nullptr, 834 T, 835 TInfo, 836 ExpandedTypes, 837 ExpandedTInfos); 838 } else { 839 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 840 SourceLocation(), 841 SourceLocation(), 842 NTTP->getDepth(), 843 NTTP->getPosition(), nullptr, 844 T, 845 NTTP->isParameterPack(), 846 TInfo); 847 } 848 if (AutoType *AT = T->getContainedAutoType()) { 849 if (AT->isConstrained()) { 850 Param->setPlaceholderTypeConstraint( 851 canonicalizeImmediatelyDeclaredConstraint( 852 *this, NTTP->getPlaceholderTypeConstraint(), T)); 853 } 854 } 855 CanonParams.push_back(Param); 856 857 } else 858 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 859 cast<TemplateTemplateParmDecl>(*P))); 860 } 861 862 Expr *CanonRequiresClause = nullptr; 863 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 864 CanonRequiresClause = RequiresClause; 865 866 TemplateTemplateParmDecl *CanonTTP 867 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 868 SourceLocation(), TTP->getDepth(), 869 TTP->getPosition(), 870 TTP->isParameterPack(), 871 nullptr, 872 TemplateParameterList::Create(*this, SourceLocation(), 873 SourceLocation(), 874 CanonParams, 875 SourceLocation(), 876 CanonRequiresClause)); 877 878 // Get the new insert position for the node we care about. 879 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 880 assert(!Canonical && "Shouldn't be in the map!"); 881 (void)Canonical; 882 883 // Create the canonical template template parameter entry. 884 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 885 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 886 return CanonTTP; 887 } 888 889 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 890 auto Kind = getTargetInfo().getCXXABI().getKind(); 891 return getLangOpts().CXXABI.getValueOr(Kind); 892 } 893 894 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 895 if (!LangOpts.CPlusPlus) return nullptr; 896 897 switch (getCXXABIKind()) { 898 case TargetCXXABI::AppleARM64: 899 case TargetCXXABI::Fuchsia: 900 case TargetCXXABI::GenericARM: // Same as Itanium at this level 901 case TargetCXXABI::iOS: 902 case TargetCXXABI::WatchOS: 903 case TargetCXXABI::GenericAArch64: 904 case TargetCXXABI::GenericMIPS: 905 case TargetCXXABI::GenericItanium: 906 case TargetCXXABI::WebAssembly: 907 case TargetCXXABI::XL: 908 return CreateItaniumCXXABI(*this); 909 case TargetCXXABI::Microsoft: 910 return CreateMicrosoftCXXABI(*this); 911 } 912 llvm_unreachable("Invalid CXXABI type!"); 913 } 914 915 interp::Context &ASTContext::getInterpContext() { 916 if (!InterpContext) { 917 InterpContext.reset(new interp::Context(*this)); 918 } 919 return *InterpContext.get(); 920 } 921 922 ParentMapContext &ASTContext::getParentMapContext() { 923 if (!ParentMapCtx) 924 ParentMapCtx.reset(new ParentMapContext(*this)); 925 return *ParentMapCtx.get(); 926 } 927 928 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 929 const LangOptions &LOpts) { 930 if (LOpts.FakeAddressSpaceMap) { 931 // The fake address space map must have a distinct entry for each 932 // language-specific address space. 933 static const unsigned FakeAddrSpaceMap[] = { 934 0, // Default 935 1, // opencl_global 936 3, // opencl_local 937 2, // opencl_constant 938 0, // opencl_private 939 4, // opencl_generic 940 5, // opencl_global_device 941 6, // opencl_global_host 942 7, // cuda_device 943 8, // cuda_constant 944 9, // cuda_shared 945 1, // sycl_global 946 5, // sycl_global_device 947 6, // sycl_global_host 948 3, // sycl_local 949 0, // sycl_private 950 10, // ptr32_sptr 951 11, // ptr32_uptr 952 12 // ptr64 953 }; 954 return &FakeAddrSpaceMap; 955 } else { 956 return &T.getAddressSpaceMap(); 957 } 958 } 959 960 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 961 const LangOptions &LangOpts) { 962 switch (LangOpts.getAddressSpaceMapMangling()) { 963 case LangOptions::ASMM_Target: 964 return TI.useAddressSpaceMapMangling(); 965 case LangOptions::ASMM_On: 966 return true; 967 case LangOptions::ASMM_Off: 968 return false; 969 } 970 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 971 } 972 973 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 974 IdentifierTable &idents, SelectorTable &sels, 975 Builtin::Context &builtins, TranslationUnitKind TUKind) 976 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize), 977 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize), 978 TemplateSpecializationTypes(this_()), 979 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 980 SubstTemplateTemplateParmPacks(this_()), 981 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 982 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 983 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 984 LangOpts.XRayNeverInstrumentFiles, 985 LangOpts.XRayAttrListFiles, SM)), 986 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 987 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 988 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 989 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 990 CompCategories(this_()), LastSDM(nullptr, 0) { 991 addTranslationUnitDecl(); 992 } 993 994 void ASTContext::cleanup() { 995 // Release the DenseMaps associated with DeclContext objects. 996 // FIXME: Is this the ideal solution? 997 ReleaseDeclContextMaps(); 998 999 // Call all of the deallocation functions on all of their targets. 1000 for (auto &Pair : Deallocations) 1001 (Pair.first)(Pair.second); 1002 Deallocations.clear(); 1003 1004 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 1005 // because they can contain DenseMaps. 1006 for (llvm::DenseMap<const ObjCContainerDecl*, 1007 const ASTRecordLayout*>::iterator 1008 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1009 // Increment in loop to prevent using deallocated memory. 1010 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1011 R->Destroy(*this); 1012 ObjCLayouts.clear(); 1013 1014 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1015 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1016 // Increment in loop to prevent using deallocated memory. 1017 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1018 R->Destroy(*this); 1019 } 1020 ASTRecordLayouts.clear(); 1021 1022 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1023 AEnd = DeclAttrs.end(); 1024 A != AEnd; ++A) 1025 A->second->~AttrVec(); 1026 DeclAttrs.clear(); 1027 1028 for (const auto &Value : ModuleInitializers) 1029 Value.second->~PerModuleInitializers(); 1030 ModuleInitializers.clear(); 1031 } 1032 1033 ASTContext::~ASTContext() { cleanup(); } 1034 1035 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1036 TraversalScope = TopLevelDecls; 1037 getParentMapContext().clear(); 1038 } 1039 1040 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1041 Deallocations.push_back({Callback, Data}); 1042 } 1043 1044 void 1045 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1046 ExternalSource = std::move(Source); 1047 } 1048 1049 void ASTContext::PrintStats() const { 1050 llvm::errs() << "\n*** AST Context Stats:\n"; 1051 llvm::errs() << " " << Types.size() << " types total.\n"; 1052 1053 unsigned counts[] = { 1054 #define TYPE(Name, Parent) 0, 1055 #define ABSTRACT_TYPE(Name, Parent) 1056 #include "clang/AST/TypeNodes.inc" 1057 0 // Extra 1058 }; 1059 1060 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1061 Type *T = Types[i]; 1062 counts[(unsigned)T->getTypeClass()]++; 1063 } 1064 1065 unsigned Idx = 0; 1066 unsigned TotalBytes = 0; 1067 #define TYPE(Name, Parent) \ 1068 if (counts[Idx]) \ 1069 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1070 << " types, " << sizeof(Name##Type) << " each " \ 1071 << "(" << counts[Idx] * sizeof(Name##Type) \ 1072 << " bytes)\n"; \ 1073 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1074 ++Idx; 1075 #define ABSTRACT_TYPE(Name, Parent) 1076 #include "clang/AST/TypeNodes.inc" 1077 1078 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1079 1080 // Implicit special member functions. 1081 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1082 << NumImplicitDefaultConstructors 1083 << " implicit default constructors created\n"; 1084 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1085 << NumImplicitCopyConstructors 1086 << " implicit copy constructors created\n"; 1087 if (getLangOpts().CPlusPlus) 1088 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1089 << NumImplicitMoveConstructors 1090 << " implicit move constructors created\n"; 1091 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1092 << NumImplicitCopyAssignmentOperators 1093 << " implicit copy assignment operators created\n"; 1094 if (getLangOpts().CPlusPlus) 1095 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1096 << NumImplicitMoveAssignmentOperators 1097 << " implicit move assignment operators created\n"; 1098 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1099 << NumImplicitDestructors 1100 << " implicit destructors created\n"; 1101 1102 if (ExternalSource) { 1103 llvm::errs() << "\n"; 1104 ExternalSource->PrintStats(); 1105 } 1106 1107 BumpAlloc.PrintStats(); 1108 } 1109 1110 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1111 bool NotifyListeners) { 1112 if (NotifyListeners) 1113 if (auto *Listener = getASTMutationListener()) 1114 Listener->RedefinedHiddenDefinition(ND, M); 1115 1116 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1117 } 1118 1119 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1120 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1121 if (It == MergedDefModules.end()) 1122 return; 1123 1124 auto &Merged = It->second; 1125 llvm::DenseSet<Module*> Found; 1126 for (Module *&M : Merged) 1127 if (!Found.insert(M).second) 1128 M = nullptr; 1129 llvm::erase_value(Merged, nullptr); 1130 } 1131 1132 ArrayRef<Module *> 1133 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1134 auto MergedIt = 1135 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1136 if (MergedIt == MergedDefModules.end()) 1137 return None; 1138 return MergedIt->second; 1139 } 1140 1141 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1142 if (LazyInitializers.empty()) 1143 return; 1144 1145 auto *Source = Ctx.getExternalSource(); 1146 assert(Source && "lazy initializers but no external source"); 1147 1148 auto LazyInits = std::move(LazyInitializers); 1149 LazyInitializers.clear(); 1150 1151 for (auto ID : LazyInits) 1152 Initializers.push_back(Source->GetExternalDecl(ID)); 1153 1154 assert(LazyInitializers.empty() && 1155 "GetExternalDecl for lazy module initializer added more inits"); 1156 } 1157 1158 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1159 // One special case: if we add a module initializer that imports another 1160 // module, and that module's only initializer is an ImportDecl, simplify. 1161 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1162 auto It = ModuleInitializers.find(ID->getImportedModule()); 1163 1164 // Maybe the ImportDecl does nothing at all. (Common case.) 1165 if (It == ModuleInitializers.end()) 1166 return; 1167 1168 // Maybe the ImportDecl only imports another ImportDecl. 1169 auto &Imported = *It->second; 1170 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1171 Imported.resolve(*this); 1172 auto *OnlyDecl = Imported.Initializers.front(); 1173 if (isa<ImportDecl>(OnlyDecl)) 1174 D = OnlyDecl; 1175 } 1176 } 1177 1178 auto *&Inits = ModuleInitializers[M]; 1179 if (!Inits) 1180 Inits = new (*this) PerModuleInitializers; 1181 Inits->Initializers.push_back(D); 1182 } 1183 1184 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1185 auto *&Inits = ModuleInitializers[M]; 1186 if (!Inits) 1187 Inits = new (*this) PerModuleInitializers; 1188 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1189 IDs.begin(), IDs.end()); 1190 } 1191 1192 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1193 auto It = ModuleInitializers.find(M); 1194 if (It == ModuleInitializers.end()) 1195 return None; 1196 1197 auto *Inits = It->second; 1198 Inits->resolve(*this); 1199 return Inits->Initializers; 1200 } 1201 1202 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1203 if (!ExternCContext) 1204 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1205 1206 return ExternCContext; 1207 } 1208 1209 BuiltinTemplateDecl * 1210 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1211 const IdentifierInfo *II) const { 1212 auto *BuiltinTemplate = 1213 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1214 BuiltinTemplate->setImplicit(); 1215 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1216 1217 return BuiltinTemplate; 1218 } 1219 1220 BuiltinTemplateDecl * 1221 ASTContext::getMakeIntegerSeqDecl() const { 1222 if (!MakeIntegerSeqDecl) 1223 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1224 getMakeIntegerSeqName()); 1225 return MakeIntegerSeqDecl; 1226 } 1227 1228 BuiltinTemplateDecl * 1229 ASTContext::getTypePackElementDecl() const { 1230 if (!TypePackElementDecl) 1231 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1232 getTypePackElementName()); 1233 return TypePackElementDecl; 1234 } 1235 1236 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1237 RecordDecl::TagKind TK) const { 1238 SourceLocation Loc; 1239 RecordDecl *NewDecl; 1240 if (getLangOpts().CPlusPlus) 1241 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1242 Loc, &Idents.get(Name)); 1243 else 1244 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1245 &Idents.get(Name)); 1246 NewDecl->setImplicit(); 1247 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1248 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1249 return NewDecl; 1250 } 1251 1252 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1253 StringRef Name) const { 1254 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1255 TypedefDecl *NewDecl = TypedefDecl::Create( 1256 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1257 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1258 NewDecl->setImplicit(); 1259 return NewDecl; 1260 } 1261 1262 TypedefDecl *ASTContext::getInt128Decl() const { 1263 if (!Int128Decl) 1264 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1265 return Int128Decl; 1266 } 1267 1268 TypedefDecl *ASTContext::getUInt128Decl() const { 1269 if (!UInt128Decl) 1270 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1271 return UInt128Decl; 1272 } 1273 1274 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1275 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1276 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1277 Types.push_back(Ty); 1278 } 1279 1280 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1281 const TargetInfo *AuxTarget) { 1282 assert((!this->Target || this->Target == &Target) && 1283 "Incorrect target reinitialization"); 1284 assert(VoidTy.isNull() && "Context reinitialized?"); 1285 1286 this->Target = &Target; 1287 this->AuxTarget = AuxTarget; 1288 1289 ABI.reset(createCXXABI(Target)); 1290 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1291 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1292 1293 // C99 6.2.5p19. 1294 InitBuiltinType(VoidTy, BuiltinType::Void); 1295 1296 // C99 6.2.5p2. 1297 InitBuiltinType(BoolTy, BuiltinType::Bool); 1298 // C99 6.2.5p3. 1299 if (LangOpts.CharIsSigned) 1300 InitBuiltinType(CharTy, BuiltinType::Char_S); 1301 else 1302 InitBuiltinType(CharTy, BuiltinType::Char_U); 1303 // C99 6.2.5p4. 1304 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1305 InitBuiltinType(ShortTy, BuiltinType::Short); 1306 InitBuiltinType(IntTy, BuiltinType::Int); 1307 InitBuiltinType(LongTy, BuiltinType::Long); 1308 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1309 1310 // C99 6.2.5p6. 1311 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1312 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1313 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1314 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1315 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1316 1317 // C99 6.2.5p10. 1318 InitBuiltinType(FloatTy, BuiltinType::Float); 1319 InitBuiltinType(DoubleTy, BuiltinType::Double); 1320 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1321 1322 // GNU extension, __float128 for IEEE quadruple precision 1323 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1324 1325 // __ibm128 for IBM extended precision 1326 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); 1327 1328 // C11 extension ISO/IEC TS 18661-3 1329 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1330 1331 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1332 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1333 InitBuiltinType(AccumTy, BuiltinType::Accum); 1334 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1335 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1336 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1337 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1338 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1339 InitBuiltinType(FractTy, BuiltinType::Fract); 1340 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1341 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1342 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1343 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1344 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1345 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1346 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1347 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1348 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1349 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1350 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1351 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1352 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1353 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1354 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1355 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1356 1357 // GNU extension, 128-bit integers. 1358 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1359 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1360 1361 // C++ 3.9.1p5 1362 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1363 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1364 else // -fshort-wchar makes wchar_t be unsigned. 1365 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1366 if (LangOpts.CPlusPlus && LangOpts.WChar) 1367 WideCharTy = WCharTy; 1368 else { 1369 // C99 (or C++ using -fno-wchar). 1370 WideCharTy = getFromTargetType(Target.getWCharType()); 1371 } 1372 1373 WIntTy = getFromTargetType(Target.getWIntType()); 1374 1375 // C++20 (proposed) 1376 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1377 1378 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1379 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1380 else // C99 1381 Char16Ty = getFromTargetType(Target.getChar16Type()); 1382 1383 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1384 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1385 else // C99 1386 Char32Ty = getFromTargetType(Target.getChar32Type()); 1387 1388 // Placeholder type for type-dependent expressions whose type is 1389 // completely unknown. No code should ever check a type against 1390 // DependentTy and users should never see it; however, it is here to 1391 // help diagnose failures to properly check for type-dependent 1392 // expressions. 1393 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1394 1395 // Placeholder type for functions. 1396 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1397 1398 // Placeholder type for bound members. 1399 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1400 1401 // Placeholder type for pseudo-objects. 1402 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1403 1404 // "any" type; useful for debugger-like clients. 1405 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1406 1407 // Placeholder type for unbridged ARC casts. 1408 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1409 1410 // Placeholder type for builtin functions. 1411 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1412 1413 // Placeholder type for OMP array sections. 1414 if (LangOpts.OpenMP) { 1415 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1416 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1417 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1418 } 1419 if (LangOpts.MatrixTypes) 1420 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1421 1422 // Builtin types for 'id', 'Class', and 'SEL'. 1423 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1424 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1425 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1426 1427 if (LangOpts.OpenCL) { 1428 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1429 InitBuiltinType(SingletonId, BuiltinType::Id); 1430 #include "clang/Basic/OpenCLImageTypes.def" 1431 1432 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1433 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1434 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1435 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1436 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1437 1438 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1439 InitBuiltinType(Id##Ty, BuiltinType::Id); 1440 #include "clang/Basic/OpenCLExtensionTypes.def" 1441 } 1442 1443 if (Target.hasAArch64SVETypes()) { 1444 #define SVE_TYPE(Name, Id, SingletonId) \ 1445 InitBuiltinType(SingletonId, BuiltinType::Id); 1446 #include "clang/Basic/AArch64SVEACLETypes.def" 1447 } 1448 1449 if (Target.getTriple().isPPC64()) { 1450 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1451 InitBuiltinType(Id##Ty, BuiltinType::Id); 1452 #include "clang/Basic/PPCTypes.def" 1453 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1454 InitBuiltinType(Id##Ty, BuiltinType::Id); 1455 #include "clang/Basic/PPCTypes.def" 1456 } 1457 1458 if (Target.hasRISCVVTypes()) { 1459 #define RVV_TYPE(Name, Id, SingletonId) \ 1460 InitBuiltinType(SingletonId, BuiltinType::Id); 1461 #include "clang/Basic/RISCVVTypes.def" 1462 } 1463 1464 // Builtin type for __objc_yes and __objc_no 1465 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1466 SignedCharTy : BoolTy); 1467 1468 ObjCConstantStringType = QualType(); 1469 1470 ObjCSuperType = QualType(); 1471 1472 // void * type 1473 if (LangOpts.OpenCLGenericAddressSpace) { 1474 auto Q = VoidTy.getQualifiers(); 1475 Q.setAddressSpace(LangAS::opencl_generic); 1476 VoidPtrTy = getPointerType(getCanonicalType( 1477 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1478 } else { 1479 VoidPtrTy = getPointerType(VoidTy); 1480 } 1481 1482 // nullptr type (C++0x 2.14.7) 1483 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1484 1485 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1486 InitBuiltinType(HalfTy, BuiltinType::Half); 1487 1488 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1489 1490 // Builtin type used to help define __builtin_va_list. 1491 VaListTagDecl = nullptr; 1492 1493 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1494 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1495 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1496 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1497 } 1498 } 1499 1500 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1501 return SourceMgr.getDiagnostics(); 1502 } 1503 1504 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1505 AttrVec *&Result = DeclAttrs[D]; 1506 if (!Result) { 1507 void *Mem = Allocate(sizeof(AttrVec)); 1508 Result = new (Mem) AttrVec; 1509 } 1510 1511 return *Result; 1512 } 1513 1514 /// Erase the attributes corresponding to the given declaration. 1515 void ASTContext::eraseDeclAttrs(const Decl *D) { 1516 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1517 if (Pos != DeclAttrs.end()) { 1518 Pos->second->~AttrVec(); 1519 DeclAttrs.erase(Pos); 1520 } 1521 } 1522 1523 // FIXME: Remove ? 1524 MemberSpecializationInfo * 1525 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1526 assert(Var->isStaticDataMember() && "Not a static data member"); 1527 return getTemplateOrSpecializationInfo(Var) 1528 .dyn_cast<MemberSpecializationInfo *>(); 1529 } 1530 1531 ASTContext::TemplateOrSpecializationInfo 1532 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1533 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1534 TemplateOrInstantiation.find(Var); 1535 if (Pos == TemplateOrInstantiation.end()) 1536 return {}; 1537 1538 return Pos->second; 1539 } 1540 1541 void 1542 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1543 TemplateSpecializationKind TSK, 1544 SourceLocation PointOfInstantiation) { 1545 assert(Inst->isStaticDataMember() && "Not a static data member"); 1546 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1547 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1548 Tmpl, TSK, PointOfInstantiation)); 1549 } 1550 1551 void 1552 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1553 TemplateOrSpecializationInfo TSI) { 1554 assert(!TemplateOrInstantiation[Inst] && 1555 "Already noted what the variable was instantiated from"); 1556 TemplateOrInstantiation[Inst] = TSI; 1557 } 1558 1559 NamedDecl * 1560 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1561 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1562 if (Pos == InstantiatedFromUsingDecl.end()) 1563 return nullptr; 1564 1565 return Pos->second; 1566 } 1567 1568 void 1569 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1570 assert((isa<UsingDecl>(Pattern) || 1571 isa<UnresolvedUsingValueDecl>(Pattern) || 1572 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1573 "pattern decl is not a using decl"); 1574 assert((isa<UsingDecl>(Inst) || 1575 isa<UnresolvedUsingValueDecl>(Inst) || 1576 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1577 "instantiation did not produce a using decl"); 1578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1579 InstantiatedFromUsingDecl[Inst] = Pattern; 1580 } 1581 1582 UsingEnumDecl * 1583 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1584 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1585 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1586 return nullptr; 1587 1588 return Pos->second; 1589 } 1590 1591 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1592 UsingEnumDecl *Pattern) { 1593 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1594 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1595 } 1596 1597 UsingShadowDecl * 1598 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1599 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1600 = InstantiatedFromUsingShadowDecl.find(Inst); 1601 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1602 return nullptr; 1603 1604 return Pos->second; 1605 } 1606 1607 void 1608 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1609 UsingShadowDecl *Pattern) { 1610 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1611 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1612 } 1613 1614 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1615 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1616 = InstantiatedFromUnnamedFieldDecl.find(Field); 1617 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1618 return nullptr; 1619 1620 return Pos->second; 1621 } 1622 1623 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1624 FieldDecl *Tmpl) { 1625 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1626 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1627 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1628 "Already noted what unnamed field was instantiated from"); 1629 1630 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1631 } 1632 1633 ASTContext::overridden_cxx_method_iterator 1634 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1635 return overridden_methods(Method).begin(); 1636 } 1637 1638 ASTContext::overridden_cxx_method_iterator 1639 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1640 return overridden_methods(Method).end(); 1641 } 1642 1643 unsigned 1644 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1645 auto Range = overridden_methods(Method); 1646 return Range.end() - Range.begin(); 1647 } 1648 1649 ASTContext::overridden_method_range 1650 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1651 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1652 OverriddenMethods.find(Method->getCanonicalDecl()); 1653 if (Pos == OverriddenMethods.end()) 1654 return overridden_method_range(nullptr, nullptr); 1655 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1656 } 1657 1658 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1659 const CXXMethodDecl *Overridden) { 1660 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1661 OverriddenMethods[Method].push_back(Overridden); 1662 } 1663 1664 void ASTContext::getOverriddenMethods( 1665 const NamedDecl *D, 1666 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1667 assert(D); 1668 1669 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1670 Overridden.append(overridden_methods_begin(CXXMethod), 1671 overridden_methods_end(CXXMethod)); 1672 return; 1673 } 1674 1675 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1676 if (!Method) 1677 return; 1678 1679 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1680 Method->getOverriddenMethods(OverDecls); 1681 Overridden.append(OverDecls.begin(), OverDecls.end()); 1682 } 1683 1684 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1685 assert(!Import->getNextLocalImport() && 1686 "Import declaration already in the chain"); 1687 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1688 if (!FirstLocalImport) { 1689 FirstLocalImport = Import; 1690 LastLocalImport = Import; 1691 return; 1692 } 1693 1694 LastLocalImport->setNextLocalImport(Import); 1695 LastLocalImport = Import; 1696 } 1697 1698 //===----------------------------------------------------------------------===// 1699 // Type Sizing and Analysis 1700 //===----------------------------------------------------------------------===// 1701 1702 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1703 /// scalar floating point type. 1704 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1705 switch (T->castAs<BuiltinType>()->getKind()) { 1706 default: 1707 llvm_unreachable("Not a floating point type!"); 1708 case BuiltinType::BFloat16: 1709 return Target->getBFloat16Format(); 1710 case BuiltinType::Float16: 1711 case BuiltinType::Half: 1712 return Target->getHalfFormat(); 1713 case BuiltinType::Float: return Target->getFloatFormat(); 1714 case BuiltinType::Double: return Target->getDoubleFormat(); 1715 case BuiltinType::Ibm128: 1716 return Target->getIbm128Format(); 1717 case BuiltinType::LongDouble: 1718 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1719 return AuxTarget->getLongDoubleFormat(); 1720 return Target->getLongDoubleFormat(); 1721 case BuiltinType::Float128: 1722 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1723 return AuxTarget->getFloat128Format(); 1724 return Target->getFloat128Format(); 1725 } 1726 } 1727 1728 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1729 unsigned Align = Target->getCharWidth(); 1730 1731 bool UseAlignAttrOnly = false; 1732 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1733 Align = AlignFromAttr; 1734 1735 // __attribute__((aligned)) can increase or decrease alignment 1736 // *except* on a struct or struct member, where it only increases 1737 // alignment unless 'packed' is also specified. 1738 // 1739 // It is an error for alignas to decrease alignment, so we can 1740 // ignore that possibility; Sema should diagnose it. 1741 if (isa<FieldDecl>(D)) { 1742 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1743 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1744 } else { 1745 UseAlignAttrOnly = true; 1746 } 1747 } 1748 else if (isa<FieldDecl>(D)) 1749 UseAlignAttrOnly = 1750 D->hasAttr<PackedAttr>() || 1751 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1752 1753 // If we're using the align attribute only, just ignore everything 1754 // else about the declaration and its type. 1755 if (UseAlignAttrOnly) { 1756 // do nothing 1757 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1758 QualType T = VD->getType(); 1759 if (const auto *RT = T->getAs<ReferenceType>()) { 1760 if (ForAlignof) 1761 T = RT->getPointeeType(); 1762 else 1763 T = getPointerType(RT->getPointeeType()); 1764 } 1765 QualType BaseT = getBaseElementType(T); 1766 if (T->isFunctionType()) 1767 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1768 else if (!BaseT->isIncompleteType()) { 1769 // Adjust alignments of declarations with array type by the 1770 // large-array alignment on the target. 1771 if (const ArrayType *arrayType = getAsArrayType(T)) { 1772 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1773 if (!ForAlignof && MinWidth) { 1774 if (isa<VariableArrayType>(arrayType)) 1775 Align = std::max(Align, Target->getLargeArrayAlign()); 1776 else if (isa<ConstantArrayType>(arrayType) && 1777 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1778 Align = std::max(Align, Target->getLargeArrayAlign()); 1779 } 1780 } 1781 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1782 if (BaseT.getQualifiers().hasUnaligned()) 1783 Align = Target->getCharWidth(); 1784 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1785 if (VD->hasGlobalStorage() && !ForAlignof) { 1786 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1787 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1788 } 1789 } 1790 } 1791 1792 // Fields can be subject to extra alignment constraints, like if 1793 // the field is packed, the struct is packed, or the struct has a 1794 // a max-field-alignment constraint (#pragma pack). So calculate 1795 // the actual alignment of the field within the struct, and then 1796 // (as we're expected to) constrain that by the alignment of the type. 1797 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1798 const RecordDecl *Parent = Field->getParent(); 1799 // We can only produce a sensible answer if the record is valid. 1800 if (!Parent->isInvalidDecl()) { 1801 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1802 1803 // Start with the record's overall alignment. 1804 unsigned FieldAlign = toBits(Layout.getAlignment()); 1805 1806 // Use the GCD of that and the offset within the record. 1807 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1808 if (Offset > 0) { 1809 // Alignment is always a power of 2, so the GCD will be a power of 2, 1810 // which means we get to do this crazy thing instead of Euclid's. 1811 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1812 if (LowBitOfOffset < FieldAlign) 1813 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1814 } 1815 1816 Align = std::min(Align, FieldAlign); 1817 } 1818 } 1819 } 1820 1821 // Some targets have hard limitation on the maximum requestable alignment in 1822 // aligned attribute for static variables. 1823 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1824 const auto *VD = dyn_cast<VarDecl>(D); 1825 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1826 Align = std::min(Align, MaxAlignedAttr); 1827 1828 return toCharUnitsFromBits(Align); 1829 } 1830 1831 CharUnits ASTContext::getExnObjectAlignment() const { 1832 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1833 } 1834 1835 // getTypeInfoDataSizeInChars - Return the size of a type, in 1836 // chars. If the type is a record, its data size is returned. This is 1837 // the size of the memcpy that's performed when assigning this type 1838 // using a trivial copy/move assignment operator. 1839 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1840 TypeInfoChars Info = getTypeInfoInChars(T); 1841 1842 // In C++, objects can sometimes be allocated into the tail padding 1843 // of a base-class subobject. We decide whether that's possible 1844 // during class layout, so here we can just trust the layout results. 1845 if (getLangOpts().CPlusPlus) { 1846 if (const auto *RT = T->getAs<RecordType>()) { 1847 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1848 Info.Width = layout.getDataSize(); 1849 } 1850 } 1851 1852 return Info; 1853 } 1854 1855 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1856 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1857 TypeInfoChars 1858 static getConstantArrayInfoInChars(const ASTContext &Context, 1859 const ConstantArrayType *CAT) { 1860 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1861 uint64_t Size = CAT->getSize().getZExtValue(); 1862 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1863 (uint64_t)(-1)/Size) && 1864 "Overflow in array type char size evaluation"); 1865 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1866 unsigned Align = EltInfo.Align.getQuantity(); 1867 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1868 Context.getTargetInfo().getPointerWidth(0) == 64) 1869 Width = llvm::alignTo(Width, Align); 1870 return TypeInfoChars(CharUnits::fromQuantity(Width), 1871 CharUnits::fromQuantity(Align), 1872 EltInfo.AlignRequirement); 1873 } 1874 1875 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1876 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1877 return getConstantArrayInfoInChars(*this, CAT); 1878 TypeInfo Info = getTypeInfo(T); 1879 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1880 toCharUnitsFromBits(Info.Align), Info.AlignRequirement); 1881 } 1882 1883 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1884 return getTypeInfoInChars(T.getTypePtr()); 1885 } 1886 1887 bool ASTContext::isAlignmentRequired(const Type *T) const { 1888 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; 1889 } 1890 1891 bool ASTContext::isAlignmentRequired(QualType T) const { 1892 return isAlignmentRequired(T.getTypePtr()); 1893 } 1894 1895 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1896 bool NeedsPreferredAlignment) const { 1897 // An alignment on a typedef overrides anything else. 1898 if (const auto *TT = T->getAs<TypedefType>()) 1899 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1900 return Align; 1901 1902 // If we have an (array of) complete type, we're done. 1903 T = getBaseElementType(T); 1904 if (!T->isIncompleteType()) 1905 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1906 1907 // If we had an array type, its element type might be a typedef 1908 // type with an alignment attribute. 1909 if (const auto *TT = T->getAs<TypedefType>()) 1910 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1911 return Align; 1912 1913 // Otherwise, see if the declaration of the type had an attribute. 1914 if (const auto *TT = T->getAs<TagType>()) 1915 return TT->getDecl()->getMaxAlignment(); 1916 1917 return 0; 1918 } 1919 1920 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1921 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1922 if (I != MemoizedTypeInfo.end()) 1923 return I->second; 1924 1925 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1926 TypeInfo TI = getTypeInfoImpl(T); 1927 MemoizedTypeInfo[T] = TI; 1928 return TI; 1929 } 1930 1931 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1932 /// method does not work on incomplete types. 1933 /// 1934 /// FIXME: Pointers into different addr spaces could have different sizes and 1935 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1936 /// should take a QualType, &c. 1937 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1938 uint64_t Width = 0; 1939 unsigned Align = 8; 1940 AlignRequirementKind AlignRequirement = AlignRequirementKind::None; 1941 unsigned AS = 0; 1942 switch (T->getTypeClass()) { 1943 #define TYPE(Class, Base) 1944 #define ABSTRACT_TYPE(Class, Base) 1945 #define NON_CANONICAL_TYPE(Class, Base) 1946 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1947 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1948 case Type::Class: \ 1949 assert(!T->isDependentType() && "should not see dependent types here"); \ 1950 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1951 #include "clang/AST/TypeNodes.inc" 1952 llvm_unreachable("Should not see dependent types"); 1953 1954 case Type::FunctionNoProto: 1955 case Type::FunctionProto: 1956 // GCC extension: alignof(function) = 32 bits 1957 Width = 0; 1958 Align = 32; 1959 break; 1960 1961 case Type::IncompleteArray: 1962 case Type::VariableArray: 1963 case Type::ConstantArray: { 1964 // Model non-constant sized arrays as size zero, but track the alignment. 1965 uint64_t Size = 0; 1966 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1967 Size = CAT->getSize().getZExtValue(); 1968 1969 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1970 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1971 "Overflow in array type bit size evaluation"); 1972 Width = EltInfo.Width * Size; 1973 Align = EltInfo.Align; 1974 AlignRequirement = EltInfo.AlignRequirement; 1975 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1976 getTargetInfo().getPointerWidth(0) == 64) 1977 Width = llvm::alignTo(Width, Align); 1978 break; 1979 } 1980 1981 case Type::ExtVector: 1982 case Type::Vector: { 1983 const auto *VT = cast<VectorType>(T); 1984 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1985 Width = VT->isExtVectorBoolType() ? VT->getNumElements() 1986 : EltInfo.Width * VT->getNumElements(); 1987 // Enforce at least byte alignment. 1988 Align = std::max<unsigned>(8, Width); 1989 1990 // If the alignment is not a power of 2, round up to the next power of 2. 1991 // This happens for non-power-of-2 length vectors. 1992 if (Align & (Align-1)) { 1993 Align = llvm::NextPowerOf2(Align); 1994 Width = llvm::alignTo(Width, Align); 1995 } 1996 // Adjust the alignment based on the target max. 1997 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1998 if (TargetVectorAlign && TargetVectorAlign < Align) 1999 Align = TargetVectorAlign; 2000 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 2001 // Adjust the alignment for fixed-length SVE vectors. This is important 2002 // for non-power-of-2 vector lengths. 2003 Align = 128; 2004 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 2005 // Adjust the alignment for fixed-length SVE predicates. 2006 Align = 16; 2007 break; 2008 } 2009 2010 case Type::ConstantMatrix: { 2011 const auto *MT = cast<ConstantMatrixType>(T); 2012 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2013 // The internal layout of a matrix value is implementation defined. 2014 // Initially be ABI compatible with arrays with respect to alignment and 2015 // size. 2016 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2017 Align = ElementInfo.Align; 2018 break; 2019 } 2020 2021 case Type::Builtin: 2022 switch (cast<BuiltinType>(T)->getKind()) { 2023 default: llvm_unreachable("Unknown builtin type!"); 2024 case BuiltinType::Void: 2025 // GCC extension: alignof(void) = 8 bits. 2026 Width = 0; 2027 Align = 8; 2028 break; 2029 case BuiltinType::Bool: 2030 Width = Target->getBoolWidth(); 2031 Align = Target->getBoolAlign(); 2032 break; 2033 case BuiltinType::Char_S: 2034 case BuiltinType::Char_U: 2035 case BuiltinType::UChar: 2036 case BuiltinType::SChar: 2037 case BuiltinType::Char8: 2038 Width = Target->getCharWidth(); 2039 Align = Target->getCharAlign(); 2040 break; 2041 case BuiltinType::WChar_S: 2042 case BuiltinType::WChar_U: 2043 Width = Target->getWCharWidth(); 2044 Align = Target->getWCharAlign(); 2045 break; 2046 case BuiltinType::Char16: 2047 Width = Target->getChar16Width(); 2048 Align = Target->getChar16Align(); 2049 break; 2050 case BuiltinType::Char32: 2051 Width = Target->getChar32Width(); 2052 Align = Target->getChar32Align(); 2053 break; 2054 case BuiltinType::UShort: 2055 case BuiltinType::Short: 2056 Width = Target->getShortWidth(); 2057 Align = Target->getShortAlign(); 2058 break; 2059 case BuiltinType::UInt: 2060 case BuiltinType::Int: 2061 Width = Target->getIntWidth(); 2062 Align = Target->getIntAlign(); 2063 break; 2064 case BuiltinType::ULong: 2065 case BuiltinType::Long: 2066 Width = Target->getLongWidth(); 2067 Align = Target->getLongAlign(); 2068 break; 2069 case BuiltinType::ULongLong: 2070 case BuiltinType::LongLong: 2071 Width = Target->getLongLongWidth(); 2072 Align = Target->getLongLongAlign(); 2073 break; 2074 case BuiltinType::Int128: 2075 case BuiltinType::UInt128: 2076 Width = 128; 2077 Align = 128; // int128_t is 128-bit aligned on all targets. 2078 break; 2079 case BuiltinType::ShortAccum: 2080 case BuiltinType::UShortAccum: 2081 case BuiltinType::SatShortAccum: 2082 case BuiltinType::SatUShortAccum: 2083 Width = Target->getShortAccumWidth(); 2084 Align = Target->getShortAccumAlign(); 2085 break; 2086 case BuiltinType::Accum: 2087 case BuiltinType::UAccum: 2088 case BuiltinType::SatAccum: 2089 case BuiltinType::SatUAccum: 2090 Width = Target->getAccumWidth(); 2091 Align = Target->getAccumAlign(); 2092 break; 2093 case BuiltinType::LongAccum: 2094 case BuiltinType::ULongAccum: 2095 case BuiltinType::SatLongAccum: 2096 case BuiltinType::SatULongAccum: 2097 Width = Target->getLongAccumWidth(); 2098 Align = Target->getLongAccumAlign(); 2099 break; 2100 case BuiltinType::ShortFract: 2101 case BuiltinType::UShortFract: 2102 case BuiltinType::SatShortFract: 2103 case BuiltinType::SatUShortFract: 2104 Width = Target->getShortFractWidth(); 2105 Align = Target->getShortFractAlign(); 2106 break; 2107 case BuiltinType::Fract: 2108 case BuiltinType::UFract: 2109 case BuiltinType::SatFract: 2110 case BuiltinType::SatUFract: 2111 Width = Target->getFractWidth(); 2112 Align = Target->getFractAlign(); 2113 break; 2114 case BuiltinType::LongFract: 2115 case BuiltinType::ULongFract: 2116 case BuiltinType::SatLongFract: 2117 case BuiltinType::SatULongFract: 2118 Width = Target->getLongFractWidth(); 2119 Align = Target->getLongFractAlign(); 2120 break; 2121 case BuiltinType::BFloat16: 2122 Width = Target->getBFloat16Width(); 2123 Align = Target->getBFloat16Align(); 2124 break; 2125 case BuiltinType::Float16: 2126 case BuiltinType::Half: 2127 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2128 !getLangOpts().OpenMPIsDevice) { 2129 Width = Target->getHalfWidth(); 2130 Align = Target->getHalfAlign(); 2131 } else { 2132 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2133 "Expected OpenMP device compilation."); 2134 Width = AuxTarget->getHalfWidth(); 2135 Align = AuxTarget->getHalfAlign(); 2136 } 2137 break; 2138 case BuiltinType::Float: 2139 Width = Target->getFloatWidth(); 2140 Align = Target->getFloatAlign(); 2141 break; 2142 case BuiltinType::Double: 2143 Width = Target->getDoubleWidth(); 2144 Align = Target->getDoubleAlign(); 2145 break; 2146 case BuiltinType::Ibm128: 2147 Width = Target->getIbm128Width(); 2148 Align = Target->getIbm128Align(); 2149 break; 2150 case BuiltinType::LongDouble: 2151 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2152 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2153 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2154 Width = AuxTarget->getLongDoubleWidth(); 2155 Align = AuxTarget->getLongDoubleAlign(); 2156 } else { 2157 Width = Target->getLongDoubleWidth(); 2158 Align = Target->getLongDoubleAlign(); 2159 } 2160 break; 2161 case BuiltinType::Float128: 2162 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2163 !getLangOpts().OpenMPIsDevice) { 2164 Width = Target->getFloat128Width(); 2165 Align = Target->getFloat128Align(); 2166 } else { 2167 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2168 "Expected OpenMP device compilation."); 2169 Width = AuxTarget->getFloat128Width(); 2170 Align = AuxTarget->getFloat128Align(); 2171 } 2172 break; 2173 case BuiltinType::NullPtr: 2174 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2175 Align = Target->getPointerAlign(0); // == sizeof(void*) 2176 break; 2177 case BuiltinType::ObjCId: 2178 case BuiltinType::ObjCClass: 2179 case BuiltinType::ObjCSel: 2180 Width = Target->getPointerWidth(0); 2181 Align = Target->getPointerAlign(0); 2182 break; 2183 case BuiltinType::OCLSampler: 2184 case BuiltinType::OCLEvent: 2185 case BuiltinType::OCLClkEvent: 2186 case BuiltinType::OCLQueue: 2187 case BuiltinType::OCLReserveID: 2188 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2189 case BuiltinType::Id: 2190 #include "clang/Basic/OpenCLImageTypes.def" 2191 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2192 case BuiltinType::Id: 2193 #include "clang/Basic/OpenCLExtensionTypes.def" 2194 AS = getTargetAddressSpace( 2195 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2196 Width = Target->getPointerWidth(AS); 2197 Align = Target->getPointerAlign(AS); 2198 break; 2199 // The SVE types are effectively target-specific. The length of an 2200 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2201 // of 128 bits. There is one predicate bit for each vector byte, so the 2202 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2203 // 2204 // Because the length is only known at runtime, we use a dummy value 2205 // of 0 for the static length. The alignment values are those defined 2206 // by the Procedure Call Standard for the Arm Architecture. 2207 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2208 IsSigned, IsFP, IsBF) \ 2209 case BuiltinType::Id: \ 2210 Width = 0; \ 2211 Align = 128; \ 2212 break; 2213 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2214 case BuiltinType::Id: \ 2215 Width = 0; \ 2216 Align = 16; \ 2217 break; 2218 #include "clang/Basic/AArch64SVEACLETypes.def" 2219 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2220 case BuiltinType::Id: \ 2221 Width = Size; \ 2222 Align = Size; \ 2223 break; 2224 #include "clang/Basic/PPCTypes.def" 2225 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2226 IsFP) \ 2227 case BuiltinType::Id: \ 2228 Width = 0; \ 2229 Align = ElBits; \ 2230 break; 2231 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2232 case BuiltinType::Id: \ 2233 Width = 0; \ 2234 Align = 8; \ 2235 break; 2236 #include "clang/Basic/RISCVVTypes.def" 2237 } 2238 break; 2239 case Type::ObjCObjectPointer: 2240 Width = Target->getPointerWidth(0); 2241 Align = Target->getPointerAlign(0); 2242 break; 2243 case Type::BlockPointer: 2244 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2245 Width = Target->getPointerWidth(AS); 2246 Align = Target->getPointerAlign(AS); 2247 break; 2248 case Type::LValueReference: 2249 case Type::RValueReference: 2250 // alignof and sizeof should never enter this code path here, so we go 2251 // the pointer route. 2252 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2253 Width = Target->getPointerWidth(AS); 2254 Align = Target->getPointerAlign(AS); 2255 break; 2256 case Type::Pointer: 2257 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2258 Width = Target->getPointerWidth(AS); 2259 Align = Target->getPointerAlign(AS); 2260 break; 2261 case Type::MemberPointer: { 2262 const auto *MPT = cast<MemberPointerType>(T); 2263 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2264 Width = MPI.Width; 2265 Align = MPI.Align; 2266 break; 2267 } 2268 case Type::Complex: { 2269 // Complex types have the same alignment as their elements, but twice the 2270 // size. 2271 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2272 Width = EltInfo.Width * 2; 2273 Align = EltInfo.Align; 2274 break; 2275 } 2276 case Type::ObjCObject: 2277 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2278 case Type::Adjusted: 2279 case Type::Decayed: 2280 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2281 case Type::ObjCInterface: { 2282 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2283 if (ObjCI->getDecl()->isInvalidDecl()) { 2284 Width = 8; 2285 Align = 8; 2286 break; 2287 } 2288 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2289 Width = toBits(Layout.getSize()); 2290 Align = toBits(Layout.getAlignment()); 2291 break; 2292 } 2293 case Type::BitInt: { 2294 const auto *EIT = cast<BitIntType>(T); 2295 Align = 2296 std::min(static_cast<unsigned>(std::max( 2297 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2298 Target->getLongLongAlign()); 2299 Width = llvm::alignTo(EIT->getNumBits(), Align); 2300 break; 2301 } 2302 case Type::Record: 2303 case Type::Enum: { 2304 const auto *TT = cast<TagType>(T); 2305 2306 if (TT->getDecl()->isInvalidDecl()) { 2307 Width = 8; 2308 Align = 8; 2309 break; 2310 } 2311 2312 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2313 const EnumDecl *ED = ET->getDecl(); 2314 TypeInfo Info = 2315 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2316 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2317 Info.Align = AttrAlign; 2318 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum; 2319 } 2320 return Info; 2321 } 2322 2323 const auto *RT = cast<RecordType>(TT); 2324 const RecordDecl *RD = RT->getDecl(); 2325 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2326 Width = toBits(Layout.getSize()); 2327 Align = toBits(Layout.getAlignment()); 2328 AlignRequirement = RD->hasAttr<AlignedAttr>() 2329 ? AlignRequirementKind::RequiredByRecord 2330 : AlignRequirementKind::None; 2331 break; 2332 } 2333 2334 case Type::SubstTemplateTypeParm: 2335 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2336 getReplacementType().getTypePtr()); 2337 2338 case Type::Auto: 2339 case Type::DeducedTemplateSpecialization: { 2340 const auto *A = cast<DeducedType>(T); 2341 assert(!A->getDeducedType().isNull() && 2342 "cannot request the size of an undeduced or dependent auto type"); 2343 return getTypeInfo(A->getDeducedType().getTypePtr()); 2344 } 2345 2346 case Type::Paren: 2347 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2348 2349 case Type::MacroQualified: 2350 return getTypeInfo( 2351 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2352 2353 case Type::ObjCTypeParam: 2354 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2355 2356 case Type::Using: 2357 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr()); 2358 2359 case Type::Typedef: { 2360 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2361 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2362 // If the typedef has an aligned attribute on it, it overrides any computed 2363 // alignment we have. This violates the GCC documentation (which says that 2364 // attribute(aligned) can only round up) but matches its implementation. 2365 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2366 Align = AttrAlign; 2367 AlignRequirement = AlignRequirementKind::RequiredByTypedef; 2368 } else { 2369 Align = Info.Align; 2370 AlignRequirement = Info.AlignRequirement; 2371 } 2372 Width = Info.Width; 2373 break; 2374 } 2375 2376 case Type::Elaborated: 2377 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2378 2379 case Type::Attributed: 2380 return getTypeInfo( 2381 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2382 2383 case Type::Atomic: { 2384 // Start with the base type information. 2385 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2386 Width = Info.Width; 2387 Align = Info.Align; 2388 2389 if (!Width) { 2390 // An otherwise zero-sized type should still generate an 2391 // atomic operation. 2392 Width = Target->getCharWidth(); 2393 assert(Align); 2394 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2395 // If the size of the type doesn't exceed the platform's max 2396 // atomic promotion width, make the size and alignment more 2397 // favorable to atomic operations: 2398 2399 // Round the size up to a power of 2. 2400 if (!llvm::isPowerOf2_64(Width)) 2401 Width = llvm::NextPowerOf2(Width); 2402 2403 // Set the alignment equal to the size. 2404 Align = static_cast<unsigned>(Width); 2405 } 2406 } 2407 break; 2408 2409 case Type::Pipe: 2410 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2411 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2412 break; 2413 } 2414 2415 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2416 return TypeInfo(Width, Align, AlignRequirement); 2417 } 2418 2419 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2420 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2421 if (I != MemoizedUnadjustedAlign.end()) 2422 return I->second; 2423 2424 unsigned UnadjustedAlign; 2425 if (const auto *RT = T->getAs<RecordType>()) { 2426 const RecordDecl *RD = RT->getDecl(); 2427 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2428 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2429 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2430 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2431 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2432 } else { 2433 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2434 } 2435 2436 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2437 return UnadjustedAlign; 2438 } 2439 2440 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2441 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2442 return SimdAlign; 2443 } 2444 2445 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2446 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2447 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2448 } 2449 2450 /// toBits - Convert a size in characters to a size in characters. 2451 int64_t ASTContext::toBits(CharUnits CharSize) const { 2452 return CharSize.getQuantity() * getCharWidth(); 2453 } 2454 2455 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2456 /// This method does not work on incomplete types. 2457 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2458 return getTypeInfoInChars(T).Width; 2459 } 2460 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2461 return getTypeInfoInChars(T).Width; 2462 } 2463 2464 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2465 /// characters. This method does not work on incomplete types. 2466 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2467 return toCharUnitsFromBits(getTypeAlign(T)); 2468 } 2469 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2470 return toCharUnitsFromBits(getTypeAlign(T)); 2471 } 2472 2473 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2474 /// type, in characters, before alignment adustments. This method does 2475 /// not work on incomplete types. 2476 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2477 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2478 } 2479 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2480 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2481 } 2482 2483 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2484 /// type for the current target in bits. This can be different than the ABI 2485 /// alignment in cases where it is beneficial for performance or backwards 2486 /// compatibility preserving to overalign a data type. (Note: despite the name, 2487 /// the preferred alignment is ABI-impacting, and not an optimization.) 2488 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2489 TypeInfo TI = getTypeInfo(T); 2490 unsigned ABIAlign = TI.Align; 2491 2492 T = T->getBaseElementTypeUnsafe(); 2493 2494 // The preferred alignment of member pointers is that of a pointer. 2495 if (T->isMemberPointerType()) 2496 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2497 2498 if (!Target->allowsLargerPreferedTypeAlignment()) 2499 return ABIAlign; 2500 2501 if (const auto *RT = T->getAs<RecordType>()) { 2502 const RecordDecl *RD = RT->getDecl(); 2503 2504 // When used as part of a typedef, or together with a 'packed' attribute, 2505 // the 'aligned' attribute can be used to decrease alignment. Note that the 2506 // 'packed' case is already taken into consideration when computing the 2507 // alignment, we only need to handle the typedef case here. 2508 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef || 2509 RD->isInvalidDecl()) 2510 return ABIAlign; 2511 2512 unsigned PreferredAlign = static_cast<unsigned>( 2513 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2514 assert(PreferredAlign >= ABIAlign && 2515 "PreferredAlign should be at least as large as ABIAlign."); 2516 return PreferredAlign; 2517 } 2518 2519 // Double (and, for targets supporting AIX `power` alignment, long double) and 2520 // long long should be naturally aligned (despite requiring less alignment) if 2521 // possible. 2522 if (const auto *CT = T->getAs<ComplexType>()) 2523 T = CT->getElementType().getTypePtr(); 2524 if (const auto *ET = T->getAs<EnumType>()) 2525 T = ET->getDecl()->getIntegerType().getTypePtr(); 2526 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2527 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2528 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2529 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2530 Target->defaultsToAIXPowerAlignment())) 2531 // Don't increase the alignment if an alignment attribute was specified on a 2532 // typedef declaration. 2533 if (!TI.isAlignRequired()) 2534 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2535 2536 return ABIAlign; 2537 } 2538 2539 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2540 /// for __attribute__((aligned)) on this target, to be used if no alignment 2541 /// value is specified. 2542 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2543 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2544 } 2545 2546 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2547 /// to a global variable of the specified type. 2548 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2549 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2550 return std::max(getPreferredTypeAlign(T), 2551 getTargetInfo().getMinGlobalAlign(TypeSize)); 2552 } 2553 2554 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2555 /// should be given to a global variable of the specified type. 2556 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2557 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2558 } 2559 2560 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2561 CharUnits Offset = CharUnits::Zero(); 2562 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2563 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2564 Offset += Layout->getBaseClassOffset(Base); 2565 Layout = &getASTRecordLayout(Base); 2566 } 2567 return Offset; 2568 } 2569 2570 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2571 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2572 CharUnits ThisAdjustment = CharUnits::Zero(); 2573 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2574 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2575 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2576 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2577 const CXXRecordDecl *Base = RD; 2578 const CXXRecordDecl *Derived = Path[I]; 2579 if (DerivedMember) 2580 std::swap(Base, Derived); 2581 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2582 RD = Path[I]; 2583 } 2584 if (DerivedMember) 2585 ThisAdjustment = -ThisAdjustment; 2586 return ThisAdjustment; 2587 } 2588 2589 /// DeepCollectObjCIvars - 2590 /// This routine first collects all declared, but not synthesized, ivars in 2591 /// super class and then collects all ivars, including those synthesized for 2592 /// current class. This routine is used for implementation of current class 2593 /// when all ivars, declared and synthesized are known. 2594 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2595 bool leafClass, 2596 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2597 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2598 DeepCollectObjCIvars(SuperClass, false, Ivars); 2599 if (!leafClass) { 2600 for (const auto *I : OI->ivars()) 2601 Ivars.push_back(I); 2602 } else { 2603 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2604 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2605 Iv= Iv->getNextIvar()) 2606 Ivars.push_back(Iv); 2607 } 2608 } 2609 2610 /// CollectInheritedProtocols - Collect all protocols in current class and 2611 /// those inherited by it. 2612 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2613 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2614 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2615 // We can use protocol_iterator here instead of 2616 // all_referenced_protocol_iterator since we are walking all categories. 2617 for (auto *Proto : OI->all_referenced_protocols()) { 2618 CollectInheritedProtocols(Proto, Protocols); 2619 } 2620 2621 // Categories of this Interface. 2622 for (const auto *Cat : OI->visible_categories()) 2623 CollectInheritedProtocols(Cat, Protocols); 2624 2625 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2626 while (SD) { 2627 CollectInheritedProtocols(SD, Protocols); 2628 SD = SD->getSuperClass(); 2629 } 2630 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2631 for (auto *Proto : OC->protocols()) { 2632 CollectInheritedProtocols(Proto, Protocols); 2633 } 2634 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2635 // Insert the protocol. 2636 if (!Protocols.insert( 2637 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2638 return; 2639 2640 for (auto *Proto : OP->protocols()) 2641 CollectInheritedProtocols(Proto, Protocols); 2642 } 2643 } 2644 2645 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2646 const RecordDecl *RD) { 2647 assert(RD->isUnion() && "Must be union type"); 2648 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2649 2650 for (const auto *Field : RD->fields()) { 2651 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2652 return false; 2653 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2654 if (FieldSize != UnionSize) 2655 return false; 2656 } 2657 return !RD->field_empty(); 2658 } 2659 2660 static int64_t getSubobjectOffset(const FieldDecl *Field, 2661 const ASTContext &Context, 2662 const clang::ASTRecordLayout & /*Layout*/) { 2663 return Context.getFieldOffset(Field); 2664 } 2665 2666 static int64_t getSubobjectOffset(const CXXRecordDecl *RD, 2667 const ASTContext &Context, 2668 const clang::ASTRecordLayout &Layout) { 2669 return Context.toBits(Layout.getBaseClassOffset(RD)); 2670 } 2671 2672 static llvm::Optional<int64_t> 2673 structHasUniqueObjectRepresentations(const ASTContext &Context, 2674 const RecordDecl *RD); 2675 2676 static llvm::Optional<int64_t> 2677 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { 2678 if (Field->getType()->isRecordType()) { 2679 const RecordDecl *RD = Field->getType()->getAsRecordDecl(); 2680 if (!RD->isUnion()) 2681 return structHasUniqueObjectRepresentations(Context, RD); 2682 } 2683 if (!Field->getType()->isReferenceType() && 2684 !Context.hasUniqueObjectRepresentations(Field->getType())) 2685 return llvm::None; 2686 2687 int64_t FieldSizeInBits = 2688 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2689 if (Field->isBitField()) { 2690 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2691 if (BitfieldSize > FieldSizeInBits) 2692 return llvm::None; 2693 FieldSizeInBits = BitfieldSize; 2694 } 2695 return FieldSizeInBits; 2696 } 2697 2698 static llvm::Optional<int64_t> 2699 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { 2700 return structHasUniqueObjectRepresentations(Context, RD); 2701 } 2702 2703 template <typename RangeT> 2704 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations( 2705 const RangeT &Subobjects, int64_t CurOffsetInBits, 2706 const ASTContext &Context, const clang::ASTRecordLayout &Layout) { 2707 for (const auto *Subobject : Subobjects) { 2708 llvm::Optional<int64_t> SizeInBits = 2709 getSubobjectSizeInBits(Subobject, Context); 2710 if (!SizeInBits) 2711 return llvm::None; 2712 if (*SizeInBits != 0) { 2713 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout); 2714 if (Offset != CurOffsetInBits) 2715 return llvm::None; 2716 CurOffsetInBits += *SizeInBits; 2717 } 2718 } 2719 return CurOffsetInBits; 2720 } 2721 2722 static llvm::Optional<int64_t> 2723 structHasUniqueObjectRepresentations(const ASTContext &Context, 2724 const RecordDecl *RD) { 2725 assert(!RD->isUnion() && "Must be struct/class type"); 2726 const auto &Layout = Context.getASTRecordLayout(RD); 2727 2728 int64_t CurOffsetInBits = 0; 2729 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2730 if (ClassDecl->isDynamicClass()) 2731 return llvm::None; 2732 2733 SmallVector<CXXRecordDecl *, 4> Bases; 2734 for (const auto &Base : ClassDecl->bases()) { 2735 // Empty types can be inherited from, and non-empty types can potentially 2736 // have tail padding, so just make sure there isn't an error. 2737 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); 2738 } 2739 2740 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { 2741 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); 2742 }); 2743 2744 llvm::Optional<int64_t> OffsetAfterBases = 2745 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits, 2746 Context, Layout); 2747 if (!OffsetAfterBases) 2748 return llvm::None; 2749 CurOffsetInBits = *OffsetAfterBases; 2750 } 2751 2752 llvm::Optional<int64_t> OffsetAfterFields = 2753 structSubobjectsHaveUniqueObjectRepresentations( 2754 RD->fields(), CurOffsetInBits, Context, Layout); 2755 if (!OffsetAfterFields) 2756 return llvm::None; 2757 CurOffsetInBits = *OffsetAfterFields; 2758 2759 return CurOffsetInBits; 2760 } 2761 2762 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2763 // C++17 [meta.unary.prop]: 2764 // The predicate condition for a template specialization 2765 // has_unique_object_representations<T> shall be 2766 // satisfied if and only if: 2767 // (9.1) - T is trivially copyable, and 2768 // (9.2) - any two objects of type T with the same value have the same 2769 // object representation, where two objects 2770 // of array or non-union class type are considered to have the same value 2771 // if their respective sequences of 2772 // direct subobjects have the same values, and two objects of union type 2773 // are considered to have the same 2774 // value if they have the same active member and the corresponding members 2775 // have the same value. 2776 // The set of scalar types for which this condition holds is 2777 // implementation-defined. [ Note: If a type has padding 2778 // bits, the condition does not hold; otherwise, the condition holds true 2779 // for unsigned integral types. -- end note ] 2780 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2781 2782 // Arrays are unique only if their element type is unique. 2783 if (Ty->isArrayType()) 2784 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2785 2786 // (9.1) - T is trivially copyable... 2787 if (!Ty.isTriviallyCopyableType(*this)) 2788 return false; 2789 2790 // All integrals and enums are unique. 2791 if (Ty->isIntegralOrEnumerationType()) 2792 return true; 2793 2794 // All other pointers are unique. 2795 if (Ty->isPointerType()) 2796 return true; 2797 2798 if (Ty->isMemberPointerType()) { 2799 const auto *MPT = Ty->getAs<MemberPointerType>(); 2800 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2801 } 2802 2803 if (Ty->isRecordType()) { 2804 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2805 2806 if (Record->isInvalidDecl()) 2807 return false; 2808 2809 if (Record->isUnion()) 2810 return unionHasUniqueObjectRepresentations(*this, Record); 2811 2812 Optional<int64_t> StructSize = 2813 structHasUniqueObjectRepresentations(*this, Record); 2814 2815 return StructSize && 2816 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2817 } 2818 2819 // FIXME: More cases to handle here (list by rsmith): 2820 // vectors (careful about, eg, vector of 3 foo) 2821 // _Complex int and friends 2822 // _Atomic T 2823 // Obj-C block pointers 2824 // Obj-C object pointers 2825 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2826 // clk_event_t, queue_t, reserve_id_t) 2827 // There're also Obj-C class types and the Obj-C selector type, but I think it 2828 // makes sense for those to return false here. 2829 2830 return false; 2831 } 2832 2833 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2834 unsigned count = 0; 2835 // Count ivars declared in class extension. 2836 for (const auto *Ext : OI->known_extensions()) 2837 count += Ext->ivar_size(); 2838 2839 // Count ivar defined in this class's implementation. This 2840 // includes synthesized ivars. 2841 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2842 count += ImplDecl->ivar_size(); 2843 2844 return count; 2845 } 2846 2847 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2848 if (!E) 2849 return false; 2850 2851 // nullptr_t is always treated as null. 2852 if (E->getType()->isNullPtrType()) return true; 2853 2854 if (E->getType()->isAnyPointerType() && 2855 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2856 Expr::NPC_ValueDependentIsNull)) 2857 return true; 2858 2859 // Unfortunately, __null has type 'int'. 2860 if (isa<GNUNullExpr>(E)) return true; 2861 2862 return false; 2863 } 2864 2865 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2866 /// exists. 2867 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2868 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2869 I = ObjCImpls.find(D); 2870 if (I != ObjCImpls.end()) 2871 return cast<ObjCImplementationDecl>(I->second); 2872 return nullptr; 2873 } 2874 2875 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2876 /// exists. 2877 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2878 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2879 I = ObjCImpls.find(D); 2880 if (I != ObjCImpls.end()) 2881 return cast<ObjCCategoryImplDecl>(I->second); 2882 return nullptr; 2883 } 2884 2885 /// Set the implementation of ObjCInterfaceDecl. 2886 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2887 ObjCImplementationDecl *ImplD) { 2888 assert(IFaceD && ImplD && "Passed null params"); 2889 ObjCImpls[IFaceD] = ImplD; 2890 } 2891 2892 /// Set the implementation of ObjCCategoryDecl. 2893 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2894 ObjCCategoryImplDecl *ImplD) { 2895 assert(CatD && ImplD && "Passed null params"); 2896 ObjCImpls[CatD] = ImplD; 2897 } 2898 2899 const ObjCMethodDecl * 2900 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2901 return ObjCMethodRedecls.lookup(MD); 2902 } 2903 2904 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2905 const ObjCMethodDecl *Redecl) { 2906 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2907 ObjCMethodRedecls[MD] = Redecl; 2908 } 2909 2910 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2911 const NamedDecl *ND) const { 2912 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2913 return ID; 2914 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2915 return CD->getClassInterface(); 2916 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2917 return IMD->getClassInterface(); 2918 2919 return nullptr; 2920 } 2921 2922 /// Get the copy initialization expression of VarDecl, or nullptr if 2923 /// none exists. 2924 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2925 assert(VD && "Passed null params"); 2926 assert(VD->hasAttr<BlocksAttr>() && 2927 "getBlockVarCopyInits - not __block var"); 2928 auto I = BlockVarCopyInits.find(VD); 2929 if (I != BlockVarCopyInits.end()) 2930 return I->second; 2931 return {nullptr, false}; 2932 } 2933 2934 /// Set the copy initialization expression of a block var decl. 2935 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2936 bool CanThrow) { 2937 assert(VD && CopyExpr && "Passed null params"); 2938 assert(VD->hasAttr<BlocksAttr>() && 2939 "setBlockVarCopyInits - not __block var"); 2940 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2941 } 2942 2943 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2944 unsigned DataSize) const { 2945 if (!DataSize) 2946 DataSize = TypeLoc::getFullDataSizeForType(T); 2947 else 2948 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2949 "incorrect data size provided to CreateTypeSourceInfo!"); 2950 2951 auto *TInfo = 2952 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2953 new (TInfo) TypeSourceInfo(T); 2954 return TInfo; 2955 } 2956 2957 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2958 SourceLocation L) const { 2959 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2960 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2961 return DI; 2962 } 2963 2964 const ASTRecordLayout & 2965 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2966 return getObjCLayout(D, nullptr); 2967 } 2968 2969 const ASTRecordLayout & 2970 ASTContext::getASTObjCImplementationLayout( 2971 const ObjCImplementationDecl *D) const { 2972 return getObjCLayout(D->getClassInterface(), D); 2973 } 2974 2975 //===----------------------------------------------------------------------===// 2976 // Type creation/memoization methods 2977 //===----------------------------------------------------------------------===// 2978 2979 QualType 2980 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2981 unsigned fastQuals = quals.getFastQualifiers(); 2982 quals.removeFastQualifiers(); 2983 2984 // Check if we've already instantiated this type. 2985 llvm::FoldingSetNodeID ID; 2986 ExtQuals::Profile(ID, baseType, quals); 2987 void *insertPos = nullptr; 2988 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2989 assert(eq->getQualifiers() == quals); 2990 return QualType(eq, fastQuals); 2991 } 2992 2993 // If the base type is not canonical, make the appropriate canonical type. 2994 QualType canon; 2995 if (!baseType->isCanonicalUnqualified()) { 2996 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2997 canonSplit.Quals.addConsistentQualifiers(quals); 2998 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2999 3000 // Re-find the insert position. 3001 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 3002 } 3003 3004 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 3005 ExtQualNodes.InsertNode(eq, insertPos); 3006 return QualType(eq, fastQuals); 3007 } 3008 3009 QualType ASTContext::getAddrSpaceQualType(QualType T, 3010 LangAS AddressSpace) const { 3011 QualType CanT = getCanonicalType(T); 3012 if (CanT.getAddressSpace() == AddressSpace) 3013 return T; 3014 3015 // If we are composing extended qualifiers together, merge together 3016 // into one ExtQuals node. 3017 QualifierCollector Quals; 3018 const Type *TypeNode = Quals.strip(T); 3019 3020 // If this type already has an address space specified, it cannot get 3021 // another one. 3022 assert(!Quals.hasAddressSpace() && 3023 "Type cannot be in multiple addr spaces!"); 3024 Quals.addAddressSpace(AddressSpace); 3025 3026 return getExtQualType(TypeNode, Quals); 3027 } 3028 3029 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 3030 // If the type is not qualified with an address space, just return it 3031 // immediately. 3032 if (!T.hasAddressSpace()) 3033 return T; 3034 3035 // If we are composing extended qualifiers together, merge together 3036 // into one ExtQuals node. 3037 QualifierCollector Quals; 3038 const Type *TypeNode; 3039 3040 while (T.hasAddressSpace()) { 3041 TypeNode = Quals.strip(T); 3042 3043 // If the type no longer has an address space after stripping qualifiers, 3044 // jump out. 3045 if (!QualType(TypeNode, 0).hasAddressSpace()) 3046 break; 3047 3048 // There might be sugar in the way. Strip it and try again. 3049 T = T.getSingleStepDesugaredType(*this); 3050 } 3051 3052 Quals.removeAddressSpace(); 3053 3054 // Removal of the address space can mean there are no longer any 3055 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3056 // or required. 3057 if (Quals.hasNonFastQualifiers()) 3058 return getExtQualType(TypeNode, Quals); 3059 else 3060 return QualType(TypeNode, Quals.getFastQualifiers()); 3061 } 3062 3063 QualType ASTContext::getObjCGCQualType(QualType T, 3064 Qualifiers::GC GCAttr) const { 3065 QualType CanT = getCanonicalType(T); 3066 if (CanT.getObjCGCAttr() == GCAttr) 3067 return T; 3068 3069 if (const auto *ptr = T->getAs<PointerType>()) { 3070 QualType Pointee = ptr->getPointeeType(); 3071 if (Pointee->isAnyPointerType()) { 3072 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3073 return getPointerType(ResultType); 3074 } 3075 } 3076 3077 // If we are composing extended qualifiers together, merge together 3078 // into one ExtQuals node. 3079 QualifierCollector Quals; 3080 const Type *TypeNode = Quals.strip(T); 3081 3082 // If this type already has an ObjCGC specified, it cannot get 3083 // another one. 3084 assert(!Quals.hasObjCGCAttr() && 3085 "Type cannot have multiple ObjCGCs!"); 3086 Quals.addObjCGCAttr(GCAttr); 3087 3088 return getExtQualType(TypeNode, Quals); 3089 } 3090 3091 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3092 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3093 QualType Pointee = Ptr->getPointeeType(); 3094 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3095 return getPointerType(removeAddrSpaceQualType(Pointee)); 3096 } 3097 } 3098 return T; 3099 } 3100 3101 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3102 FunctionType::ExtInfo Info) { 3103 if (T->getExtInfo() == Info) 3104 return T; 3105 3106 QualType Result; 3107 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3108 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3109 } else { 3110 const auto *FPT = cast<FunctionProtoType>(T); 3111 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3112 EPI.ExtInfo = Info; 3113 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3114 } 3115 3116 return cast<FunctionType>(Result.getTypePtr()); 3117 } 3118 3119 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3120 QualType ResultType) { 3121 FD = FD->getMostRecentDecl(); 3122 while (true) { 3123 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3124 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3125 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3126 if (FunctionDecl *Next = FD->getPreviousDecl()) 3127 FD = Next; 3128 else 3129 break; 3130 } 3131 if (ASTMutationListener *L = getASTMutationListener()) 3132 L->DeducedReturnType(FD, ResultType); 3133 } 3134 3135 /// Get a function type and produce the equivalent function type with the 3136 /// specified exception specification. Type sugar that can be present on a 3137 /// declaration of a function with an exception specification is permitted 3138 /// and preserved. Other type sugar (for instance, typedefs) is not. 3139 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3140 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3141 // Might have some parens. 3142 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3143 return getParenType( 3144 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3145 3146 // Might be wrapped in a macro qualified type. 3147 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3148 return getMacroQualifiedType( 3149 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3150 MQT->getMacroIdentifier()); 3151 3152 // Might have a calling-convention attribute. 3153 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3154 return getAttributedType( 3155 AT->getAttrKind(), 3156 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3157 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3158 3159 // Anything else must be a function type. Rebuild it with the new exception 3160 // specification. 3161 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3162 return getFunctionType( 3163 Proto->getReturnType(), Proto->getParamTypes(), 3164 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3165 } 3166 3167 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3168 QualType U) { 3169 return hasSameType(T, U) || 3170 (getLangOpts().CPlusPlus17 && 3171 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3172 getFunctionTypeWithExceptionSpec(U, EST_None))); 3173 } 3174 3175 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3176 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3177 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3178 SmallVector<QualType, 16> Args(Proto->param_types()); 3179 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3180 Args[i] = removePtrSizeAddrSpace(Args[i]); 3181 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3182 } 3183 3184 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3185 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3186 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3187 } 3188 3189 return T; 3190 } 3191 3192 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3193 return hasSameType(T, U) || 3194 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3195 getFunctionTypeWithoutPtrSizes(U)); 3196 } 3197 3198 void ASTContext::adjustExceptionSpec( 3199 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3200 bool AsWritten) { 3201 // Update the type. 3202 QualType Updated = 3203 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3204 FD->setType(Updated); 3205 3206 if (!AsWritten) 3207 return; 3208 3209 // Update the type in the type source information too. 3210 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3211 // If the type and the type-as-written differ, we may need to update 3212 // the type-as-written too. 3213 if (TSInfo->getType() != FD->getType()) 3214 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3215 3216 // FIXME: When we get proper type location information for exceptions, 3217 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3218 // up the TypeSourceInfo; 3219 assert(TypeLoc::getFullDataSizeForType(Updated) == 3220 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3221 "TypeLoc size mismatch from updating exception specification"); 3222 TSInfo->overrideType(Updated); 3223 } 3224 } 3225 3226 /// getComplexType - Return the uniqued reference to the type for a complex 3227 /// number with the specified element type. 3228 QualType ASTContext::getComplexType(QualType T) const { 3229 // Unique pointers, to guarantee there is only one pointer of a particular 3230 // structure. 3231 llvm::FoldingSetNodeID ID; 3232 ComplexType::Profile(ID, T); 3233 3234 void *InsertPos = nullptr; 3235 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3236 return QualType(CT, 0); 3237 3238 // If the pointee type isn't canonical, this won't be a canonical type either, 3239 // so fill in the canonical type field. 3240 QualType Canonical; 3241 if (!T.isCanonical()) { 3242 Canonical = getComplexType(getCanonicalType(T)); 3243 3244 // Get the new insert position for the node we care about. 3245 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3246 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3247 } 3248 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3249 Types.push_back(New); 3250 ComplexTypes.InsertNode(New, InsertPos); 3251 return QualType(New, 0); 3252 } 3253 3254 /// getPointerType - Return the uniqued reference to the type for a pointer to 3255 /// the specified type. 3256 QualType ASTContext::getPointerType(QualType T) const { 3257 // Unique pointers, to guarantee there is only one pointer of a particular 3258 // structure. 3259 llvm::FoldingSetNodeID ID; 3260 PointerType::Profile(ID, T); 3261 3262 void *InsertPos = nullptr; 3263 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3264 return QualType(PT, 0); 3265 3266 // If the pointee type isn't canonical, this won't be a canonical type either, 3267 // so fill in the canonical type field. 3268 QualType Canonical; 3269 if (!T.isCanonical()) { 3270 Canonical = getPointerType(getCanonicalType(T)); 3271 3272 // Get the new insert position for the node we care about. 3273 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3274 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3275 } 3276 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3277 Types.push_back(New); 3278 PointerTypes.InsertNode(New, InsertPos); 3279 return QualType(New, 0); 3280 } 3281 3282 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3283 llvm::FoldingSetNodeID ID; 3284 AdjustedType::Profile(ID, Orig, New); 3285 void *InsertPos = nullptr; 3286 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3287 if (AT) 3288 return QualType(AT, 0); 3289 3290 QualType Canonical = getCanonicalType(New); 3291 3292 // Get the new insert position for the node we care about. 3293 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3294 assert(!AT && "Shouldn't be in the map!"); 3295 3296 AT = new (*this, TypeAlignment) 3297 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3298 Types.push_back(AT); 3299 AdjustedTypes.InsertNode(AT, InsertPos); 3300 return QualType(AT, 0); 3301 } 3302 3303 QualType ASTContext::getDecayedType(QualType T) const { 3304 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3305 3306 QualType Decayed; 3307 3308 // C99 6.7.5.3p7: 3309 // A declaration of a parameter as "array of type" shall be 3310 // adjusted to "qualified pointer to type", where the type 3311 // qualifiers (if any) are those specified within the [ and ] of 3312 // the array type derivation. 3313 if (T->isArrayType()) 3314 Decayed = getArrayDecayedType(T); 3315 3316 // C99 6.7.5.3p8: 3317 // A declaration of a parameter as "function returning type" 3318 // shall be adjusted to "pointer to function returning type", as 3319 // in 6.3.2.1. 3320 if (T->isFunctionType()) 3321 Decayed = getPointerType(T); 3322 3323 llvm::FoldingSetNodeID ID; 3324 AdjustedType::Profile(ID, T, Decayed); 3325 void *InsertPos = nullptr; 3326 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3327 if (AT) 3328 return QualType(AT, 0); 3329 3330 QualType Canonical = getCanonicalType(Decayed); 3331 3332 // Get the new insert position for the node we care about. 3333 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3334 assert(!AT && "Shouldn't be in the map!"); 3335 3336 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3337 Types.push_back(AT); 3338 AdjustedTypes.InsertNode(AT, InsertPos); 3339 return QualType(AT, 0); 3340 } 3341 3342 /// getBlockPointerType - Return the uniqued reference to the type for 3343 /// a pointer to the specified block. 3344 QualType ASTContext::getBlockPointerType(QualType T) const { 3345 assert(T->isFunctionType() && "block of function types only"); 3346 // Unique pointers, to guarantee there is only one block of a particular 3347 // structure. 3348 llvm::FoldingSetNodeID ID; 3349 BlockPointerType::Profile(ID, T); 3350 3351 void *InsertPos = nullptr; 3352 if (BlockPointerType *PT = 3353 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3354 return QualType(PT, 0); 3355 3356 // If the block pointee type isn't canonical, this won't be a canonical 3357 // type either so fill in the canonical type field. 3358 QualType Canonical; 3359 if (!T.isCanonical()) { 3360 Canonical = getBlockPointerType(getCanonicalType(T)); 3361 3362 // Get the new insert position for the node we care about. 3363 BlockPointerType *NewIP = 3364 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3365 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3366 } 3367 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3368 Types.push_back(New); 3369 BlockPointerTypes.InsertNode(New, InsertPos); 3370 return QualType(New, 0); 3371 } 3372 3373 /// getLValueReferenceType - Return the uniqued reference to the type for an 3374 /// lvalue reference to the specified type. 3375 QualType 3376 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3377 assert((!T->isPlaceholderType() || 3378 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3379 "Unresolved placeholder type"); 3380 3381 // Unique pointers, to guarantee there is only one pointer of a particular 3382 // structure. 3383 llvm::FoldingSetNodeID ID; 3384 ReferenceType::Profile(ID, T, SpelledAsLValue); 3385 3386 void *InsertPos = nullptr; 3387 if (LValueReferenceType *RT = 3388 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3389 return QualType(RT, 0); 3390 3391 const auto *InnerRef = T->getAs<ReferenceType>(); 3392 3393 // If the referencee type isn't canonical, this won't be a canonical type 3394 // either, so fill in the canonical type field. 3395 QualType Canonical; 3396 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3397 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3398 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3399 3400 // Get the new insert position for the node we care about. 3401 LValueReferenceType *NewIP = 3402 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3403 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3404 } 3405 3406 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3407 SpelledAsLValue); 3408 Types.push_back(New); 3409 LValueReferenceTypes.InsertNode(New, InsertPos); 3410 3411 return QualType(New, 0); 3412 } 3413 3414 /// getRValueReferenceType - Return the uniqued reference to the type for an 3415 /// rvalue reference to the specified type. 3416 QualType ASTContext::getRValueReferenceType(QualType T) const { 3417 assert((!T->isPlaceholderType() || 3418 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && 3419 "Unresolved placeholder type"); 3420 3421 // Unique pointers, to guarantee there is only one pointer of a particular 3422 // structure. 3423 llvm::FoldingSetNodeID ID; 3424 ReferenceType::Profile(ID, T, false); 3425 3426 void *InsertPos = nullptr; 3427 if (RValueReferenceType *RT = 3428 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3429 return QualType(RT, 0); 3430 3431 const auto *InnerRef = T->getAs<ReferenceType>(); 3432 3433 // If the referencee type isn't canonical, this won't be a canonical type 3434 // either, so fill in the canonical type field. 3435 QualType Canonical; 3436 if (InnerRef || !T.isCanonical()) { 3437 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3438 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3439 3440 // Get the new insert position for the node we care about. 3441 RValueReferenceType *NewIP = 3442 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3443 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3444 } 3445 3446 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3447 Types.push_back(New); 3448 RValueReferenceTypes.InsertNode(New, InsertPos); 3449 return QualType(New, 0); 3450 } 3451 3452 /// getMemberPointerType - Return the uniqued reference to the type for a 3453 /// member pointer to the specified type, in the specified class. 3454 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3455 // Unique pointers, to guarantee there is only one pointer of a particular 3456 // structure. 3457 llvm::FoldingSetNodeID ID; 3458 MemberPointerType::Profile(ID, T, Cls); 3459 3460 void *InsertPos = nullptr; 3461 if (MemberPointerType *PT = 3462 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3463 return QualType(PT, 0); 3464 3465 // If the pointee or class type isn't canonical, this won't be a canonical 3466 // type either, so fill in the canonical type field. 3467 QualType Canonical; 3468 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3469 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3470 3471 // Get the new insert position for the node we care about. 3472 MemberPointerType *NewIP = 3473 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3474 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3475 } 3476 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3477 Types.push_back(New); 3478 MemberPointerTypes.InsertNode(New, InsertPos); 3479 return QualType(New, 0); 3480 } 3481 3482 /// getConstantArrayType - Return the unique reference to the type for an 3483 /// array of the specified element type. 3484 QualType ASTContext::getConstantArrayType(QualType EltTy, 3485 const llvm::APInt &ArySizeIn, 3486 const Expr *SizeExpr, 3487 ArrayType::ArraySizeModifier ASM, 3488 unsigned IndexTypeQuals) const { 3489 assert((EltTy->isDependentType() || 3490 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3491 "Constant array of VLAs is illegal!"); 3492 3493 // We only need the size as part of the type if it's instantiation-dependent. 3494 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3495 SizeExpr = nullptr; 3496 3497 // Convert the array size into a canonical width matching the pointer size for 3498 // the target. 3499 llvm::APInt ArySize(ArySizeIn); 3500 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3501 3502 llvm::FoldingSetNodeID ID; 3503 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3504 IndexTypeQuals); 3505 3506 void *InsertPos = nullptr; 3507 if (ConstantArrayType *ATP = 3508 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3509 return QualType(ATP, 0); 3510 3511 // If the element type isn't canonical or has qualifiers, or the array bound 3512 // is instantiation-dependent, this won't be a canonical type either, so fill 3513 // in the canonical type field. 3514 QualType Canon; 3515 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3516 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3517 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3518 ASM, IndexTypeQuals); 3519 Canon = getQualifiedType(Canon, canonSplit.Quals); 3520 3521 // Get the new insert position for the node we care about. 3522 ConstantArrayType *NewIP = 3523 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3524 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3525 } 3526 3527 void *Mem = Allocate( 3528 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3529 TypeAlignment); 3530 auto *New = new (Mem) 3531 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3532 ConstantArrayTypes.InsertNode(New, InsertPos); 3533 Types.push_back(New); 3534 return QualType(New, 0); 3535 } 3536 3537 /// getVariableArrayDecayedType - Turns the given type, which may be 3538 /// variably-modified, into the corresponding type with all the known 3539 /// sizes replaced with [*]. 3540 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3541 // Vastly most common case. 3542 if (!type->isVariablyModifiedType()) return type; 3543 3544 QualType result; 3545 3546 SplitQualType split = type.getSplitDesugaredType(); 3547 const Type *ty = split.Ty; 3548 switch (ty->getTypeClass()) { 3549 #define TYPE(Class, Base) 3550 #define ABSTRACT_TYPE(Class, Base) 3551 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3552 #include "clang/AST/TypeNodes.inc" 3553 llvm_unreachable("didn't desugar past all non-canonical types?"); 3554 3555 // These types should never be variably-modified. 3556 case Type::Builtin: 3557 case Type::Complex: 3558 case Type::Vector: 3559 case Type::DependentVector: 3560 case Type::ExtVector: 3561 case Type::DependentSizedExtVector: 3562 case Type::ConstantMatrix: 3563 case Type::DependentSizedMatrix: 3564 case Type::DependentAddressSpace: 3565 case Type::ObjCObject: 3566 case Type::ObjCInterface: 3567 case Type::ObjCObjectPointer: 3568 case Type::Record: 3569 case Type::Enum: 3570 case Type::UnresolvedUsing: 3571 case Type::TypeOfExpr: 3572 case Type::TypeOf: 3573 case Type::Decltype: 3574 case Type::UnaryTransform: 3575 case Type::DependentName: 3576 case Type::InjectedClassName: 3577 case Type::TemplateSpecialization: 3578 case Type::DependentTemplateSpecialization: 3579 case Type::TemplateTypeParm: 3580 case Type::SubstTemplateTypeParmPack: 3581 case Type::Auto: 3582 case Type::DeducedTemplateSpecialization: 3583 case Type::PackExpansion: 3584 case Type::BitInt: 3585 case Type::DependentBitInt: 3586 llvm_unreachable("type should never be variably-modified"); 3587 3588 // These types can be variably-modified but should never need to 3589 // further decay. 3590 case Type::FunctionNoProto: 3591 case Type::FunctionProto: 3592 case Type::BlockPointer: 3593 case Type::MemberPointer: 3594 case Type::Pipe: 3595 return type; 3596 3597 // These types can be variably-modified. All these modifications 3598 // preserve structure except as noted by comments. 3599 // TODO: if we ever care about optimizing VLAs, there are no-op 3600 // optimizations available here. 3601 case Type::Pointer: 3602 result = getPointerType(getVariableArrayDecayedType( 3603 cast<PointerType>(ty)->getPointeeType())); 3604 break; 3605 3606 case Type::LValueReference: { 3607 const auto *lv = cast<LValueReferenceType>(ty); 3608 result = getLValueReferenceType( 3609 getVariableArrayDecayedType(lv->getPointeeType()), 3610 lv->isSpelledAsLValue()); 3611 break; 3612 } 3613 3614 case Type::RValueReference: { 3615 const auto *lv = cast<RValueReferenceType>(ty); 3616 result = getRValueReferenceType( 3617 getVariableArrayDecayedType(lv->getPointeeType())); 3618 break; 3619 } 3620 3621 case Type::Atomic: { 3622 const auto *at = cast<AtomicType>(ty); 3623 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3624 break; 3625 } 3626 3627 case Type::ConstantArray: { 3628 const auto *cat = cast<ConstantArrayType>(ty); 3629 result = getConstantArrayType( 3630 getVariableArrayDecayedType(cat->getElementType()), 3631 cat->getSize(), 3632 cat->getSizeExpr(), 3633 cat->getSizeModifier(), 3634 cat->getIndexTypeCVRQualifiers()); 3635 break; 3636 } 3637 3638 case Type::DependentSizedArray: { 3639 const auto *dat = cast<DependentSizedArrayType>(ty); 3640 result = getDependentSizedArrayType( 3641 getVariableArrayDecayedType(dat->getElementType()), 3642 dat->getSizeExpr(), 3643 dat->getSizeModifier(), 3644 dat->getIndexTypeCVRQualifiers(), 3645 dat->getBracketsRange()); 3646 break; 3647 } 3648 3649 // Turn incomplete types into [*] types. 3650 case Type::IncompleteArray: { 3651 const auto *iat = cast<IncompleteArrayType>(ty); 3652 result = getVariableArrayType( 3653 getVariableArrayDecayedType(iat->getElementType()), 3654 /*size*/ nullptr, 3655 ArrayType::Normal, 3656 iat->getIndexTypeCVRQualifiers(), 3657 SourceRange()); 3658 break; 3659 } 3660 3661 // Turn VLA types into [*] types. 3662 case Type::VariableArray: { 3663 const auto *vat = cast<VariableArrayType>(ty); 3664 result = getVariableArrayType( 3665 getVariableArrayDecayedType(vat->getElementType()), 3666 /*size*/ nullptr, 3667 ArrayType::Star, 3668 vat->getIndexTypeCVRQualifiers(), 3669 vat->getBracketsRange()); 3670 break; 3671 } 3672 } 3673 3674 // Apply the top-level qualifiers from the original. 3675 return getQualifiedType(result, split.Quals); 3676 } 3677 3678 /// getVariableArrayType - Returns a non-unique reference to the type for a 3679 /// variable array of the specified element type. 3680 QualType ASTContext::getVariableArrayType(QualType EltTy, 3681 Expr *NumElts, 3682 ArrayType::ArraySizeModifier ASM, 3683 unsigned IndexTypeQuals, 3684 SourceRange Brackets) const { 3685 // Since we don't unique expressions, it isn't possible to unique VLA's 3686 // that have an expression provided for their size. 3687 QualType Canon; 3688 3689 // Be sure to pull qualifiers off the element type. 3690 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3691 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3692 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3693 IndexTypeQuals, Brackets); 3694 Canon = getQualifiedType(Canon, canonSplit.Quals); 3695 } 3696 3697 auto *New = new (*this, TypeAlignment) 3698 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3699 3700 VariableArrayTypes.push_back(New); 3701 Types.push_back(New); 3702 return QualType(New, 0); 3703 } 3704 3705 /// getDependentSizedArrayType - Returns a non-unique reference to 3706 /// the type for a dependently-sized array of the specified element 3707 /// type. 3708 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3709 Expr *numElements, 3710 ArrayType::ArraySizeModifier ASM, 3711 unsigned elementTypeQuals, 3712 SourceRange brackets) const { 3713 assert((!numElements || numElements->isTypeDependent() || 3714 numElements->isValueDependent()) && 3715 "Size must be type- or value-dependent!"); 3716 3717 // Dependently-sized array types that do not have a specified number 3718 // of elements will have their sizes deduced from a dependent 3719 // initializer. We do no canonicalization here at all, which is okay 3720 // because they can't be used in most locations. 3721 if (!numElements) { 3722 auto *newType 3723 = new (*this, TypeAlignment) 3724 DependentSizedArrayType(*this, elementType, QualType(), 3725 numElements, ASM, elementTypeQuals, 3726 brackets); 3727 Types.push_back(newType); 3728 return QualType(newType, 0); 3729 } 3730 3731 // Otherwise, we actually build a new type every time, but we 3732 // also build a canonical type. 3733 3734 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3735 3736 void *insertPos = nullptr; 3737 llvm::FoldingSetNodeID ID; 3738 DependentSizedArrayType::Profile(ID, *this, 3739 QualType(canonElementType.Ty, 0), 3740 ASM, elementTypeQuals, numElements); 3741 3742 // Look for an existing type with these properties. 3743 DependentSizedArrayType *canonTy = 3744 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3745 3746 // If we don't have one, build one. 3747 if (!canonTy) { 3748 canonTy = new (*this, TypeAlignment) 3749 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3750 QualType(), numElements, ASM, elementTypeQuals, 3751 brackets); 3752 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3753 Types.push_back(canonTy); 3754 } 3755 3756 // Apply qualifiers from the element type to the array. 3757 QualType canon = getQualifiedType(QualType(canonTy,0), 3758 canonElementType.Quals); 3759 3760 // If we didn't need extra canonicalization for the element type or the size 3761 // expression, then just use that as our result. 3762 if (QualType(canonElementType.Ty, 0) == elementType && 3763 canonTy->getSizeExpr() == numElements) 3764 return canon; 3765 3766 // Otherwise, we need to build a type which follows the spelling 3767 // of the element type. 3768 auto *sugaredType 3769 = new (*this, TypeAlignment) 3770 DependentSizedArrayType(*this, elementType, canon, numElements, 3771 ASM, elementTypeQuals, brackets); 3772 Types.push_back(sugaredType); 3773 return QualType(sugaredType, 0); 3774 } 3775 3776 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3777 ArrayType::ArraySizeModifier ASM, 3778 unsigned elementTypeQuals) const { 3779 llvm::FoldingSetNodeID ID; 3780 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3781 3782 void *insertPos = nullptr; 3783 if (IncompleteArrayType *iat = 3784 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3785 return QualType(iat, 0); 3786 3787 // If the element type isn't canonical, this won't be a canonical type 3788 // either, so fill in the canonical type field. We also have to pull 3789 // qualifiers off the element type. 3790 QualType canon; 3791 3792 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3793 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3794 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3795 ASM, elementTypeQuals); 3796 canon = getQualifiedType(canon, canonSplit.Quals); 3797 3798 // Get the new insert position for the node we care about. 3799 IncompleteArrayType *existing = 3800 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3801 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3802 } 3803 3804 auto *newType = new (*this, TypeAlignment) 3805 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3806 3807 IncompleteArrayTypes.InsertNode(newType, insertPos); 3808 Types.push_back(newType); 3809 return QualType(newType, 0); 3810 } 3811 3812 ASTContext::BuiltinVectorTypeInfo 3813 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3814 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3815 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3816 NUMVECTORS}; 3817 3818 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3819 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3820 3821 switch (Ty->getKind()) { 3822 default: 3823 llvm_unreachable("Unsupported builtin vector type"); 3824 case BuiltinType::SveInt8: 3825 return SVE_INT_ELTTY(8, 16, true, 1); 3826 case BuiltinType::SveUint8: 3827 return SVE_INT_ELTTY(8, 16, false, 1); 3828 case BuiltinType::SveInt8x2: 3829 return SVE_INT_ELTTY(8, 16, true, 2); 3830 case BuiltinType::SveUint8x2: 3831 return SVE_INT_ELTTY(8, 16, false, 2); 3832 case BuiltinType::SveInt8x3: 3833 return SVE_INT_ELTTY(8, 16, true, 3); 3834 case BuiltinType::SveUint8x3: 3835 return SVE_INT_ELTTY(8, 16, false, 3); 3836 case BuiltinType::SveInt8x4: 3837 return SVE_INT_ELTTY(8, 16, true, 4); 3838 case BuiltinType::SveUint8x4: 3839 return SVE_INT_ELTTY(8, 16, false, 4); 3840 case BuiltinType::SveInt16: 3841 return SVE_INT_ELTTY(16, 8, true, 1); 3842 case BuiltinType::SveUint16: 3843 return SVE_INT_ELTTY(16, 8, false, 1); 3844 case BuiltinType::SveInt16x2: 3845 return SVE_INT_ELTTY(16, 8, true, 2); 3846 case BuiltinType::SveUint16x2: 3847 return SVE_INT_ELTTY(16, 8, false, 2); 3848 case BuiltinType::SveInt16x3: 3849 return SVE_INT_ELTTY(16, 8, true, 3); 3850 case BuiltinType::SveUint16x3: 3851 return SVE_INT_ELTTY(16, 8, false, 3); 3852 case BuiltinType::SveInt16x4: 3853 return SVE_INT_ELTTY(16, 8, true, 4); 3854 case BuiltinType::SveUint16x4: 3855 return SVE_INT_ELTTY(16, 8, false, 4); 3856 case BuiltinType::SveInt32: 3857 return SVE_INT_ELTTY(32, 4, true, 1); 3858 case BuiltinType::SveUint32: 3859 return SVE_INT_ELTTY(32, 4, false, 1); 3860 case BuiltinType::SveInt32x2: 3861 return SVE_INT_ELTTY(32, 4, true, 2); 3862 case BuiltinType::SveUint32x2: 3863 return SVE_INT_ELTTY(32, 4, false, 2); 3864 case BuiltinType::SveInt32x3: 3865 return SVE_INT_ELTTY(32, 4, true, 3); 3866 case BuiltinType::SveUint32x3: 3867 return SVE_INT_ELTTY(32, 4, false, 3); 3868 case BuiltinType::SveInt32x4: 3869 return SVE_INT_ELTTY(32, 4, true, 4); 3870 case BuiltinType::SveUint32x4: 3871 return SVE_INT_ELTTY(32, 4, false, 4); 3872 case BuiltinType::SveInt64: 3873 return SVE_INT_ELTTY(64, 2, true, 1); 3874 case BuiltinType::SveUint64: 3875 return SVE_INT_ELTTY(64, 2, false, 1); 3876 case BuiltinType::SveInt64x2: 3877 return SVE_INT_ELTTY(64, 2, true, 2); 3878 case BuiltinType::SveUint64x2: 3879 return SVE_INT_ELTTY(64, 2, false, 2); 3880 case BuiltinType::SveInt64x3: 3881 return SVE_INT_ELTTY(64, 2, true, 3); 3882 case BuiltinType::SveUint64x3: 3883 return SVE_INT_ELTTY(64, 2, false, 3); 3884 case BuiltinType::SveInt64x4: 3885 return SVE_INT_ELTTY(64, 2, true, 4); 3886 case BuiltinType::SveUint64x4: 3887 return SVE_INT_ELTTY(64, 2, false, 4); 3888 case BuiltinType::SveBool: 3889 return SVE_ELTTY(BoolTy, 16, 1); 3890 case BuiltinType::SveFloat16: 3891 return SVE_ELTTY(HalfTy, 8, 1); 3892 case BuiltinType::SveFloat16x2: 3893 return SVE_ELTTY(HalfTy, 8, 2); 3894 case BuiltinType::SveFloat16x3: 3895 return SVE_ELTTY(HalfTy, 8, 3); 3896 case BuiltinType::SveFloat16x4: 3897 return SVE_ELTTY(HalfTy, 8, 4); 3898 case BuiltinType::SveFloat32: 3899 return SVE_ELTTY(FloatTy, 4, 1); 3900 case BuiltinType::SveFloat32x2: 3901 return SVE_ELTTY(FloatTy, 4, 2); 3902 case BuiltinType::SveFloat32x3: 3903 return SVE_ELTTY(FloatTy, 4, 3); 3904 case BuiltinType::SveFloat32x4: 3905 return SVE_ELTTY(FloatTy, 4, 4); 3906 case BuiltinType::SveFloat64: 3907 return SVE_ELTTY(DoubleTy, 2, 1); 3908 case BuiltinType::SveFloat64x2: 3909 return SVE_ELTTY(DoubleTy, 2, 2); 3910 case BuiltinType::SveFloat64x3: 3911 return SVE_ELTTY(DoubleTy, 2, 3); 3912 case BuiltinType::SveFloat64x4: 3913 return SVE_ELTTY(DoubleTy, 2, 4); 3914 case BuiltinType::SveBFloat16: 3915 return SVE_ELTTY(BFloat16Ty, 8, 1); 3916 case BuiltinType::SveBFloat16x2: 3917 return SVE_ELTTY(BFloat16Ty, 8, 2); 3918 case BuiltinType::SveBFloat16x3: 3919 return SVE_ELTTY(BFloat16Ty, 8, 3); 3920 case BuiltinType::SveBFloat16x4: 3921 return SVE_ELTTY(BFloat16Ty, 8, 4); 3922 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3923 IsSigned) \ 3924 case BuiltinType::Id: \ 3925 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3926 llvm::ElementCount::getScalable(NumEls), NF}; 3927 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3928 case BuiltinType::Id: \ 3929 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3930 llvm::ElementCount::getScalable(NumEls), NF}; 3931 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3932 case BuiltinType::Id: \ 3933 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3934 #include "clang/Basic/RISCVVTypes.def" 3935 } 3936 } 3937 3938 /// getScalableVectorType - Return the unique reference to a scalable vector 3939 /// type of the specified element type and size. VectorType must be a built-in 3940 /// type. 3941 QualType ASTContext::getScalableVectorType(QualType EltTy, 3942 unsigned NumElts) const { 3943 if (Target->hasAArch64SVETypes()) { 3944 uint64_t EltTySize = getTypeSize(EltTy); 3945 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3946 IsSigned, IsFP, IsBF) \ 3947 if (!EltTy->isBooleanType() && \ 3948 ((EltTy->hasIntegerRepresentation() && \ 3949 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3950 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3951 IsFP && !IsBF) || \ 3952 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3953 IsBF && !IsFP)) && \ 3954 EltTySize == ElBits && NumElts == NumEls) { \ 3955 return SingletonId; \ 3956 } 3957 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3958 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3959 return SingletonId; 3960 #include "clang/Basic/AArch64SVEACLETypes.def" 3961 } else if (Target->hasRISCVVTypes()) { 3962 uint64_t EltTySize = getTypeSize(EltTy); 3963 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3964 IsFP) \ 3965 if (!EltTy->isBooleanType() && \ 3966 ((EltTy->hasIntegerRepresentation() && \ 3967 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3968 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3969 EltTySize == ElBits && NumElts == NumEls) \ 3970 return SingletonId; 3971 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3972 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3973 return SingletonId; 3974 #include "clang/Basic/RISCVVTypes.def" 3975 } 3976 return QualType(); 3977 } 3978 3979 /// getVectorType - Return the unique reference to a vector type of 3980 /// the specified element type and size. VectorType must be a built-in type. 3981 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3982 VectorType::VectorKind VecKind) const { 3983 assert(vecType->isBuiltinType()); 3984 3985 // Check if we've already instantiated a vector of this type. 3986 llvm::FoldingSetNodeID ID; 3987 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3988 3989 void *InsertPos = nullptr; 3990 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3991 return QualType(VTP, 0); 3992 3993 // If the element type isn't canonical, this won't be a canonical type either, 3994 // so fill in the canonical type field. 3995 QualType Canonical; 3996 if (!vecType.isCanonical()) { 3997 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3998 3999 // Get the new insert position for the node we care about. 4000 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4001 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4002 } 4003 auto *New = new (*this, TypeAlignment) 4004 VectorType(vecType, NumElts, Canonical, VecKind); 4005 VectorTypes.InsertNode(New, InsertPos); 4006 Types.push_back(New); 4007 return QualType(New, 0); 4008 } 4009 4010 QualType 4011 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 4012 SourceLocation AttrLoc, 4013 VectorType::VectorKind VecKind) const { 4014 llvm::FoldingSetNodeID ID; 4015 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 4016 VecKind); 4017 void *InsertPos = nullptr; 4018 DependentVectorType *Canon = 4019 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4020 DependentVectorType *New; 4021 4022 if (Canon) { 4023 New = new (*this, TypeAlignment) DependentVectorType( 4024 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 4025 } else { 4026 QualType CanonVecTy = getCanonicalType(VecType); 4027 if (CanonVecTy == VecType) { 4028 New = new (*this, TypeAlignment) DependentVectorType( 4029 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 4030 4031 DependentVectorType *CanonCheck = 4032 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4033 assert(!CanonCheck && 4034 "Dependent-sized vector_size canonical type broken"); 4035 (void)CanonCheck; 4036 DependentVectorTypes.InsertNode(New, InsertPos); 4037 } else { 4038 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 4039 SourceLocation(), VecKind); 4040 New = new (*this, TypeAlignment) DependentVectorType( 4041 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 4042 } 4043 } 4044 4045 Types.push_back(New); 4046 return QualType(New, 0); 4047 } 4048 4049 /// getExtVectorType - Return the unique reference to an extended vector type of 4050 /// the specified element type and size. VectorType must be a built-in type. 4051 QualType 4052 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4053 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4054 4055 // Check if we've already instantiated a vector of this type. 4056 llvm::FoldingSetNodeID ID; 4057 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4058 VectorType::GenericVector); 4059 void *InsertPos = nullptr; 4060 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4061 return QualType(VTP, 0); 4062 4063 // If the element type isn't canonical, this won't be a canonical type either, 4064 // so fill in the canonical type field. 4065 QualType Canonical; 4066 if (!vecType.isCanonical()) { 4067 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4068 4069 // Get the new insert position for the node we care about. 4070 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4071 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4072 } 4073 auto *New = new (*this, TypeAlignment) 4074 ExtVectorType(vecType, NumElts, Canonical); 4075 VectorTypes.InsertNode(New, InsertPos); 4076 Types.push_back(New); 4077 return QualType(New, 0); 4078 } 4079 4080 QualType 4081 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4082 Expr *SizeExpr, 4083 SourceLocation AttrLoc) const { 4084 llvm::FoldingSetNodeID ID; 4085 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4086 SizeExpr); 4087 4088 void *InsertPos = nullptr; 4089 DependentSizedExtVectorType *Canon 4090 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4091 DependentSizedExtVectorType *New; 4092 if (Canon) { 4093 // We already have a canonical version of this array type; use it as 4094 // the canonical type for a newly-built type. 4095 New = new (*this, TypeAlignment) 4096 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4097 SizeExpr, AttrLoc); 4098 } else { 4099 QualType CanonVecTy = getCanonicalType(vecType); 4100 if (CanonVecTy == vecType) { 4101 New = new (*this, TypeAlignment) 4102 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4103 AttrLoc); 4104 4105 DependentSizedExtVectorType *CanonCheck 4106 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4107 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4108 (void)CanonCheck; 4109 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4110 } else { 4111 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4112 SourceLocation()); 4113 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4114 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4115 } 4116 } 4117 4118 Types.push_back(New); 4119 return QualType(New, 0); 4120 } 4121 4122 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4123 unsigned NumColumns) const { 4124 llvm::FoldingSetNodeID ID; 4125 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4126 Type::ConstantMatrix); 4127 4128 assert(MatrixType::isValidElementType(ElementTy) && 4129 "need a valid element type"); 4130 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4131 ConstantMatrixType::isDimensionValid(NumColumns) && 4132 "need valid matrix dimensions"); 4133 void *InsertPos = nullptr; 4134 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4135 return QualType(MTP, 0); 4136 4137 QualType Canonical; 4138 if (!ElementTy.isCanonical()) { 4139 Canonical = 4140 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4141 4142 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4143 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4144 (void)NewIP; 4145 } 4146 4147 auto *New = new (*this, TypeAlignment) 4148 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4149 MatrixTypes.InsertNode(New, InsertPos); 4150 Types.push_back(New); 4151 return QualType(New, 0); 4152 } 4153 4154 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4155 Expr *RowExpr, 4156 Expr *ColumnExpr, 4157 SourceLocation AttrLoc) const { 4158 QualType CanonElementTy = getCanonicalType(ElementTy); 4159 llvm::FoldingSetNodeID ID; 4160 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4161 ColumnExpr); 4162 4163 void *InsertPos = nullptr; 4164 DependentSizedMatrixType *Canon = 4165 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4166 4167 if (!Canon) { 4168 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4169 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4170 #ifndef NDEBUG 4171 DependentSizedMatrixType *CanonCheck = 4172 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4173 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4174 #endif 4175 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4176 Types.push_back(Canon); 4177 } 4178 4179 // Already have a canonical version of the matrix type 4180 // 4181 // If it exactly matches the requested type, use it directly. 4182 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4183 Canon->getRowExpr() == ColumnExpr) 4184 return QualType(Canon, 0); 4185 4186 // Use Canon as the canonical type for newly-built type. 4187 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4188 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4189 ColumnExpr, AttrLoc); 4190 Types.push_back(New); 4191 return QualType(New, 0); 4192 } 4193 4194 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4195 Expr *AddrSpaceExpr, 4196 SourceLocation AttrLoc) const { 4197 assert(AddrSpaceExpr->isInstantiationDependent()); 4198 4199 QualType canonPointeeType = getCanonicalType(PointeeType); 4200 4201 void *insertPos = nullptr; 4202 llvm::FoldingSetNodeID ID; 4203 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4204 AddrSpaceExpr); 4205 4206 DependentAddressSpaceType *canonTy = 4207 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4208 4209 if (!canonTy) { 4210 canonTy = new (*this, TypeAlignment) 4211 DependentAddressSpaceType(*this, canonPointeeType, 4212 QualType(), AddrSpaceExpr, AttrLoc); 4213 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4214 Types.push_back(canonTy); 4215 } 4216 4217 if (canonPointeeType == PointeeType && 4218 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4219 return QualType(canonTy, 0); 4220 4221 auto *sugaredType 4222 = new (*this, TypeAlignment) 4223 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4224 AddrSpaceExpr, AttrLoc); 4225 Types.push_back(sugaredType); 4226 return QualType(sugaredType, 0); 4227 } 4228 4229 /// Determine whether \p T is canonical as the result type of a function. 4230 static bool isCanonicalResultType(QualType T) { 4231 return T.isCanonical() && 4232 (T.getObjCLifetime() == Qualifiers::OCL_None || 4233 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4234 } 4235 4236 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4237 QualType 4238 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4239 const FunctionType::ExtInfo &Info) const { 4240 // Unique functions, to guarantee there is only one function of a particular 4241 // structure. 4242 llvm::FoldingSetNodeID ID; 4243 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4244 4245 void *InsertPos = nullptr; 4246 if (FunctionNoProtoType *FT = 4247 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4248 return QualType(FT, 0); 4249 4250 QualType Canonical; 4251 if (!isCanonicalResultType(ResultTy)) { 4252 Canonical = 4253 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4254 4255 // Get the new insert position for the node we care about. 4256 FunctionNoProtoType *NewIP = 4257 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4258 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4259 } 4260 4261 auto *New = new (*this, TypeAlignment) 4262 FunctionNoProtoType(ResultTy, Canonical, Info); 4263 Types.push_back(New); 4264 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4265 return QualType(New, 0); 4266 } 4267 4268 CanQualType 4269 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4270 CanQualType CanResultType = getCanonicalType(ResultType); 4271 4272 // Canonical result types do not have ARC lifetime qualifiers. 4273 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4274 Qualifiers Qs = CanResultType.getQualifiers(); 4275 Qs.removeObjCLifetime(); 4276 return CanQualType::CreateUnsafe( 4277 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4278 } 4279 4280 return CanResultType; 4281 } 4282 4283 static bool isCanonicalExceptionSpecification( 4284 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4285 if (ESI.Type == EST_None) 4286 return true; 4287 if (!NoexceptInType) 4288 return false; 4289 4290 // C++17 onwards: exception specification is part of the type, as a simple 4291 // boolean "can this function type throw". 4292 if (ESI.Type == EST_BasicNoexcept) 4293 return true; 4294 4295 // A noexcept(expr) specification is (possibly) canonical if expr is 4296 // value-dependent. 4297 if (ESI.Type == EST_DependentNoexcept) 4298 return true; 4299 4300 // A dynamic exception specification is canonical if it only contains pack 4301 // expansions (so we can't tell whether it's non-throwing) and all its 4302 // contained types are canonical. 4303 if (ESI.Type == EST_Dynamic) { 4304 bool AnyPackExpansions = false; 4305 for (QualType ET : ESI.Exceptions) { 4306 if (!ET.isCanonical()) 4307 return false; 4308 if (ET->getAs<PackExpansionType>()) 4309 AnyPackExpansions = true; 4310 } 4311 return AnyPackExpansions; 4312 } 4313 4314 return false; 4315 } 4316 4317 QualType ASTContext::getFunctionTypeInternal( 4318 QualType ResultTy, ArrayRef<QualType> ArgArray, 4319 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4320 size_t NumArgs = ArgArray.size(); 4321 4322 // Unique functions, to guarantee there is only one function of a particular 4323 // structure. 4324 llvm::FoldingSetNodeID ID; 4325 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4326 *this, true); 4327 4328 QualType Canonical; 4329 bool Unique = false; 4330 4331 void *InsertPos = nullptr; 4332 if (FunctionProtoType *FPT = 4333 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4334 QualType Existing = QualType(FPT, 0); 4335 4336 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4337 // it so long as our exception specification doesn't contain a dependent 4338 // noexcept expression, or we're just looking for a canonical type. 4339 // Otherwise, we're going to need to create a type 4340 // sugar node to hold the concrete expression. 4341 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4342 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4343 return Existing; 4344 4345 // We need a new type sugar node for this one, to hold the new noexcept 4346 // expression. We do no canonicalization here, but that's OK since we don't 4347 // expect to see the same noexcept expression much more than once. 4348 Canonical = getCanonicalType(Existing); 4349 Unique = true; 4350 } 4351 4352 bool NoexceptInType = getLangOpts().CPlusPlus17; 4353 bool IsCanonicalExceptionSpec = 4354 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4355 4356 // Determine whether the type being created is already canonical or not. 4357 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4358 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4359 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4360 if (!ArgArray[i].isCanonicalAsParam()) 4361 isCanonical = false; 4362 4363 if (OnlyWantCanonical) 4364 assert(isCanonical && 4365 "given non-canonical parameters constructing canonical type"); 4366 4367 // If this type isn't canonical, get the canonical version of it if we don't 4368 // already have it. The exception spec is only partially part of the 4369 // canonical type, and only in C++17 onwards. 4370 if (!isCanonical && Canonical.isNull()) { 4371 SmallVector<QualType, 16> CanonicalArgs; 4372 CanonicalArgs.reserve(NumArgs); 4373 for (unsigned i = 0; i != NumArgs; ++i) 4374 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4375 4376 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4377 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4378 CanonicalEPI.HasTrailingReturn = false; 4379 4380 if (IsCanonicalExceptionSpec) { 4381 // Exception spec is already OK. 4382 } else if (NoexceptInType) { 4383 switch (EPI.ExceptionSpec.Type) { 4384 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4385 // We don't know yet. It shouldn't matter what we pick here; no-one 4386 // should ever look at this. 4387 LLVM_FALLTHROUGH; 4388 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4389 CanonicalEPI.ExceptionSpec.Type = EST_None; 4390 break; 4391 4392 // A dynamic exception specification is almost always "not noexcept", 4393 // with the exception that a pack expansion might expand to no types. 4394 case EST_Dynamic: { 4395 bool AnyPacks = false; 4396 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4397 if (ET->getAs<PackExpansionType>()) 4398 AnyPacks = true; 4399 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4400 } 4401 if (!AnyPacks) 4402 CanonicalEPI.ExceptionSpec.Type = EST_None; 4403 else { 4404 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4405 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4406 } 4407 break; 4408 } 4409 4410 case EST_DynamicNone: 4411 case EST_BasicNoexcept: 4412 case EST_NoexceptTrue: 4413 case EST_NoThrow: 4414 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4415 break; 4416 4417 case EST_DependentNoexcept: 4418 llvm_unreachable("dependent noexcept is already canonical"); 4419 } 4420 } else { 4421 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4422 } 4423 4424 // Adjust the canonical function result type. 4425 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4426 Canonical = 4427 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4428 4429 // Get the new insert position for the node we care about. 4430 FunctionProtoType *NewIP = 4431 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4432 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4433 } 4434 4435 // Compute the needed size to hold this FunctionProtoType and the 4436 // various trailing objects. 4437 auto ESH = FunctionProtoType::getExceptionSpecSize( 4438 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4439 size_t Size = FunctionProtoType::totalSizeToAlloc< 4440 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4441 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4442 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4443 NumArgs, EPI.Variadic, 4444 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4445 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4446 EPI.ExtParameterInfos ? NumArgs : 0, 4447 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4448 4449 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4450 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4451 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4452 Types.push_back(FTP); 4453 if (!Unique) 4454 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4455 return QualType(FTP, 0); 4456 } 4457 4458 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4459 llvm::FoldingSetNodeID ID; 4460 PipeType::Profile(ID, T, ReadOnly); 4461 4462 void *InsertPos = nullptr; 4463 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4464 return QualType(PT, 0); 4465 4466 // If the pipe element type isn't canonical, this won't be a canonical type 4467 // either, so fill in the canonical type field. 4468 QualType Canonical; 4469 if (!T.isCanonical()) { 4470 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4471 4472 // Get the new insert position for the node we care about. 4473 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4474 assert(!NewIP && "Shouldn't be in the map!"); 4475 (void)NewIP; 4476 } 4477 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4478 Types.push_back(New); 4479 PipeTypes.InsertNode(New, InsertPos); 4480 return QualType(New, 0); 4481 } 4482 4483 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4484 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4485 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4486 : Ty; 4487 } 4488 4489 QualType ASTContext::getReadPipeType(QualType T) const { 4490 return getPipeType(T, true); 4491 } 4492 4493 QualType ASTContext::getWritePipeType(QualType T) const { 4494 return getPipeType(T, false); 4495 } 4496 4497 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const { 4498 llvm::FoldingSetNodeID ID; 4499 BitIntType::Profile(ID, IsUnsigned, NumBits); 4500 4501 void *InsertPos = nullptr; 4502 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4503 return QualType(EIT, 0); 4504 4505 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits); 4506 BitIntTypes.InsertNode(New, InsertPos); 4507 Types.push_back(New); 4508 return QualType(New, 0); 4509 } 4510 4511 QualType ASTContext::getDependentBitIntType(bool IsUnsigned, 4512 Expr *NumBitsExpr) const { 4513 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4514 llvm::FoldingSetNodeID ID; 4515 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4516 4517 void *InsertPos = nullptr; 4518 if (DependentBitIntType *Existing = 4519 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4520 return QualType(Existing, 0); 4521 4522 auto *New = new (*this, TypeAlignment) 4523 DependentBitIntType(*this, IsUnsigned, NumBitsExpr); 4524 DependentBitIntTypes.InsertNode(New, InsertPos); 4525 4526 Types.push_back(New); 4527 return QualType(New, 0); 4528 } 4529 4530 #ifndef NDEBUG 4531 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4532 if (!isa<CXXRecordDecl>(D)) return false; 4533 const auto *RD = cast<CXXRecordDecl>(D); 4534 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4535 return true; 4536 if (RD->getDescribedClassTemplate() && 4537 !isa<ClassTemplateSpecializationDecl>(RD)) 4538 return true; 4539 return false; 4540 } 4541 #endif 4542 4543 /// getInjectedClassNameType - Return the unique reference to the 4544 /// injected class name type for the specified templated declaration. 4545 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4546 QualType TST) const { 4547 assert(NeedsInjectedClassNameType(Decl)); 4548 if (Decl->TypeForDecl) { 4549 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4550 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4551 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4552 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4553 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4554 } else { 4555 Type *newType = 4556 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4557 Decl->TypeForDecl = newType; 4558 Types.push_back(newType); 4559 } 4560 return QualType(Decl->TypeForDecl, 0); 4561 } 4562 4563 /// getTypeDeclType - Return the unique reference to the type for the 4564 /// specified type declaration. 4565 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4566 assert(Decl && "Passed null for Decl param"); 4567 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4568 4569 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4570 return getTypedefType(Typedef); 4571 4572 assert(!isa<TemplateTypeParmDecl>(Decl) && 4573 "Template type parameter types are always available."); 4574 4575 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4576 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4577 assert(!NeedsInjectedClassNameType(Record)); 4578 return getRecordType(Record); 4579 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4580 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4581 return getEnumType(Enum); 4582 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4583 return getUnresolvedUsingType(Using); 4584 } else 4585 llvm_unreachable("TypeDecl without a type?"); 4586 4587 return QualType(Decl->TypeForDecl, 0); 4588 } 4589 4590 /// getTypedefType - Return the unique reference to the type for the 4591 /// specified typedef name decl. 4592 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4593 QualType Underlying) const { 4594 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4595 4596 if (Underlying.isNull()) 4597 Underlying = Decl->getUnderlyingType(); 4598 QualType Canonical = getCanonicalType(Underlying); 4599 auto *newType = new (*this, TypeAlignment) 4600 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4601 Decl->TypeForDecl = newType; 4602 Types.push_back(newType); 4603 return QualType(newType, 0); 4604 } 4605 4606 QualType ASTContext::getUsingType(const UsingShadowDecl *Found, 4607 QualType Underlying) const { 4608 llvm::FoldingSetNodeID ID; 4609 UsingType::Profile(ID, Found); 4610 4611 void *InsertPos = nullptr; 4612 UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); 4613 if (T) 4614 return QualType(T, 0); 4615 4616 assert(!Underlying.hasLocalQualifiers()); 4617 assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl()))); 4618 QualType Canon = Underlying.getCanonicalType(); 4619 4620 UsingType *NewType = 4621 new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); 4622 Types.push_back(NewType); 4623 UsingTypes.InsertNode(NewType, InsertPos); 4624 return QualType(NewType, 0); 4625 } 4626 4627 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4628 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4629 4630 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4631 if (PrevDecl->TypeForDecl) 4632 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4633 4634 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4635 Decl->TypeForDecl = newType; 4636 Types.push_back(newType); 4637 return QualType(newType, 0); 4638 } 4639 4640 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4641 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4642 4643 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4644 if (PrevDecl->TypeForDecl) 4645 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4646 4647 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4648 Decl->TypeForDecl = newType; 4649 Types.push_back(newType); 4650 return QualType(newType, 0); 4651 } 4652 4653 QualType ASTContext::getUnresolvedUsingType( 4654 const UnresolvedUsingTypenameDecl *Decl) const { 4655 if (Decl->TypeForDecl) 4656 return QualType(Decl->TypeForDecl, 0); 4657 4658 if (const UnresolvedUsingTypenameDecl *CanonicalDecl = 4659 Decl->getCanonicalDecl()) 4660 if (CanonicalDecl->TypeForDecl) 4661 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0); 4662 4663 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl); 4664 Decl->TypeForDecl = newType; 4665 Types.push_back(newType); 4666 return QualType(newType, 0); 4667 } 4668 4669 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4670 QualType modifiedType, 4671 QualType equivalentType) { 4672 llvm::FoldingSetNodeID id; 4673 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4674 4675 void *insertPos = nullptr; 4676 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4677 if (type) return QualType(type, 0); 4678 4679 QualType canon = getCanonicalType(equivalentType); 4680 type = new (*this, TypeAlignment) 4681 AttributedType(canon, attrKind, modifiedType, equivalentType); 4682 4683 Types.push_back(type); 4684 AttributedTypes.InsertNode(type, insertPos); 4685 4686 return QualType(type, 0); 4687 } 4688 4689 /// Retrieve a substitution-result type. 4690 QualType 4691 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4692 QualType Replacement) const { 4693 assert(Replacement.isCanonical() 4694 && "replacement types must always be canonical"); 4695 4696 llvm::FoldingSetNodeID ID; 4697 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4698 void *InsertPos = nullptr; 4699 SubstTemplateTypeParmType *SubstParm 4700 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4701 4702 if (!SubstParm) { 4703 SubstParm = new (*this, TypeAlignment) 4704 SubstTemplateTypeParmType(Parm, Replacement); 4705 Types.push_back(SubstParm); 4706 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4707 } 4708 4709 return QualType(SubstParm, 0); 4710 } 4711 4712 /// Retrieve a 4713 QualType ASTContext::getSubstTemplateTypeParmPackType( 4714 const TemplateTypeParmType *Parm, 4715 const TemplateArgument &ArgPack) { 4716 #ifndef NDEBUG 4717 for (const auto &P : ArgPack.pack_elements()) { 4718 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4719 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4720 } 4721 #endif 4722 4723 llvm::FoldingSetNodeID ID; 4724 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4725 void *InsertPos = nullptr; 4726 if (SubstTemplateTypeParmPackType *SubstParm 4727 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4728 return QualType(SubstParm, 0); 4729 4730 QualType Canon; 4731 if (!Parm->isCanonicalUnqualified()) { 4732 Canon = getCanonicalType(QualType(Parm, 0)); 4733 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4734 ArgPack); 4735 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4736 } 4737 4738 auto *SubstParm 4739 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4740 ArgPack); 4741 Types.push_back(SubstParm); 4742 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4743 return QualType(SubstParm, 0); 4744 } 4745 4746 /// Retrieve the template type parameter type for a template 4747 /// parameter or parameter pack with the given depth, index, and (optionally) 4748 /// name. 4749 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4750 bool ParameterPack, 4751 TemplateTypeParmDecl *TTPDecl) const { 4752 llvm::FoldingSetNodeID ID; 4753 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4754 void *InsertPos = nullptr; 4755 TemplateTypeParmType *TypeParm 4756 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4757 4758 if (TypeParm) 4759 return QualType(TypeParm, 0); 4760 4761 if (TTPDecl) { 4762 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4763 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4764 4765 TemplateTypeParmType *TypeCheck 4766 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4767 assert(!TypeCheck && "Template type parameter canonical type broken"); 4768 (void)TypeCheck; 4769 } else 4770 TypeParm = new (*this, TypeAlignment) 4771 TemplateTypeParmType(Depth, Index, ParameterPack); 4772 4773 Types.push_back(TypeParm); 4774 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4775 4776 return QualType(TypeParm, 0); 4777 } 4778 4779 TypeSourceInfo * 4780 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4781 SourceLocation NameLoc, 4782 const TemplateArgumentListInfo &Args, 4783 QualType Underlying) const { 4784 assert(!Name.getAsDependentTemplateName() && 4785 "No dependent template names here!"); 4786 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4787 4788 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4789 TemplateSpecializationTypeLoc TL = 4790 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4791 TL.setTemplateKeywordLoc(SourceLocation()); 4792 TL.setTemplateNameLoc(NameLoc); 4793 TL.setLAngleLoc(Args.getLAngleLoc()); 4794 TL.setRAngleLoc(Args.getRAngleLoc()); 4795 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4796 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4797 return DI; 4798 } 4799 4800 QualType 4801 ASTContext::getTemplateSpecializationType(TemplateName Template, 4802 const TemplateArgumentListInfo &Args, 4803 QualType Underlying) const { 4804 assert(!Template.getAsDependentTemplateName() && 4805 "No dependent template names here!"); 4806 4807 SmallVector<TemplateArgument, 4> ArgVec; 4808 ArgVec.reserve(Args.size()); 4809 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4810 ArgVec.push_back(Arg.getArgument()); 4811 4812 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4813 } 4814 4815 #ifndef NDEBUG 4816 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4817 for (const TemplateArgument &Arg : Args) 4818 if (Arg.isPackExpansion()) 4819 return true; 4820 4821 return true; 4822 } 4823 #endif 4824 4825 QualType 4826 ASTContext::getTemplateSpecializationType(TemplateName Template, 4827 ArrayRef<TemplateArgument> Args, 4828 QualType Underlying) const { 4829 assert(!Template.getAsDependentTemplateName() && 4830 "No dependent template names here!"); 4831 // Look through qualified template names. 4832 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4833 Template = TemplateName(QTN->getTemplateDecl()); 4834 4835 bool IsTypeAlias = 4836 Template.getAsTemplateDecl() && 4837 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4838 QualType CanonType; 4839 if (!Underlying.isNull()) 4840 CanonType = getCanonicalType(Underlying); 4841 else { 4842 // We can get here with an alias template when the specialization contains 4843 // a pack expansion that does not match up with a parameter pack. 4844 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4845 "Caller must compute aliased type"); 4846 IsTypeAlias = false; 4847 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4848 } 4849 4850 // Allocate the (non-canonical) template specialization type, but don't 4851 // try to unique it: these types typically have location information that 4852 // we don't unique and don't want to lose. 4853 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4854 sizeof(TemplateArgument) * Args.size() + 4855 (IsTypeAlias? sizeof(QualType) : 0), 4856 TypeAlignment); 4857 auto *Spec 4858 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4859 IsTypeAlias ? Underlying : QualType()); 4860 4861 Types.push_back(Spec); 4862 return QualType(Spec, 0); 4863 } 4864 4865 static bool 4866 getCanonicalTemplateArguments(const ASTContext &C, 4867 ArrayRef<TemplateArgument> OrigArgs, 4868 SmallVectorImpl<TemplateArgument> &CanonArgs) { 4869 bool AnyNonCanonArgs = false; 4870 unsigned NumArgs = OrigArgs.size(); 4871 CanonArgs.resize(NumArgs); 4872 for (unsigned I = 0; I != NumArgs; ++I) { 4873 const TemplateArgument &OrigArg = OrigArgs[I]; 4874 TemplateArgument &CanonArg = CanonArgs[I]; 4875 CanonArg = C.getCanonicalTemplateArgument(OrigArg); 4876 if (!CanonArg.structurallyEquals(OrigArg)) 4877 AnyNonCanonArgs = true; 4878 } 4879 return AnyNonCanonArgs; 4880 } 4881 4882 QualType ASTContext::getCanonicalTemplateSpecializationType( 4883 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4884 assert(!Template.getAsDependentTemplateName() && 4885 "No dependent template names here!"); 4886 4887 // Look through qualified template names. 4888 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4889 Template = TemplateName(QTN->getTemplateDecl()); 4890 4891 // Build the canonical template specialization type. 4892 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4893 SmallVector<TemplateArgument, 4> CanonArgs; 4894 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 4895 4896 // Determine whether this canonical template specialization type already 4897 // exists. 4898 llvm::FoldingSetNodeID ID; 4899 TemplateSpecializationType::Profile(ID, CanonTemplate, 4900 CanonArgs, *this); 4901 4902 void *InsertPos = nullptr; 4903 TemplateSpecializationType *Spec 4904 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4905 4906 if (!Spec) { 4907 // Allocate a new canonical template specialization type. 4908 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4909 sizeof(TemplateArgument) * CanonArgs.size()), 4910 TypeAlignment); 4911 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4912 CanonArgs, 4913 QualType(), QualType()); 4914 Types.push_back(Spec); 4915 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4916 } 4917 4918 assert(Spec->isDependentType() && 4919 "Non-dependent template-id type must have a canonical type"); 4920 return QualType(Spec, 0); 4921 } 4922 4923 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4924 NestedNameSpecifier *NNS, 4925 QualType NamedType, 4926 TagDecl *OwnedTagDecl) const { 4927 llvm::FoldingSetNodeID ID; 4928 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4929 4930 void *InsertPos = nullptr; 4931 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4932 if (T) 4933 return QualType(T, 0); 4934 4935 QualType Canon = NamedType; 4936 if (!Canon.isCanonical()) { 4937 Canon = getCanonicalType(NamedType); 4938 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4939 assert(!CheckT && "Elaborated canonical type broken"); 4940 (void)CheckT; 4941 } 4942 4943 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4944 TypeAlignment); 4945 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4946 4947 Types.push_back(T); 4948 ElaboratedTypes.InsertNode(T, InsertPos); 4949 return QualType(T, 0); 4950 } 4951 4952 QualType 4953 ASTContext::getParenType(QualType InnerType) const { 4954 llvm::FoldingSetNodeID ID; 4955 ParenType::Profile(ID, InnerType); 4956 4957 void *InsertPos = nullptr; 4958 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4959 if (T) 4960 return QualType(T, 0); 4961 4962 QualType Canon = InnerType; 4963 if (!Canon.isCanonical()) { 4964 Canon = getCanonicalType(InnerType); 4965 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4966 assert(!CheckT && "Paren canonical type broken"); 4967 (void)CheckT; 4968 } 4969 4970 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4971 Types.push_back(T); 4972 ParenTypes.InsertNode(T, InsertPos); 4973 return QualType(T, 0); 4974 } 4975 4976 QualType 4977 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4978 const IdentifierInfo *MacroII) const { 4979 QualType Canon = UnderlyingTy; 4980 if (!Canon.isCanonical()) 4981 Canon = getCanonicalType(UnderlyingTy); 4982 4983 auto *newType = new (*this, TypeAlignment) 4984 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4985 Types.push_back(newType); 4986 return QualType(newType, 0); 4987 } 4988 4989 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4990 NestedNameSpecifier *NNS, 4991 const IdentifierInfo *Name, 4992 QualType Canon) const { 4993 if (Canon.isNull()) { 4994 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4995 if (CanonNNS != NNS) 4996 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4997 } 4998 4999 llvm::FoldingSetNodeID ID; 5000 DependentNameType::Profile(ID, Keyword, NNS, Name); 5001 5002 void *InsertPos = nullptr; 5003 DependentNameType *T 5004 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 5005 if (T) 5006 return QualType(T, 0); 5007 5008 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 5009 Types.push_back(T); 5010 DependentNameTypes.InsertNode(T, InsertPos); 5011 return QualType(T, 0); 5012 } 5013 5014 QualType 5015 ASTContext::getDependentTemplateSpecializationType( 5016 ElaboratedTypeKeyword Keyword, 5017 NestedNameSpecifier *NNS, 5018 const IdentifierInfo *Name, 5019 const TemplateArgumentListInfo &Args) const { 5020 // TODO: avoid this copy 5021 SmallVector<TemplateArgument, 16> ArgCopy; 5022 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5023 ArgCopy.push_back(Args[I].getArgument()); 5024 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 5025 } 5026 5027 QualType 5028 ASTContext::getDependentTemplateSpecializationType( 5029 ElaboratedTypeKeyword Keyword, 5030 NestedNameSpecifier *NNS, 5031 const IdentifierInfo *Name, 5032 ArrayRef<TemplateArgument> Args) const { 5033 assert((!NNS || NNS->isDependent()) && 5034 "nested-name-specifier must be dependent"); 5035 5036 llvm::FoldingSetNodeID ID; 5037 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 5038 Name, Args); 5039 5040 void *InsertPos = nullptr; 5041 DependentTemplateSpecializationType *T 5042 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5043 if (T) 5044 return QualType(T, 0); 5045 5046 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5047 5048 ElaboratedTypeKeyword CanonKeyword = Keyword; 5049 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 5050 5051 SmallVector<TemplateArgument, 16> CanonArgs; 5052 bool AnyNonCanonArgs = 5053 ::getCanonicalTemplateArguments(*this, Args, CanonArgs); 5054 5055 QualType Canon; 5056 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 5057 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 5058 Name, 5059 CanonArgs); 5060 5061 // Find the insert position again. 5062 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 5063 } 5064 5065 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 5066 sizeof(TemplateArgument) * Args.size()), 5067 TypeAlignment); 5068 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 5069 Name, Args, Canon); 5070 Types.push_back(T); 5071 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 5072 return QualType(T, 0); 5073 } 5074 5075 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 5076 TemplateArgument Arg; 5077 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 5078 QualType ArgType = getTypeDeclType(TTP); 5079 if (TTP->isParameterPack()) 5080 ArgType = getPackExpansionType(ArgType, None); 5081 5082 Arg = TemplateArgument(ArgType); 5083 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5084 QualType T = 5085 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 5086 // For class NTTPs, ensure we include the 'const' so the type matches that 5087 // of a real template argument. 5088 // FIXME: It would be more faithful to model this as something like an 5089 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 5090 if (T->isRecordType()) 5091 T.addConst(); 5092 Expr *E = new (*this) DeclRefExpr( 5093 *this, NTTP, /*enclosing*/ false, T, 5094 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 5095 5096 if (NTTP->isParameterPack()) 5097 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5098 None); 5099 Arg = TemplateArgument(E); 5100 } else { 5101 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5102 if (TTP->isParameterPack()) 5103 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5104 else 5105 Arg = TemplateArgument(TemplateName(TTP)); 5106 } 5107 5108 if (Param->isTemplateParameterPack()) 5109 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5110 5111 return Arg; 5112 } 5113 5114 void 5115 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5116 SmallVectorImpl<TemplateArgument> &Args) { 5117 Args.reserve(Args.size() + Params->size()); 5118 5119 for (NamedDecl *Param : *Params) 5120 Args.push_back(getInjectedTemplateArg(Param)); 5121 } 5122 5123 QualType ASTContext::getPackExpansionType(QualType Pattern, 5124 Optional<unsigned> NumExpansions, 5125 bool ExpectPackInType) { 5126 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5127 "Pack expansions must expand one or more parameter packs"); 5128 5129 llvm::FoldingSetNodeID ID; 5130 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5131 5132 void *InsertPos = nullptr; 5133 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5134 if (T) 5135 return QualType(T, 0); 5136 5137 QualType Canon; 5138 if (!Pattern.isCanonical()) { 5139 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5140 /*ExpectPackInType=*/false); 5141 5142 // Find the insert position again, in case we inserted an element into 5143 // PackExpansionTypes and invalidated our insert position. 5144 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5145 } 5146 5147 T = new (*this, TypeAlignment) 5148 PackExpansionType(Pattern, Canon, NumExpansions); 5149 Types.push_back(T); 5150 PackExpansionTypes.InsertNode(T, InsertPos); 5151 return QualType(T, 0); 5152 } 5153 5154 /// CmpProtocolNames - Comparison predicate for sorting protocols 5155 /// alphabetically. 5156 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5157 ObjCProtocolDecl *const *RHS) { 5158 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5159 } 5160 5161 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5162 if (Protocols.empty()) return true; 5163 5164 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5165 return false; 5166 5167 for (unsigned i = 1; i != Protocols.size(); ++i) 5168 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5169 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5170 return false; 5171 return true; 5172 } 5173 5174 static void 5175 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5176 // Sort protocols, keyed by name. 5177 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5178 5179 // Canonicalize. 5180 for (ObjCProtocolDecl *&P : Protocols) 5181 P = P->getCanonicalDecl(); 5182 5183 // Remove duplicates. 5184 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5185 Protocols.erase(ProtocolsEnd, Protocols.end()); 5186 } 5187 5188 QualType ASTContext::getObjCObjectType(QualType BaseType, 5189 ObjCProtocolDecl * const *Protocols, 5190 unsigned NumProtocols) const { 5191 return getObjCObjectType(BaseType, {}, 5192 llvm::makeArrayRef(Protocols, NumProtocols), 5193 /*isKindOf=*/false); 5194 } 5195 5196 QualType ASTContext::getObjCObjectType( 5197 QualType baseType, 5198 ArrayRef<QualType> typeArgs, 5199 ArrayRef<ObjCProtocolDecl *> protocols, 5200 bool isKindOf) const { 5201 // If the base type is an interface and there aren't any protocols or 5202 // type arguments to add, then the interface type will do just fine. 5203 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5204 isa<ObjCInterfaceType>(baseType)) 5205 return baseType; 5206 5207 // Look in the folding set for an existing type. 5208 llvm::FoldingSetNodeID ID; 5209 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5210 void *InsertPos = nullptr; 5211 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5212 return QualType(QT, 0); 5213 5214 // Determine the type arguments to be used for canonicalization, 5215 // which may be explicitly specified here or written on the base 5216 // type. 5217 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5218 if (effectiveTypeArgs.empty()) { 5219 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5220 effectiveTypeArgs = baseObject->getTypeArgs(); 5221 } 5222 5223 // Build the canonical type, which has the canonical base type and a 5224 // sorted-and-uniqued list of protocols and the type arguments 5225 // canonicalized. 5226 QualType canonical; 5227 bool typeArgsAreCanonical = llvm::all_of( 5228 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); }); 5229 bool protocolsSorted = areSortedAndUniqued(protocols); 5230 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5231 // Determine the canonical type arguments. 5232 ArrayRef<QualType> canonTypeArgs; 5233 SmallVector<QualType, 4> canonTypeArgsVec; 5234 if (!typeArgsAreCanonical) { 5235 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5236 for (auto typeArg : effectiveTypeArgs) 5237 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5238 canonTypeArgs = canonTypeArgsVec; 5239 } else { 5240 canonTypeArgs = effectiveTypeArgs; 5241 } 5242 5243 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5244 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5245 if (!protocolsSorted) { 5246 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5247 SortAndUniqueProtocols(canonProtocolsVec); 5248 canonProtocols = canonProtocolsVec; 5249 } else { 5250 canonProtocols = protocols; 5251 } 5252 5253 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5254 canonProtocols, isKindOf); 5255 5256 // Regenerate InsertPos. 5257 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5258 } 5259 5260 unsigned size = sizeof(ObjCObjectTypeImpl); 5261 size += typeArgs.size() * sizeof(QualType); 5262 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5263 void *mem = Allocate(size, TypeAlignment); 5264 auto *T = 5265 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5266 isKindOf); 5267 5268 Types.push_back(T); 5269 ObjCObjectTypes.InsertNode(T, InsertPos); 5270 return QualType(T, 0); 5271 } 5272 5273 /// Apply Objective-C protocol qualifiers to the given type. 5274 /// If this is for the canonical type of a type parameter, we can apply 5275 /// protocol qualifiers on the ObjCObjectPointerType. 5276 QualType 5277 ASTContext::applyObjCProtocolQualifiers(QualType type, 5278 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5279 bool allowOnPointerType) const { 5280 hasError = false; 5281 5282 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5283 return getObjCTypeParamType(objT->getDecl(), protocols); 5284 } 5285 5286 // Apply protocol qualifiers to ObjCObjectPointerType. 5287 if (allowOnPointerType) { 5288 if (const auto *objPtr = 5289 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5290 const ObjCObjectType *objT = objPtr->getObjectType(); 5291 // Merge protocol lists and construct ObjCObjectType. 5292 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5293 protocolsVec.append(objT->qual_begin(), 5294 objT->qual_end()); 5295 protocolsVec.append(protocols.begin(), protocols.end()); 5296 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5297 type = getObjCObjectType( 5298 objT->getBaseType(), 5299 objT->getTypeArgsAsWritten(), 5300 protocols, 5301 objT->isKindOfTypeAsWritten()); 5302 return getObjCObjectPointerType(type); 5303 } 5304 } 5305 5306 // Apply protocol qualifiers to ObjCObjectType. 5307 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5308 // FIXME: Check for protocols to which the class type is already 5309 // known to conform. 5310 5311 return getObjCObjectType(objT->getBaseType(), 5312 objT->getTypeArgsAsWritten(), 5313 protocols, 5314 objT->isKindOfTypeAsWritten()); 5315 } 5316 5317 // If the canonical type is ObjCObjectType, ... 5318 if (type->isObjCObjectType()) { 5319 // Silently overwrite any existing protocol qualifiers. 5320 // TODO: determine whether that's the right thing to do. 5321 5322 // FIXME: Check for protocols to which the class type is already 5323 // known to conform. 5324 return getObjCObjectType(type, {}, protocols, false); 5325 } 5326 5327 // id<protocol-list> 5328 if (type->isObjCIdType()) { 5329 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5330 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5331 objPtr->isKindOfType()); 5332 return getObjCObjectPointerType(type); 5333 } 5334 5335 // Class<protocol-list> 5336 if (type->isObjCClassType()) { 5337 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5338 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5339 objPtr->isKindOfType()); 5340 return getObjCObjectPointerType(type); 5341 } 5342 5343 hasError = true; 5344 return type; 5345 } 5346 5347 QualType 5348 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5349 ArrayRef<ObjCProtocolDecl *> protocols) const { 5350 // Look in the folding set for an existing type. 5351 llvm::FoldingSetNodeID ID; 5352 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5353 void *InsertPos = nullptr; 5354 if (ObjCTypeParamType *TypeParam = 5355 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5356 return QualType(TypeParam, 0); 5357 5358 // We canonicalize to the underlying type. 5359 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5360 if (!protocols.empty()) { 5361 // Apply the protocol qualifers. 5362 bool hasError; 5363 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5364 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5365 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5366 } 5367 5368 unsigned size = sizeof(ObjCTypeParamType); 5369 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5370 void *mem = Allocate(size, TypeAlignment); 5371 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5372 5373 Types.push_back(newType); 5374 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5375 return QualType(newType, 0); 5376 } 5377 5378 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5379 ObjCTypeParamDecl *New) const { 5380 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5381 // Update TypeForDecl after updating TypeSourceInfo. 5382 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5383 SmallVector<ObjCProtocolDecl *, 8> protocols; 5384 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5385 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5386 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5387 } 5388 5389 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5390 /// protocol list adopt all protocols in QT's qualified-id protocol 5391 /// list. 5392 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5393 ObjCInterfaceDecl *IC) { 5394 if (!QT->isObjCQualifiedIdType()) 5395 return false; 5396 5397 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5398 // If both the right and left sides have qualifiers. 5399 for (auto *Proto : OPT->quals()) { 5400 if (!IC->ClassImplementsProtocol(Proto, false)) 5401 return false; 5402 } 5403 return true; 5404 } 5405 return false; 5406 } 5407 5408 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5409 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5410 /// of protocols. 5411 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5412 ObjCInterfaceDecl *IDecl) { 5413 if (!QT->isObjCQualifiedIdType()) 5414 return false; 5415 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5416 if (!OPT) 5417 return false; 5418 if (!IDecl->hasDefinition()) 5419 return false; 5420 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5421 CollectInheritedProtocols(IDecl, InheritedProtocols); 5422 if (InheritedProtocols.empty()) 5423 return false; 5424 // Check that if every protocol in list of id<plist> conforms to a protocol 5425 // of IDecl's, then bridge casting is ok. 5426 bool Conforms = false; 5427 for (auto *Proto : OPT->quals()) { 5428 Conforms = false; 5429 for (auto *PI : InheritedProtocols) { 5430 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5431 Conforms = true; 5432 break; 5433 } 5434 } 5435 if (!Conforms) 5436 break; 5437 } 5438 if (Conforms) 5439 return true; 5440 5441 for (auto *PI : InheritedProtocols) { 5442 // If both the right and left sides have qualifiers. 5443 bool Adopts = false; 5444 for (auto *Proto : OPT->quals()) { 5445 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5446 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5447 break; 5448 } 5449 if (!Adopts) 5450 return false; 5451 } 5452 return true; 5453 } 5454 5455 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5456 /// the given object type. 5457 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5458 llvm::FoldingSetNodeID ID; 5459 ObjCObjectPointerType::Profile(ID, ObjectT); 5460 5461 void *InsertPos = nullptr; 5462 if (ObjCObjectPointerType *QT = 5463 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5464 return QualType(QT, 0); 5465 5466 // Find the canonical object type. 5467 QualType Canonical; 5468 if (!ObjectT.isCanonical()) { 5469 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5470 5471 // Regenerate InsertPos. 5472 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5473 } 5474 5475 // No match. 5476 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5477 auto *QType = 5478 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5479 5480 Types.push_back(QType); 5481 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5482 return QualType(QType, 0); 5483 } 5484 5485 /// getObjCInterfaceType - Return the unique reference to the type for the 5486 /// specified ObjC interface decl. The list of protocols is optional. 5487 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5488 ObjCInterfaceDecl *PrevDecl) const { 5489 if (Decl->TypeForDecl) 5490 return QualType(Decl->TypeForDecl, 0); 5491 5492 if (PrevDecl) { 5493 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5494 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5495 return QualType(PrevDecl->TypeForDecl, 0); 5496 } 5497 5498 // Prefer the definition, if there is one. 5499 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5500 Decl = Def; 5501 5502 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5503 auto *T = new (Mem) ObjCInterfaceType(Decl); 5504 Decl->TypeForDecl = T; 5505 Types.push_back(T); 5506 return QualType(T, 0); 5507 } 5508 5509 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5510 /// TypeOfExprType AST's (since expression's are never shared). For example, 5511 /// multiple declarations that refer to "typeof(x)" all contain different 5512 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5513 /// on canonical type's (which are always unique). 5514 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5515 TypeOfExprType *toe; 5516 if (tofExpr->isTypeDependent()) { 5517 llvm::FoldingSetNodeID ID; 5518 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5519 5520 void *InsertPos = nullptr; 5521 DependentTypeOfExprType *Canon 5522 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5523 if (Canon) { 5524 // We already have a "canonical" version of an identical, dependent 5525 // typeof(expr) type. Use that as our canonical type. 5526 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5527 QualType((TypeOfExprType*)Canon, 0)); 5528 } else { 5529 // Build a new, canonical typeof(expr) type. 5530 Canon 5531 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5532 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5533 toe = Canon; 5534 } 5535 } else { 5536 QualType Canonical = getCanonicalType(tofExpr->getType()); 5537 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5538 } 5539 Types.push_back(toe); 5540 return QualType(toe, 0); 5541 } 5542 5543 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5544 /// TypeOfType nodes. The only motivation to unique these nodes would be 5545 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5546 /// an issue. This doesn't affect the type checker, since it operates 5547 /// on canonical types (which are always unique). 5548 QualType ASTContext::getTypeOfType(QualType tofType) const { 5549 QualType Canonical = getCanonicalType(tofType); 5550 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5551 Types.push_back(tot); 5552 return QualType(tot, 0); 5553 } 5554 5555 /// getReferenceQualifiedType - Given an expr, will return the type for 5556 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5557 /// and class member access into account. 5558 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5559 // C++11 [dcl.type.simple]p4: 5560 // [...] 5561 QualType T = E->getType(); 5562 switch (E->getValueKind()) { 5563 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5564 // type of e; 5565 case VK_XValue: 5566 return getRValueReferenceType(T); 5567 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5568 // type of e; 5569 case VK_LValue: 5570 return getLValueReferenceType(T); 5571 // - otherwise, decltype(e) is the type of e. 5572 case VK_PRValue: 5573 return T; 5574 } 5575 llvm_unreachable("Unknown value kind"); 5576 } 5577 5578 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5579 /// nodes. This would never be helpful, since each such type has its own 5580 /// expression, and would not give a significant memory saving, since there 5581 /// is an Expr tree under each such type. 5582 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5583 DecltypeType *dt; 5584 5585 // C++11 [temp.type]p2: 5586 // If an expression e involves a template parameter, decltype(e) denotes a 5587 // unique dependent type. Two such decltype-specifiers refer to the same 5588 // type only if their expressions are equivalent (14.5.6.1). 5589 if (e->isInstantiationDependent()) { 5590 llvm::FoldingSetNodeID ID; 5591 DependentDecltypeType::Profile(ID, *this, e); 5592 5593 void *InsertPos = nullptr; 5594 DependentDecltypeType *Canon 5595 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5596 if (!Canon) { 5597 // Build a new, canonical decltype(expr) type. 5598 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5599 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5600 } 5601 dt = new (*this, TypeAlignment) 5602 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5603 } else { 5604 dt = new (*this, TypeAlignment) 5605 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5606 } 5607 Types.push_back(dt); 5608 return QualType(dt, 0); 5609 } 5610 5611 /// getUnaryTransformationType - We don't unique these, since the memory 5612 /// savings are minimal and these are rare. 5613 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5614 QualType UnderlyingType, 5615 UnaryTransformType::UTTKind Kind) 5616 const { 5617 UnaryTransformType *ut = nullptr; 5618 5619 if (BaseType->isDependentType()) { 5620 // Look in the folding set for an existing type. 5621 llvm::FoldingSetNodeID ID; 5622 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5623 5624 void *InsertPos = nullptr; 5625 DependentUnaryTransformType *Canon 5626 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5627 5628 if (!Canon) { 5629 // Build a new, canonical __underlying_type(type) type. 5630 Canon = new (*this, TypeAlignment) 5631 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5632 Kind); 5633 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5634 } 5635 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5636 QualType(), Kind, 5637 QualType(Canon, 0)); 5638 } else { 5639 QualType CanonType = getCanonicalType(UnderlyingType); 5640 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5641 UnderlyingType, Kind, 5642 CanonType); 5643 } 5644 Types.push_back(ut); 5645 return QualType(ut, 0); 5646 } 5647 5648 QualType ASTContext::getAutoTypeInternal( 5649 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, 5650 bool IsPack, ConceptDecl *TypeConstraintConcept, 5651 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const { 5652 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5653 !TypeConstraintConcept && !IsDependent) 5654 return getAutoDeductType(); 5655 5656 // Look in the folding set for an existing type. 5657 void *InsertPos = nullptr; 5658 llvm::FoldingSetNodeID ID; 5659 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5660 TypeConstraintConcept, TypeConstraintArgs); 5661 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5662 return QualType(AT, 0); 5663 5664 QualType Canon; 5665 if (!IsCanon) { 5666 if (DeducedType.isNull()) { 5667 SmallVector<TemplateArgument, 4> CanonArgs; 5668 bool AnyNonCanonArgs = 5669 ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs); 5670 if (AnyNonCanonArgs) { 5671 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack, 5672 TypeConstraintConcept, CanonArgs, true); 5673 // Find the insert position again. 5674 AutoTypes.FindNodeOrInsertPos(ID, InsertPos); 5675 } 5676 } else { 5677 Canon = DeducedType.getCanonicalType(); 5678 } 5679 } 5680 5681 void *Mem = Allocate(sizeof(AutoType) + 5682 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5683 TypeAlignment); 5684 auto *AT = new (Mem) AutoType( 5685 DeducedType, Keyword, 5686 (IsDependent ? TypeDependence::DependentInstantiation 5687 : TypeDependence::None) | 5688 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5689 Canon, TypeConstraintConcept, TypeConstraintArgs); 5690 Types.push_back(AT); 5691 AutoTypes.InsertNode(AT, InsertPos); 5692 return QualType(AT, 0); 5693 } 5694 5695 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5696 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5697 /// canonical deduced-but-dependent 'auto' type. 5698 QualType 5699 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5700 bool IsDependent, bool IsPack, 5701 ConceptDecl *TypeConstraintConcept, 5702 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5703 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5704 assert((!IsDependent || DeducedType.isNull()) && 5705 "A dependent auto should be undeduced"); 5706 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack, 5707 TypeConstraintConcept, TypeConstraintArgs); 5708 } 5709 5710 /// Return the uniqued reference to the deduced template specialization type 5711 /// which has been deduced to the given type, or to the canonical undeduced 5712 /// such type, or the canonical deduced-but-dependent such type. 5713 QualType ASTContext::getDeducedTemplateSpecializationType( 5714 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5715 // Look in the folding set for an existing type. 5716 void *InsertPos = nullptr; 5717 llvm::FoldingSetNodeID ID; 5718 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5719 IsDependent); 5720 if (DeducedTemplateSpecializationType *DTST = 5721 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5722 return QualType(DTST, 0); 5723 5724 auto *DTST = new (*this, TypeAlignment) 5725 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5726 llvm::FoldingSetNodeID TempID; 5727 DTST->Profile(TempID); 5728 assert(ID == TempID && "ID does not match"); 5729 Types.push_back(DTST); 5730 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5731 return QualType(DTST, 0); 5732 } 5733 5734 /// getAtomicType - Return the uniqued reference to the atomic type for 5735 /// the given value type. 5736 QualType ASTContext::getAtomicType(QualType T) const { 5737 // Unique pointers, to guarantee there is only one pointer of a particular 5738 // structure. 5739 llvm::FoldingSetNodeID ID; 5740 AtomicType::Profile(ID, T); 5741 5742 void *InsertPos = nullptr; 5743 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5744 return QualType(AT, 0); 5745 5746 // If the atomic value type isn't canonical, this won't be a canonical type 5747 // either, so fill in the canonical type field. 5748 QualType Canonical; 5749 if (!T.isCanonical()) { 5750 Canonical = getAtomicType(getCanonicalType(T)); 5751 5752 // Get the new insert position for the node we care about. 5753 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5754 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5755 } 5756 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5757 Types.push_back(New); 5758 AtomicTypes.InsertNode(New, InsertPos); 5759 return QualType(New, 0); 5760 } 5761 5762 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5763 QualType ASTContext::getAutoDeductType() const { 5764 if (AutoDeductTy.isNull()) 5765 AutoDeductTy = QualType(new (*this, TypeAlignment) 5766 AutoType(QualType(), AutoTypeKeyword::Auto, 5767 TypeDependence::None, QualType(), 5768 /*concept*/ nullptr, /*args*/ {}), 5769 0); 5770 return AutoDeductTy; 5771 } 5772 5773 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5774 QualType ASTContext::getAutoRRefDeductType() const { 5775 if (AutoRRefDeductTy.isNull()) 5776 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5777 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5778 return AutoRRefDeductTy; 5779 } 5780 5781 /// getTagDeclType - Return the unique reference to the type for the 5782 /// specified TagDecl (struct/union/class/enum) decl. 5783 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5784 assert(Decl); 5785 // FIXME: What is the design on getTagDeclType when it requires casting 5786 // away const? mutable? 5787 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5788 } 5789 5790 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5791 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5792 /// needs to agree with the definition in <stddef.h>. 5793 CanQualType ASTContext::getSizeType() const { 5794 return getFromTargetType(Target->getSizeType()); 5795 } 5796 5797 /// Return the unique signed counterpart of the integer type 5798 /// corresponding to size_t. 5799 CanQualType ASTContext::getSignedSizeType() const { 5800 return getFromTargetType(Target->getSignedSizeType()); 5801 } 5802 5803 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5804 CanQualType ASTContext::getIntMaxType() const { 5805 return getFromTargetType(Target->getIntMaxType()); 5806 } 5807 5808 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5809 CanQualType ASTContext::getUIntMaxType() const { 5810 return getFromTargetType(Target->getUIntMaxType()); 5811 } 5812 5813 /// getSignedWCharType - Return the type of "signed wchar_t". 5814 /// Used when in C++, as a GCC extension. 5815 QualType ASTContext::getSignedWCharType() const { 5816 // FIXME: derive from "Target" ? 5817 return WCharTy; 5818 } 5819 5820 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5821 /// Used when in C++, as a GCC extension. 5822 QualType ASTContext::getUnsignedWCharType() const { 5823 // FIXME: derive from "Target" ? 5824 return UnsignedIntTy; 5825 } 5826 5827 QualType ASTContext::getIntPtrType() const { 5828 return getFromTargetType(Target->getIntPtrType()); 5829 } 5830 5831 QualType ASTContext::getUIntPtrType() const { 5832 return getCorrespondingUnsignedType(getIntPtrType()); 5833 } 5834 5835 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5836 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5837 QualType ASTContext::getPointerDiffType() const { 5838 return getFromTargetType(Target->getPtrDiffType(0)); 5839 } 5840 5841 /// Return the unique unsigned counterpart of "ptrdiff_t" 5842 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5843 /// in the definition of %tu format specifier. 5844 QualType ASTContext::getUnsignedPointerDiffType() const { 5845 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5846 } 5847 5848 /// Return the unique type for "pid_t" defined in 5849 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5850 QualType ASTContext::getProcessIDType() const { 5851 return getFromTargetType(Target->getProcessIDType()); 5852 } 5853 5854 //===----------------------------------------------------------------------===// 5855 // Type Operators 5856 //===----------------------------------------------------------------------===// 5857 5858 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5859 // Push qualifiers into arrays, and then discard any remaining 5860 // qualifiers. 5861 T = getCanonicalType(T); 5862 T = getVariableArrayDecayedType(T); 5863 const Type *Ty = T.getTypePtr(); 5864 QualType Result; 5865 if (isa<ArrayType>(Ty)) { 5866 Result = getArrayDecayedType(QualType(Ty,0)); 5867 } else if (isa<FunctionType>(Ty)) { 5868 Result = getPointerType(QualType(Ty, 0)); 5869 } else { 5870 Result = QualType(Ty, 0); 5871 } 5872 5873 return CanQualType::CreateUnsafe(Result); 5874 } 5875 5876 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5877 Qualifiers &quals) { 5878 SplitQualType splitType = type.getSplitUnqualifiedType(); 5879 5880 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5881 // the unqualified desugared type and then drops it on the floor. 5882 // We then have to strip that sugar back off with 5883 // getUnqualifiedDesugaredType(), which is silly. 5884 const auto *AT = 5885 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5886 5887 // If we don't have an array, just use the results in splitType. 5888 if (!AT) { 5889 quals = splitType.Quals; 5890 return QualType(splitType.Ty, 0); 5891 } 5892 5893 // Otherwise, recurse on the array's element type. 5894 QualType elementType = AT->getElementType(); 5895 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5896 5897 // If that didn't change the element type, AT has no qualifiers, so we 5898 // can just use the results in splitType. 5899 if (elementType == unqualElementType) { 5900 assert(quals.empty()); // from the recursive call 5901 quals = splitType.Quals; 5902 return QualType(splitType.Ty, 0); 5903 } 5904 5905 // Otherwise, add in the qualifiers from the outermost type, then 5906 // build the type back up. 5907 quals.addConsistentQualifiers(splitType.Quals); 5908 5909 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5910 return getConstantArrayType(unqualElementType, CAT->getSize(), 5911 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5912 } 5913 5914 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5915 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5916 } 5917 5918 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5919 return getVariableArrayType(unqualElementType, 5920 VAT->getSizeExpr(), 5921 VAT->getSizeModifier(), 5922 VAT->getIndexTypeCVRQualifiers(), 5923 VAT->getBracketsRange()); 5924 } 5925 5926 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5927 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5928 DSAT->getSizeModifier(), 0, 5929 SourceRange()); 5930 } 5931 5932 /// Attempt to unwrap two types that may both be array types with the same bound 5933 /// (or both be array types of unknown bound) for the purpose of comparing the 5934 /// cv-decomposition of two types per C++ [conv.qual]. 5935 /// 5936 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5937 /// C++20 [conv.qual], if permitted by the current language mode. 5938 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 5939 bool AllowPiMismatch) { 5940 while (true) { 5941 auto *AT1 = getAsArrayType(T1); 5942 if (!AT1) 5943 return; 5944 5945 auto *AT2 = getAsArrayType(T2); 5946 if (!AT2) 5947 return; 5948 5949 // If we don't have two array types with the same constant bound nor two 5950 // incomplete array types, we've unwrapped everything we can. 5951 // C++20 also permits one type to be a constant array type and the other 5952 // to be an incomplete array type. 5953 // FIXME: Consider also unwrapping array of unknown bound and VLA. 5954 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5955 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5956 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) || 5957 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5958 isa<IncompleteArrayType>(AT2)))) 5959 return; 5960 } else if (isa<IncompleteArrayType>(AT1)) { 5961 if (!(isa<IncompleteArrayType>(AT2) || 5962 (AllowPiMismatch && getLangOpts().CPlusPlus20 && 5963 isa<ConstantArrayType>(AT2)))) 5964 return; 5965 } else { 5966 return; 5967 } 5968 5969 T1 = AT1->getElementType(); 5970 T2 = AT2->getElementType(); 5971 } 5972 } 5973 5974 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5975 /// 5976 /// If T1 and T2 are both pointer types of the same kind, or both array types 5977 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5978 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5979 /// 5980 /// This function will typically be called in a loop that successively 5981 /// "unwraps" pointer and pointer-to-member types to compare them at each 5982 /// level. 5983 /// 5984 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in 5985 /// C++20 [conv.qual], if permitted by the current language mode. 5986 /// 5987 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5988 /// pair of types that can't be unwrapped further. 5989 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2, 5990 bool AllowPiMismatch) { 5991 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch); 5992 5993 const auto *T1PtrType = T1->getAs<PointerType>(); 5994 const auto *T2PtrType = T2->getAs<PointerType>(); 5995 if (T1PtrType && T2PtrType) { 5996 T1 = T1PtrType->getPointeeType(); 5997 T2 = T2PtrType->getPointeeType(); 5998 return true; 5999 } 6000 6001 const auto *T1MPType = T1->getAs<MemberPointerType>(); 6002 const auto *T2MPType = T2->getAs<MemberPointerType>(); 6003 if (T1MPType && T2MPType && 6004 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 6005 QualType(T2MPType->getClass(), 0))) { 6006 T1 = T1MPType->getPointeeType(); 6007 T2 = T2MPType->getPointeeType(); 6008 return true; 6009 } 6010 6011 if (getLangOpts().ObjC) { 6012 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 6013 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 6014 if (T1OPType && T2OPType) { 6015 T1 = T1OPType->getPointeeType(); 6016 T2 = T2OPType->getPointeeType(); 6017 return true; 6018 } 6019 } 6020 6021 // FIXME: Block pointers, too? 6022 6023 return false; 6024 } 6025 6026 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 6027 while (true) { 6028 Qualifiers Quals; 6029 T1 = getUnqualifiedArrayType(T1, Quals); 6030 T2 = getUnqualifiedArrayType(T2, Quals); 6031 if (hasSameType(T1, T2)) 6032 return true; 6033 if (!UnwrapSimilarTypes(T1, T2)) 6034 return false; 6035 } 6036 } 6037 6038 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 6039 while (true) { 6040 Qualifiers Quals1, Quals2; 6041 T1 = getUnqualifiedArrayType(T1, Quals1); 6042 T2 = getUnqualifiedArrayType(T2, Quals2); 6043 6044 Quals1.removeCVRQualifiers(); 6045 Quals2.removeCVRQualifiers(); 6046 if (Quals1 != Quals2) 6047 return false; 6048 6049 if (hasSameType(T1, T2)) 6050 return true; 6051 6052 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false)) 6053 return false; 6054 } 6055 } 6056 6057 DeclarationNameInfo 6058 ASTContext::getNameForTemplate(TemplateName Name, 6059 SourceLocation NameLoc) const { 6060 switch (Name.getKind()) { 6061 case TemplateName::QualifiedTemplate: 6062 case TemplateName::Template: 6063 // DNInfo work in progress: CHECKME: what about DNLoc? 6064 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 6065 NameLoc); 6066 6067 case TemplateName::OverloadedTemplate: { 6068 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 6069 // DNInfo work in progress: CHECKME: what about DNLoc? 6070 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 6071 } 6072 6073 case TemplateName::AssumedTemplate: { 6074 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 6075 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 6076 } 6077 6078 case TemplateName::DependentTemplate: { 6079 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6080 DeclarationName DName; 6081 if (DTN->isIdentifier()) { 6082 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 6083 return DeclarationNameInfo(DName, NameLoc); 6084 } else { 6085 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 6086 // DNInfo work in progress: FIXME: source locations? 6087 DeclarationNameLoc DNLoc = 6088 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 6089 return DeclarationNameInfo(DName, NameLoc, DNLoc); 6090 } 6091 } 6092 6093 case TemplateName::SubstTemplateTemplateParm: { 6094 SubstTemplateTemplateParmStorage *subst 6095 = Name.getAsSubstTemplateTemplateParm(); 6096 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 6097 NameLoc); 6098 } 6099 6100 case TemplateName::SubstTemplateTemplateParmPack: { 6101 SubstTemplateTemplateParmPackStorage *subst 6102 = Name.getAsSubstTemplateTemplateParmPack(); 6103 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 6104 NameLoc); 6105 } 6106 } 6107 6108 llvm_unreachable("bad template name kind!"); 6109 } 6110 6111 TemplateName 6112 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const { 6113 switch (Name.getKind()) { 6114 case TemplateName::QualifiedTemplate: 6115 case TemplateName::Template: { 6116 TemplateDecl *Template = Name.getAsTemplateDecl(); 6117 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 6118 Template = getCanonicalTemplateTemplateParmDecl(TTP); 6119 6120 // The canonical template name is the canonical template declaration. 6121 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 6122 } 6123 6124 case TemplateName::OverloadedTemplate: 6125 case TemplateName::AssumedTemplate: 6126 llvm_unreachable("cannot canonicalize unresolved template"); 6127 6128 case TemplateName::DependentTemplate: { 6129 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 6130 assert(DTN && "Non-dependent template names must refer to template decls."); 6131 return DTN->CanonicalTemplateName; 6132 } 6133 6134 case TemplateName::SubstTemplateTemplateParm: { 6135 SubstTemplateTemplateParmStorage *subst 6136 = Name.getAsSubstTemplateTemplateParm(); 6137 return getCanonicalTemplateName(subst->getReplacement()); 6138 } 6139 6140 case TemplateName::SubstTemplateTemplateParmPack: { 6141 SubstTemplateTemplateParmPackStorage *subst 6142 = Name.getAsSubstTemplateTemplateParmPack(); 6143 TemplateTemplateParmDecl *canonParameter 6144 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6145 TemplateArgument canonArgPack 6146 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6147 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6148 } 6149 } 6150 6151 llvm_unreachable("bad template name!"); 6152 } 6153 6154 bool ASTContext::hasSameTemplateName(const TemplateName &X, 6155 const TemplateName &Y) const { 6156 return getCanonicalTemplateName(X).getAsVoidPointer() == 6157 getCanonicalTemplateName(Y).getAsVoidPointer(); 6158 } 6159 6160 bool ASTContext::isSameTemplateParameter(const NamedDecl *X, 6161 const NamedDecl *Y) { 6162 if (X->getKind() != Y->getKind()) 6163 return false; 6164 6165 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 6166 auto *TY = cast<TemplateTypeParmDecl>(Y); 6167 if (TX->isParameterPack() != TY->isParameterPack()) 6168 return false; 6169 if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) 6170 return false; 6171 const TypeConstraint *TXTC = TX->getTypeConstraint(); 6172 const TypeConstraint *TYTC = TY->getTypeConstraint(); 6173 if (!TXTC != !TYTC) 6174 return false; 6175 if (TXTC && TYTC) { 6176 auto *NCX = TXTC->getNamedConcept(); 6177 auto *NCY = TYTC->getNamedConcept(); 6178 if (!NCX || !NCY || !isSameEntity(NCX, NCY)) 6179 return false; 6180 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) 6181 return false; 6182 if (TXTC->hasExplicitTemplateArgs()) { 6183 auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); 6184 auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); 6185 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) 6186 return false; 6187 llvm::FoldingSetNodeID XID, YID; 6188 for (auto &ArgLoc : TXTCArgs->arguments()) 6189 ArgLoc.getArgument().Profile(XID, X->getASTContext()); 6190 for (auto &ArgLoc : TYTCArgs->arguments()) 6191 ArgLoc.getArgument().Profile(YID, Y->getASTContext()); 6192 if (XID != YID) 6193 return false; 6194 } 6195 } 6196 return true; 6197 } 6198 6199 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 6200 auto *TY = cast<NonTypeTemplateParmDecl>(Y); 6201 return TX->isParameterPack() == TY->isParameterPack() && 6202 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 6203 } 6204 6205 auto *TX = cast<TemplateTemplateParmDecl>(X); 6206 auto *TY = cast<TemplateTemplateParmDecl>(Y); 6207 return TX->isParameterPack() == TY->isParameterPack() && 6208 isSameTemplateParameterList(TX->getTemplateParameters(), 6209 TY->getTemplateParameters()); 6210 } 6211 6212 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, 6213 const TemplateParameterList *Y) { 6214 if (X->size() != Y->size()) 6215 return false; 6216 6217 for (unsigned I = 0, N = X->size(); I != N; ++I) 6218 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 6219 return false; 6220 6221 const Expr *XRC = X->getRequiresClause(); 6222 const Expr *YRC = Y->getRequiresClause(); 6223 if (!XRC != !YRC) 6224 return false; 6225 if (XRC) { 6226 llvm::FoldingSetNodeID XRCID, YRCID; 6227 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6228 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6229 if (XRCID != YRCID) 6230 return false; 6231 } 6232 6233 return true; 6234 } 6235 6236 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 6237 if (auto *NS = X->getAsNamespace()) 6238 return NS; 6239 if (auto *NAS = X->getAsNamespaceAlias()) 6240 return NAS->getNamespace(); 6241 return nullptr; 6242 } 6243 6244 static bool isSameQualifier(const NestedNameSpecifier *X, 6245 const NestedNameSpecifier *Y) { 6246 if (auto *NSX = getNamespace(X)) { 6247 auto *NSY = getNamespace(Y); 6248 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 6249 return false; 6250 } else if (X->getKind() != Y->getKind()) 6251 return false; 6252 6253 // FIXME: For namespaces and types, we're permitted to check that the entity 6254 // is named via the same tokens. We should probably do so. 6255 switch (X->getKind()) { 6256 case NestedNameSpecifier::Identifier: 6257 if (X->getAsIdentifier() != Y->getAsIdentifier()) 6258 return false; 6259 break; 6260 case NestedNameSpecifier::Namespace: 6261 case NestedNameSpecifier::NamespaceAlias: 6262 // We've already checked that we named the same namespace. 6263 break; 6264 case NestedNameSpecifier::TypeSpec: 6265 case NestedNameSpecifier::TypeSpecWithTemplate: 6266 if (X->getAsType()->getCanonicalTypeInternal() != 6267 Y->getAsType()->getCanonicalTypeInternal()) 6268 return false; 6269 break; 6270 case NestedNameSpecifier::Global: 6271 case NestedNameSpecifier::Super: 6272 return true; 6273 } 6274 6275 // Recurse into earlier portion of NNS, if any. 6276 auto *PX = X->getPrefix(); 6277 auto *PY = Y->getPrefix(); 6278 if (PX && PY) 6279 return isSameQualifier(PX, PY); 6280 return !PX && !PY; 6281 } 6282 6283 /// Determine whether the attributes we can overload on are identical for A and 6284 /// B. Will ignore any overloadable attrs represented in the type of A and B. 6285 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 6286 const FunctionDecl *B) { 6287 // Note that pass_object_size attributes are represented in the function's 6288 // ExtParameterInfo, so we don't need to check them here. 6289 6290 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 6291 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>(); 6292 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>(); 6293 6294 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) { 6295 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 6296 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 6297 6298 // Return false if the number of enable_if attributes is different. 6299 if (!Cand1A || !Cand2A) 6300 return false; 6301 6302 Cand1ID.clear(); 6303 Cand2ID.clear(); 6304 6305 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true); 6306 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true); 6307 6308 // Return false if any of the enable_if expressions of A and B are 6309 // different. 6310 if (Cand1ID != Cand2ID) 6311 return false; 6312 } 6313 return true; 6314 } 6315 6316 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { 6317 if (X == Y) 6318 return true; 6319 6320 if (X->getDeclName() != Y->getDeclName()) 6321 return false; 6322 6323 // Must be in the same context. 6324 // 6325 // Note that we can't use DeclContext::Equals here, because the DeclContexts 6326 // could be two different declarations of the same function. (We will fix the 6327 // semantic DC to refer to the primary definition after merging.) 6328 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()), 6329 cast<Decl>(Y->getDeclContext()->getRedeclContext()))) 6330 return false; 6331 6332 // Two typedefs refer to the same entity if they have the same underlying 6333 // type. 6334 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X)) 6335 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 6336 return hasSameType(TypedefX->getUnderlyingType(), 6337 TypedefY->getUnderlyingType()); 6338 6339 // Must have the same kind. 6340 if (X->getKind() != Y->getKind()) 6341 return false; 6342 6343 // Objective-C classes and protocols with the same name always match. 6344 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 6345 return true; 6346 6347 if (isa<ClassTemplateSpecializationDecl>(X)) { 6348 // No need to handle these here: we merge them when adding them to the 6349 // template. 6350 return false; 6351 } 6352 6353 // Compatible tags match. 6354 if (const auto *TagX = dyn_cast<TagDecl>(X)) { 6355 const auto *TagY = cast<TagDecl>(Y); 6356 return (TagX->getTagKind() == TagY->getTagKind()) || 6357 ((TagX->getTagKind() == TTK_Struct || 6358 TagX->getTagKind() == TTK_Class || 6359 TagX->getTagKind() == TTK_Interface) && 6360 (TagY->getTagKind() == TTK_Struct || 6361 TagY->getTagKind() == TTK_Class || 6362 TagY->getTagKind() == TTK_Interface)); 6363 } 6364 6365 // Functions with the same type and linkage match. 6366 // FIXME: This needs to cope with merging of prototyped/non-prototyped 6367 // functions, etc. 6368 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) { 6369 const auto *FuncY = cast<FunctionDecl>(Y); 6370 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 6371 const auto *CtorY = cast<CXXConstructorDecl>(Y); 6372 if (CtorX->getInheritedConstructor() && 6373 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 6374 CtorY->getInheritedConstructor().getConstructor())) 6375 return false; 6376 } 6377 6378 if (FuncX->isMultiVersion() != FuncY->isMultiVersion()) 6379 return false; 6380 6381 // Multiversioned functions with different feature strings are represented 6382 // as separate declarations. 6383 if (FuncX->isMultiVersion()) { 6384 const auto *TAX = FuncX->getAttr<TargetAttr>(); 6385 const auto *TAY = FuncY->getAttr<TargetAttr>(); 6386 assert(TAX && TAY && "Multiversion Function without target attribute"); 6387 6388 if (TAX->getFeaturesStr() != TAY->getFeaturesStr()) 6389 return false; 6390 } 6391 6392 const Expr *XRC = FuncX->getTrailingRequiresClause(); 6393 const Expr *YRC = FuncY->getTrailingRequiresClause(); 6394 if (!XRC != !YRC) 6395 return false; 6396 if (XRC) { 6397 llvm::FoldingSetNodeID XRCID, YRCID; 6398 XRC->Profile(XRCID, *this, /*Canonical=*/true); 6399 YRC->Profile(YRCID, *this, /*Canonical=*/true); 6400 if (XRCID != YRCID) 6401 return false; 6402 } 6403 6404 auto GetTypeAsWritten = [](const FunctionDecl *FD) { 6405 // Map to the first declaration that we've already merged into this one. 6406 // The TSI of redeclarations might not match (due to calling conventions 6407 // being inherited onto the type but not the TSI), but the TSI type of 6408 // the first declaration of the function should match across modules. 6409 FD = FD->getCanonicalDecl(); 6410 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType() 6411 : FD->getType(); 6412 }; 6413 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY); 6414 if (!hasSameType(XT, YT)) { 6415 // We can get functions with different types on the redecl chain in C++17 6416 // if they have differing exception specifications and at least one of 6417 // the excpetion specs is unresolved. 6418 auto *XFPT = XT->getAs<FunctionProtoType>(); 6419 auto *YFPT = YT->getAs<FunctionProtoType>(); 6420 if (getLangOpts().CPlusPlus17 && XFPT && YFPT && 6421 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || 6422 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && 6423 // FIXME: We could make isSameEntity const after we make 6424 // hasSameFunctionTypeIgnoringExceptionSpec const. 6425 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) 6426 return true; 6427 return false; 6428 } 6429 6430 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 6431 hasSameOverloadableAttrs(FuncX, FuncY); 6432 } 6433 6434 // Variables with the same type and linkage match. 6435 if (const auto *VarX = dyn_cast<VarDecl>(X)) { 6436 const auto *VarY = cast<VarDecl>(Y); 6437 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 6438 if (hasSameType(VarX->getType(), VarY->getType())) 6439 return true; 6440 6441 // We can get decls with different types on the redecl chain. Eg. 6442 // template <typename T> struct S { static T Var[]; }; // #1 6443 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 6444 // Only? happens when completing an incomplete array type. In this case 6445 // when comparing #1 and #2 we should go through their element type. 6446 const ArrayType *VarXTy = getAsArrayType(VarX->getType()); 6447 const ArrayType *VarYTy = getAsArrayType(VarY->getType()); 6448 if (!VarXTy || !VarYTy) 6449 return false; 6450 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 6451 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 6452 } 6453 return false; 6454 } 6455 6456 // Namespaces with the same name and inlinedness match. 6457 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 6458 const auto *NamespaceY = cast<NamespaceDecl>(Y); 6459 return NamespaceX->isInline() == NamespaceY->isInline(); 6460 } 6461 6462 // Identical template names and kinds match if their template parameter lists 6463 // and patterns match. 6464 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) { 6465 const auto *TemplateY = cast<TemplateDecl>(Y); 6466 return isSameEntity(TemplateX->getTemplatedDecl(), 6467 TemplateY->getTemplatedDecl()) && 6468 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 6469 TemplateY->getTemplateParameters()); 6470 } 6471 6472 // Fields with the same name and the same type match. 6473 if (const auto *FDX = dyn_cast<FieldDecl>(X)) { 6474 const auto *FDY = cast<FieldDecl>(Y); 6475 // FIXME: Also check the bitwidth is odr-equivalent, if any. 6476 return hasSameType(FDX->getType(), FDY->getType()); 6477 } 6478 6479 // Indirect fields with the same target field match. 6480 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 6481 const auto *IFDY = cast<IndirectFieldDecl>(Y); 6482 return IFDX->getAnonField()->getCanonicalDecl() == 6483 IFDY->getAnonField()->getCanonicalDecl(); 6484 } 6485 6486 // Enumerators with the same name match. 6487 if (isa<EnumConstantDecl>(X)) 6488 // FIXME: Also check the value is odr-equivalent. 6489 return true; 6490 6491 // Using shadow declarations with the same target match. 6492 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) { 6493 const auto *USY = cast<UsingShadowDecl>(Y); 6494 return USX->getTargetDecl() == USY->getTargetDecl(); 6495 } 6496 6497 // Using declarations with the same qualifier match. (We already know that 6498 // the name matches.) 6499 if (const auto *UX = dyn_cast<UsingDecl>(X)) { 6500 const auto *UY = cast<UsingDecl>(Y); 6501 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6502 UX->hasTypename() == UY->hasTypename() && 6503 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6504 } 6505 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 6506 const auto *UY = cast<UnresolvedUsingValueDecl>(Y); 6507 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 6508 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 6509 } 6510 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) { 6511 return isSameQualifier( 6512 UX->getQualifier(), 6513 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 6514 } 6515 6516 // Using-pack declarations are only created by instantiation, and match if 6517 // they're instantiated from matching UnresolvedUsing...Decls. 6518 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) { 6519 return declaresSameEntity( 6520 UX->getInstantiatedFromUsingDecl(), 6521 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl()); 6522 } 6523 6524 // Namespace alias definitions with the same target match. 6525 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 6526 const auto *NAY = cast<NamespaceAliasDecl>(Y); 6527 return NAX->getNamespace()->Equals(NAY->getNamespace()); 6528 } 6529 6530 return false; 6531 } 6532 6533 TemplateArgument 6534 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6535 switch (Arg.getKind()) { 6536 case TemplateArgument::Null: 6537 return Arg; 6538 6539 case TemplateArgument::Expression: 6540 return Arg; 6541 6542 case TemplateArgument::Declaration: { 6543 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6544 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6545 } 6546 6547 case TemplateArgument::NullPtr: 6548 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6549 /*isNullPtr*/true); 6550 6551 case TemplateArgument::Template: 6552 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6553 6554 case TemplateArgument::TemplateExpansion: 6555 return TemplateArgument(getCanonicalTemplateName( 6556 Arg.getAsTemplateOrTemplatePattern()), 6557 Arg.getNumTemplateExpansions()); 6558 6559 case TemplateArgument::Integral: 6560 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6561 6562 case TemplateArgument::Type: 6563 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6564 6565 case TemplateArgument::Pack: { 6566 if (Arg.pack_size() == 0) 6567 return Arg; 6568 6569 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6570 unsigned Idx = 0; 6571 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6572 AEnd = Arg.pack_end(); 6573 A != AEnd; (void)++A, ++Idx) 6574 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6575 6576 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6577 } 6578 } 6579 6580 // Silence GCC warning 6581 llvm_unreachable("Unhandled template argument kind"); 6582 } 6583 6584 NestedNameSpecifier * 6585 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6586 if (!NNS) 6587 return nullptr; 6588 6589 switch (NNS->getKind()) { 6590 case NestedNameSpecifier::Identifier: 6591 // Canonicalize the prefix but keep the identifier the same. 6592 return NestedNameSpecifier::Create(*this, 6593 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6594 NNS->getAsIdentifier()); 6595 6596 case NestedNameSpecifier::Namespace: 6597 // A namespace is canonical; build a nested-name-specifier with 6598 // this namespace and no prefix. 6599 return NestedNameSpecifier::Create(*this, nullptr, 6600 NNS->getAsNamespace()->getOriginalNamespace()); 6601 6602 case NestedNameSpecifier::NamespaceAlias: 6603 // A namespace is canonical; build a nested-name-specifier with 6604 // this namespace and no prefix. 6605 return NestedNameSpecifier::Create(*this, nullptr, 6606 NNS->getAsNamespaceAlias()->getNamespace() 6607 ->getOriginalNamespace()); 6608 6609 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6610 // latter will have the 'template' keyword when printed. 6611 case NestedNameSpecifier::TypeSpec: 6612 case NestedNameSpecifier::TypeSpecWithTemplate: { 6613 const Type *T = getCanonicalType(NNS->getAsType()); 6614 6615 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6616 // break it apart into its prefix and identifier, then reconsititute those 6617 // as the canonical nested-name-specifier. This is required to canonicalize 6618 // a dependent nested-name-specifier involving typedefs of dependent-name 6619 // types, e.g., 6620 // typedef typename T::type T1; 6621 // typedef typename T1::type T2; 6622 if (const auto *DNT = T->getAs<DependentNameType>()) 6623 return NestedNameSpecifier::Create( 6624 *this, DNT->getQualifier(), 6625 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6626 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6627 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6628 const_cast<Type *>(T)); 6629 6630 // TODO: Set 'Template' parameter to true for other template types. 6631 return NestedNameSpecifier::Create(*this, nullptr, false, 6632 const_cast<Type *>(T)); 6633 } 6634 6635 case NestedNameSpecifier::Global: 6636 case NestedNameSpecifier::Super: 6637 // The global specifier and __super specifer are canonical and unique. 6638 return NNS; 6639 } 6640 6641 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6642 } 6643 6644 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6645 // Handle the non-qualified case efficiently. 6646 if (!T.hasLocalQualifiers()) { 6647 // Handle the common positive case fast. 6648 if (const auto *AT = dyn_cast<ArrayType>(T)) 6649 return AT; 6650 } 6651 6652 // Handle the common negative case fast. 6653 if (!isa<ArrayType>(T.getCanonicalType())) 6654 return nullptr; 6655 6656 // Apply any qualifiers from the array type to the element type. This 6657 // implements C99 6.7.3p8: "If the specification of an array type includes 6658 // any type qualifiers, the element type is so qualified, not the array type." 6659 6660 // If we get here, we either have type qualifiers on the type, or we have 6661 // sugar such as a typedef in the way. If we have type qualifiers on the type 6662 // we must propagate them down into the element type. 6663 6664 SplitQualType split = T.getSplitDesugaredType(); 6665 Qualifiers qs = split.Quals; 6666 6667 // If we have a simple case, just return now. 6668 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6669 if (!ATy || qs.empty()) 6670 return ATy; 6671 6672 // Otherwise, we have an array and we have qualifiers on it. Push the 6673 // qualifiers into the array element type and return a new array type. 6674 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6675 6676 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6677 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6678 CAT->getSizeExpr(), 6679 CAT->getSizeModifier(), 6680 CAT->getIndexTypeCVRQualifiers())); 6681 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6682 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6683 IAT->getSizeModifier(), 6684 IAT->getIndexTypeCVRQualifiers())); 6685 6686 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6687 return cast<ArrayType>( 6688 getDependentSizedArrayType(NewEltTy, 6689 DSAT->getSizeExpr(), 6690 DSAT->getSizeModifier(), 6691 DSAT->getIndexTypeCVRQualifiers(), 6692 DSAT->getBracketsRange())); 6693 6694 const auto *VAT = cast<VariableArrayType>(ATy); 6695 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6696 VAT->getSizeExpr(), 6697 VAT->getSizeModifier(), 6698 VAT->getIndexTypeCVRQualifiers(), 6699 VAT->getBracketsRange())); 6700 } 6701 6702 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6703 if (T->isArrayType() || T->isFunctionType()) 6704 return getDecayedType(T); 6705 return T; 6706 } 6707 6708 QualType ASTContext::getSignatureParameterType(QualType T) const { 6709 T = getVariableArrayDecayedType(T); 6710 T = getAdjustedParameterType(T); 6711 return T.getUnqualifiedType(); 6712 } 6713 6714 QualType ASTContext::getExceptionObjectType(QualType T) const { 6715 // C++ [except.throw]p3: 6716 // A throw-expression initializes a temporary object, called the exception 6717 // object, the type of which is determined by removing any top-level 6718 // cv-qualifiers from the static type of the operand of throw and adjusting 6719 // the type from "array of T" or "function returning T" to "pointer to T" 6720 // or "pointer to function returning T", [...] 6721 T = getVariableArrayDecayedType(T); 6722 if (T->isArrayType() || T->isFunctionType()) 6723 T = getDecayedType(T); 6724 return T.getUnqualifiedType(); 6725 } 6726 6727 /// getArrayDecayedType - Return the properly qualified result of decaying the 6728 /// specified array type to a pointer. This operation is non-trivial when 6729 /// handling typedefs etc. The canonical type of "T" must be an array type, 6730 /// this returns a pointer to a properly qualified element of the array. 6731 /// 6732 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6733 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6734 // Get the element type with 'getAsArrayType' so that we don't lose any 6735 // typedefs in the element type of the array. This also handles propagation 6736 // of type qualifiers from the array type into the element type if present 6737 // (C99 6.7.3p8). 6738 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6739 assert(PrettyArrayType && "Not an array type!"); 6740 6741 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6742 6743 // int x[restrict 4] -> int *restrict 6744 QualType Result = getQualifiedType(PtrTy, 6745 PrettyArrayType->getIndexTypeQualifiers()); 6746 6747 // int x[_Nullable] -> int * _Nullable 6748 if (auto Nullability = Ty->getNullability(*this)) { 6749 Result = const_cast<ASTContext *>(this)->getAttributedType( 6750 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6751 } 6752 return Result; 6753 } 6754 6755 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6756 return getBaseElementType(array->getElementType()); 6757 } 6758 6759 QualType ASTContext::getBaseElementType(QualType type) const { 6760 Qualifiers qs; 6761 while (true) { 6762 SplitQualType split = type.getSplitDesugaredType(); 6763 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6764 if (!array) break; 6765 6766 type = array->getElementType(); 6767 qs.addConsistentQualifiers(split.Quals); 6768 } 6769 6770 return getQualifiedType(type, qs); 6771 } 6772 6773 /// getConstantArrayElementCount - Returns number of constant array elements. 6774 uint64_t 6775 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6776 uint64_t ElementCount = 1; 6777 do { 6778 ElementCount *= CA->getSize().getZExtValue(); 6779 CA = dyn_cast_or_null<ConstantArrayType>( 6780 CA->getElementType()->getAsArrayTypeUnsafe()); 6781 } while (CA); 6782 return ElementCount; 6783 } 6784 6785 /// getFloatingRank - Return a relative rank for floating point types. 6786 /// This routine will assert if passed a built-in type that isn't a float. 6787 static FloatingRank getFloatingRank(QualType T) { 6788 if (const auto *CT = T->getAs<ComplexType>()) 6789 return getFloatingRank(CT->getElementType()); 6790 6791 switch (T->castAs<BuiltinType>()->getKind()) { 6792 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6793 case BuiltinType::Float16: return Float16Rank; 6794 case BuiltinType::Half: return HalfRank; 6795 case BuiltinType::Float: return FloatRank; 6796 case BuiltinType::Double: return DoubleRank; 6797 case BuiltinType::LongDouble: return LongDoubleRank; 6798 case BuiltinType::Float128: return Float128Rank; 6799 case BuiltinType::BFloat16: return BFloat16Rank; 6800 case BuiltinType::Ibm128: return Ibm128Rank; 6801 } 6802 } 6803 6804 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6805 /// point types, ignoring the domain of the type (i.e. 'double' == 6806 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6807 /// LHS < RHS, return -1. 6808 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6809 FloatingRank LHSR = getFloatingRank(LHS); 6810 FloatingRank RHSR = getFloatingRank(RHS); 6811 6812 if (LHSR == RHSR) 6813 return 0; 6814 if (LHSR > RHSR) 6815 return 1; 6816 return -1; 6817 } 6818 6819 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6820 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6821 return 0; 6822 return getFloatingTypeOrder(LHS, RHS); 6823 } 6824 6825 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6826 /// routine will assert if passed a built-in type that isn't an integer or enum, 6827 /// or if it is not canonicalized. 6828 unsigned ASTContext::getIntegerRank(const Type *T) const { 6829 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6830 6831 // Results in this 'losing' to any type of the same size, but winning if 6832 // larger. 6833 if (const auto *EIT = dyn_cast<BitIntType>(T)) 6834 return 0 + (EIT->getNumBits() << 3); 6835 6836 switch (cast<BuiltinType>(T)->getKind()) { 6837 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6838 case BuiltinType::Bool: 6839 return 1 + (getIntWidth(BoolTy) << 3); 6840 case BuiltinType::Char_S: 6841 case BuiltinType::Char_U: 6842 case BuiltinType::SChar: 6843 case BuiltinType::UChar: 6844 return 2 + (getIntWidth(CharTy) << 3); 6845 case BuiltinType::Short: 6846 case BuiltinType::UShort: 6847 return 3 + (getIntWidth(ShortTy) << 3); 6848 case BuiltinType::Int: 6849 case BuiltinType::UInt: 6850 return 4 + (getIntWidth(IntTy) << 3); 6851 case BuiltinType::Long: 6852 case BuiltinType::ULong: 6853 return 5 + (getIntWidth(LongTy) << 3); 6854 case BuiltinType::LongLong: 6855 case BuiltinType::ULongLong: 6856 return 6 + (getIntWidth(LongLongTy) << 3); 6857 case BuiltinType::Int128: 6858 case BuiltinType::UInt128: 6859 return 7 + (getIntWidth(Int128Ty) << 3); 6860 } 6861 } 6862 6863 /// Whether this is a promotable bitfield reference according 6864 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6865 /// 6866 /// \returns the type this bit-field will promote to, or NULL if no 6867 /// promotion occurs. 6868 QualType ASTContext::isPromotableBitField(Expr *E) const { 6869 if (E->isTypeDependent() || E->isValueDependent()) 6870 return {}; 6871 6872 // C++ [conv.prom]p5: 6873 // If the bit-field has an enumerated type, it is treated as any other 6874 // value of that type for promotion purposes. 6875 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6876 return {}; 6877 6878 // FIXME: We should not do this unless E->refersToBitField() is true. This 6879 // matters in C where getSourceBitField() will find bit-fields for various 6880 // cases where the source expression is not a bit-field designator. 6881 6882 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6883 if (!Field) 6884 return {}; 6885 6886 QualType FT = Field->getType(); 6887 6888 uint64_t BitWidth = Field->getBitWidthValue(*this); 6889 uint64_t IntSize = getTypeSize(IntTy); 6890 // C++ [conv.prom]p5: 6891 // A prvalue for an integral bit-field can be converted to a prvalue of type 6892 // int if int can represent all the values of the bit-field; otherwise, it 6893 // can be converted to unsigned int if unsigned int can represent all the 6894 // values of the bit-field. If the bit-field is larger yet, no integral 6895 // promotion applies to it. 6896 // C11 6.3.1.1/2: 6897 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6898 // If an int can represent all values of the original type (as restricted by 6899 // the width, for a bit-field), the value is converted to an int; otherwise, 6900 // it is converted to an unsigned int. 6901 // 6902 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6903 // We perform that promotion here to match GCC and C++. 6904 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6905 // greater than that of 'int'. We perform that promotion to match GCC. 6906 if (BitWidth < IntSize) 6907 return IntTy; 6908 6909 if (BitWidth == IntSize) 6910 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6911 6912 // Bit-fields wider than int are not subject to promotions, and therefore act 6913 // like the base type. GCC has some weird bugs in this area that we 6914 // deliberately do not follow (GCC follows a pre-standard resolution to 6915 // C's DR315 which treats bit-width as being part of the type, and this leaks 6916 // into their semantics in some cases). 6917 return {}; 6918 } 6919 6920 /// getPromotedIntegerType - Returns the type that Promotable will 6921 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6922 /// integer type. 6923 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6924 assert(!Promotable.isNull()); 6925 assert(Promotable->isPromotableIntegerType()); 6926 if (const auto *ET = Promotable->getAs<EnumType>()) 6927 return ET->getDecl()->getPromotionType(); 6928 6929 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6930 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6931 // (3.9.1) can be converted to a prvalue of the first of the following 6932 // types that can represent all the values of its underlying type: 6933 // int, unsigned int, long int, unsigned long int, long long int, or 6934 // unsigned long long int [...] 6935 // FIXME: Is there some better way to compute this? 6936 if (BT->getKind() == BuiltinType::WChar_S || 6937 BT->getKind() == BuiltinType::WChar_U || 6938 BT->getKind() == BuiltinType::Char8 || 6939 BT->getKind() == BuiltinType::Char16 || 6940 BT->getKind() == BuiltinType::Char32) { 6941 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6942 uint64_t FromSize = getTypeSize(BT); 6943 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6944 LongLongTy, UnsignedLongLongTy }; 6945 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6946 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6947 if (FromSize < ToSize || 6948 (FromSize == ToSize && 6949 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6950 return PromoteTypes[Idx]; 6951 } 6952 llvm_unreachable("char type should fit into long long"); 6953 } 6954 } 6955 6956 // At this point, we should have a signed or unsigned integer type. 6957 if (Promotable->isSignedIntegerType()) 6958 return IntTy; 6959 uint64_t PromotableSize = getIntWidth(Promotable); 6960 uint64_t IntSize = getIntWidth(IntTy); 6961 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6962 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6963 } 6964 6965 /// Recurses in pointer/array types until it finds an objc retainable 6966 /// type and returns its ownership. 6967 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6968 while (!T.isNull()) { 6969 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6970 return T.getObjCLifetime(); 6971 if (T->isArrayType()) 6972 T = getBaseElementType(T); 6973 else if (const auto *PT = T->getAs<PointerType>()) 6974 T = PT->getPointeeType(); 6975 else if (const auto *RT = T->getAs<ReferenceType>()) 6976 T = RT->getPointeeType(); 6977 else 6978 break; 6979 } 6980 6981 return Qualifiers::OCL_None; 6982 } 6983 6984 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6985 // Incomplete enum types are not treated as integer types. 6986 // FIXME: In C++, enum types are never integer types. 6987 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6988 return ET->getDecl()->getIntegerType().getTypePtr(); 6989 return nullptr; 6990 } 6991 6992 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6993 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6994 /// LHS < RHS, return -1. 6995 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6996 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6997 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6998 6999 // Unwrap enums to their underlying type. 7000 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 7001 LHSC = getIntegerTypeForEnum(ET); 7002 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 7003 RHSC = getIntegerTypeForEnum(ET); 7004 7005 if (LHSC == RHSC) return 0; 7006 7007 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 7008 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 7009 7010 unsigned LHSRank = getIntegerRank(LHSC); 7011 unsigned RHSRank = getIntegerRank(RHSC); 7012 7013 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 7014 if (LHSRank == RHSRank) return 0; 7015 return LHSRank > RHSRank ? 1 : -1; 7016 } 7017 7018 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 7019 if (LHSUnsigned) { 7020 // If the unsigned [LHS] type is larger, return it. 7021 if (LHSRank >= RHSRank) 7022 return 1; 7023 7024 // If the signed type can represent all values of the unsigned type, it 7025 // wins. Because we are dealing with 2's complement and types that are 7026 // powers of two larger than each other, this is always safe. 7027 return -1; 7028 } 7029 7030 // If the unsigned [RHS] type is larger, return it. 7031 if (RHSRank >= LHSRank) 7032 return -1; 7033 7034 // If the signed type can represent all values of the unsigned type, it 7035 // wins. Because we are dealing with 2's complement and types that are 7036 // powers of two larger than each other, this is always safe. 7037 return 1; 7038 } 7039 7040 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 7041 if (CFConstantStringTypeDecl) 7042 return CFConstantStringTypeDecl; 7043 7044 assert(!CFConstantStringTagDecl && 7045 "tag and typedef should be initialized together"); 7046 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 7047 CFConstantStringTagDecl->startDefinition(); 7048 7049 struct { 7050 QualType Type; 7051 const char *Name; 7052 } Fields[5]; 7053 unsigned Count = 0; 7054 7055 /// Objective-C ABI 7056 /// 7057 /// typedef struct __NSConstantString_tag { 7058 /// const int *isa; 7059 /// int flags; 7060 /// const char *str; 7061 /// long length; 7062 /// } __NSConstantString; 7063 /// 7064 /// Swift ABI (4.1, 4.2) 7065 /// 7066 /// typedef struct __NSConstantString_tag { 7067 /// uintptr_t _cfisa; 7068 /// uintptr_t _swift_rc; 7069 /// _Atomic(uint64_t) _cfinfoa; 7070 /// const char *_ptr; 7071 /// uint32_t _length; 7072 /// } __NSConstantString; 7073 /// 7074 /// Swift ABI (5.0) 7075 /// 7076 /// typedef struct __NSConstantString_tag { 7077 /// uintptr_t _cfisa; 7078 /// uintptr_t _swift_rc; 7079 /// _Atomic(uint64_t) _cfinfoa; 7080 /// const char *_ptr; 7081 /// uintptr_t _length; 7082 /// } __NSConstantString; 7083 7084 const auto CFRuntime = getLangOpts().CFRuntime; 7085 if (static_cast<unsigned>(CFRuntime) < 7086 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 7087 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 7088 Fields[Count++] = { IntTy, "flags" }; 7089 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 7090 Fields[Count++] = { LongTy, "length" }; 7091 } else { 7092 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 7093 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 7094 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 7095 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 7096 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 7097 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 7098 Fields[Count++] = { IntTy, "_ptr" }; 7099 else 7100 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 7101 } 7102 7103 // Create fields 7104 for (unsigned i = 0; i < Count; ++i) { 7105 FieldDecl *Field = 7106 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 7107 SourceLocation(), &Idents.get(Fields[i].Name), 7108 Fields[i].Type, /*TInfo=*/nullptr, 7109 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7110 Field->setAccess(AS_public); 7111 CFConstantStringTagDecl->addDecl(Field); 7112 } 7113 7114 CFConstantStringTagDecl->completeDefinition(); 7115 // This type is designed to be compatible with NSConstantString, but cannot 7116 // use the same name, since NSConstantString is an interface. 7117 auto tagType = getTagDeclType(CFConstantStringTagDecl); 7118 CFConstantStringTypeDecl = 7119 buildImplicitTypedef(tagType, "__NSConstantString"); 7120 7121 return CFConstantStringTypeDecl; 7122 } 7123 7124 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 7125 if (!CFConstantStringTagDecl) 7126 getCFConstantStringDecl(); // Build the tag and the typedef. 7127 return CFConstantStringTagDecl; 7128 } 7129 7130 // getCFConstantStringType - Return the type used for constant CFStrings. 7131 QualType ASTContext::getCFConstantStringType() const { 7132 return getTypedefType(getCFConstantStringDecl()); 7133 } 7134 7135 QualType ASTContext::getObjCSuperType() const { 7136 if (ObjCSuperType.isNull()) { 7137 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 7138 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 7139 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 7140 } 7141 return ObjCSuperType; 7142 } 7143 7144 void ASTContext::setCFConstantStringType(QualType T) { 7145 const auto *TD = T->castAs<TypedefType>(); 7146 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 7147 const auto *TagType = 7148 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 7149 CFConstantStringTagDecl = TagType->getDecl(); 7150 } 7151 7152 QualType ASTContext::getBlockDescriptorType() const { 7153 if (BlockDescriptorType) 7154 return getTagDeclType(BlockDescriptorType); 7155 7156 RecordDecl *RD; 7157 // FIXME: Needs the FlagAppleBlock bit. 7158 RD = buildImplicitRecord("__block_descriptor"); 7159 RD->startDefinition(); 7160 7161 QualType FieldTypes[] = { 7162 UnsignedLongTy, 7163 UnsignedLongTy, 7164 }; 7165 7166 static const char *const FieldNames[] = { 7167 "reserved", 7168 "Size" 7169 }; 7170 7171 for (size_t i = 0; i < 2; ++i) { 7172 FieldDecl *Field = FieldDecl::Create( 7173 *this, RD, SourceLocation(), SourceLocation(), 7174 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7175 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 7176 Field->setAccess(AS_public); 7177 RD->addDecl(Field); 7178 } 7179 7180 RD->completeDefinition(); 7181 7182 BlockDescriptorType = RD; 7183 7184 return getTagDeclType(BlockDescriptorType); 7185 } 7186 7187 QualType ASTContext::getBlockDescriptorExtendedType() const { 7188 if (BlockDescriptorExtendedType) 7189 return getTagDeclType(BlockDescriptorExtendedType); 7190 7191 RecordDecl *RD; 7192 // FIXME: Needs the FlagAppleBlock bit. 7193 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 7194 RD->startDefinition(); 7195 7196 QualType FieldTypes[] = { 7197 UnsignedLongTy, 7198 UnsignedLongTy, 7199 getPointerType(VoidPtrTy), 7200 getPointerType(VoidPtrTy) 7201 }; 7202 7203 static const char *const FieldNames[] = { 7204 "reserved", 7205 "Size", 7206 "CopyFuncPtr", 7207 "DestroyFuncPtr" 7208 }; 7209 7210 for (size_t i = 0; i < 4; ++i) { 7211 FieldDecl *Field = FieldDecl::Create( 7212 *this, RD, SourceLocation(), SourceLocation(), 7213 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 7214 /*BitWidth=*/nullptr, 7215 /*Mutable=*/false, ICIS_NoInit); 7216 Field->setAccess(AS_public); 7217 RD->addDecl(Field); 7218 } 7219 7220 RD->completeDefinition(); 7221 7222 BlockDescriptorExtendedType = RD; 7223 return getTagDeclType(BlockDescriptorExtendedType); 7224 } 7225 7226 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 7227 const auto *BT = dyn_cast<BuiltinType>(T); 7228 7229 if (!BT) { 7230 if (isa<PipeType>(T)) 7231 return OCLTK_Pipe; 7232 7233 return OCLTK_Default; 7234 } 7235 7236 switch (BT->getKind()) { 7237 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7238 case BuiltinType::Id: \ 7239 return OCLTK_Image; 7240 #include "clang/Basic/OpenCLImageTypes.def" 7241 7242 case BuiltinType::OCLClkEvent: 7243 return OCLTK_ClkEvent; 7244 7245 case BuiltinType::OCLEvent: 7246 return OCLTK_Event; 7247 7248 case BuiltinType::OCLQueue: 7249 return OCLTK_Queue; 7250 7251 case BuiltinType::OCLReserveID: 7252 return OCLTK_ReserveID; 7253 7254 case BuiltinType::OCLSampler: 7255 return OCLTK_Sampler; 7256 7257 default: 7258 return OCLTK_Default; 7259 } 7260 } 7261 7262 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 7263 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 7264 } 7265 7266 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 7267 /// requires copy/dispose. Note that this must match the logic 7268 /// in buildByrefHelpers. 7269 bool ASTContext::BlockRequiresCopying(QualType Ty, 7270 const VarDecl *D) { 7271 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 7272 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 7273 if (!copyExpr && record->hasTrivialDestructor()) return false; 7274 7275 return true; 7276 } 7277 7278 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 7279 // move or destroy. 7280 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 7281 return true; 7282 7283 if (!Ty->isObjCRetainableType()) return false; 7284 7285 Qualifiers qs = Ty.getQualifiers(); 7286 7287 // If we have lifetime, that dominates. 7288 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 7289 switch (lifetime) { 7290 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 7291 7292 // These are just bits as far as the runtime is concerned. 7293 case Qualifiers::OCL_ExplicitNone: 7294 case Qualifiers::OCL_Autoreleasing: 7295 return false; 7296 7297 // These cases should have been taken care of when checking the type's 7298 // non-triviality. 7299 case Qualifiers::OCL_Weak: 7300 case Qualifiers::OCL_Strong: 7301 llvm_unreachable("impossible"); 7302 } 7303 llvm_unreachable("fell out of lifetime switch!"); 7304 } 7305 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 7306 Ty->isObjCObjectPointerType()); 7307 } 7308 7309 bool ASTContext::getByrefLifetime(QualType Ty, 7310 Qualifiers::ObjCLifetime &LifeTime, 7311 bool &HasByrefExtendedLayout) const { 7312 if (!getLangOpts().ObjC || 7313 getLangOpts().getGC() != LangOptions::NonGC) 7314 return false; 7315 7316 HasByrefExtendedLayout = false; 7317 if (Ty->isRecordType()) { 7318 HasByrefExtendedLayout = true; 7319 LifeTime = Qualifiers::OCL_None; 7320 } else if ((LifeTime = Ty.getObjCLifetime())) { 7321 // Honor the ARC qualifiers. 7322 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 7323 // The MRR rule. 7324 LifeTime = Qualifiers::OCL_ExplicitNone; 7325 } else { 7326 LifeTime = Qualifiers::OCL_None; 7327 } 7328 return true; 7329 } 7330 7331 CanQualType ASTContext::getNSUIntegerType() const { 7332 assert(Target && "Expected target to be initialized"); 7333 const llvm::Triple &T = Target->getTriple(); 7334 // Windows is LLP64 rather than LP64 7335 if (T.isOSWindows() && T.isArch64Bit()) 7336 return UnsignedLongLongTy; 7337 return UnsignedLongTy; 7338 } 7339 7340 CanQualType ASTContext::getNSIntegerType() const { 7341 assert(Target && "Expected target to be initialized"); 7342 const llvm::Triple &T = Target->getTriple(); 7343 // Windows is LLP64 rather than LP64 7344 if (T.isOSWindows() && T.isArch64Bit()) 7345 return LongLongTy; 7346 return LongTy; 7347 } 7348 7349 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 7350 if (!ObjCInstanceTypeDecl) 7351 ObjCInstanceTypeDecl = 7352 buildImplicitTypedef(getObjCIdType(), "instancetype"); 7353 return ObjCInstanceTypeDecl; 7354 } 7355 7356 // This returns true if a type has been typedefed to BOOL: 7357 // typedef <type> BOOL; 7358 static bool isTypeTypedefedAsBOOL(QualType T) { 7359 if (const auto *TT = dyn_cast<TypedefType>(T)) 7360 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 7361 return II->isStr("BOOL"); 7362 7363 return false; 7364 } 7365 7366 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 7367 /// purpose. 7368 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 7369 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 7370 return CharUnits::Zero(); 7371 7372 CharUnits sz = getTypeSizeInChars(type); 7373 7374 // Make all integer and enum types at least as large as an int 7375 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 7376 sz = std::max(sz, getTypeSizeInChars(IntTy)); 7377 // Treat arrays as pointers, since that's how they're passed in. 7378 else if (type->isArrayType()) 7379 sz = getTypeSizeInChars(VoidPtrTy); 7380 return sz; 7381 } 7382 7383 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 7384 return getTargetInfo().getCXXABI().isMicrosoft() && 7385 VD->isStaticDataMember() && 7386 VD->getType()->isIntegralOrEnumerationType() && 7387 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 7388 } 7389 7390 ASTContext::InlineVariableDefinitionKind 7391 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 7392 if (!VD->isInline()) 7393 return InlineVariableDefinitionKind::None; 7394 7395 // In almost all cases, it's a weak definition. 7396 auto *First = VD->getFirstDecl(); 7397 if (First->isInlineSpecified() || !First->isStaticDataMember()) 7398 return InlineVariableDefinitionKind::Weak; 7399 7400 // If there's a file-context declaration in this translation unit, it's a 7401 // non-discardable definition. 7402 for (auto *D : VD->redecls()) 7403 if (D->getLexicalDeclContext()->isFileContext() && 7404 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 7405 return InlineVariableDefinitionKind::Strong; 7406 7407 // If we've not seen one yet, we don't know. 7408 return InlineVariableDefinitionKind::WeakUnknown; 7409 } 7410 7411 static std::string charUnitsToString(const CharUnits &CU) { 7412 return llvm::itostr(CU.getQuantity()); 7413 } 7414 7415 /// getObjCEncodingForBlock - Return the encoded type for this block 7416 /// declaration. 7417 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 7418 std::string S; 7419 7420 const BlockDecl *Decl = Expr->getBlockDecl(); 7421 QualType BlockTy = 7422 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 7423 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 7424 // Encode result type. 7425 if (getLangOpts().EncodeExtendedBlockSig) 7426 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 7427 true /*Extended*/); 7428 else 7429 getObjCEncodingForType(BlockReturnTy, S); 7430 // Compute size of all parameters. 7431 // Start with computing size of a pointer in number of bytes. 7432 // FIXME: There might(should) be a better way of doing this computation! 7433 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7434 CharUnits ParmOffset = PtrSize; 7435 for (auto PI : Decl->parameters()) { 7436 QualType PType = PI->getType(); 7437 CharUnits sz = getObjCEncodingTypeSize(PType); 7438 if (sz.isZero()) 7439 continue; 7440 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 7441 ParmOffset += sz; 7442 } 7443 // Size of the argument frame 7444 S += charUnitsToString(ParmOffset); 7445 // Block pointer and offset. 7446 S += "@?0"; 7447 7448 // Argument types. 7449 ParmOffset = PtrSize; 7450 for (auto PVDecl : Decl->parameters()) { 7451 QualType PType = PVDecl->getOriginalType(); 7452 if (const auto *AT = 7453 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7454 // Use array's original type only if it has known number of 7455 // elements. 7456 if (!isa<ConstantArrayType>(AT)) 7457 PType = PVDecl->getType(); 7458 } else if (PType->isFunctionType()) 7459 PType = PVDecl->getType(); 7460 if (getLangOpts().EncodeExtendedBlockSig) 7461 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 7462 S, true /*Extended*/); 7463 else 7464 getObjCEncodingForType(PType, S); 7465 S += charUnitsToString(ParmOffset); 7466 ParmOffset += getObjCEncodingTypeSize(PType); 7467 } 7468 7469 return S; 7470 } 7471 7472 std::string 7473 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 7474 std::string S; 7475 // Encode result type. 7476 getObjCEncodingForType(Decl->getReturnType(), S); 7477 CharUnits ParmOffset; 7478 // Compute size of all parameters. 7479 for (auto PI : Decl->parameters()) { 7480 QualType PType = PI->getType(); 7481 CharUnits sz = getObjCEncodingTypeSize(PType); 7482 if (sz.isZero()) 7483 continue; 7484 7485 assert(sz.isPositive() && 7486 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7487 ParmOffset += sz; 7488 } 7489 S += charUnitsToString(ParmOffset); 7490 ParmOffset = CharUnits::Zero(); 7491 7492 // Argument types. 7493 for (auto PVDecl : Decl->parameters()) { 7494 QualType PType = PVDecl->getOriginalType(); 7495 if (const auto *AT = 7496 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7497 // Use array's original type only if it has known number of 7498 // elements. 7499 if (!isa<ConstantArrayType>(AT)) 7500 PType = PVDecl->getType(); 7501 } else if (PType->isFunctionType()) 7502 PType = PVDecl->getType(); 7503 getObjCEncodingForType(PType, S); 7504 S += charUnitsToString(ParmOffset); 7505 ParmOffset += getObjCEncodingTypeSize(PType); 7506 } 7507 7508 return S; 7509 } 7510 7511 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7512 /// method parameter or return type. If Extended, include class names and 7513 /// block object types. 7514 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7515 QualType T, std::string& S, 7516 bool Extended) const { 7517 // Encode type qualifier, 'in', 'inout', etc. for the parameter. 7518 getObjCEncodingForTypeQualifier(QT, S); 7519 // Encode parameter type. 7520 ObjCEncOptions Options = ObjCEncOptions() 7521 .setExpandPointedToStructures() 7522 .setExpandStructures() 7523 .setIsOutermostType(); 7524 if (Extended) 7525 Options.setEncodeBlockParameters().setEncodeClassNames(); 7526 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7527 } 7528 7529 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7530 /// declaration. 7531 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7532 bool Extended) const { 7533 // FIXME: This is not very efficient. 7534 // Encode return type. 7535 std::string S; 7536 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7537 Decl->getReturnType(), S, Extended); 7538 // Compute size of all parameters. 7539 // Start with computing size of a pointer in number of bytes. 7540 // FIXME: There might(should) be a better way of doing this computation! 7541 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7542 // The first two arguments (self and _cmd) are pointers; account for 7543 // their size. 7544 CharUnits ParmOffset = 2 * PtrSize; 7545 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7546 E = Decl->sel_param_end(); PI != E; ++PI) { 7547 QualType PType = (*PI)->getType(); 7548 CharUnits sz = getObjCEncodingTypeSize(PType); 7549 if (sz.isZero()) 7550 continue; 7551 7552 assert(sz.isPositive() && 7553 "getObjCEncodingForMethodDecl - Incomplete param type"); 7554 ParmOffset += sz; 7555 } 7556 S += charUnitsToString(ParmOffset); 7557 S += "@0:"; 7558 S += charUnitsToString(PtrSize); 7559 7560 // Argument types. 7561 ParmOffset = 2 * PtrSize; 7562 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7563 E = Decl->sel_param_end(); PI != E; ++PI) { 7564 const ParmVarDecl *PVDecl = *PI; 7565 QualType PType = PVDecl->getOriginalType(); 7566 if (const auto *AT = 7567 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7568 // Use array's original type only if it has known number of 7569 // elements. 7570 if (!isa<ConstantArrayType>(AT)) 7571 PType = PVDecl->getType(); 7572 } else if (PType->isFunctionType()) 7573 PType = PVDecl->getType(); 7574 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7575 PType, S, Extended); 7576 S += charUnitsToString(ParmOffset); 7577 ParmOffset += getObjCEncodingTypeSize(PType); 7578 } 7579 7580 return S; 7581 } 7582 7583 ObjCPropertyImplDecl * 7584 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7585 const ObjCPropertyDecl *PD, 7586 const Decl *Container) const { 7587 if (!Container) 7588 return nullptr; 7589 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7590 for (auto *PID : CID->property_impls()) 7591 if (PID->getPropertyDecl() == PD) 7592 return PID; 7593 } else { 7594 const auto *OID = cast<ObjCImplementationDecl>(Container); 7595 for (auto *PID : OID->property_impls()) 7596 if (PID->getPropertyDecl() == PD) 7597 return PID; 7598 } 7599 return nullptr; 7600 } 7601 7602 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7603 /// property declaration. If non-NULL, Container must be either an 7604 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7605 /// NULL when getting encodings for protocol properties. 7606 /// Property attributes are stored as a comma-delimited C string. The simple 7607 /// attributes readonly and bycopy are encoded as single characters. The 7608 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7609 /// encoded as single characters, followed by an identifier. Property types 7610 /// are also encoded as a parametrized attribute. The characters used to encode 7611 /// these attributes are defined by the following enumeration: 7612 /// @code 7613 /// enum PropertyAttributes { 7614 /// kPropertyReadOnly = 'R', // property is read-only. 7615 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7616 /// kPropertyByref = '&', // property is a reference to the value last assigned 7617 /// kPropertyDynamic = 'D', // property is dynamic 7618 /// kPropertyGetter = 'G', // followed by getter selector name 7619 /// kPropertySetter = 'S', // followed by setter selector name 7620 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7621 /// kPropertyType = 'T' // followed by old-style type encoding. 7622 /// kPropertyWeak = 'W' // 'weak' property 7623 /// kPropertyStrong = 'P' // property GC'able 7624 /// kPropertyNonAtomic = 'N' // property non-atomic 7625 /// }; 7626 /// @endcode 7627 std::string 7628 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7629 const Decl *Container) const { 7630 // Collect information from the property implementation decl(s). 7631 bool Dynamic = false; 7632 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7633 7634 if (ObjCPropertyImplDecl *PropertyImpDecl = 7635 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7636 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7637 Dynamic = true; 7638 else 7639 SynthesizePID = PropertyImpDecl; 7640 } 7641 7642 // FIXME: This is not very efficient. 7643 std::string S = "T"; 7644 7645 // Encode result type. 7646 // GCC has some special rules regarding encoding of properties which 7647 // closely resembles encoding of ivars. 7648 getObjCEncodingForPropertyType(PD->getType(), S); 7649 7650 if (PD->isReadOnly()) { 7651 S += ",R"; 7652 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7653 S += ",C"; 7654 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7655 S += ",&"; 7656 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7657 S += ",W"; 7658 } else { 7659 switch (PD->getSetterKind()) { 7660 case ObjCPropertyDecl::Assign: break; 7661 case ObjCPropertyDecl::Copy: S += ",C"; break; 7662 case ObjCPropertyDecl::Retain: S += ",&"; break; 7663 case ObjCPropertyDecl::Weak: S += ",W"; break; 7664 } 7665 } 7666 7667 // It really isn't clear at all what this means, since properties 7668 // are "dynamic by default". 7669 if (Dynamic) 7670 S += ",D"; 7671 7672 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7673 S += ",N"; 7674 7675 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7676 S += ",G"; 7677 S += PD->getGetterName().getAsString(); 7678 } 7679 7680 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7681 S += ",S"; 7682 S += PD->getSetterName().getAsString(); 7683 } 7684 7685 if (SynthesizePID) { 7686 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7687 S += ",V"; 7688 S += OID->getNameAsString(); 7689 } 7690 7691 // FIXME: OBJCGC: weak & strong 7692 return S; 7693 } 7694 7695 /// getLegacyIntegralTypeEncoding - 7696 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7697 /// 'l' or 'L' , but not always. For typedefs, we need to use 7698 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7699 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7700 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7701 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7702 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7703 PointeeTy = UnsignedIntTy; 7704 else 7705 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7706 PointeeTy = IntTy; 7707 } 7708 } 7709 } 7710 7711 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7712 const FieldDecl *Field, 7713 QualType *NotEncodedT) const { 7714 // We follow the behavior of gcc, expanding structures which are 7715 // directly pointed to, and expanding embedded structures. Note that 7716 // these rules are sufficient to prevent recursive encoding of the 7717 // same type. 7718 getObjCEncodingForTypeImpl(T, S, 7719 ObjCEncOptions() 7720 .setExpandPointedToStructures() 7721 .setExpandStructures() 7722 .setIsOutermostType(), 7723 Field, NotEncodedT); 7724 } 7725 7726 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7727 std::string& S) const { 7728 // Encode result type. 7729 // GCC has some special rules regarding encoding of properties which 7730 // closely resembles encoding of ivars. 7731 getObjCEncodingForTypeImpl(T, S, 7732 ObjCEncOptions() 7733 .setExpandPointedToStructures() 7734 .setExpandStructures() 7735 .setIsOutermostType() 7736 .setEncodingProperty(), 7737 /*Field=*/nullptr); 7738 } 7739 7740 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7741 const BuiltinType *BT) { 7742 BuiltinType::Kind kind = BT->getKind(); 7743 switch (kind) { 7744 case BuiltinType::Void: return 'v'; 7745 case BuiltinType::Bool: return 'B'; 7746 case BuiltinType::Char8: 7747 case BuiltinType::Char_U: 7748 case BuiltinType::UChar: return 'C'; 7749 case BuiltinType::Char16: 7750 case BuiltinType::UShort: return 'S'; 7751 case BuiltinType::Char32: 7752 case BuiltinType::UInt: return 'I'; 7753 case BuiltinType::ULong: 7754 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7755 case BuiltinType::UInt128: return 'T'; 7756 case BuiltinType::ULongLong: return 'Q'; 7757 case BuiltinType::Char_S: 7758 case BuiltinType::SChar: return 'c'; 7759 case BuiltinType::Short: return 's'; 7760 case BuiltinType::WChar_S: 7761 case BuiltinType::WChar_U: 7762 case BuiltinType::Int: return 'i'; 7763 case BuiltinType::Long: 7764 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7765 case BuiltinType::LongLong: return 'q'; 7766 case BuiltinType::Int128: return 't'; 7767 case BuiltinType::Float: return 'f'; 7768 case BuiltinType::Double: return 'd'; 7769 case BuiltinType::LongDouble: return 'D'; 7770 case BuiltinType::NullPtr: return '*'; // like char* 7771 7772 case BuiltinType::BFloat16: 7773 case BuiltinType::Float16: 7774 case BuiltinType::Float128: 7775 case BuiltinType::Ibm128: 7776 case BuiltinType::Half: 7777 case BuiltinType::ShortAccum: 7778 case BuiltinType::Accum: 7779 case BuiltinType::LongAccum: 7780 case BuiltinType::UShortAccum: 7781 case BuiltinType::UAccum: 7782 case BuiltinType::ULongAccum: 7783 case BuiltinType::ShortFract: 7784 case BuiltinType::Fract: 7785 case BuiltinType::LongFract: 7786 case BuiltinType::UShortFract: 7787 case BuiltinType::UFract: 7788 case BuiltinType::ULongFract: 7789 case BuiltinType::SatShortAccum: 7790 case BuiltinType::SatAccum: 7791 case BuiltinType::SatLongAccum: 7792 case BuiltinType::SatUShortAccum: 7793 case BuiltinType::SatUAccum: 7794 case BuiltinType::SatULongAccum: 7795 case BuiltinType::SatShortFract: 7796 case BuiltinType::SatFract: 7797 case BuiltinType::SatLongFract: 7798 case BuiltinType::SatUShortFract: 7799 case BuiltinType::SatUFract: 7800 case BuiltinType::SatULongFract: 7801 // FIXME: potentially need @encodes for these! 7802 return ' '; 7803 7804 #define SVE_TYPE(Name, Id, SingletonId) \ 7805 case BuiltinType::Id: 7806 #include "clang/Basic/AArch64SVEACLETypes.def" 7807 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7808 #include "clang/Basic/RISCVVTypes.def" 7809 { 7810 DiagnosticsEngine &Diags = C->getDiagnostics(); 7811 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7812 "cannot yet @encode type %0"); 7813 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7814 return ' '; 7815 } 7816 7817 case BuiltinType::ObjCId: 7818 case BuiltinType::ObjCClass: 7819 case BuiltinType::ObjCSel: 7820 llvm_unreachable("@encoding ObjC primitive type"); 7821 7822 // OpenCL and placeholder types don't need @encodings. 7823 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7824 case BuiltinType::Id: 7825 #include "clang/Basic/OpenCLImageTypes.def" 7826 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7827 case BuiltinType::Id: 7828 #include "clang/Basic/OpenCLExtensionTypes.def" 7829 case BuiltinType::OCLEvent: 7830 case BuiltinType::OCLClkEvent: 7831 case BuiltinType::OCLQueue: 7832 case BuiltinType::OCLReserveID: 7833 case BuiltinType::OCLSampler: 7834 case BuiltinType::Dependent: 7835 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7836 case BuiltinType::Id: 7837 #include "clang/Basic/PPCTypes.def" 7838 #define BUILTIN_TYPE(KIND, ID) 7839 #define PLACEHOLDER_TYPE(KIND, ID) \ 7840 case BuiltinType::KIND: 7841 #include "clang/AST/BuiltinTypes.def" 7842 llvm_unreachable("invalid builtin type for @encode"); 7843 } 7844 llvm_unreachable("invalid BuiltinType::Kind value"); 7845 } 7846 7847 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7848 EnumDecl *Enum = ET->getDecl(); 7849 7850 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7851 if (!Enum->isFixed()) 7852 return 'i'; 7853 7854 // The encoding of a fixed enum type matches its fixed underlying type. 7855 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7856 return getObjCEncodingForPrimitiveType(C, BT); 7857 } 7858 7859 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7860 QualType T, const FieldDecl *FD) { 7861 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7862 S += 'b'; 7863 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7864 // The GNU runtime requires more information; bitfields are encoded as b, 7865 // then the offset (in bits) of the first element, then the type of the 7866 // bitfield, then the size in bits. For example, in this structure: 7867 // 7868 // struct 7869 // { 7870 // int integer; 7871 // int flags:2; 7872 // }; 7873 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7874 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7875 // information is not especially sensible, but we're stuck with it for 7876 // compatibility with GCC, although providing it breaks anything that 7877 // actually uses runtime introspection and wants to work on both runtimes... 7878 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7879 uint64_t Offset; 7880 7881 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7882 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7883 IVD); 7884 } else { 7885 const RecordDecl *RD = FD->getParent(); 7886 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7887 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7888 } 7889 7890 S += llvm::utostr(Offset); 7891 7892 if (const auto *ET = T->getAs<EnumType>()) 7893 S += ObjCEncodingForEnumType(Ctx, ET); 7894 else { 7895 const auto *BT = T->castAs<BuiltinType>(); 7896 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7897 } 7898 } 7899 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7900 } 7901 7902 // Helper function for determining whether the encoded type string would include 7903 // a template specialization type. 7904 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7905 bool VisitBasesAndFields) { 7906 T = T->getBaseElementTypeUnsafe(); 7907 7908 if (auto *PT = T->getAs<PointerType>()) 7909 return hasTemplateSpecializationInEncodedString( 7910 PT->getPointeeType().getTypePtr(), false); 7911 7912 auto *CXXRD = T->getAsCXXRecordDecl(); 7913 7914 if (!CXXRD) 7915 return false; 7916 7917 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7918 return true; 7919 7920 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7921 return false; 7922 7923 for (auto B : CXXRD->bases()) 7924 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7925 true)) 7926 return true; 7927 7928 for (auto *FD : CXXRD->fields()) 7929 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7930 true)) 7931 return true; 7932 7933 return false; 7934 } 7935 7936 // FIXME: Use SmallString for accumulating string. 7937 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7938 const ObjCEncOptions Options, 7939 const FieldDecl *FD, 7940 QualType *NotEncodedT) const { 7941 CanQualType CT = getCanonicalType(T); 7942 switch (CT->getTypeClass()) { 7943 case Type::Builtin: 7944 case Type::Enum: 7945 if (FD && FD->isBitField()) 7946 return EncodeBitField(this, S, T, FD); 7947 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7948 S += getObjCEncodingForPrimitiveType(this, BT); 7949 else 7950 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7951 return; 7952 7953 case Type::Complex: 7954 S += 'j'; 7955 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7956 ObjCEncOptions(), 7957 /*Field=*/nullptr); 7958 return; 7959 7960 case Type::Atomic: 7961 S += 'A'; 7962 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7963 ObjCEncOptions(), 7964 /*Field=*/nullptr); 7965 return; 7966 7967 // encoding for pointer or reference types. 7968 case Type::Pointer: 7969 case Type::LValueReference: 7970 case Type::RValueReference: { 7971 QualType PointeeTy; 7972 if (isa<PointerType>(CT)) { 7973 const auto *PT = T->castAs<PointerType>(); 7974 if (PT->isObjCSelType()) { 7975 S += ':'; 7976 return; 7977 } 7978 PointeeTy = PT->getPointeeType(); 7979 } else { 7980 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7981 } 7982 7983 bool isReadOnly = false; 7984 // For historical/compatibility reasons, the read-only qualifier of the 7985 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7986 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7987 // Also, do not emit the 'r' for anything but the outermost type! 7988 if (isa<TypedefType>(T.getTypePtr())) { 7989 if (Options.IsOutermostType() && T.isConstQualified()) { 7990 isReadOnly = true; 7991 S += 'r'; 7992 } 7993 } else if (Options.IsOutermostType()) { 7994 QualType P = PointeeTy; 7995 while (auto PT = P->getAs<PointerType>()) 7996 P = PT->getPointeeType(); 7997 if (P.isConstQualified()) { 7998 isReadOnly = true; 7999 S += 'r'; 8000 } 8001 } 8002 if (isReadOnly) { 8003 // Another legacy compatibility encoding. Some ObjC qualifier and type 8004 // combinations need to be rearranged. 8005 // Rewrite "in const" from "nr" to "rn" 8006 if (StringRef(S).endswith("nr")) 8007 S.replace(S.end()-2, S.end(), "rn"); 8008 } 8009 8010 if (PointeeTy->isCharType()) { 8011 // char pointer types should be encoded as '*' unless it is a 8012 // type that has been typedef'd to 'BOOL'. 8013 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 8014 S += '*'; 8015 return; 8016 } 8017 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 8018 // GCC binary compat: Need to convert "struct objc_class *" to "#". 8019 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 8020 S += '#'; 8021 return; 8022 } 8023 // GCC binary compat: Need to convert "struct objc_object *" to "@". 8024 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 8025 S += '@'; 8026 return; 8027 } 8028 // If the encoded string for the class includes template names, just emit 8029 // "^v" for pointers to the class. 8030 if (getLangOpts().CPlusPlus && 8031 (!getLangOpts().EncodeCXXClassTemplateSpec && 8032 hasTemplateSpecializationInEncodedString( 8033 RTy, Options.ExpandPointedToStructures()))) { 8034 S += "^v"; 8035 return; 8036 } 8037 // fall through... 8038 } 8039 S += '^'; 8040 getLegacyIntegralTypeEncoding(PointeeTy); 8041 8042 ObjCEncOptions NewOptions; 8043 if (Options.ExpandPointedToStructures()) 8044 NewOptions.setExpandStructures(); 8045 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 8046 /*Field=*/nullptr, NotEncodedT); 8047 return; 8048 } 8049 8050 case Type::ConstantArray: 8051 case Type::IncompleteArray: 8052 case Type::VariableArray: { 8053 const auto *AT = cast<ArrayType>(CT); 8054 8055 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 8056 // Incomplete arrays are encoded as a pointer to the array element. 8057 S += '^'; 8058 8059 getObjCEncodingForTypeImpl( 8060 AT->getElementType(), S, 8061 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 8062 } else { 8063 S += '['; 8064 8065 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8066 S += llvm::utostr(CAT->getSize().getZExtValue()); 8067 else { 8068 //Variable length arrays are encoded as a regular array with 0 elements. 8069 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 8070 "Unknown array type!"); 8071 S += '0'; 8072 } 8073 8074 getObjCEncodingForTypeImpl( 8075 AT->getElementType(), S, 8076 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 8077 NotEncodedT); 8078 S += ']'; 8079 } 8080 return; 8081 } 8082 8083 case Type::FunctionNoProto: 8084 case Type::FunctionProto: 8085 S += '?'; 8086 return; 8087 8088 case Type::Record: { 8089 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 8090 S += RDecl->isUnion() ? '(' : '{'; 8091 // Anonymous structures print as '?' 8092 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 8093 S += II->getName(); 8094 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 8095 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 8096 llvm::raw_string_ostream OS(S); 8097 printTemplateArgumentList(OS, TemplateArgs.asArray(), 8098 getPrintingPolicy()); 8099 } 8100 } else { 8101 S += '?'; 8102 } 8103 if (Options.ExpandStructures()) { 8104 S += '='; 8105 if (!RDecl->isUnion()) { 8106 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 8107 } else { 8108 for (const auto *Field : RDecl->fields()) { 8109 if (FD) { 8110 S += '"'; 8111 S += Field->getNameAsString(); 8112 S += '"'; 8113 } 8114 8115 // Special case bit-fields. 8116 if (Field->isBitField()) { 8117 getObjCEncodingForTypeImpl(Field->getType(), S, 8118 ObjCEncOptions().setExpandStructures(), 8119 Field); 8120 } else { 8121 QualType qt = Field->getType(); 8122 getLegacyIntegralTypeEncoding(qt); 8123 getObjCEncodingForTypeImpl( 8124 qt, S, 8125 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 8126 NotEncodedT); 8127 } 8128 } 8129 } 8130 } 8131 S += RDecl->isUnion() ? ')' : '}'; 8132 return; 8133 } 8134 8135 case Type::BlockPointer: { 8136 const auto *BT = T->castAs<BlockPointerType>(); 8137 S += "@?"; // Unlike a pointer-to-function, which is "^?". 8138 if (Options.EncodeBlockParameters()) { 8139 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 8140 8141 S += '<'; 8142 // Block return type 8143 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 8144 Options.forComponentType(), FD, NotEncodedT); 8145 // Block self 8146 S += "@?"; 8147 // Block parameters 8148 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 8149 for (const auto &I : FPT->param_types()) 8150 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 8151 NotEncodedT); 8152 } 8153 S += '>'; 8154 } 8155 return; 8156 } 8157 8158 case Type::ObjCObject: { 8159 // hack to match legacy encoding of *id and *Class 8160 QualType Ty = getObjCObjectPointerType(CT); 8161 if (Ty->isObjCIdType()) { 8162 S += "{objc_object=}"; 8163 return; 8164 } 8165 else if (Ty->isObjCClassType()) { 8166 S += "{objc_class=}"; 8167 return; 8168 } 8169 // TODO: Double check to make sure this intentionally falls through. 8170 LLVM_FALLTHROUGH; 8171 } 8172 8173 case Type::ObjCInterface: { 8174 // Ignore protocol qualifiers when mangling at this level. 8175 // @encode(class_name) 8176 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 8177 S += '{'; 8178 S += OI->getObjCRuntimeNameAsString(); 8179 if (Options.ExpandStructures()) { 8180 S += '='; 8181 SmallVector<const ObjCIvarDecl*, 32> Ivars; 8182 DeepCollectObjCIvars(OI, true, Ivars); 8183 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 8184 const FieldDecl *Field = Ivars[i]; 8185 if (Field->isBitField()) 8186 getObjCEncodingForTypeImpl(Field->getType(), S, 8187 ObjCEncOptions().setExpandStructures(), 8188 Field); 8189 else 8190 getObjCEncodingForTypeImpl(Field->getType(), S, 8191 ObjCEncOptions().setExpandStructures(), FD, 8192 NotEncodedT); 8193 } 8194 } 8195 S += '}'; 8196 return; 8197 } 8198 8199 case Type::ObjCObjectPointer: { 8200 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 8201 if (OPT->isObjCIdType()) { 8202 S += '@'; 8203 return; 8204 } 8205 8206 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 8207 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 8208 // Since this is a binary compatibility issue, need to consult with 8209 // runtime folks. Fortunately, this is a *very* obscure construct. 8210 S += '#'; 8211 return; 8212 } 8213 8214 if (OPT->isObjCQualifiedIdType()) { 8215 getObjCEncodingForTypeImpl( 8216 getObjCIdType(), S, 8217 Options.keepingOnly(ObjCEncOptions() 8218 .setExpandPointedToStructures() 8219 .setExpandStructures()), 8220 FD); 8221 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 8222 // Note that we do extended encoding of protocol qualifier list 8223 // Only when doing ivar or property encoding. 8224 S += '"'; 8225 for (const auto *I : OPT->quals()) { 8226 S += '<'; 8227 S += I->getObjCRuntimeNameAsString(); 8228 S += '>'; 8229 } 8230 S += '"'; 8231 } 8232 return; 8233 } 8234 8235 S += '@'; 8236 if (OPT->getInterfaceDecl() && 8237 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 8238 S += '"'; 8239 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 8240 for (const auto *I : OPT->quals()) { 8241 S += '<'; 8242 S += I->getObjCRuntimeNameAsString(); 8243 S += '>'; 8244 } 8245 S += '"'; 8246 } 8247 return; 8248 } 8249 8250 // gcc just blithely ignores member pointers. 8251 // FIXME: we should do better than that. 'M' is available. 8252 case Type::MemberPointer: 8253 // This matches gcc's encoding, even though technically it is insufficient. 8254 //FIXME. We should do a better job than gcc. 8255 case Type::Vector: 8256 case Type::ExtVector: 8257 // Until we have a coherent encoding of these three types, issue warning. 8258 if (NotEncodedT) 8259 *NotEncodedT = T; 8260 return; 8261 8262 case Type::ConstantMatrix: 8263 if (NotEncodedT) 8264 *NotEncodedT = T; 8265 return; 8266 8267 case Type::BitInt: 8268 if (NotEncodedT) 8269 *NotEncodedT = T; 8270 return; 8271 8272 // We could see an undeduced auto type here during error recovery. 8273 // Just ignore it. 8274 case Type::Auto: 8275 case Type::DeducedTemplateSpecialization: 8276 return; 8277 8278 case Type::Pipe: 8279 #define ABSTRACT_TYPE(KIND, BASE) 8280 #define TYPE(KIND, BASE) 8281 #define DEPENDENT_TYPE(KIND, BASE) \ 8282 case Type::KIND: 8283 #define NON_CANONICAL_TYPE(KIND, BASE) \ 8284 case Type::KIND: 8285 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 8286 case Type::KIND: 8287 #include "clang/AST/TypeNodes.inc" 8288 llvm_unreachable("@encode for dependent type!"); 8289 } 8290 llvm_unreachable("bad type kind!"); 8291 } 8292 8293 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 8294 std::string &S, 8295 const FieldDecl *FD, 8296 bool includeVBases, 8297 QualType *NotEncodedT) const { 8298 assert(RDecl && "Expected non-null RecordDecl"); 8299 assert(!RDecl->isUnion() && "Should not be called for unions"); 8300 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 8301 return; 8302 8303 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 8304 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 8305 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 8306 8307 if (CXXRec) { 8308 for (const auto &BI : CXXRec->bases()) { 8309 if (!BI.isVirtual()) { 8310 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8311 if (base->isEmpty()) 8312 continue; 8313 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 8314 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8315 std::make_pair(offs, base)); 8316 } 8317 } 8318 } 8319 8320 unsigned i = 0; 8321 for (FieldDecl *Field : RDecl->fields()) { 8322 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 8323 continue; 8324 uint64_t offs = layout.getFieldOffset(i); 8325 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8326 std::make_pair(offs, Field)); 8327 ++i; 8328 } 8329 8330 if (CXXRec && includeVBases) { 8331 for (const auto &BI : CXXRec->vbases()) { 8332 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 8333 if (base->isEmpty()) 8334 continue; 8335 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 8336 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 8337 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 8338 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 8339 std::make_pair(offs, base)); 8340 } 8341 } 8342 8343 CharUnits size; 8344 if (CXXRec) { 8345 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 8346 } else { 8347 size = layout.getSize(); 8348 } 8349 8350 #ifndef NDEBUG 8351 uint64_t CurOffs = 0; 8352 #endif 8353 std::multimap<uint64_t, NamedDecl *>::iterator 8354 CurLayObj = FieldOrBaseOffsets.begin(); 8355 8356 if (CXXRec && CXXRec->isDynamicClass() && 8357 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 8358 if (FD) { 8359 S += "\"_vptr$"; 8360 std::string recname = CXXRec->getNameAsString(); 8361 if (recname.empty()) recname = "?"; 8362 S += recname; 8363 S += '"'; 8364 } 8365 S += "^^?"; 8366 #ifndef NDEBUG 8367 CurOffs += getTypeSize(VoidPtrTy); 8368 #endif 8369 } 8370 8371 if (!RDecl->hasFlexibleArrayMember()) { 8372 // Mark the end of the structure. 8373 uint64_t offs = toBits(size); 8374 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 8375 std::make_pair(offs, nullptr)); 8376 } 8377 8378 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 8379 #ifndef NDEBUG 8380 assert(CurOffs <= CurLayObj->first); 8381 if (CurOffs < CurLayObj->first) { 8382 uint64_t padding = CurLayObj->first - CurOffs; 8383 // FIXME: There doesn't seem to be a way to indicate in the encoding that 8384 // packing/alignment of members is different that normal, in which case 8385 // the encoding will be out-of-sync with the real layout. 8386 // If the runtime switches to just consider the size of types without 8387 // taking into account alignment, we could make padding explicit in the 8388 // encoding (e.g. using arrays of chars). The encoding strings would be 8389 // longer then though. 8390 CurOffs += padding; 8391 } 8392 #endif 8393 8394 NamedDecl *dcl = CurLayObj->second; 8395 if (!dcl) 8396 break; // reached end of structure. 8397 8398 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 8399 // We expand the bases without their virtual bases since those are going 8400 // in the initial structure. Note that this differs from gcc which 8401 // expands virtual bases each time one is encountered in the hierarchy, 8402 // making the encoding type bigger than it really is. 8403 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 8404 NotEncodedT); 8405 assert(!base->isEmpty()); 8406 #ifndef NDEBUG 8407 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 8408 #endif 8409 } else { 8410 const auto *field = cast<FieldDecl>(dcl); 8411 if (FD) { 8412 S += '"'; 8413 S += field->getNameAsString(); 8414 S += '"'; 8415 } 8416 8417 if (field->isBitField()) { 8418 EncodeBitField(this, S, field->getType(), field); 8419 #ifndef NDEBUG 8420 CurOffs += field->getBitWidthValue(*this); 8421 #endif 8422 } else { 8423 QualType qt = field->getType(); 8424 getLegacyIntegralTypeEncoding(qt); 8425 getObjCEncodingForTypeImpl( 8426 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 8427 FD, NotEncodedT); 8428 #ifndef NDEBUG 8429 CurOffs += getTypeSize(field->getType()); 8430 #endif 8431 } 8432 } 8433 } 8434 } 8435 8436 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 8437 std::string& S) const { 8438 if (QT & Decl::OBJC_TQ_In) 8439 S += 'n'; 8440 if (QT & Decl::OBJC_TQ_Inout) 8441 S += 'N'; 8442 if (QT & Decl::OBJC_TQ_Out) 8443 S += 'o'; 8444 if (QT & Decl::OBJC_TQ_Bycopy) 8445 S += 'O'; 8446 if (QT & Decl::OBJC_TQ_Byref) 8447 S += 'R'; 8448 if (QT & Decl::OBJC_TQ_Oneway) 8449 S += 'V'; 8450 } 8451 8452 TypedefDecl *ASTContext::getObjCIdDecl() const { 8453 if (!ObjCIdDecl) { 8454 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 8455 T = getObjCObjectPointerType(T); 8456 ObjCIdDecl = buildImplicitTypedef(T, "id"); 8457 } 8458 return ObjCIdDecl; 8459 } 8460 8461 TypedefDecl *ASTContext::getObjCSelDecl() const { 8462 if (!ObjCSelDecl) { 8463 QualType T = getPointerType(ObjCBuiltinSelTy); 8464 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 8465 } 8466 return ObjCSelDecl; 8467 } 8468 8469 TypedefDecl *ASTContext::getObjCClassDecl() const { 8470 if (!ObjCClassDecl) { 8471 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 8472 T = getObjCObjectPointerType(T); 8473 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 8474 } 8475 return ObjCClassDecl; 8476 } 8477 8478 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 8479 if (!ObjCProtocolClassDecl) { 8480 ObjCProtocolClassDecl 8481 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 8482 SourceLocation(), 8483 &Idents.get("Protocol"), 8484 /*typeParamList=*/nullptr, 8485 /*PrevDecl=*/nullptr, 8486 SourceLocation(), true); 8487 } 8488 8489 return ObjCProtocolClassDecl; 8490 } 8491 8492 //===----------------------------------------------------------------------===// 8493 // __builtin_va_list Construction Functions 8494 //===----------------------------------------------------------------------===// 8495 8496 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8497 StringRef Name) { 8498 // typedef char* __builtin[_ms]_va_list; 8499 QualType T = Context->getPointerType(Context->CharTy); 8500 return Context->buildImplicitTypedef(T, Name); 8501 } 8502 8503 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8504 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8505 } 8506 8507 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8508 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8509 } 8510 8511 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8512 // typedef void* __builtin_va_list; 8513 QualType T = Context->getPointerType(Context->VoidTy); 8514 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8515 } 8516 8517 static TypedefDecl * 8518 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8519 // struct __va_list 8520 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8521 if (Context->getLangOpts().CPlusPlus) { 8522 // namespace std { struct __va_list { 8523 auto *NS = NamespaceDecl::Create( 8524 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8525 /*Inline*/ false, SourceLocation(), SourceLocation(), 8526 &Context->Idents.get("std"), 8527 /*PrevDecl*/ nullptr); 8528 NS->setImplicit(); 8529 VaListTagDecl->setDeclContext(NS); 8530 } 8531 8532 VaListTagDecl->startDefinition(); 8533 8534 const size_t NumFields = 5; 8535 QualType FieldTypes[NumFields]; 8536 const char *FieldNames[NumFields]; 8537 8538 // void *__stack; 8539 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8540 FieldNames[0] = "__stack"; 8541 8542 // void *__gr_top; 8543 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8544 FieldNames[1] = "__gr_top"; 8545 8546 // void *__vr_top; 8547 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8548 FieldNames[2] = "__vr_top"; 8549 8550 // int __gr_offs; 8551 FieldTypes[3] = Context->IntTy; 8552 FieldNames[3] = "__gr_offs"; 8553 8554 // int __vr_offs; 8555 FieldTypes[4] = Context->IntTy; 8556 FieldNames[4] = "__vr_offs"; 8557 8558 // Create fields 8559 for (unsigned i = 0; i < NumFields; ++i) { 8560 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8561 VaListTagDecl, 8562 SourceLocation(), 8563 SourceLocation(), 8564 &Context->Idents.get(FieldNames[i]), 8565 FieldTypes[i], /*TInfo=*/nullptr, 8566 /*BitWidth=*/nullptr, 8567 /*Mutable=*/false, 8568 ICIS_NoInit); 8569 Field->setAccess(AS_public); 8570 VaListTagDecl->addDecl(Field); 8571 } 8572 VaListTagDecl->completeDefinition(); 8573 Context->VaListTagDecl = VaListTagDecl; 8574 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8575 8576 // } __builtin_va_list; 8577 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8578 } 8579 8580 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8581 // typedef struct __va_list_tag { 8582 RecordDecl *VaListTagDecl; 8583 8584 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8585 VaListTagDecl->startDefinition(); 8586 8587 const size_t NumFields = 5; 8588 QualType FieldTypes[NumFields]; 8589 const char *FieldNames[NumFields]; 8590 8591 // unsigned char gpr; 8592 FieldTypes[0] = Context->UnsignedCharTy; 8593 FieldNames[0] = "gpr"; 8594 8595 // unsigned char fpr; 8596 FieldTypes[1] = Context->UnsignedCharTy; 8597 FieldNames[1] = "fpr"; 8598 8599 // unsigned short reserved; 8600 FieldTypes[2] = Context->UnsignedShortTy; 8601 FieldNames[2] = "reserved"; 8602 8603 // void* overflow_arg_area; 8604 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8605 FieldNames[3] = "overflow_arg_area"; 8606 8607 // void* reg_save_area; 8608 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8609 FieldNames[4] = "reg_save_area"; 8610 8611 // Create fields 8612 for (unsigned i = 0; i < NumFields; ++i) { 8613 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8614 SourceLocation(), 8615 SourceLocation(), 8616 &Context->Idents.get(FieldNames[i]), 8617 FieldTypes[i], /*TInfo=*/nullptr, 8618 /*BitWidth=*/nullptr, 8619 /*Mutable=*/false, 8620 ICIS_NoInit); 8621 Field->setAccess(AS_public); 8622 VaListTagDecl->addDecl(Field); 8623 } 8624 VaListTagDecl->completeDefinition(); 8625 Context->VaListTagDecl = VaListTagDecl; 8626 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8627 8628 // } __va_list_tag; 8629 TypedefDecl *VaListTagTypedefDecl = 8630 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8631 8632 QualType VaListTagTypedefType = 8633 Context->getTypedefType(VaListTagTypedefDecl); 8634 8635 // typedef __va_list_tag __builtin_va_list[1]; 8636 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8637 QualType VaListTagArrayType 8638 = Context->getConstantArrayType(VaListTagTypedefType, 8639 Size, nullptr, ArrayType::Normal, 0); 8640 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8641 } 8642 8643 static TypedefDecl * 8644 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8645 // struct __va_list_tag { 8646 RecordDecl *VaListTagDecl; 8647 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8648 VaListTagDecl->startDefinition(); 8649 8650 const size_t NumFields = 4; 8651 QualType FieldTypes[NumFields]; 8652 const char *FieldNames[NumFields]; 8653 8654 // unsigned gp_offset; 8655 FieldTypes[0] = Context->UnsignedIntTy; 8656 FieldNames[0] = "gp_offset"; 8657 8658 // unsigned fp_offset; 8659 FieldTypes[1] = Context->UnsignedIntTy; 8660 FieldNames[1] = "fp_offset"; 8661 8662 // void* overflow_arg_area; 8663 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8664 FieldNames[2] = "overflow_arg_area"; 8665 8666 // void* reg_save_area; 8667 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8668 FieldNames[3] = "reg_save_area"; 8669 8670 // Create fields 8671 for (unsigned i = 0; i < NumFields; ++i) { 8672 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8673 VaListTagDecl, 8674 SourceLocation(), 8675 SourceLocation(), 8676 &Context->Idents.get(FieldNames[i]), 8677 FieldTypes[i], /*TInfo=*/nullptr, 8678 /*BitWidth=*/nullptr, 8679 /*Mutable=*/false, 8680 ICIS_NoInit); 8681 Field->setAccess(AS_public); 8682 VaListTagDecl->addDecl(Field); 8683 } 8684 VaListTagDecl->completeDefinition(); 8685 Context->VaListTagDecl = VaListTagDecl; 8686 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8687 8688 // }; 8689 8690 // typedef struct __va_list_tag __builtin_va_list[1]; 8691 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8692 QualType VaListTagArrayType = Context->getConstantArrayType( 8693 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8694 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8695 } 8696 8697 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8698 // typedef int __builtin_va_list[4]; 8699 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8700 QualType IntArrayType = Context->getConstantArrayType( 8701 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8702 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8703 } 8704 8705 static TypedefDecl * 8706 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8707 // struct __va_list 8708 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8709 if (Context->getLangOpts().CPlusPlus) { 8710 // namespace std { struct __va_list { 8711 NamespaceDecl *NS; 8712 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8713 Context->getTranslationUnitDecl(), 8714 /*Inline*/false, SourceLocation(), 8715 SourceLocation(), &Context->Idents.get("std"), 8716 /*PrevDecl*/ nullptr); 8717 NS->setImplicit(); 8718 VaListDecl->setDeclContext(NS); 8719 } 8720 8721 VaListDecl->startDefinition(); 8722 8723 // void * __ap; 8724 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8725 VaListDecl, 8726 SourceLocation(), 8727 SourceLocation(), 8728 &Context->Idents.get("__ap"), 8729 Context->getPointerType(Context->VoidTy), 8730 /*TInfo=*/nullptr, 8731 /*BitWidth=*/nullptr, 8732 /*Mutable=*/false, 8733 ICIS_NoInit); 8734 Field->setAccess(AS_public); 8735 VaListDecl->addDecl(Field); 8736 8737 // }; 8738 VaListDecl->completeDefinition(); 8739 Context->VaListTagDecl = VaListDecl; 8740 8741 // typedef struct __va_list __builtin_va_list; 8742 QualType T = Context->getRecordType(VaListDecl); 8743 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8744 } 8745 8746 static TypedefDecl * 8747 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8748 // struct __va_list_tag { 8749 RecordDecl *VaListTagDecl; 8750 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8751 VaListTagDecl->startDefinition(); 8752 8753 const size_t NumFields = 4; 8754 QualType FieldTypes[NumFields]; 8755 const char *FieldNames[NumFields]; 8756 8757 // long __gpr; 8758 FieldTypes[0] = Context->LongTy; 8759 FieldNames[0] = "__gpr"; 8760 8761 // long __fpr; 8762 FieldTypes[1] = Context->LongTy; 8763 FieldNames[1] = "__fpr"; 8764 8765 // void *__overflow_arg_area; 8766 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8767 FieldNames[2] = "__overflow_arg_area"; 8768 8769 // void *__reg_save_area; 8770 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8771 FieldNames[3] = "__reg_save_area"; 8772 8773 // Create fields 8774 for (unsigned i = 0; i < NumFields; ++i) { 8775 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8776 VaListTagDecl, 8777 SourceLocation(), 8778 SourceLocation(), 8779 &Context->Idents.get(FieldNames[i]), 8780 FieldTypes[i], /*TInfo=*/nullptr, 8781 /*BitWidth=*/nullptr, 8782 /*Mutable=*/false, 8783 ICIS_NoInit); 8784 Field->setAccess(AS_public); 8785 VaListTagDecl->addDecl(Field); 8786 } 8787 VaListTagDecl->completeDefinition(); 8788 Context->VaListTagDecl = VaListTagDecl; 8789 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8790 8791 // }; 8792 8793 // typedef __va_list_tag __builtin_va_list[1]; 8794 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8795 QualType VaListTagArrayType = Context->getConstantArrayType( 8796 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8797 8798 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8799 } 8800 8801 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8802 // typedef struct __va_list_tag { 8803 RecordDecl *VaListTagDecl; 8804 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8805 VaListTagDecl->startDefinition(); 8806 8807 const size_t NumFields = 3; 8808 QualType FieldTypes[NumFields]; 8809 const char *FieldNames[NumFields]; 8810 8811 // void *CurrentSavedRegisterArea; 8812 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8813 FieldNames[0] = "__current_saved_reg_area_pointer"; 8814 8815 // void *SavedRegAreaEnd; 8816 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8817 FieldNames[1] = "__saved_reg_area_end_pointer"; 8818 8819 // void *OverflowArea; 8820 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8821 FieldNames[2] = "__overflow_area_pointer"; 8822 8823 // Create fields 8824 for (unsigned i = 0; i < NumFields; ++i) { 8825 FieldDecl *Field = FieldDecl::Create( 8826 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8827 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8828 /*TInfo=*/nullptr, 8829 /*BitWidth=*/nullptr, 8830 /*Mutable=*/false, ICIS_NoInit); 8831 Field->setAccess(AS_public); 8832 VaListTagDecl->addDecl(Field); 8833 } 8834 VaListTagDecl->completeDefinition(); 8835 Context->VaListTagDecl = VaListTagDecl; 8836 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8837 8838 // } __va_list_tag; 8839 TypedefDecl *VaListTagTypedefDecl = 8840 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8841 8842 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8843 8844 // typedef __va_list_tag __builtin_va_list[1]; 8845 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8846 QualType VaListTagArrayType = Context->getConstantArrayType( 8847 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8848 8849 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8850 } 8851 8852 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8853 TargetInfo::BuiltinVaListKind Kind) { 8854 switch (Kind) { 8855 case TargetInfo::CharPtrBuiltinVaList: 8856 return CreateCharPtrBuiltinVaListDecl(Context); 8857 case TargetInfo::VoidPtrBuiltinVaList: 8858 return CreateVoidPtrBuiltinVaListDecl(Context); 8859 case TargetInfo::AArch64ABIBuiltinVaList: 8860 return CreateAArch64ABIBuiltinVaListDecl(Context); 8861 case TargetInfo::PowerABIBuiltinVaList: 8862 return CreatePowerABIBuiltinVaListDecl(Context); 8863 case TargetInfo::X86_64ABIBuiltinVaList: 8864 return CreateX86_64ABIBuiltinVaListDecl(Context); 8865 case TargetInfo::PNaClABIBuiltinVaList: 8866 return CreatePNaClABIBuiltinVaListDecl(Context); 8867 case TargetInfo::AAPCSABIBuiltinVaList: 8868 return CreateAAPCSABIBuiltinVaListDecl(Context); 8869 case TargetInfo::SystemZBuiltinVaList: 8870 return CreateSystemZBuiltinVaListDecl(Context); 8871 case TargetInfo::HexagonBuiltinVaList: 8872 return CreateHexagonBuiltinVaListDecl(Context); 8873 } 8874 8875 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8876 } 8877 8878 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8879 if (!BuiltinVaListDecl) { 8880 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8881 assert(BuiltinVaListDecl->isImplicit()); 8882 } 8883 8884 return BuiltinVaListDecl; 8885 } 8886 8887 Decl *ASTContext::getVaListTagDecl() const { 8888 // Force the creation of VaListTagDecl by building the __builtin_va_list 8889 // declaration. 8890 if (!VaListTagDecl) 8891 (void)getBuiltinVaListDecl(); 8892 8893 return VaListTagDecl; 8894 } 8895 8896 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8897 if (!BuiltinMSVaListDecl) 8898 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8899 8900 return BuiltinMSVaListDecl; 8901 } 8902 8903 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8904 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8905 } 8906 8907 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8908 assert(ObjCConstantStringType.isNull() && 8909 "'NSConstantString' type already set!"); 8910 8911 ObjCConstantStringType = getObjCInterfaceType(Decl); 8912 } 8913 8914 /// Retrieve the template name that corresponds to a non-empty 8915 /// lookup. 8916 TemplateName 8917 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8918 UnresolvedSetIterator End) const { 8919 unsigned size = End - Begin; 8920 assert(size > 1 && "set is not overloaded!"); 8921 8922 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8923 size * sizeof(FunctionTemplateDecl*)); 8924 auto *OT = new (memory) OverloadedTemplateStorage(size); 8925 8926 NamedDecl **Storage = OT->getStorage(); 8927 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8928 NamedDecl *D = *I; 8929 assert(isa<FunctionTemplateDecl>(D) || 8930 isa<UnresolvedUsingValueDecl>(D) || 8931 (isa<UsingShadowDecl>(D) && 8932 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8933 *Storage++ = D; 8934 } 8935 8936 return TemplateName(OT); 8937 } 8938 8939 /// Retrieve a template name representing an unqualified-id that has been 8940 /// assumed to name a template for ADL purposes. 8941 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8942 auto *OT = new (*this) AssumedTemplateStorage(Name); 8943 return TemplateName(OT); 8944 } 8945 8946 /// Retrieve the template name that represents a qualified 8947 /// template name such as \c std::vector. 8948 TemplateName 8949 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8950 bool TemplateKeyword, 8951 TemplateDecl *Template) const { 8952 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8953 8954 // FIXME: Canonicalization? 8955 llvm::FoldingSetNodeID ID; 8956 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8957 8958 void *InsertPos = nullptr; 8959 QualifiedTemplateName *QTN = 8960 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8961 if (!QTN) { 8962 QTN = new (*this, alignof(QualifiedTemplateName)) 8963 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8964 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8965 } 8966 8967 return TemplateName(QTN); 8968 } 8969 8970 /// Retrieve the template name that represents a dependent 8971 /// template name such as \c MetaFun::template apply. 8972 TemplateName 8973 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8974 const IdentifierInfo *Name) const { 8975 assert((!NNS || NNS->isDependent()) && 8976 "Nested name specifier must be dependent"); 8977 8978 llvm::FoldingSetNodeID ID; 8979 DependentTemplateName::Profile(ID, NNS, Name); 8980 8981 void *InsertPos = nullptr; 8982 DependentTemplateName *QTN = 8983 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8984 8985 if (QTN) 8986 return TemplateName(QTN); 8987 8988 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8989 if (CanonNNS == NNS) { 8990 QTN = new (*this, alignof(DependentTemplateName)) 8991 DependentTemplateName(NNS, Name); 8992 } else { 8993 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8994 QTN = new (*this, alignof(DependentTemplateName)) 8995 DependentTemplateName(NNS, Name, Canon); 8996 DependentTemplateName *CheckQTN = 8997 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8998 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8999 (void)CheckQTN; 9000 } 9001 9002 DependentTemplateNames.InsertNode(QTN, InsertPos); 9003 return TemplateName(QTN); 9004 } 9005 9006 /// Retrieve the template name that represents a dependent 9007 /// template name such as \c MetaFun::template operator+. 9008 TemplateName 9009 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 9010 OverloadedOperatorKind Operator) const { 9011 assert((!NNS || NNS->isDependent()) && 9012 "Nested name specifier must be dependent"); 9013 9014 llvm::FoldingSetNodeID ID; 9015 DependentTemplateName::Profile(ID, NNS, Operator); 9016 9017 void *InsertPos = nullptr; 9018 DependentTemplateName *QTN 9019 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9020 9021 if (QTN) 9022 return TemplateName(QTN); 9023 9024 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 9025 if (CanonNNS == NNS) { 9026 QTN = new (*this, alignof(DependentTemplateName)) 9027 DependentTemplateName(NNS, Operator); 9028 } else { 9029 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 9030 QTN = new (*this, alignof(DependentTemplateName)) 9031 DependentTemplateName(NNS, Operator, Canon); 9032 9033 DependentTemplateName *CheckQTN 9034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 9035 assert(!CheckQTN && "Dependent template name canonicalization broken"); 9036 (void)CheckQTN; 9037 } 9038 9039 DependentTemplateNames.InsertNode(QTN, InsertPos); 9040 return TemplateName(QTN); 9041 } 9042 9043 TemplateName 9044 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 9045 TemplateName replacement) const { 9046 llvm::FoldingSetNodeID ID; 9047 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 9048 9049 void *insertPos = nullptr; 9050 SubstTemplateTemplateParmStorage *subst 9051 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 9052 9053 if (!subst) { 9054 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 9055 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 9056 } 9057 9058 return TemplateName(subst); 9059 } 9060 9061 TemplateName 9062 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 9063 const TemplateArgument &ArgPack) const { 9064 auto &Self = const_cast<ASTContext &>(*this); 9065 llvm::FoldingSetNodeID ID; 9066 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 9067 9068 void *InsertPos = nullptr; 9069 SubstTemplateTemplateParmPackStorage *Subst 9070 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 9071 9072 if (!Subst) { 9073 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 9074 ArgPack.pack_size(), 9075 ArgPack.pack_begin()); 9076 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 9077 } 9078 9079 return TemplateName(Subst); 9080 } 9081 9082 /// getFromTargetType - Given one of the integer types provided by 9083 /// TargetInfo, produce the corresponding type. The unsigned @p Type 9084 /// is actually a value of type @c TargetInfo::IntType. 9085 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 9086 switch (Type) { 9087 case TargetInfo::NoInt: return {}; 9088 case TargetInfo::SignedChar: return SignedCharTy; 9089 case TargetInfo::UnsignedChar: return UnsignedCharTy; 9090 case TargetInfo::SignedShort: return ShortTy; 9091 case TargetInfo::UnsignedShort: return UnsignedShortTy; 9092 case TargetInfo::SignedInt: return IntTy; 9093 case TargetInfo::UnsignedInt: return UnsignedIntTy; 9094 case TargetInfo::SignedLong: return LongTy; 9095 case TargetInfo::UnsignedLong: return UnsignedLongTy; 9096 case TargetInfo::SignedLongLong: return LongLongTy; 9097 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 9098 } 9099 9100 llvm_unreachable("Unhandled TargetInfo::IntType value"); 9101 } 9102 9103 //===----------------------------------------------------------------------===// 9104 // Type Predicates. 9105 //===----------------------------------------------------------------------===// 9106 9107 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 9108 /// garbage collection attribute. 9109 /// 9110 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 9111 if (getLangOpts().getGC() == LangOptions::NonGC) 9112 return Qualifiers::GCNone; 9113 9114 assert(getLangOpts().ObjC); 9115 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 9116 9117 // Default behaviour under objective-C's gc is for ObjC pointers 9118 // (or pointers to them) be treated as though they were declared 9119 // as __strong. 9120 if (GCAttrs == Qualifiers::GCNone) { 9121 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 9122 return Qualifiers::Strong; 9123 else if (Ty->isPointerType()) 9124 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 9125 } else { 9126 // It's not valid to set GC attributes on anything that isn't a 9127 // pointer. 9128 #ifndef NDEBUG 9129 QualType CT = Ty->getCanonicalTypeInternal(); 9130 while (const auto *AT = dyn_cast<ArrayType>(CT)) 9131 CT = AT->getElementType(); 9132 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 9133 #endif 9134 } 9135 return GCAttrs; 9136 } 9137 9138 //===----------------------------------------------------------------------===// 9139 // Type Compatibility Testing 9140 //===----------------------------------------------------------------------===// 9141 9142 /// areCompatVectorTypes - Return true if the two specified vector types are 9143 /// compatible. 9144 static bool areCompatVectorTypes(const VectorType *LHS, 9145 const VectorType *RHS) { 9146 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9147 return LHS->getElementType() == RHS->getElementType() && 9148 LHS->getNumElements() == RHS->getNumElements(); 9149 } 9150 9151 /// areCompatMatrixTypes - Return true if the two specified matrix types are 9152 /// compatible. 9153 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 9154 const ConstantMatrixType *RHS) { 9155 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 9156 return LHS->getElementType() == RHS->getElementType() && 9157 LHS->getNumRows() == RHS->getNumRows() && 9158 LHS->getNumColumns() == RHS->getNumColumns(); 9159 } 9160 9161 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 9162 QualType SecondVec) { 9163 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 9164 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 9165 9166 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 9167 return true; 9168 9169 // Treat Neon vector types and most AltiVec vector types as if they are the 9170 // equivalent GCC vector types. 9171 const auto *First = FirstVec->castAs<VectorType>(); 9172 const auto *Second = SecondVec->castAs<VectorType>(); 9173 if (First->getNumElements() == Second->getNumElements() && 9174 hasSameType(First->getElementType(), Second->getElementType()) && 9175 First->getVectorKind() != VectorType::AltiVecPixel && 9176 First->getVectorKind() != VectorType::AltiVecBool && 9177 Second->getVectorKind() != VectorType::AltiVecPixel && 9178 Second->getVectorKind() != VectorType::AltiVecBool && 9179 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 9180 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 9181 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 9182 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 9183 return true; 9184 9185 return false; 9186 } 9187 9188 /// getSVETypeSize - Return SVE vector or predicate register size. 9189 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 9190 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 9191 return Ty->getKind() == BuiltinType::SveBool 9192 ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth() 9193 : Context.getLangOpts().VScaleMin * 128; 9194 } 9195 9196 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 9197 QualType SecondType) { 9198 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9199 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9200 "Expected SVE builtin type and vector type!"); 9201 9202 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 9203 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 9204 if (const auto *VT = SecondType->getAs<VectorType>()) { 9205 // Predicates have the same representation as uint8 so we also have to 9206 // check the kind to make these types incompatible. 9207 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 9208 return BT->getKind() == BuiltinType::SveBool; 9209 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 9210 return VT->getElementType().getCanonicalType() == 9211 FirstType->getSveEltType(*this); 9212 else if (VT->getVectorKind() == VectorType::GenericVector) 9213 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 9214 hasSameType(VT->getElementType(), 9215 getBuiltinVectorTypeInfo(BT).ElementType); 9216 } 9217 } 9218 return false; 9219 }; 9220 9221 return IsValidCast(FirstType, SecondType) || 9222 IsValidCast(SecondType, FirstType); 9223 } 9224 9225 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 9226 QualType SecondType) { 9227 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 9228 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 9229 "Expected SVE builtin type and vector type!"); 9230 9231 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 9232 const auto *BT = FirstType->getAs<BuiltinType>(); 9233 if (!BT) 9234 return false; 9235 9236 const auto *VecTy = SecondType->getAs<VectorType>(); 9237 if (VecTy && 9238 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 9239 VecTy->getVectorKind() == VectorType::GenericVector)) { 9240 const LangOptions::LaxVectorConversionKind LVCKind = 9241 getLangOpts().getLaxVectorConversions(); 9242 9243 // Can not convert between sve predicates and sve vectors because of 9244 // different size. 9245 if (BT->getKind() == BuiltinType::SveBool && 9246 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 9247 return false; 9248 9249 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 9250 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 9251 // converts to VLAT and VLAT implicitly converts to GNUT." 9252 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 9253 // predicates. 9254 if (VecTy->getVectorKind() == VectorType::GenericVector && 9255 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 9256 return false; 9257 9258 // If -flax-vector-conversions=all is specified, the types are 9259 // certainly compatible. 9260 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 9261 return true; 9262 9263 // If -flax-vector-conversions=integer is specified, the types are 9264 // compatible if the elements are integer types. 9265 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 9266 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 9267 FirstType->getSveEltType(*this)->isIntegerType(); 9268 } 9269 9270 return false; 9271 }; 9272 9273 return IsLaxCompatible(FirstType, SecondType) || 9274 IsLaxCompatible(SecondType, FirstType); 9275 } 9276 9277 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 9278 while (true) { 9279 // __strong id 9280 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 9281 if (Attr->getAttrKind() == attr::ObjCOwnership) 9282 return true; 9283 9284 Ty = Attr->getModifiedType(); 9285 9286 // X *__strong (...) 9287 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 9288 Ty = Paren->getInnerType(); 9289 9290 // We do not want to look through typedefs, typeof(expr), 9291 // typeof(type), or any other way that the type is somehow 9292 // abstracted. 9293 } else { 9294 return false; 9295 } 9296 } 9297 } 9298 9299 //===----------------------------------------------------------------------===// 9300 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 9301 //===----------------------------------------------------------------------===// 9302 9303 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 9304 /// inheritance hierarchy of 'rProto'. 9305 bool 9306 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 9307 ObjCProtocolDecl *rProto) const { 9308 if (declaresSameEntity(lProto, rProto)) 9309 return true; 9310 for (auto *PI : rProto->protocols()) 9311 if (ProtocolCompatibleWithProtocol(lProto, PI)) 9312 return true; 9313 return false; 9314 } 9315 9316 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 9317 /// Class<pr1, ...>. 9318 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 9319 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 9320 for (auto *lhsProto : lhs->quals()) { 9321 bool match = false; 9322 for (auto *rhsProto : rhs->quals()) { 9323 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 9324 match = true; 9325 break; 9326 } 9327 } 9328 if (!match) 9329 return false; 9330 } 9331 return true; 9332 } 9333 9334 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 9335 /// ObjCQualifiedIDType. 9336 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 9337 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 9338 bool compare) { 9339 // Allow id<P..> and an 'id' in all cases. 9340 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 9341 return true; 9342 9343 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 9344 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 9345 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 9346 return false; 9347 9348 if (lhs->isObjCQualifiedIdType()) { 9349 if (rhs->qual_empty()) { 9350 // If the RHS is a unqualified interface pointer "NSString*", 9351 // make sure we check the class hierarchy. 9352 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9353 for (auto *I : lhs->quals()) { 9354 // when comparing an id<P> on lhs with a static type on rhs, 9355 // see if static class implements all of id's protocols, directly or 9356 // through its super class and categories. 9357 if (!rhsID->ClassImplementsProtocol(I, true)) 9358 return false; 9359 } 9360 } 9361 // If there are no qualifiers and no interface, we have an 'id'. 9362 return true; 9363 } 9364 // Both the right and left sides have qualifiers. 9365 for (auto *lhsProto : lhs->quals()) { 9366 bool match = false; 9367 9368 // when comparing an id<P> on lhs with a static type on rhs, 9369 // see if static class implements all of id's protocols, directly or 9370 // through its super class and categories. 9371 for (auto *rhsProto : rhs->quals()) { 9372 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9373 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9374 match = true; 9375 break; 9376 } 9377 } 9378 // If the RHS is a qualified interface pointer "NSString<P>*", 9379 // make sure we check the class hierarchy. 9380 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 9381 for (auto *I : lhs->quals()) { 9382 // when comparing an id<P> on lhs with a static type on rhs, 9383 // see if static class implements all of id's protocols, directly or 9384 // through its super class and categories. 9385 if (rhsID->ClassImplementsProtocol(I, true)) { 9386 match = true; 9387 break; 9388 } 9389 } 9390 } 9391 if (!match) 9392 return false; 9393 } 9394 9395 return true; 9396 } 9397 9398 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 9399 9400 if (lhs->getInterfaceType()) { 9401 // If both the right and left sides have qualifiers. 9402 for (auto *lhsProto : lhs->quals()) { 9403 bool match = false; 9404 9405 // when comparing an id<P> on rhs with a static type on lhs, 9406 // see if static class implements all of id's protocols, directly or 9407 // through its super class and categories. 9408 // First, lhs protocols in the qualifier list must be found, direct 9409 // or indirect in rhs's qualifier list or it is a mismatch. 9410 for (auto *rhsProto : rhs->quals()) { 9411 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9412 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9413 match = true; 9414 break; 9415 } 9416 } 9417 if (!match) 9418 return false; 9419 } 9420 9421 // Static class's protocols, or its super class or category protocols 9422 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 9423 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 9424 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 9425 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 9426 // This is rather dubious but matches gcc's behavior. If lhs has 9427 // no type qualifier and its class has no static protocol(s) 9428 // assume that it is mismatch. 9429 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 9430 return false; 9431 for (auto *lhsProto : LHSInheritedProtocols) { 9432 bool match = false; 9433 for (auto *rhsProto : rhs->quals()) { 9434 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 9435 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 9436 match = true; 9437 break; 9438 } 9439 } 9440 if (!match) 9441 return false; 9442 } 9443 } 9444 return true; 9445 } 9446 return false; 9447 } 9448 9449 /// canAssignObjCInterfaces - Return true if the two interface types are 9450 /// compatible for assignment from RHS to LHS. This handles validation of any 9451 /// protocol qualifiers on the LHS or RHS. 9452 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 9453 const ObjCObjectPointerType *RHSOPT) { 9454 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9455 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9456 9457 // If either type represents the built-in 'id' type, return true. 9458 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 9459 return true; 9460 9461 // Function object that propagates a successful result or handles 9462 // __kindof types. 9463 auto finish = [&](bool succeeded) -> bool { 9464 if (succeeded) 9465 return true; 9466 9467 if (!RHS->isKindOfType()) 9468 return false; 9469 9470 // Strip off __kindof and protocol qualifiers, then check whether 9471 // we can assign the other way. 9472 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9473 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 9474 }; 9475 9476 // Casts from or to id<P> are allowed when the other side has compatible 9477 // protocols. 9478 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 9479 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 9480 } 9481 9482 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 9483 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9484 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9485 } 9486 9487 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9488 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9489 return true; 9490 } 9491 9492 // If we have 2 user-defined types, fall into that path. 9493 if (LHS->getInterface() && RHS->getInterface()) { 9494 return finish(canAssignObjCInterfaces(LHS, RHS)); 9495 } 9496 9497 return false; 9498 } 9499 9500 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9501 /// for providing type-safety for objective-c pointers used to pass/return 9502 /// arguments in block literals. When passed as arguments, passing 'A*' where 9503 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9504 /// not OK. For the return type, the opposite is not OK. 9505 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9506 const ObjCObjectPointerType *LHSOPT, 9507 const ObjCObjectPointerType *RHSOPT, 9508 bool BlockReturnType) { 9509 9510 // Function object that propagates a successful result or handles 9511 // __kindof types. 9512 auto finish = [&](bool succeeded) -> bool { 9513 if (succeeded) 9514 return true; 9515 9516 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9517 if (!Expected->isKindOfType()) 9518 return false; 9519 9520 // Strip off __kindof and protocol qualifiers, then check whether 9521 // we can assign the other way. 9522 return canAssignObjCInterfacesInBlockPointer( 9523 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9524 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9525 BlockReturnType); 9526 }; 9527 9528 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9529 return true; 9530 9531 if (LHSOPT->isObjCBuiltinType()) { 9532 return finish(RHSOPT->isObjCBuiltinType() || 9533 RHSOPT->isObjCQualifiedIdType()); 9534 } 9535 9536 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9537 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9538 // Use for block parameters previous type checking for compatibility. 9539 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9540 // Or corrected type checking as in non-compat mode. 9541 (!BlockReturnType && 9542 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9543 else 9544 return finish(ObjCQualifiedIdTypesAreCompatible( 9545 (BlockReturnType ? LHSOPT : RHSOPT), 9546 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9547 } 9548 9549 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9550 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9551 if (LHS && RHS) { // We have 2 user-defined types. 9552 if (LHS != RHS) { 9553 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9554 return finish(BlockReturnType); 9555 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9556 return finish(!BlockReturnType); 9557 } 9558 else 9559 return true; 9560 } 9561 return false; 9562 } 9563 9564 /// Comparison routine for Objective-C protocols to be used with 9565 /// llvm::array_pod_sort. 9566 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9567 ObjCProtocolDecl * const *rhs) { 9568 return (*lhs)->getName().compare((*rhs)->getName()); 9569 } 9570 9571 /// getIntersectionOfProtocols - This routine finds the intersection of set 9572 /// of protocols inherited from two distinct objective-c pointer objects with 9573 /// the given common base. 9574 /// It is used to build composite qualifier list of the composite type of 9575 /// the conditional expression involving two objective-c pointer objects. 9576 static 9577 void getIntersectionOfProtocols(ASTContext &Context, 9578 const ObjCInterfaceDecl *CommonBase, 9579 const ObjCObjectPointerType *LHSOPT, 9580 const ObjCObjectPointerType *RHSOPT, 9581 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9582 9583 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9584 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9585 assert(LHS->getInterface() && "LHS must have an interface base"); 9586 assert(RHS->getInterface() && "RHS must have an interface base"); 9587 9588 // Add all of the protocols for the LHS. 9589 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9590 9591 // Start with the protocol qualifiers. 9592 for (auto proto : LHS->quals()) { 9593 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9594 } 9595 9596 // Also add the protocols associated with the LHS interface. 9597 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9598 9599 // Add all of the protocols for the RHS. 9600 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9601 9602 // Start with the protocol qualifiers. 9603 for (auto proto : RHS->quals()) { 9604 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9605 } 9606 9607 // Also add the protocols associated with the RHS interface. 9608 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9609 9610 // Compute the intersection of the collected protocol sets. 9611 for (auto proto : LHSProtocolSet) { 9612 if (RHSProtocolSet.count(proto)) 9613 IntersectionSet.push_back(proto); 9614 } 9615 9616 // Compute the set of protocols that is implied by either the common type or 9617 // the protocols within the intersection. 9618 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9619 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9620 9621 // Remove any implied protocols from the list of inherited protocols. 9622 if (!ImpliedProtocols.empty()) { 9623 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool { 9624 return ImpliedProtocols.contains(proto); 9625 }); 9626 } 9627 9628 // Sort the remaining protocols by name. 9629 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9630 compareObjCProtocolsByName); 9631 } 9632 9633 /// Determine whether the first type is a subtype of the second. 9634 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9635 QualType rhs) { 9636 // Common case: two object pointers. 9637 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9638 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9639 if (lhsOPT && rhsOPT) 9640 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9641 9642 // Two block pointers. 9643 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9644 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9645 if (lhsBlock && rhsBlock) 9646 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9647 9648 // If either is an unqualified 'id' and the other is a block, it's 9649 // acceptable. 9650 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9651 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9652 return true; 9653 9654 return false; 9655 } 9656 9657 // Check that the given Objective-C type argument lists are equivalent. 9658 static bool sameObjCTypeArgs(ASTContext &ctx, 9659 const ObjCInterfaceDecl *iface, 9660 ArrayRef<QualType> lhsArgs, 9661 ArrayRef<QualType> rhsArgs, 9662 bool stripKindOf) { 9663 if (lhsArgs.size() != rhsArgs.size()) 9664 return false; 9665 9666 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9667 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9668 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9669 continue; 9670 9671 switch (typeParams->begin()[i]->getVariance()) { 9672 case ObjCTypeParamVariance::Invariant: 9673 if (!stripKindOf || 9674 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9675 rhsArgs[i].stripObjCKindOfType(ctx))) { 9676 return false; 9677 } 9678 break; 9679 9680 case ObjCTypeParamVariance::Covariant: 9681 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9682 return false; 9683 break; 9684 9685 case ObjCTypeParamVariance::Contravariant: 9686 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9687 return false; 9688 break; 9689 } 9690 } 9691 9692 return true; 9693 } 9694 9695 QualType ASTContext::areCommonBaseCompatible( 9696 const ObjCObjectPointerType *Lptr, 9697 const ObjCObjectPointerType *Rptr) { 9698 const ObjCObjectType *LHS = Lptr->getObjectType(); 9699 const ObjCObjectType *RHS = Rptr->getObjectType(); 9700 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9701 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9702 9703 if (!LDecl || !RDecl) 9704 return {}; 9705 9706 // When either LHS or RHS is a kindof type, we should return a kindof type. 9707 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9708 // kindof(A). 9709 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9710 9711 // Follow the left-hand side up the class hierarchy until we either hit a 9712 // root or find the RHS. Record the ancestors in case we don't find it. 9713 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9714 LHSAncestors; 9715 while (true) { 9716 // Record this ancestor. We'll need this if the common type isn't in the 9717 // path from the LHS to the root. 9718 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9719 9720 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9721 // Get the type arguments. 9722 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9723 bool anyChanges = false; 9724 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9725 // Both have type arguments, compare them. 9726 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9727 LHS->getTypeArgs(), RHS->getTypeArgs(), 9728 /*stripKindOf=*/true)) 9729 return {}; 9730 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9731 // If only one has type arguments, the result will not have type 9732 // arguments. 9733 LHSTypeArgs = {}; 9734 anyChanges = true; 9735 } 9736 9737 // Compute the intersection of protocols. 9738 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9739 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9740 Protocols); 9741 if (!Protocols.empty()) 9742 anyChanges = true; 9743 9744 // If anything in the LHS will have changed, build a new result type. 9745 // If we need to return a kindof type but LHS is not a kindof type, we 9746 // build a new result type. 9747 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9748 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9749 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9750 anyKindOf || LHS->isKindOfType()); 9751 return getObjCObjectPointerType(Result); 9752 } 9753 9754 return getObjCObjectPointerType(QualType(LHS, 0)); 9755 } 9756 9757 // Find the superclass. 9758 QualType LHSSuperType = LHS->getSuperClassType(); 9759 if (LHSSuperType.isNull()) 9760 break; 9761 9762 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9763 } 9764 9765 // We didn't find anything by following the LHS to its root; now check 9766 // the RHS against the cached set of ancestors. 9767 while (true) { 9768 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9769 if (KnownLHS != LHSAncestors.end()) { 9770 LHS = KnownLHS->second; 9771 9772 // Get the type arguments. 9773 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9774 bool anyChanges = false; 9775 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9776 // Both have type arguments, compare them. 9777 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9778 LHS->getTypeArgs(), RHS->getTypeArgs(), 9779 /*stripKindOf=*/true)) 9780 return {}; 9781 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9782 // If only one has type arguments, the result will not have type 9783 // arguments. 9784 RHSTypeArgs = {}; 9785 anyChanges = true; 9786 } 9787 9788 // Compute the intersection of protocols. 9789 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9790 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9791 Protocols); 9792 if (!Protocols.empty()) 9793 anyChanges = true; 9794 9795 // If we need to return a kindof type but RHS is not a kindof type, we 9796 // build a new result type. 9797 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9798 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9799 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9800 anyKindOf || RHS->isKindOfType()); 9801 return getObjCObjectPointerType(Result); 9802 } 9803 9804 return getObjCObjectPointerType(QualType(RHS, 0)); 9805 } 9806 9807 // Find the superclass of the RHS. 9808 QualType RHSSuperType = RHS->getSuperClassType(); 9809 if (RHSSuperType.isNull()) 9810 break; 9811 9812 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9813 } 9814 9815 return {}; 9816 } 9817 9818 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9819 const ObjCObjectType *RHS) { 9820 assert(LHS->getInterface() && "LHS is not an interface type"); 9821 assert(RHS->getInterface() && "RHS is not an interface type"); 9822 9823 // Verify that the base decls are compatible: the RHS must be a subclass of 9824 // the LHS. 9825 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9826 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9827 if (!IsSuperClass) 9828 return false; 9829 9830 // If the LHS has protocol qualifiers, determine whether all of them are 9831 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9832 // LHS). 9833 if (LHS->getNumProtocols() > 0) { 9834 // OK if conversion of LHS to SuperClass results in narrowing of types 9835 // ; i.e., SuperClass may implement at least one of the protocols 9836 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9837 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9838 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9839 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9840 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9841 // qualifiers. 9842 for (auto *RHSPI : RHS->quals()) 9843 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9844 // If there is no protocols associated with RHS, it is not a match. 9845 if (SuperClassInheritedProtocols.empty()) 9846 return false; 9847 9848 for (const auto *LHSProto : LHS->quals()) { 9849 bool SuperImplementsProtocol = false; 9850 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9851 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9852 SuperImplementsProtocol = true; 9853 break; 9854 } 9855 if (!SuperImplementsProtocol) 9856 return false; 9857 } 9858 } 9859 9860 // If the LHS is specialized, we may need to check type arguments. 9861 if (LHS->isSpecialized()) { 9862 // Follow the superclass chain until we've matched the LHS class in the 9863 // hierarchy. This substitutes type arguments through. 9864 const ObjCObjectType *RHSSuper = RHS; 9865 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9866 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9867 9868 // If the RHS is specializd, compare type arguments. 9869 if (RHSSuper->isSpecialized() && 9870 !sameObjCTypeArgs(*this, LHS->getInterface(), 9871 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9872 /*stripKindOf=*/true)) { 9873 return false; 9874 } 9875 } 9876 9877 return true; 9878 } 9879 9880 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9881 // get the "pointed to" types 9882 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9883 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9884 9885 if (!LHSOPT || !RHSOPT) 9886 return false; 9887 9888 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9889 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9890 } 9891 9892 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9893 return canAssignObjCInterfaces( 9894 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9895 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9896 } 9897 9898 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9899 /// both shall have the identically qualified version of a compatible type. 9900 /// C99 6.2.7p1: Two types have compatible types if their types are the 9901 /// same. See 6.7.[2,3,5] for additional rules. 9902 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9903 bool CompareUnqualified) { 9904 if (getLangOpts().CPlusPlus) 9905 return hasSameType(LHS, RHS); 9906 9907 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9908 } 9909 9910 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9911 return typesAreCompatible(LHS, RHS); 9912 } 9913 9914 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9915 return !mergeTypes(LHS, RHS, true).isNull(); 9916 } 9917 9918 /// mergeTransparentUnionType - if T is a transparent union type and a member 9919 /// of T is compatible with SubType, return the merged type, else return 9920 /// QualType() 9921 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9922 bool OfBlockPointer, 9923 bool Unqualified) { 9924 if (const RecordType *UT = T->getAsUnionType()) { 9925 RecordDecl *UD = UT->getDecl(); 9926 if (UD->hasAttr<TransparentUnionAttr>()) { 9927 for (const auto *I : UD->fields()) { 9928 QualType ET = I->getType().getUnqualifiedType(); 9929 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9930 if (!MT.isNull()) 9931 return MT; 9932 } 9933 } 9934 } 9935 9936 return {}; 9937 } 9938 9939 /// mergeFunctionParameterTypes - merge two types which appear as function 9940 /// parameter types 9941 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9942 bool OfBlockPointer, 9943 bool Unqualified) { 9944 // GNU extension: two types are compatible if they appear as a function 9945 // argument, one of the types is a transparent union type and the other 9946 // type is compatible with a union member 9947 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9948 Unqualified); 9949 if (!lmerge.isNull()) 9950 return lmerge; 9951 9952 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9953 Unqualified); 9954 if (!rmerge.isNull()) 9955 return rmerge; 9956 9957 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9958 } 9959 9960 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9961 bool OfBlockPointer, bool Unqualified, 9962 bool AllowCXX) { 9963 const auto *lbase = lhs->castAs<FunctionType>(); 9964 const auto *rbase = rhs->castAs<FunctionType>(); 9965 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9966 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9967 bool allLTypes = true; 9968 bool allRTypes = true; 9969 9970 // Check return type 9971 QualType retType; 9972 if (OfBlockPointer) { 9973 QualType RHS = rbase->getReturnType(); 9974 QualType LHS = lbase->getReturnType(); 9975 bool UnqualifiedResult = Unqualified; 9976 if (!UnqualifiedResult) 9977 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9978 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9979 } 9980 else 9981 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9982 Unqualified); 9983 if (retType.isNull()) 9984 return {}; 9985 9986 if (Unqualified) 9987 retType = retType.getUnqualifiedType(); 9988 9989 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9990 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9991 if (Unqualified) { 9992 LRetType = LRetType.getUnqualifiedType(); 9993 RRetType = RRetType.getUnqualifiedType(); 9994 } 9995 9996 if (getCanonicalType(retType) != LRetType) 9997 allLTypes = false; 9998 if (getCanonicalType(retType) != RRetType) 9999 allRTypes = false; 10000 10001 // FIXME: double check this 10002 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 10003 // rbase->getRegParmAttr() != 0 && 10004 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 10005 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 10006 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 10007 10008 // Compatible functions must have compatible calling conventions 10009 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 10010 return {}; 10011 10012 // Regparm is part of the calling convention. 10013 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 10014 return {}; 10015 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 10016 return {}; 10017 10018 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 10019 return {}; 10020 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 10021 return {}; 10022 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 10023 return {}; 10024 10025 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 10026 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 10027 10028 if (lbaseInfo.getNoReturn() != NoReturn) 10029 allLTypes = false; 10030 if (rbaseInfo.getNoReturn() != NoReturn) 10031 allRTypes = false; 10032 10033 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 10034 10035 if (lproto && rproto) { // two C99 style function prototypes 10036 assert((AllowCXX || 10037 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 10038 "C++ shouldn't be here"); 10039 // Compatible functions must have the same number of parameters 10040 if (lproto->getNumParams() != rproto->getNumParams()) 10041 return {}; 10042 10043 // Variadic and non-variadic functions aren't compatible 10044 if (lproto->isVariadic() != rproto->isVariadic()) 10045 return {}; 10046 10047 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 10048 return {}; 10049 10050 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 10051 bool canUseLeft, canUseRight; 10052 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 10053 newParamInfos)) 10054 return {}; 10055 10056 if (!canUseLeft) 10057 allLTypes = false; 10058 if (!canUseRight) 10059 allRTypes = false; 10060 10061 // Check parameter type compatibility 10062 SmallVector<QualType, 10> types; 10063 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 10064 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 10065 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 10066 QualType paramType = mergeFunctionParameterTypes( 10067 lParamType, rParamType, OfBlockPointer, Unqualified); 10068 if (paramType.isNull()) 10069 return {}; 10070 10071 if (Unqualified) 10072 paramType = paramType.getUnqualifiedType(); 10073 10074 types.push_back(paramType); 10075 if (Unqualified) { 10076 lParamType = lParamType.getUnqualifiedType(); 10077 rParamType = rParamType.getUnqualifiedType(); 10078 } 10079 10080 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 10081 allLTypes = false; 10082 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 10083 allRTypes = false; 10084 } 10085 10086 if (allLTypes) return lhs; 10087 if (allRTypes) return rhs; 10088 10089 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 10090 EPI.ExtInfo = einfo; 10091 EPI.ExtParameterInfos = 10092 newParamInfos.empty() ? nullptr : newParamInfos.data(); 10093 return getFunctionType(retType, types, EPI); 10094 } 10095 10096 if (lproto) allRTypes = false; 10097 if (rproto) allLTypes = false; 10098 10099 const FunctionProtoType *proto = lproto ? lproto : rproto; 10100 if (proto) { 10101 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 10102 if (proto->isVariadic()) 10103 return {}; 10104 // Check that the types are compatible with the types that 10105 // would result from default argument promotions (C99 6.7.5.3p15). 10106 // The only types actually affected are promotable integer 10107 // types and floats, which would be passed as a different 10108 // type depending on whether the prototype is visible. 10109 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 10110 QualType paramTy = proto->getParamType(i); 10111 10112 // Look at the converted type of enum types, since that is the type used 10113 // to pass enum values. 10114 if (const auto *Enum = paramTy->getAs<EnumType>()) { 10115 paramTy = Enum->getDecl()->getIntegerType(); 10116 if (paramTy.isNull()) 10117 return {}; 10118 } 10119 10120 if (paramTy->isPromotableIntegerType() || 10121 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 10122 return {}; 10123 } 10124 10125 if (allLTypes) return lhs; 10126 if (allRTypes) return rhs; 10127 10128 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 10129 EPI.ExtInfo = einfo; 10130 return getFunctionType(retType, proto->getParamTypes(), EPI); 10131 } 10132 10133 if (allLTypes) return lhs; 10134 if (allRTypes) return rhs; 10135 return getFunctionNoProtoType(retType, einfo); 10136 } 10137 10138 /// Given that we have an enum type and a non-enum type, try to merge them. 10139 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 10140 QualType other, bool isBlockReturnType) { 10141 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 10142 // a signed integer type, or an unsigned integer type. 10143 // Compatibility is based on the underlying type, not the promotion 10144 // type. 10145 QualType underlyingType = ET->getDecl()->getIntegerType(); 10146 if (underlyingType.isNull()) 10147 return {}; 10148 if (Context.hasSameType(underlyingType, other)) 10149 return other; 10150 10151 // In block return types, we're more permissive and accept any 10152 // integral type of the same size. 10153 if (isBlockReturnType && other->isIntegerType() && 10154 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 10155 return other; 10156 10157 return {}; 10158 } 10159 10160 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 10161 bool OfBlockPointer, 10162 bool Unqualified, bool BlockReturnType) { 10163 // For C++ we will not reach this code with reference types (see below), 10164 // for OpenMP variant call overloading we might. 10165 // 10166 // C++ [expr]: If an expression initially has the type "reference to T", the 10167 // type is adjusted to "T" prior to any further analysis, the expression 10168 // designates the object or function denoted by the reference, and the 10169 // expression is an lvalue unless the reference is an rvalue reference and 10170 // the expression is a function call (possibly inside parentheses). 10171 auto *LHSRefTy = LHS->getAs<ReferenceType>(); 10172 auto *RHSRefTy = RHS->getAs<ReferenceType>(); 10173 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy && 10174 LHS->getTypeClass() == RHS->getTypeClass()) 10175 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(), 10176 OfBlockPointer, Unqualified, BlockReturnType); 10177 if (LHSRefTy || RHSRefTy) 10178 return {}; 10179 10180 if (Unqualified) { 10181 LHS = LHS.getUnqualifiedType(); 10182 RHS = RHS.getUnqualifiedType(); 10183 } 10184 10185 QualType LHSCan = getCanonicalType(LHS), 10186 RHSCan = getCanonicalType(RHS); 10187 10188 // If two types are identical, they are compatible. 10189 if (LHSCan == RHSCan) 10190 return LHS; 10191 10192 // If the qualifiers are different, the types aren't compatible... mostly. 10193 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10194 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10195 if (LQuals != RQuals) { 10196 // If any of these qualifiers are different, we have a type 10197 // mismatch. 10198 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10199 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 10200 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 10201 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 10202 return {}; 10203 10204 // Exactly one GC qualifier difference is allowed: __strong is 10205 // okay if the other type has no GC qualifier but is an Objective 10206 // C object pointer (i.e. implicitly strong by default). We fix 10207 // this by pretending that the unqualified type was actually 10208 // qualified __strong. 10209 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10210 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10211 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10212 10213 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10214 return {}; 10215 10216 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 10217 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 10218 } 10219 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 10220 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 10221 } 10222 return {}; 10223 } 10224 10225 // Okay, qualifiers are equal. 10226 10227 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 10228 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 10229 10230 // We want to consider the two function types to be the same for these 10231 // comparisons, just force one to the other. 10232 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 10233 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 10234 10235 // Same as above for arrays 10236 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 10237 LHSClass = Type::ConstantArray; 10238 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 10239 RHSClass = Type::ConstantArray; 10240 10241 // ObjCInterfaces are just specialized ObjCObjects. 10242 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 10243 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 10244 10245 // Canonicalize ExtVector -> Vector. 10246 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 10247 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 10248 10249 // If the canonical type classes don't match. 10250 if (LHSClass != RHSClass) { 10251 // Note that we only have special rules for turning block enum 10252 // returns into block int returns, not vice-versa. 10253 if (const auto *ETy = LHS->getAs<EnumType>()) { 10254 return mergeEnumWithInteger(*this, ETy, RHS, false); 10255 } 10256 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 10257 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 10258 } 10259 // allow block pointer type to match an 'id' type. 10260 if (OfBlockPointer && !BlockReturnType) { 10261 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 10262 return LHS; 10263 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 10264 return RHS; 10265 } 10266 10267 return {}; 10268 } 10269 10270 // The canonical type classes match. 10271 switch (LHSClass) { 10272 #define TYPE(Class, Base) 10273 #define ABSTRACT_TYPE(Class, Base) 10274 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 10275 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 10276 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 10277 #include "clang/AST/TypeNodes.inc" 10278 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 10279 10280 case Type::Auto: 10281 case Type::DeducedTemplateSpecialization: 10282 case Type::LValueReference: 10283 case Type::RValueReference: 10284 case Type::MemberPointer: 10285 llvm_unreachable("C++ should never be in mergeTypes"); 10286 10287 case Type::ObjCInterface: 10288 case Type::IncompleteArray: 10289 case Type::VariableArray: 10290 case Type::FunctionProto: 10291 case Type::ExtVector: 10292 llvm_unreachable("Types are eliminated above"); 10293 10294 case Type::Pointer: 10295 { 10296 // Merge two pointer types, while trying to preserve typedef info 10297 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 10298 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 10299 if (Unqualified) { 10300 LHSPointee = LHSPointee.getUnqualifiedType(); 10301 RHSPointee = RHSPointee.getUnqualifiedType(); 10302 } 10303 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 10304 Unqualified); 10305 if (ResultType.isNull()) 10306 return {}; 10307 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10308 return LHS; 10309 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10310 return RHS; 10311 return getPointerType(ResultType); 10312 } 10313 case Type::BlockPointer: 10314 { 10315 // Merge two block pointer types, while trying to preserve typedef info 10316 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 10317 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 10318 if (Unqualified) { 10319 LHSPointee = LHSPointee.getUnqualifiedType(); 10320 RHSPointee = RHSPointee.getUnqualifiedType(); 10321 } 10322 if (getLangOpts().OpenCL) { 10323 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 10324 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 10325 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 10326 // 6.12.5) thus the following check is asymmetric. 10327 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 10328 return {}; 10329 LHSPteeQual.removeAddressSpace(); 10330 RHSPteeQual.removeAddressSpace(); 10331 LHSPointee = 10332 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 10333 RHSPointee = 10334 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 10335 } 10336 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 10337 Unqualified); 10338 if (ResultType.isNull()) 10339 return {}; 10340 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 10341 return LHS; 10342 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 10343 return RHS; 10344 return getBlockPointerType(ResultType); 10345 } 10346 case Type::Atomic: 10347 { 10348 // Merge two pointer types, while trying to preserve typedef info 10349 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 10350 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 10351 if (Unqualified) { 10352 LHSValue = LHSValue.getUnqualifiedType(); 10353 RHSValue = RHSValue.getUnqualifiedType(); 10354 } 10355 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 10356 Unqualified); 10357 if (ResultType.isNull()) 10358 return {}; 10359 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 10360 return LHS; 10361 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 10362 return RHS; 10363 return getAtomicType(ResultType); 10364 } 10365 case Type::ConstantArray: 10366 { 10367 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 10368 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 10369 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 10370 return {}; 10371 10372 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 10373 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 10374 if (Unqualified) { 10375 LHSElem = LHSElem.getUnqualifiedType(); 10376 RHSElem = RHSElem.getUnqualifiedType(); 10377 } 10378 10379 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 10380 if (ResultType.isNull()) 10381 return {}; 10382 10383 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 10384 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 10385 10386 // If either side is a variable array, and both are complete, check whether 10387 // the current dimension is definite. 10388 if (LVAT || RVAT) { 10389 auto SizeFetch = [this](const VariableArrayType* VAT, 10390 const ConstantArrayType* CAT) 10391 -> std::pair<bool,llvm::APInt> { 10392 if (VAT) { 10393 Optional<llvm::APSInt> TheInt; 10394 Expr *E = VAT->getSizeExpr(); 10395 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 10396 return std::make_pair(true, *TheInt); 10397 return std::make_pair(false, llvm::APSInt()); 10398 } 10399 if (CAT) 10400 return std::make_pair(true, CAT->getSize()); 10401 return std::make_pair(false, llvm::APInt()); 10402 }; 10403 10404 bool HaveLSize, HaveRSize; 10405 llvm::APInt LSize, RSize; 10406 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 10407 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 10408 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 10409 return {}; // Definite, but unequal, array dimension 10410 } 10411 10412 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10413 return LHS; 10414 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10415 return RHS; 10416 if (LCAT) 10417 return getConstantArrayType(ResultType, LCAT->getSize(), 10418 LCAT->getSizeExpr(), 10419 ArrayType::ArraySizeModifier(), 0); 10420 if (RCAT) 10421 return getConstantArrayType(ResultType, RCAT->getSize(), 10422 RCAT->getSizeExpr(), 10423 ArrayType::ArraySizeModifier(), 0); 10424 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 10425 return LHS; 10426 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 10427 return RHS; 10428 if (LVAT) { 10429 // FIXME: This isn't correct! But tricky to implement because 10430 // the array's size has to be the size of LHS, but the type 10431 // has to be different. 10432 return LHS; 10433 } 10434 if (RVAT) { 10435 // FIXME: This isn't correct! But tricky to implement because 10436 // the array's size has to be the size of RHS, but the type 10437 // has to be different. 10438 return RHS; 10439 } 10440 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 10441 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 10442 return getIncompleteArrayType(ResultType, 10443 ArrayType::ArraySizeModifier(), 0); 10444 } 10445 case Type::FunctionNoProto: 10446 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 10447 case Type::Record: 10448 case Type::Enum: 10449 return {}; 10450 case Type::Builtin: 10451 // Only exactly equal builtin types are compatible, which is tested above. 10452 return {}; 10453 case Type::Complex: 10454 // Distinct complex types are incompatible. 10455 return {}; 10456 case Type::Vector: 10457 // FIXME: The merged type should be an ExtVector! 10458 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 10459 RHSCan->castAs<VectorType>())) 10460 return LHS; 10461 return {}; 10462 case Type::ConstantMatrix: 10463 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 10464 RHSCan->castAs<ConstantMatrixType>())) 10465 return LHS; 10466 return {}; 10467 case Type::ObjCObject: { 10468 // Check if the types are assignment compatible. 10469 // FIXME: This should be type compatibility, e.g. whether 10470 // "LHS x; RHS x;" at global scope is legal. 10471 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 10472 RHS->castAs<ObjCObjectType>())) 10473 return LHS; 10474 return {}; 10475 } 10476 case Type::ObjCObjectPointer: 10477 if (OfBlockPointer) { 10478 if (canAssignObjCInterfacesInBlockPointer( 10479 LHS->castAs<ObjCObjectPointerType>(), 10480 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 10481 return LHS; 10482 return {}; 10483 } 10484 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 10485 RHS->castAs<ObjCObjectPointerType>())) 10486 return LHS; 10487 return {}; 10488 case Type::Pipe: 10489 assert(LHS != RHS && 10490 "Equivalent pipe types should have already been handled!"); 10491 return {}; 10492 case Type::BitInt: { 10493 // Merge two bit-precise int types, while trying to preserve typedef info. 10494 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned(); 10495 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned(); 10496 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits(); 10497 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits(); 10498 10499 // Like unsigned/int, shouldn't have a type if they don't match. 10500 if (LHSUnsigned != RHSUnsigned) 10501 return {}; 10502 10503 if (LHSBits != RHSBits) 10504 return {}; 10505 return LHS; 10506 } 10507 } 10508 10509 llvm_unreachable("Invalid Type::Class!"); 10510 } 10511 10512 bool ASTContext::mergeExtParameterInfo( 10513 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10514 bool &CanUseFirst, bool &CanUseSecond, 10515 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10516 assert(NewParamInfos.empty() && "param info list not empty"); 10517 CanUseFirst = CanUseSecond = true; 10518 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10519 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10520 10521 // Fast path: if the first type doesn't have ext parameter infos, 10522 // we match if and only if the second type also doesn't have them. 10523 if (!FirstHasInfo && !SecondHasInfo) 10524 return true; 10525 10526 bool NeedParamInfo = false; 10527 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10528 : SecondFnType->getExtParameterInfos().size(); 10529 10530 for (size_t I = 0; I < E; ++I) { 10531 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10532 if (FirstHasInfo) 10533 FirstParam = FirstFnType->getExtParameterInfo(I); 10534 if (SecondHasInfo) 10535 SecondParam = SecondFnType->getExtParameterInfo(I); 10536 10537 // Cannot merge unless everything except the noescape flag matches. 10538 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10539 return false; 10540 10541 bool FirstNoEscape = FirstParam.isNoEscape(); 10542 bool SecondNoEscape = SecondParam.isNoEscape(); 10543 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10544 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10545 if (NewParamInfos.back().getOpaqueValue()) 10546 NeedParamInfo = true; 10547 if (FirstNoEscape != IsNoEscape) 10548 CanUseFirst = false; 10549 if (SecondNoEscape != IsNoEscape) 10550 CanUseSecond = false; 10551 } 10552 10553 if (!NeedParamInfo) 10554 NewParamInfos.clear(); 10555 10556 return true; 10557 } 10558 10559 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10560 ObjCLayouts[CD] = nullptr; 10561 } 10562 10563 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10564 /// 'RHS' attributes and returns the merged version; including for function 10565 /// return types. 10566 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10567 QualType LHSCan = getCanonicalType(LHS), 10568 RHSCan = getCanonicalType(RHS); 10569 // If two types are identical, they are compatible. 10570 if (LHSCan == RHSCan) 10571 return LHS; 10572 if (RHSCan->isFunctionType()) { 10573 if (!LHSCan->isFunctionType()) 10574 return {}; 10575 QualType OldReturnType = 10576 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10577 QualType NewReturnType = 10578 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10579 QualType ResReturnType = 10580 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10581 if (ResReturnType.isNull()) 10582 return {}; 10583 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10584 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10585 // In either case, use OldReturnType to build the new function type. 10586 const auto *F = LHS->castAs<FunctionType>(); 10587 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10588 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10589 EPI.ExtInfo = getFunctionExtInfo(LHS); 10590 QualType ResultType = 10591 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10592 return ResultType; 10593 } 10594 } 10595 return {}; 10596 } 10597 10598 // If the qualifiers are different, the types can still be merged. 10599 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10600 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10601 if (LQuals != RQuals) { 10602 // If any of these qualifiers are different, we have a type mismatch. 10603 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10604 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10605 return {}; 10606 10607 // Exactly one GC qualifier difference is allowed: __strong is 10608 // okay if the other type has no GC qualifier but is an Objective 10609 // C object pointer (i.e. implicitly strong by default). We fix 10610 // this by pretending that the unqualified type was actually 10611 // qualified __strong. 10612 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10613 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10614 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10615 10616 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10617 return {}; 10618 10619 if (GC_L == Qualifiers::Strong) 10620 return LHS; 10621 if (GC_R == Qualifiers::Strong) 10622 return RHS; 10623 return {}; 10624 } 10625 10626 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10627 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10628 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10629 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10630 if (ResQT == LHSBaseQT) 10631 return LHS; 10632 if (ResQT == RHSBaseQT) 10633 return RHS; 10634 } 10635 return {}; 10636 } 10637 10638 //===----------------------------------------------------------------------===// 10639 // Integer Predicates 10640 //===----------------------------------------------------------------------===// 10641 10642 unsigned ASTContext::getIntWidth(QualType T) const { 10643 if (const auto *ET = T->getAs<EnumType>()) 10644 T = ET->getDecl()->getIntegerType(); 10645 if (T->isBooleanType()) 10646 return 1; 10647 if (const auto *EIT = T->getAs<BitIntType>()) 10648 return EIT->getNumBits(); 10649 // For builtin types, just use the standard type sizing method 10650 return (unsigned)getTypeSize(T); 10651 } 10652 10653 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10654 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10655 "Unexpected type"); 10656 10657 // Turn <4 x signed int> -> <4 x unsigned int> 10658 if (const auto *VTy = T->getAs<VectorType>()) 10659 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10660 VTy->getNumElements(), VTy->getVectorKind()); 10661 10662 // For _BitInt, return an unsigned _BitInt with same width. 10663 if (const auto *EITy = T->getAs<BitIntType>()) 10664 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits()); 10665 10666 // For enums, get the underlying integer type of the enum, and let the general 10667 // integer type signchanging code handle it. 10668 if (const auto *ETy = T->getAs<EnumType>()) 10669 T = ETy->getDecl()->getIntegerType(); 10670 10671 switch (T->castAs<BuiltinType>()->getKind()) { 10672 case BuiltinType::Char_S: 10673 case BuiltinType::SChar: 10674 return UnsignedCharTy; 10675 case BuiltinType::Short: 10676 return UnsignedShortTy; 10677 case BuiltinType::Int: 10678 return UnsignedIntTy; 10679 case BuiltinType::Long: 10680 return UnsignedLongTy; 10681 case BuiltinType::LongLong: 10682 return UnsignedLongLongTy; 10683 case BuiltinType::Int128: 10684 return UnsignedInt128Ty; 10685 // wchar_t is special. It is either signed or not, but when it's signed, 10686 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10687 // version of it's underlying type instead. 10688 case BuiltinType::WChar_S: 10689 return getUnsignedWCharType(); 10690 10691 case BuiltinType::ShortAccum: 10692 return UnsignedShortAccumTy; 10693 case BuiltinType::Accum: 10694 return UnsignedAccumTy; 10695 case BuiltinType::LongAccum: 10696 return UnsignedLongAccumTy; 10697 case BuiltinType::SatShortAccum: 10698 return SatUnsignedShortAccumTy; 10699 case BuiltinType::SatAccum: 10700 return SatUnsignedAccumTy; 10701 case BuiltinType::SatLongAccum: 10702 return SatUnsignedLongAccumTy; 10703 case BuiltinType::ShortFract: 10704 return UnsignedShortFractTy; 10705 case BuiltinType::Fract: 10706 return UnsignedFractTy; 10707 case BuiltinType::LongFract: 10708 return UnsignedLongFractTy; 10709 case BuiltinType::SatShortFract: 10710 return SatUnsignedShortFractTy; 10711 case BuiltinType::SatFract: 10712 return SatUnsignedFractTy; 10713 case BuiltinType::SatLongFract: 10714 return SatUnsignedLongFractTy; 10715 default: 10716 llvm_unreachable("Unexpected signed integer or fixed point type"); 10717 } 10718 } 10719 10720 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10721 assert((T->hasUnsignedIntegerRepresentation() || 10722 T->isUnsignedFixedPointType()) && 10723 "Unexpected type"); 10724 10725 // Turn <4 x unsigned int> -> <4 x signed int> 10726 if (const auto *VTy = T->getAs<VectorType>()) 10727 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10728 VTy->getNumElements(), VTy->getVectorKind()); 10729 10730 // For _BitInt, return a signed _BitInt with same width. 10731 if (const auto *EITy = T->getAs<BitIntType>()) 10732 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits()); 10733 10734 // For enums, get the underlying integer type of the enum, and let the general 10735 // integer type signchanging code handle it. 10736 if (const auto *ETy = T->getAs<EnumType>()) 10737 T = ETy->getDecl()->getIntegerType(); 10738 10739 switch (T->castAs<BuiltinType>()->getKind()) { 10740 case BuiltinType::Char_U: 10741 case BuiltinType::UChar: 10742 return SignedCharTy; 10743 case BuiltinType::UShort: 10744 return ShortTy; 10745 case BuiltinType::UInt: 10746 return IntTy; 10747 case BuiltinType::ULong: 10748 return LongTy; 10749 case BuiltinType::ULongLong: 10750 return LongLongTy; 10751 case BuiltinType::UInt128: 10752 return Int128Ty; 10753 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10754 // there's no matching "signed wchar_t". Therefore we return the signed 10755 // version of it's underlying type instead. 10756 case BuiltinType::WChar_U: 10757 return getSignedWCharType(); 10758 10759 case BuiltinType::UShortAccum: 10760 return ShortAccumTy; 10761 case BuiltinType::UAccum: 10762 return AccumTy; 10763 case BuiltinType::ULongAccum: 10764 return LongAccumTy; 10765 case BuiltinType::SatUShortAccum: 10766 return SatShortAccumTy; 10767 case BuiltinType::SatUAccum: 10768 return SatAccumTy; 10769 case BuiltinType::SatULongAccum: 10770 return SatLongAccumTy; 10771 case BuiltinType::UShortFract: 10772 return ShortFractTy; 10773 case BuiltinType::UFract: 10774 return FractTy; 10775 case BuiltinType::ULongFract: 10776 return LongFractTy; 10777 case BuiltinType::SatUShortFract: 10778 return SatShortFractTy; 10779 case BuiltinType::SatUFract: 10780 return SatFractTy; 10781 case BuiltinType::SatULongFract: 10782 return SatLongFractTy; 10783 default: 10784 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10785 } 10786 } 10787 10788 ASTMutationListener::~ASTMutationListener() = default; 10789 10790 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10791 QualType ReturnType) {} 10792 10793 //===----------------------------------------------------------------------===// 10794 // Builtin Type Computation 10795 //===----------------------------------------------------------------------===// 10796 10797 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10798 /// pointer over the consumed characters. This returns the resultant type. If 10799 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10800 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10801 /// a vector of "i*". 10802 /// 10803 /// RequiresICE is filled in on return to indicate whether the value is required 10804 /// to be an Integer Constant Expression. 10805 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10806 ASTContext::GetBuiltinTypeError &Error, 10807 bool &RequiresICE, 10808 bool AllowTypeModifiers) { 10809 // Modifiers. 10810 int HowLong = 0; 10811 bool Signed = false, Unsigned = false; 10812 RequiresICE = false; 10813 10814 // Read the prefixed modifiers first. 10815 bool Done = false; 10816 #ifndef NDEBUG 10817 bool IsSpecial = false; 10818 #endif 10819 while (!Done) { 10820 switch (*Str++) { 10821 default: Done = true; --Str; break; 10822 case 'I': 10823 RequiresICE = true; 10824 break; 10825 case 'S': 10826 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10827 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10828 Signed = true; 10829 break; 10830 case 'U': 10831 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10832 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10833 Unsigned = true; 10834 break; 10835 case 'L': 10836 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10837 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10838 ++HowLong; 10839 break; 10840 case 'N': 10841 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10842 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10843 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10844 #ifndef NDEBUG 10845 IsSpecial = true; 10846 #endif 10847 if (Context.getTargetInfo().getLongWidth() == 32) 10848 ++HowLong; 10849 break; 10850 case 'W': 10851 // This modifier represents int64 type. 10852 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10853 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10854 #ifndef NDEBUG 10855 IsSpecial = true; 10856 #endif 10857 switch (Context.getTargetInfo().getInt64Type()) { 10858 default: 10859 llvm_unreachable("Unexpected integer type"); 10860 case TargetInfo::SignedLong: 10861 HowLong = 1; 10862 break; 10863 case TargetInfo::SignedLongLong: 10864 HowLong = 2; 10865 break; 10866 } 10867 break; 10868 case 'Z': 10869 // This modifier represents int32 type. 10870 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10871 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10872 #ifndef NDEBUG 10873 IsSpecial = true; 10874 #endif 10875 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10876 default: 10877 llvm_unreachable("Unexpected integer type"); 10878 case TargetInfo::SignedInt: 10879 HowLong = 0; 10880 break; 10881 case TargetInfo::SignedLong: 10882 HowLong = 1; 10883 break; 10884 case TargetInfo::SignedLongLong: 10885 HowLong = 2; 10886 break; 10887 } 10888 break; 10889 case 'O': 10890 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10891 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10892 #ifndef NDEBUG 10893 IsSpecial = true; 10894 #endif 10895 if (Context.getLangOpts().OpenCL) 10896 HowLong = 1; 10897 else 10898 HowLong = 2; 10899 break; 10900 } 10901 } 10902 10903 QualType Type; 10904 10905 // Read the base type. 10906 switch (*Str++) { 10907 default: llvm_unreachable("Unknown builtin type letter!"); 10908 case 'x': 10909 assert(HowLong == 0 && !Signed && !Unsigned && 10910 "Bad modifiers used with 'x'!"); 10911 Type = Context.Float16Ty; 10912 break; 10913 case 'y': 10914 assert(HowLong == 0 && !Signed && !Unsigned && 10915 "Bad modifiers used with 'y'!"); 10916 Type = Context.BFloat16Ty; 10917 break; 10918 case 'v': 10919 assert(HowLong == 0 && !Signed && !Unsigned && 10920 "Bad modifiers used with 'v'!"); 10921 Type = Context.VoidTy; 10922 break; 10923 case 'h': 10924 assert(HowLong == 0 && !Signed && !Unsigned && 10925 "Bad modifiers used with 'h'!"); 10926 Type = Context.HalfTy; 10927 break; 10928 case 'f': 10929 assert(HowLong == 0 && !Signed && !Unsigned && 10930 "Bad modifiers used with 'f'!"); 10931 Type = Context.FloatTy; 10932 break; 10933 case 'd': 10934 assert(HowLong < 3 && !Signed && !Unsigned && 10935 "Bad modifiers used with 'd'!"); 10936 if (HowLong == 1) 10937 Type = Context.LongDoubleTy; 10938 else if (HowLong == 2) 10939 Type = Context.Float128Ty; 10940 else 10941 Type = Context.DoubleTy; 10942 break; 10943 case 's': 10944 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10945 if (Unsigned) 10946 Type = Context.UnsignedShortTy; 10947 else 10948 Type = Context.ShortTy; 10949 break; 10950 case 'i': 10951 if (HowLong == 3) 10952 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10953 else if (HowLong == 2) 10954 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10955 else if (HowLong == 1) 10956 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10957 else 10958 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10959 break; 10960 case 'c': 10961 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10962 if (Signed) 10963 Type = Context.SignedCharTy; 10964 else if (Unsigned) 10965 Type = Context.UnsignedCharTy; 10966 else 10967 Type = Context.CharTy; 10968 break; 10969 case 'b': // boolean 10970 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10971 Type = Context.BoolTy; 10972 break; 10973 case 'z': // size_t. 10974 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10975 Type = Context.getSizeType(); 10976 break; 10977 case 'w': // wchar_t. 10978 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10979 Type = Context.getWideCharType(); 10980 break; 10981 case 'F': 10982 Type = Context.getCFConstantStringType(); 10983 break; 10984 case 'G': 10985 Type = Context.getObjCIdType(); 10986 break; 10987 case 'H': 10988 Type = Context.getObjCSelType(); 10989 break; 10990 case 'M': 10991 Type = Context.getObjCSuperType(); 10992 break; 10993 case 'a': 10994 Type = Context.getBuiltinVaListType(); 10995 assert(!Type.isNull() && "builtin va list type not initialized!"); 10996 break; 10997 case 'A': 10998 // This is a "reference" to a va_list; however, what exactly 10999 // this means depends on how va_list is defined. There are two 11000 // different kinds of va_list: ones passed by value, and ones 11001 // passed by reference. An example of a by-value va_list is 11002 // x86, where va_list is a char*. An example of by-ref va_list 11003 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 11004 // we want this argument to be a char*&; for x86-64, we want 11005 // it to be a __va_list_tag*. 11006 Type = Context.getBuiltinVaListType(); 11007 assert(!Type.isNull() && "builtin va list type not initialized!"); 11008 if (Type->isArrayType()) 11009 Type = Context.getArrayDecayedType(Type); 11010 else 11011 Type = Context.getLValueReferenceType(Type); 11012 break; 11013 case 'q': { 11014 char *End; 11015 unsigned NumElements = strtoul(Str, &End, 10); 11016 assert(End != Str && "Missing vector size"); 11017 Str = End; 11018 11019 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11020 RequiresICE, false); 11021 assert(!RequiresICE && "Can't require vector ICE"); 11022 11023 Type = Context.getScalableVectorType(ElementType, NumElements); 11024 break; 11025 } 11026 case 'V': { 11027 char *End; 11028 unsigned NumElements = strtoul(Str, &End, 10); 11029 assert(End != Str && "Missing vector size"); 11030 Str = End; 11031 11032 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 11033 RequiresICE, false); 11034 assert(!RequiresICE && "Can't require vector ICE"); 11035 11036 // TODO: No way to make AltiVec vectors in builtins yet. 11037 Type = Context.getVectorType(ElementType, NumElements, 11038 VectorType::GenericVector); 11039 break; 11040 } 11041 case 'E': { 11042 char *End; 11043 11044 unsigned NumElements = strtoul(Str, &End, 10); 11045 assert(End != Str && "Missing vector size"); 11046 11047 Str = End; 11048 11049 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11050 false); 11051 Type = Context.getExtVectorType(ElementType, NumElements); 11052 break; 11053 } 11054 case 'X': { 11055 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 11056 false); 11057 assert(!RequiresICE && "Can't require complex ICE"); 11058 Type = Context.getComplexType(ElementType); 11059 break; 11060 } 11061 case 'Y': 11062 Type = Context.getPointerDiffType(); 11063 break; 11064 case 'P': 11065 Type = Context.getFILEType(); 11066 if (Type.isNull()) { 11067 Error = ASTContext::GE_Missing_stdio; 11068 return {}; 11069 } 11070 break; 11071 case 'J': 11072 if (Signed) 11073 Type = Context.getsigjmp_bufType(); 11074 else 11075 Type = Context.getjmp_bufType(); 11076 11077 if (Type.isNull()) { 11078 Error = ASTContext::GE_Missing_setjmp; 11079 return {}; 11080 } 11081 break; 11082 case 'K': 11083 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 11084 Type = Context.getucontext_tType(); 11085 11086 if (Type.isNull()) { 11087 Error = ASTContext::GE_Missing_ucontext; 11088 return {}; 11089 } 11090 break; 11091 case 'p': 11092 Type = Context.getProcessIDType(); 11093 break; 11094 } 11095 11096 // If there are modifiers and if we're allowed to parse them, go for it. 11097 Done = !AllowTypeModifiers; 11098 while (!Done) { 11099 switch (char c = *Str++) { 11100 default: Done = true; --Str; break; 11101 case '*': 11102 case '&': { 11103 // Both pointers and references can have their pointee types 11104 // qualified with an address space. 11105 char *End; 11106 unsigned AddrSpace = strtoul(Str, &End, 10); 11107 if (End != Str) { 11108 // Note AddrSpace == 0 is not the same as an unspecified address space. 11109 Type = Context.getAddrSpaceQualType( 11110 Type, 11111 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 11112 Str = End; 11113 } 11114 if (c == '*') 11115 Type = Context.getPointerType(Type); 11116 else 11117 Type = Context.getLValueReferenceType(Type); 11118 break; 11119 } 11120 // FIXME: There's no way to have a built-in with an rvalue ref arg. 11121 case 'C': 11122 Type = Type.withConst(); 11123 break; 11124 case 'D': 11125 Type = Context.getVolatileType(Type); 11126 break; 11127 case 'R': 11128 Type = Type.withRestrict(); 11129 break; 11130 } 11131 } 11132 11133 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 11134 "Integer constant 'I' type must be an integer"); 11135 11136 return Type; 11137 } 11138 11139 // On some targets such as PowerPC, some of the builtins are defined with custom 11140 // type descriptors for target-dependent types. These descriptors are decoded in 11141 // other functions, but it may be useful to be able to fall back to default 11142 // descriptor decoding to define builtins mixing target-dependent and target- 11143 // independent types. This function allows decoding one type descriptor with 11144 // default decoding. 11145 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 11146 GetBuiltinTypeError &Error, bool &RequireICE, 11147 bool AllowTypeModifiers) const { 11148 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 11149 } 11150 11151 /// GetBuiltinType - Return the type for the specified builtin. 11152 QualType ASTContext::GetBuiltinType(unsigned Id, 11153 GetBuiltinTypeError &Error, 11154 unsigned *IntegerConstantArgs) const { 11155 const char *TypeStr = BuiltinInfo.getTypeString(Id); 11156 if (TypeStr[0] == '\0') { 11157 Error = GE_Missing_type; 11158 return {}; 11159 } 11160 11161 SmallVector<QualType, 8> ArgTypes; 11162 11163 bool RequiresICE = false; 11164 Error = GE_None; 11165 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 11166 RequiresICE, true); 11167 if (Error != GE_None) 11168 return {}; 11169 11170 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 11171 11172 while (TypeStr[0] && TypeStr[0] != '.') { 11173 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 11174 if (Error != GE_None) 11175 return {}; 11176 11177 // If this argument is required to be an IntegerConstantExpression and the 11178 // caller cares, fill in the bitmask we return. 11179 if (RequiresICE && IntegerConstantArgs) 11180 *IntegerConstantArgs |= 1 << ArgTypes.size(); 11181 11182 // Do array -> pointer decay. The builtin should use the decayed type. 11183 if (Ty->isArrayType()) 11184 Ty = getArrayDecayedType(Ty); 11185 11186 ArgTypes.push_back(Ty); 11187 } 11188 11189 if (Id == Builtin::BI__GetExceptionInfo) 11190 return {}; 11191 11192 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 11193 "'.' should only occur at end of builtin type list!"); 11194 11195 bool Variadic = (TypeStr[0] == '.'); 11196 11197 FunctionType::ExtInfo EI(getDefaultCallingConvention( 11198 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 11199 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 11200 11201 11202 // We really shouldn't be making a no-proto type here. 11203 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 11204 return getFunctionNoProtoType(ResType, EI); 11205 11206 FunctionProtoType::ExtProtoInfo EPI; 11207 EPI.ExtInfo = EI; 11208 EPI.Variadic = Variadic; 11209 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 11210 EPI.ExceptionSpec.Type = 11211 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 11212 11213 return getFunctionType(ResType, ArgTypes, EPI); 11214 } 11215 11216 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 11217 const FunctionDecl *FD) { 11218 if (!FD->isExternallyVisible()) 11219 return GVA_Internal; 11220 11221 // Non-user-provided functions get emitted as weak definitions with every 11222 // use, no matter whether they've been explicitly instantiated etc. 11223 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 11224 if (!MD->isUserProvided()) 11225 return GVA_DiscardableODR; 11226 11227 GVALinkage External; 11228 switch (FD->getTemplateSpecializationKind()) { 11229 case TSK_Undeclared: 11230 case TSK_ExplicitSpecialization: 11231 External = GVA_StrongExternal; 11232 break; 11233 11234 case TSK_ExplicitInstantiationDefinition: 11235 return GVA_StrongODR; 11236 11237 // C++11 [temp.explicit]p10: 11238 // [ Note: The intent is that an inline function that is the subject of 11239 // an explicit instantiation declaration will still be implicitly 11240 // instantiated when used so that the body can be considered for 11241 // inlining, but that no out-of-line copy of the inline function would be 11242 // generated in the translation unit. -- end note ] 11243 case TSK_ExplicitInstantiationDeclaration: 11244 return GVA_AvailableExternally; 11245 11246 case TSK_ImplicitInstantiation: 11247 External = GVA_DiscardableODR; 11248 break; 11249 } 11250 11251 if (!FD->isInlined()) 11252 return External; 11253 11254 if ((!Context.getLangOpts().CPlusPlus && 11255 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 11256 !FD->hasAttr<DLLExportAttr>()) || 11257 FD->hasAttr<GNUInlineAttr>()) { 11258 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 11259 11260 // GNU or C99 inline semantics. Determine whether this symbol should be 11261 // externally visible. 11262 if (FD->isInlineDefinitionExternallyVisible()) 11263 return External; 11264 11265 // C99 inline semantics, where the symbol is not externally visible. 11266 return GVA_AvailableExternally; 11267 } 11268 11269 // Functions specified with extern and inline in -fms-compatibility mode 11270 // forcibly get emitted. While the body of the function cannot be later 11271 // replaced, the function definition cannot be discarded. 11272 if (FD->isMSExternInline()) 11273 return GVA_StrongODR; 11274 11275 return GVA_DiscardableODR; 11276 } 11277 11278 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 11279 const Decl *D, GVALinkage L) { 11280 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 11281 // dllexport/dllimport on inline functions. 11282 if (D->hasAttr<DLLImportAttr>()) { 11283 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 11284 return GVA_AvailableExternally; 11285 } else if (D->hasAttr<DLLExportAttr>()) { 11286 if (L == GVA_DiscardableODR) 11287 return GVA_StrongODR; 11288 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 11289 // Device-side functions with __global__ attribute must always be 11290 // visible externally so they can be launched from host. 11291 if (D->hasAttr<CUDAGlobalAttr>() && 11292 (L == GVA_DiscardableODR || L == GVA_Internal)) 11293 return GVA_StrongODR; 11294 // Single source offloading languages like CUDA/HIP need to be able to 11295 // access static device variables from host code of the same compilation 11296 // unit. This is done by externalizing the static variable with a shared 11297 // name between the host and device compilation which is the same for the 11298 // same compilation unit whereas different among different compilation 11299 // units. 11300 if (Context.shouldExternalizeStaticVar(D)) 11301 return GVA_StrongExternal; 11302 } 11303 return L; 11304 } 11305 11306 /// Adjust the GVALinkage for a declaration based on what an external AST source 11307 /// knows about whether there can be other definitions of this declaration. 11308 static GVALinkage 11309 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 11310 GVALinkage L) { 11311 ExternalASTSource *Source = Ctx.getExternalSource(); 11312 if (!Source) 11313 return L; 11314 11315 switch (Source->hasExternalDefinitions(D)) { 11316 case ExternalASTSource::EK_Never: 11317 // Other translation units rely on us to provide the definition. 11318 if (L == GVA_DiscardableODR) 11319 return GVA_StrongODR; 11320 break; 11321 11322 case ExternalASTSource::EK_Always: 11323 return GVA_AvailableExternally; 11324 11325 case ExternalASTSource::EK_ReplyHazy: 11326 break; 11327 } 11328 return L; 11329 } 11330 11331 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 11332 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 11333 adjustGVALinkageForAttributes(*this, FD, 11334 basicGVALinkageForFunction(*this, FD))); 11335 } 11336 11337 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 11338 const VarDecl *VD) { 11339 if (!VD->isExternallyVisible()) 11340 return GVA_Internal; 11341 11342 if (VD->isStaticLocal()) { 11343 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 11344 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 11345 LexicalContext = LexicalContext->getLexicalParent(); 11346 11347 // ObjC Blocks can create local variables that don't have a FunctionDecl 11348 // LexicalContext. 11349 if (!LexicalContext) 11350 return GVA_DiscardableODR; 11351 11352 // Otherwise, let the static local variable inherit its linkage from the 11353 // nearest enclosing function. 11354 auto StaticLocalLinkage = 11355 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 11356 11357 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 11358 // be emitted in any object with references to the symbol for the object it 11359 // contains, whether inline or out-of-line." 11360 // Similar behavior is observed with MSVC. An alternative ABI could use 11361 // StrongODR/AvailableExternally to match the function, but none are 11362 // known/supported currently. 11363 if (StaticLocalLinkage == GVA_StrongODR || 11364 StaticLocalLinkage == GVA_AvailableExternally) 11365 return GVA_DiscardableODR; 11366 return StaticLocalLinkage; 11367 } 11368 11369 // MSVC treats in-class initialized static data members as definitions. 11370 // By giving them non-strong linkage, out-of-line definitions won't 11371 // cause link errors. 11372 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 11373 return GVA_DiscardableODR; 11374 11375 // Most non-template variables have strong linkage; inline variables are 11376 // linkonce_odr or (occasionally, for compatibility) weak_odr. 11377 GVALinkage StrongLinkage; 11378 switch (Context.getInlineVariableDefinitionKind(VD)) { 11379 case ASTContext::InlineVariableDefinitionKind::None: 11380 StrongLinkage = GVA_StrongExternal; 11381 break; 11382 case ASTContext::InlineVariableDefinitionKind::Weak: 11383 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 11384 StrongLinkage = GVA_DiscardableODR; 11385 break; 11386 case ASTContext::InlineVariableDefinitionKind::Strong: 11387 StrongLinkage = GVA_StrongODR; 11388 break; 11389 } 11390 11391 switch (VD->getTemplateSpecializationKind()) { 11392 case TSK_Undeclared: 11393 return StrongLinkage; 11394 11395 case TSK_ExplicitSpecialization: 11396 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 11397 VD->isStaticDataMember() 11398 ? GVA_StrongODR 11399 : StrongLinkage; 11400 11401 case TSK_ExplicitInstantiationDefinition: 11402 return GVA_StrongODR; 11403 11404 case TSK_ExplicitInstantiationDeclaration: 11405 return GVA_AvailableExternally; 11406 11407 case TSK_ImplicitInstantiation: 11408 return GVA_DiscardableODR; 11409 } 11410 11411 llvm_unreachable("Invalid Linkage!"); 11412 } 11413 11414 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 11415 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 11416 adjustGVALinkageForAttributes(*this, VD, 11417 basicGVALinkageForVariable(*this, VD))); 11418 } 11419 11420 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 11421 if (const auto *VD = dyn_cast<VarDecl>(D)) { 11422 if (!VD->isFileVarDecl()) 11423 return false; 11424 // Global named register variables (GNU extension) are never emitted. 11425 if (VD->getStorageClass() == SC_Register) 11426 return false; 11427 if (VD->getDescribedVarTemplate() || 11428 isa<VarTemplatePartialSpecializationDecl>(VD)) 11429 return false; 11430 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11431 // We never need to emit an uninstantiated function template. 11432 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11433 return false; 11434 } else if (isa<PragmaCommentDecl>(D)) 11435 return true; 11436 else if (isa<PragmaDetectMismatchDecl>(D)) 11437 return true; 11438 else if (isa<OMPRequiresDecl>(D)) 11439 return true; 11440 else if (isa<OMPThreadPrivateDecl>(D)) 11441 return !D->getDeclContext()->isDependentContext(); 11442 else if (isa<OMPAllocateDecl>(D)) 11443 return !D->getDeclContext()->isDependentContext(); 11444 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 11445 return !D->getDeclContext()->isDependentContext(); 11446 else if (isa<ImportDecl>(D)) 11447 return true; 11448 else 11449 return false; 11450 11451 // If this is a member of a class template, we do not need to emit it. 11452 if (D->getDeclContext()->isDependentContext()) 11453 return false; 11454 11455 // Weak references don't produce any output by themselves. 11456 if (D->hasAttr<WeakRefAttr>()) 11457 return false; 11458 11459 // Aliases and used decls are required. 11460 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 11461 return true; 11462 11463 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 11464 // Forward declarations aren't required. 11465 if (!FD->doesThisDeclarationHaveABody()) 11466 return FD->doesDeclarationForceExternallyVisibleDefinition(); 11467 11468 // Constructors and destructors are required. 11469 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 11470 return true; 11471 11472 // The key function for a class is required. This rule only comes 11473 // into play when inline functions can be key functions, though. 11474 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11475 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11476 const CXXRecordDecl *RD = MD->getParent(); 11477 if (MD->isOutOfLine() && RD->isDynamicClass()) { 11478 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 11479 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 11480 return true; 11481 } 11482 } 11483 } 11484 11485 GVALinkage Linkage = GetGVALinkageForFunction(FD); 11486 11487 // static, static inline, always_inline, and extern inline functions can 11488 // always be deferred. Normal inline functions can be deferred in C99/C++. 11489 // Implicit template instantiations can also be deferred in C++. 11490 return !isDiscardableGVALinkage(Linkage); 11491 } 11492 11493 const auto *VD = cast<VarDecl>(D); 11494 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11495 11496 // If the decl is marked as `declare target to`, it should be emitted for the 11497 // host and for the device. 11498 if (LangOpts.OpenMP && 11499 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11500 return true; 11501 11502 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11503 !isMSStaticDataMemberInlineDefinition(VD)) 11504 return false; 11505 11506 // Variables that can be needed in other TUs are required. 11507 auto Linkage = GetGVALinkageForVariable(VD); 11508 if (!isDiscardableGVALinkage(Linkage)) 11509 return true; 11510 11511 // We never need to emit a variable that is available in another TU. 11512 if (Linkage == GVA_AvailableExternally) 11513 return false; 11514 11515 // Variables that have destruction with side-effects are required. 11516 if (VD->needsDestruction(*this)) 11517 return true; 11518 11519 // Variables that have initialization with side-effects are required. 11520 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11521 // We can get a value-dependent initializer during error recovery. 11522 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11523 return true; 11524 11525 // Likewise, variables with tuple-like bindings are required if their 11526 // bindings have side-effects. 11527 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11528 for (const auto *BD : DD->bindings()) 11529 if (const auto *BindingVD = BD->getHoldingVar()) 11530 if (DeclMustBeEmitted(BindingVD)) 11531 return true; 11532 11533 return false; 11534 } 11535 11536 void ASTContext::forEachMultiversionedFunctionVersion( 11537 const FunctionDecl *FD, 11538 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11539 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11540 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11541 FD = FD->getMostRecentDecl(); 11542 // FIXME: The order of traversal here matters and depends on the order of 11543 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11544 // shouldn't rely on that. 11545 for (auto *CurDecl : 11546 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11547 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11548 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11549 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11550 SeenDecls.insert(CurFD); 11551 Pred(CurFD); 11552 } 11553 } 11554 } 11555 11556 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11557 bool IsCXXMethod, 11558 bool IsBuiltin) const { 11559 // Pass through to the C++ ABI object 11560 if (IsCXXMethod) 11561 return ABI->getDefaultMethodCallConv(IsVariadic); 11562 11563 // Builtins ignore user-specified default calling convention and remain the 11564 // Target's default calling convention. 11565 if (!IsBuiltin) { 11566 switch (LangOpts.getDefaultCallingConv()) { 11567 case LangOptions::DCC_None: 11568 break; 11569 case LangOptions::DCC_CDecl: 11570 return CC_C; 11571 case LangOptions::DCC_FastCall: 11572 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11573 return CC_X86FastCall; 11574 break; 11575 case LangOptions::DCC_StdCall: 11576 if (!IsVariadic) 11577 return CC_X86StdCall; 11578 break; 11579 case LangOptions::DCC_VectorCall: 11580 // __vectorcall cannot be applied to variadic functions. 11581 if (!IsVariadic) 11582 return CC_X86VectorCall; 11583 break; 11584 case LangOptions::DCC_RegCall: 11585 // __regcall cannot be applied to variadic functions. 11586 if (!IsVariadic) 11587 return CC_X86RegCall; 11588 break; 11589 } 11590 } 11591 return Target->getDefaultCallingConv(); 11592 } 11593 11594 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11595 // Pass through to the C++ ABI object 11596 return ABI->isNearlyEmpty(RD); 11597 } 11598 11599 VTableContextBase *ASTContext::getVTableContext() { 11600 if (!VTContext.get()) { 11601 auto ABI = Target->getCXXABI(); 11602 if (ABI.isMicrosoft()) 11603 VTContext.reset(new MicrosoftVTableContext(*this)); 11604 else { 11605 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11606 ? ItaniumVTableContext::Relative 11607 : ItaniumVTableContext::Pointer; 11608 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11609 } 11610 } 11611 return VTContext.get(); 11612 } 11613 11614 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11615 if (!T) 11616 T = Target; 11617 switch (T->getCXXABI().getKind()) { 11618 case TargetCXXABI::AppleARM64: 11619 case TargetCXXABI::Fuchsia: 11620 case TargetCXXABI::GenericAArch64: 11621 case TargetCXXABI::GenericItanium: 11622 case TargetCXXABI::GenericARM: 11623 case TargetCXXABI::GenericMIPS: 11624 case TargetCXXABI::iOS: 11625 case TargetCXXABI::WebAssembly: 11626 case TargetCXXABI::WatchOS: 11627 case TargetCXXABI::XL: 11628 return ItaniumMangleContext::create(*this, getDiagnostics()); 11629 case TargetCXXABI::Microsoft: 11630 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11631 } 11632 llvm_unreachable("Unsupported ABI"); 11633 } 11634 11635 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11636 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11637 "Device mangle context does not support Microsoft mangling."); 11638 switch (T.getCXXABI().getKind()) { 11639 case TargetCXXABI::AppleARM64: 11640 case TargetCXXABI::Fuchsia: 11641 case TargetCXXABI::GenericAArch64: 11642 case TargetCXXABI::GenericItanium: 11643 case TargetCXXABI::GenericARM: 11644 case TargetCXXABI::GenericMIPS: 11645 case TargetCXXABI::iOS: 11646 case TargetCXXABI::WebAssembly: 11647 case TargetCXXABI::WatchOS: 11648 case TargetCXXABI::XL: 11649 return ItaniumMangleContext::create( 11650 *this, getDiagnostics(), 11651 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11652 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11653 return RD->getDeviceLambdaManglingNumber(); 11654 return llvm::None; 11655 }); 11656 case TargetCXXABI::Microsoft: 11657 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11658 } 11659 llvm_unreachable("Unsupported ABI"); 11660 } 11661 11662 CXXABI::~CXXABI() = default; 11663 11664 size_t ASTContext::getSideTableAllocatedMemory() const { 11665 return ASTRecordLayouts.getMemorySize() + 11666 llvm::capacity_in_bytes(ObjCLayouts) + 11667 llvm::capacity_in_bytes(KeyFunctions) + 11668 llvm::capacity_in_bytes(ObjCImpls) + 11669 llvm::capacity_in_bytes(BlockVarCopyInits) + 11670 llvm::capacity_in_bytes(DeclAttrs) + 11671 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11672 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11673 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11674 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11675 llvm::capacity_in_bytes(OverriddenMethods) + 11676 llvm::capacity_in_bytes(Types) + 11677 llvm::capacity_in_bytes(VariableArrayTypes); 11678 } 11679 11680 /// getIntTypeForBitwidth - 11681 /// sets integer QualTy according to specified details: 11682 /// bitwidth, signed/unsigned. 11683 /// Returns empty type if there is no appropriate target types. 11684 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11685 unsigned Signed) const { 11686 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11687 CanQualType QualTy = getFromTargetType(Ty); 11688 if (!QualTy && DestWidth == 128) 11689 return Signed ? Int128Ty : UnsignedInt128Ty; 11690 return QualTy; 11691 } 11692 11693 /// getRealTypeForBitwidth - 11694 /// sets floating point QualTy according to specified bitwidth. 11695 /// Returns empty type if there is no appropriate target types. 11696 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11697 FloatModeKind ExplicitType) const { 11698 FloatModeKind Ty = 11699 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType); 11700 switch (Ty) { 11701 case FloatModeKind::Float: 11702 return FloatTy; 11703 case FloatModeKind::Double: 11704 return DoubleTy; 11705 case FloatModeKind::LongDouble: 11706 return LongDoubleTy; 11707 case FloatModeKind::Float128: 11708 return Float128Ty; 11709 case FloatModeKind::Ibm128: 11710 return Ibm128Ty; 11711 case FloatModeKind::NoFloat: 11712 return {}; 11713 } 11714 11715 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11716 } 11717 11718 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11719 if (Number > 1) 11720 MangleNumbers[ND] = Number; 11721 } 11722 11723 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11724 auto I = MangleNumbers.find(ND); 11725 return I != MangleNumbers.end() ? I->second : 1; 11726 } 11727 11728 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11729 if (Number > 1) 11730 StaticLocalNumbers[VD] = Number; 11731 } 11732 11733 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11734 auto I = StaticLocalNumbers.find(VD); 11735 return I != StaticLocalNumbers.end() ? I->second : 1; 11736 } 11737 11738 MangleNumberingContext & 11739 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11740 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11741 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11742 if (!MCtx) 11743 MCtx = createMangleNumberingContext(); 11744 return *MCtx; 11745 } 11746 11747 MangleNumberingContext & 11748 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11749 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11750 std::unique_ptr<MangleNumberingContext> &MCtx = 11751 ExtraMangleNumberingContexts[D]; 11752 if (!MCtx) 11753 MCtx = createMangleNumberingContext(); 11754 return *MCtx; 11755 } 11756 11757 std::unique_ptr<MangleNumberingContext> 11758 ASTContext::createMangleNumberingContext() const { 11759 return ABI->createMangleNumberingContext(); 11760 } 11761 11762 const CXXConstructorDecl * 11763 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11764 return ABI->getCopyConstructorForExceptionObject( 11765 cast<CXXRecordDecl>(RD->getFirstDecl())); 11766 } 11767 11768 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11769 CXXConstructorDecl *CD) { 11770 return ABI->addCopyConstructorForExceptionObject( 11771 cast<CXXRecordDecl>(RD->getFirstDecl()), 11772 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11773 } 11774 11775 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11776 TypedefNameDecl *DD) { 11777 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11778 } 11779 11780 TypedefNameDecl * 11781 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11782 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11783 } 11784 11785 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11786 DeclaratorDecl *DD) { 11787 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11788 } 11789 11790 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11791 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11792 } 11793 11794 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11795 ParamIndices[D] = index; 11796 } 11797 11798 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11799 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11800 assert(I != ParamIndices.end() && 11801 "ParmIndices lacks entry set by ParmVarDecl"); 11802 return I->second; 11803 } 11804 11805 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11806 unsigned Length) const { 11807 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11808 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11809 EltTy = EltTy.withConst(); 11810 11811 EltTy = adjustStringLiteralBaseType(EltTy); 11812 11813 // Get an array type for the string, according to C99 6.4.5. This includes 11814 // the null terminator character. 11815 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11816 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11817 } 11818 11819 StringLiteral * 11820 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11821 StringLiteral *&Result = StringLiteralCache[Key]; 11822 if (!Result) 11823 Result = StringLiteral::Create( 11824 *this, Key, StringLiteral::Ascii, 11825 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11826 SourceLocation()); 11827 return Result; 11828 } 11829 11830 MSGuidDecl * 11831 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11832 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11833 11834 llvm::FoldingSetNodeID ID; 11835 MSGuidDecl::Profile(ID, Parts); 11836 11837 void *InsertPos; 11838 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11839 return Existing; 11840 11841 QualType GUIDType = getMSGuidType().withConst(); 11842 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11843 MSGuidDecls.InsertNode(New, InsertPos); 11844 return New; 11845 } 11846 11847 TemplateParamObjectDecl * 11848 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11849 assert(T->isRecordType() && "template param object of unexpected type"); 11850 11851 // C++ [temp.param]p8: 11852 // [...] a static storage duration object of type 'const T' [...] 11853 T.addConst(); 11854 11855 llvm::FoldingSetNodeID ID; 11856 TemplateParamObjectDecl::Profile(ID, T, V); 11857 11858 void *InsertPos; 11859 if (TemplateParamObjectDecl *Existing = 11860 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11861 return Existing; 11862 11863 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11864 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11865 return New; 11866 } 11867 11868 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11869 const llvm::Triple &T = getTargetInfo().getTriple(); 11870 if (!T.isOSDarwin()) 11871 return false; 11872 11873 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11874 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11875 return false; 11876 11877 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11878 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11879 uint64_t Size = sizeChars.getQuantity(); 11880 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11881 unsigned Align = alignChars.getQuantity(); 11882 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11883 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11884 } 11885 11886 bool 11887 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11888 const ObjCMethodDecl *MethodImpl) { 11889 // No point trying to match an unavailable/deprecated mothod. 11890 if (MethodDecl->hasAttr<UnavailableAttr>() 11891 || MethodDecl->hasAttr<DeprecatedAttr>()) 11892 return false; 11893 if (MethodDecl->getObjCDeclQualifier() != 11894 MethodImpl->getObjCDeclQualifier()) 11895 return false; 11896 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11897 return false; 11898 11899 if (MethodDecl->param_size() != MethodImpl->param_size()) 11900 return false; 11901 11902 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11903 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11904 EF = MethodDecl->param_end(); 11905 IM != EM && IF != EF; ++IM, ++IF) { 11906 const ParmVarDecl *DeclVar = (*IF); 11907 const ParmVarDecl *ImplVar = (*IM); 11908 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11909 return false; 11910 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11911 return false; 11912 } 11913 11914 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11915 } 11916 11917 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11918 LangAS AS; 11919 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11920 AS = LangAS::Default; 11921 else 11922 AS = QT->getPointeeType().getAddressSpace(); 11923 11924 return getTargetInfo().getNullPointerValue(AS); 11925 } 11926 11927 unsigned ASTContext::getTargetAddressSpace(QualType T) const { 11928 // Return the address space for the type. If the type is a 11929 // function type without an address space qualifier, the 11930 // program address space is used. Otherwise, the target picks 11931 // the best address space based on the type information 11932 return T->isFunctionType() && !T.hasAddressSpace() 11933 ? getTargetInfo().getProgramAddressSpace() 11934 : getTargetAddressSpace(T.getQualifiers()); 11935 } 11936 11937 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const { 11938 return getTargetAddressSpace(Q.getAddressSpace()); 11939 } 11940 11941 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11942 if (isTargetAddressSpace(AS)) 11943 return toTargetAddressSpace(AS); 11944 else 11945 return (*AddrSpaceMap)[(unsigned)AS]; 11946 } 11947 11948 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11949 assert(Ty->isFixedPointType()); 11950 11951 if (Ty->isSaturatedFixedPointType()) return Ty; 11952 11953 switch (Ty->castAs<BuiltinType>()->getKind()) { 11954 default: 11955 llvm_unreachable("Not a fixed point type!"); 11956 case BuiltinType::ShortAccum: 11957 return SatShortAccumTy; 11958 case BuiltinType::Accum: 11959 return SatAccumTy; 11960 case BuiltinType::LongAccum: 11961 return SatLongAccumTy; 11962 case BuiltinType::UShortAccum: 11963 return SatUnsignedShortAccumTy; 11964 case BuiltinType::UAccum: 11965 return SatUnsignedAccumTy; 11966 case BuiltinType::ULongAccum: 11967 return SatUnsignedLongAccumTy; 11968 case BuiltinType::ShortFract: 11969 return SatShortFractTy; 11970 case BuiltinType::Fract: 11971 return SatFractTy; 11972 case BuiltinType::LongFract: 11973 return SatLongFractTy; 11974 case BuiltinType::UShortFract: 11975 return SatUnsignedShortFractTy; 11976 case BuiltinType::UFract: 11977 return SatUnsignedFractTy; 11978 case BuiltinType::ULongFract: 11979 return SatUnsignedLongFractTy; 11980 } 11981 } 11982 11983 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11984 if (LangOpts.OpenCL) 11985 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11986 11987 if (LangOpts.CUDA) 11988 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11989 11990 return getLangASFromTargetAS(AS); 11991 } 11992 11993 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11994 // doesn't include ASTContext.h 11995 template 11996 clang::LazyGenerationalUpdatePtr< 11997 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11998 clang::LazyGenerationalUpdatePtr< 11999 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 12000 const clang::ASTContext &Ctx, Decl *Value); 12001 12002 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 12003 assert(Ty->isFixedPointType()); 12004 12005 const TargetInfo &Target = getTargetInfo(); 12006 switch (Ty->castAs<BuiltinType>()->getKind()) { 12007 default: 12008 llvm_unreachable("Not a fixed point type!"); 12009 case BuiltinType::ShortAccum: 12010 case BuiltinType::SatShortAccum: 12011 return Target.getShortAccumScale(); 12012 case BuiltinType::Accum: 12013 case BuiltinType::SatAccum: 12014 return Target.getAccumScale(); 12015 case BuiltinType::LongAccum: 12016 case BuiltinType::SatLongAccum: 12017 return Target.getLongAccumScale(); 12018 case BuiltinType::UShortAccum: 12019 case BuiltinType::SatUShortAccum: 12020 return Target.getUnsignedShortAccumScale(); 12021 case BuiltinType::UAccum: 12022 case BuiltinType::SatUAccum: 12023 return Target.getUnsignedAccumScale(); 12024 case BuiltinType::ULongAccum: 12025 case BuiltinType::SatULongAccum: 12026 return Target.getUnsignedLongAccumScale(); 12027 case BuiltinType::ShortFract: 12028 case BuiltinType::SatShortFract: 12029 return Target.getShortFractScale(); 12030 case BuiltinType::Fract: 12031 case BuiltinType::SatFract: 12032 return Target.getFractScale(); 12033 case BuiltinType::LongFract: 12034 case BuiltinType::SatLongFract: 12035 return Target.getLongFractScale(); 12036 case BuiltinType::UShortFract: 12037 case BuiltinType::SatUShortFract: 12038 return Target.getUnsignedShortFractScale(); 12039 case BuiltinType::UFract: 12040 case BuiltinType::SatUFract: 12041 return Target.getUnsignedFractScale(); 12042 case BuiltinType::ULongFract: 12043 case BuiltinType::SatULongFract: 12044 return Target.getUnsignedLongFractScale(); 12045 } 12046 } 12047 12048 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 12049 assert(Ty->isFixedPointType()); 12050 12051 const TargetInfo &Target = getTargetInfo(); 12052 switch (Ty->castAs<BuiltinType>()->getKind()) { 12053 default: 12054 llvm_unreachable("Not a fixed point type!"); 12055 case BuiltinType::ShortAccum: 12056 case BuiltinType::SatShortAccum: 12057 return Target.getShortAccumIBits(); 12058 case BuiltinType::Accum: 12059 case BuiltinType::SatAccum: 12060 return Target.getAccumIBits(); 12061 case BuiltinType::LongAccum: 12062 case BuiltinType::SatLongAccum: 12063 return Target.getLongAccumIBits(); 12064 case BuiltinType::UShortAccum: 12065 case BuiltinType::SatUShortAccum: 12066 return Target.getUnsignedShortAccumIBits(); 12067 case BuiltinType::UAccum: 12068 case BuiltinType::SatUAccum: 12069 return Target.getUnsignedAccumIBits(); 12070 case BuiltinType::ULongAccum: 12071 case BuiltinType::SatULongAccum: 12072 return Target.getUnsignedLongAccumIBits(); 12073 case BuiltinType::ShortFract: 12074 case BuiltinType::SatShortFract: 12075 case BuiltinType::Fract: 12076 case BuiltinType::SatFract: 12077 case BuiltinType::LongFract: 12078 case BuiltinType::SatLongFract: 12079 case BuiltinType::UShortFract: 12080 case BuiltinType::SatUShortFract: 12081 case BuiltinType::UFract: 12082 case BuiltinType::SatUFract: 12083 case BuiltinType::ULongFract: 12084 case BuiltinType::SatULongFract: 12085 return 0; 12086 } 12087 } 12088 12089 llvm::FixedPointSemantics 12090 ASTContext::getFixedPointSemantics(QualType Ty) const { 12091 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 12092 "Can only get the fixed point semantics for a " 12093 "fixed point or integer type."); 12094 if (Ty->isIntegerType()) 12095 return llvm::FixedPointSemantics::GetIntegerSemantics( 12096 getIntWidth(Ty), Ty->isSignedIntegerType()); 12097 12098 bool isSigned = Ty->isSignedFixedPointType(); 12099 return llvm::FixedPointSemantics( 12100 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 12101 Ty->isSaturatedFixedPointType(), 12102 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 12103 } 12104 12105 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 12106 assert(Ty->isFixedPointType()); 12107 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 12108 } 12109 12110 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 12111 assert(Ty->isFixedPointType()); 12112 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 12113 } 12114 12115 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 12116 assert(Ty->isUnsignedFixedPointType() && 12117 "Expected unsigned fixed point type"); 12118 12119 switch (Ty->castAs<BuiltinType>()->getKind()) { 12120 case BuiltinType::UShortAccum: 12121 return ShortAccumTy; 12122 case BuiltinType::UAccum: 12123 return AccumTy; 12124 case BuiltinType::ULongAccum: 12125 return LongAccumTy; 12126 case BuiltinType::SatUShortAccum: 12127 return SatShortAccumTy; 12128 case BuiltinType::SatUAccum: 12129 return SatAccumTy; 12130 case BuiltinType::SatULongAccum: 12131 return SatLongAccumTy; 12132 case BuiltinType::UShortFract: 12133 return ShortFractTy; 12134 case BuiltinType::UFract: 12135 return FractTy; 12136 case BuiltinType::ULongFract: 12137 return LongFractTy; 12138 case BuiltinType::SatUShortFract: 12139 return SatShortFractTy; 12140 case BuiltinType::SatUFract: 12141 return SatFractTy; 12142 case BuiltinType::SatULongFract: 12143 return SatLongFractTy; 12144 default: 12145 llvm_unreachable("Unexpected unsigned fixed point type"); 12146 } 12147 } 12148 12149 ParsedTargetAttr 12150 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 12151 assert(TD != nullptr); 12152 ParsedTargetAttr ParsedAttr = TD->parse(); 12153 12154 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) { 12155 return !Target->isValidFeatureName(StringRef{Feat}.substr(1)); 12156 }); 12157 return ParsedAttr; 12158 } 12159 12160 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12161 const FunctionDecl *FD) const { 12162 if (FD) 12163 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 12164 else 12165 Target->initFeatureMap(FeatureMap, getDiagnostics(), 12166 Target->getTargetOpts().CPU, 12167 Target->getTargetOpts().Features); 12168 } 12169 12170 // Fills in the supplied string map with the set of target features for the 12171 // passed in function. 12172 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 12173 GlobalDecl GD) const { 12174 StringRef TargetCPU = Target->getTargetOpts().CPU; 12175 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 12176 if (const auto *TD = FD->getAttr<TargetAttr>()) { 12177 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 12178 12179 // Make a copy of the features as passed on the command line into the 12180 // beginning of the additional features from the function to override. 12181 ParsedAttr.Features.insert( 12182 ParsedAttr.Features.begin(), 12183 Target->getTargetOpts().FeaturesAsWritten.begin(), 12184 Target->getTargetOpts().FeaturesAsWritten.end()); 12185 12186 if (ParsedAttr.Architecture != "" && 12187 Target->isValidCPUName(ParsedAttr.Architecture)) 12188 TargetCPU = ParsedAttr.Architecture; 12189 12190 // Now populate the feature map, first with the TargetCPU which is either 12191 // the default or a new one from the target attribute string. Then we'll use 12192 // the passed in features (FeaturesAsWritten) along with the new ones from 12193 // the attribute. 12194 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 12195 ParsedAttr.Features); 12196 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 12197 llvm::SmallVector<StringRef, 32> FeaturesTmp; 12198 Target->getCPUSpecificCPUDispatchFeatures( 12199 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 12200 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 12201 Features.insert(Features.begin(), 12202 Target->getTargetOpts().FeaturesAsWritten.begin(), 12203 Target->getTargetOpts().FeaturesAsWritten.end()); 12204 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12205 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) { 12206 std::vector<std::string> Features; 12207 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex()); 12208 if (VersionStr.startswith("arch=")) 12209 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1); 12210 else if (VersionStr != "default") 12211 Features.push_back((StringRef{"+"} + VersionStr).str()); 12212 12213 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 12214 } else { 12215 FeatureMap = Target->getTargetOpts().FeatureMap; 12216 } 12217 } 12218 12219 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 12220 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 12221 return *OMPTraitInfoVector.back(); 12222 } 12223 12224 const StreamingDiagnostic &clang:: 12225 operator<<(const StreamingDiagnostic &DB, 12226 const ASTContext::SectionInfo &Section) { 12227 if (Section.Decl) 12228 return DB << Section.Decl; 12229 return DB << "a prior #pragma section"; 12230 } 12231 12232 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 12233 bool IsStaticVar = 12234 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 12235 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 12236 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 12237 (D->hasAttr<CUDAConstantAttr>() && 12238 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 12239 // CUDA/HIP: static managed variables need to be externalized since it is 12240 // a declaration in IR, therefore cannot have internal linkage. 12241 return IsStaticVar && 12242 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 12243 } 12244 12245 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 12246 return mayExternalizeStaticVar(D) && 12247 (D->hasAttr<HIPManagedAttr>() || 12248 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 12249 } 12250 12251 StringRef ASTContext::getCUIDHash() const { 12252 if (!CUIDHash.empty()) 12253 return CUIDHash; 12254 if (LangOpts.CUID.empty()) 12255 return StringRef(); 12256 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 12257 return CUIDHash; 12258 } 12259