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