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