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