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