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