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