1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the ASTContext interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "CXXABI.h" 15 #include "Interp/Context.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTConcept.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTTypeTraits.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/AttrIterator.h" 22 #include "clang/AST/CharUnits.h" 23 #include "clang/AST/Comment.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclBase.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclContextInternals.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/DeclarationName.h" 32 #include "clang/AST/DependenceFlags.h" 33 #include "clang/AST/Expr.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprConcepts.h" 36 #include "clang/AST/ExternalASTSource.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/MangleNumberingContext.h" 39 #include "clang/AST/NestedNameSpecifier.h" 40 #include "clang/AST/ParentMapContext.h" 41 #include "clang/AST/RawCommentList.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/Stmt.h" 44 #include "clang/AST/TemplateBase.h" 45 #include "clang/AST/TemplateName.h" 46 #include "clang/AST/Type.h" 47 #include "clang/AST/TypeLoc.h" 48 #include "clang/AST/UnresolvedSet.h" 49 #include "clang/AST/VTableBuilder.h" 50 #include "clang/Basic/AddressSpaces.h" 51 #include "clang/Basic/Builtins.h" 52 #include "clang/Basic/CommentOptions.h" 53 #include "clang/Basic/ExceptionSpecificationType.h" 54 #include "clang/Basic/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Linkage.h" 58 #include "clang/Basic/Module.h" 59 #include "clang/Basic/NoSanitizeList.h" 60 #include "clang/Basic/ObjCRuntime.h" 61 #include "clang/Basic/SourceLocation.h" 62 #include "clang/Basic/SourceManager.h" 63 #include "clang/Basic/Specifiers.h" 64 #include "clang/Basic/TargetCXXABI.h" 65 #include "clang/Basic/TargetInfo.h" 66 #include "clang/Basic/XRayLists.h" 67 #include "llvm/ADT/APFixedPoint.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/ArrayRef.h" 71 #include "llvm/ADT/DenseMap.h" 72 #include "llvm/ADT/DenseSet.h" 73 #include "llvm/ADT/FoldingSet.h" 74 #include "llvm/ADT/None.h" 75 #include "llvm/ADT/Optional.h" 76 #include "llvm/ADT/PointerUnion.h" 77 #include "llvm/ADT/STLExtras.h" 78 #include "llvm/ADT/SmallPtrSet.h" 79 #include "llvm/ADT/SmallVector.h" 80 #include "llvm/ADT/StringExtras.h" 81 #include "llvm/ADT/StringRef.h" 82 #include "llvm/ADT/Triple.h" 83 #include "llvm/Support/Capacity.h" 84 #include "llvm/Support/Casting.h" 85 #include "llvm/Support/Compiler.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/MD5.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <cstdlib> 95 #include <map> 96 #include <memory> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 103 enum FloatingRank { 104 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 105 }; 106 107 /// \returns location that is relevant when searching for Doc comments related 108 /// to \p D. 109 static SourceLocation getDeclLocForCommentSearch(const Decl *D, 110 SourceManager &SourceMgr) { 111 assert(D); 112 113 // User can not attach documentation to implicit declarations. 114 if (D->isImplicit()) 115 return {}; 116 117 // User can not attach documentation to implicit instantiations. 118 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 119 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 120 return {}; 121 } 122 123 if (const auto *VD = dyn_cast<VarDecl>(D)) { 124 if (VD->isStaticDataMember() && 125 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 126 return {}; 127 } 128 129 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 130 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 131 return {}; 132 } 133 134 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 135 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 136 if (TSK == TSK_ImplicitInstantiation || 137 TSK == TSK_Undeclared) 138 return {}; 139 } 140 141 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 142 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 143 return {}; 144 } 145 if (const auto *TD = dyn_cast<TagDecl>(D)) { 146 // When tag declaration (but not definition!) is part of the 147 // decl-specifier-seq of some other declaration, it doesn't get comment 148 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 149 return {}; 150 } 151 // TODO: handle comments for function parameters properly. 152 if (isa<ParmVarDecl>(D)) 153 return {}; 154 155 // TODO: we could look up template parameter documentation in the template 156 // documentation. 157 if (isa<TemplateTypeParmDecl>(D) || 158 isa<NonTypeTemplateParmDecl>(D) || 159 isa<TemplateTemplateParmDecl>(D)) 160 return {}; 161 162 // Find declaration location. 163 // For Objective-C declarations we generally don't expect to have multiple 164 // declarators, thus use declaration starting location as the "declaration 165 // location". 166 // For all other declarations multiple declarators are used quite frequently, 167 // so we use the location of the identifier as the "declaration location". 168 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 169 isa<ObjCPropertyDecl>(D) || 170 isa<RedeclarableTemplateDecl>(D) || 171 isa<ClassTemplateSpecializationDecl>(D) || 172 // Allow association with Y across {} in `typedef struct X {} Y`. 173 isa<TypedefDecl>(D)) 174 return D->getBeginLoc(); 175 176 const SourceLocation DeclLoc = D->getLocation(); 177 if (DeclLoc.isMacroID()) { 178 if (isa<TypedefDecl>(D)) { 179 // If location of the typedef name is in a macro, it is because being 180 // declared via a macro. Try using declaration's starting location as 181 // the "declaration location". 182 return D->getBeginLoc(); 183 } 184 185 if (const auto *TD = dyn_cast<TagDecl>(D)) { 186 // If location of the tag decl is inside a macro, but the spelling of 187 // the tag name comes from a macro argument, it looks like a special 188 // macro like NS_ENUM is being used to define the tag decl. In that 189 // case, adjust the source location to the expansion loc so that we can 190 // attach the comment to the tag decl. 191 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) 192 return SourceMgr.getExpansionLoc(DeclLoc); 193 } 194 } 195 196 return DeclLoc; 197 } 198 199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( 200 const Decl *D, const SourceLocation RepresentativeLocForDecl, 201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const { 202 // If the declaration doesn't map directly to a location in a file, we 203 // can't find the comment. 204 if (RepresentativeLocForDecl.isInvalid() || 205 !RepresentativeLocForDecl.isFileID()) 206 return nullptr; 207 208 // If there are no comments anywhere, we won't find anything. 209 if (CommentsInTheFile.empty()) 210 return nullptr; 211 212 // Decompose the location for the declaration and find the beginning of the 213 // file buffer. 214 const std::pair<FileID, unsigned> DeclLocDecomp = 215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); 216 217 // Slow path. 218 auto OffsetCommentBehindDecl = 219 CommentsInTheFile.lower_bound(DeclLocDecomp.second); 220 221 // First check whether we have a trailing comment. 222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { 223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; 224 if ((CommentBehindDecl->isDocumentation() || 225 LangOpts.CommentOpts.ParseAllComments) && 226 CommentBehindDecl->isTrailingComment() && 227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 229 230 // Check that Doxygen trailing comment comes after the declaration, starts 231 // on the same line and in the same file as the declaration. 232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == 233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, 234 OffsetCommentBehindDecl->first)) { 235 return CommentBehindDecl; 236 } 237 } 238 } 239 240 // The comment just after the declaration was not a trailing comment. 241 // Let's look at the previous comment. 242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) 243 return nullptr; 244 245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; 246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; 247 248 // Check that we actually have a non-member Doxygen comment. 249 if (!(CommentBeforeDecl->isDocumentation() || 250 LangOpts.CommentOpts.ParseAllComments) || 251 CommentBeforeDecl->isTrailingComment()) 252 return nullptr; 253 254 // Decompose the end of the comment. 255 const unsigned CommentEndOffset = 256 Comments.getCommentEndOffset(CommentBeforeDecl); 257 258 // Get the corresponding buffer. 259 bool Invalid = false; 260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 261 &Invalid).data(); 262 if (Invalid) 263 return nullptr; 264 265 // Extract text between the comment and declaration. 266 StringRef Text(Buffer + CommentEndOffset, 267 DeclLocDecomp.second - CommentEndOffset); 268 269 // There should be no other declarations or preprocessor directives between 270 // comment and declaration. 271 if (Text.find_first_of(";{}#@") != StringRef::npos) 272 return nullptr; 273 274 return CommentBeforeDecl; 275 } 276 277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 279 280 // If the declaration doesn't map directly to a location in a file, we 281 // can't find the comment. 282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 283 return nullptr; 284 285 if (ExternalSource && !CommentsLoaded) { 286 ExternalSource->ReadComments(); 287 CommentsLoaded = true; 288 } 289 290 if (Comments.empty()) 291 return nullptr; 292 293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; 294 const auto CommentsInThisFile = Comments.getCommentsInFile(File); 295 if (!CommentsInThisFile || CommentsInThisFile->empty()) 296 return nullptr; 297 298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); 299 } 300 301 void ASTContext::addComment(const RawComment &RC) { 302 assert(LangOpts.RetainCommentsFromSystemHeaders || 303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); 304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); 305 } 306 307 /// If we have a 'templated' declaration for a template, adjust 'D' to 308 /// refer to the actual template. 309 /// If we have an implicit instantiation, adjust 'D' to refer to template. 310 static const Decl &adjustDeclToTemplate(const Decl &D) { 311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { 312 // Is this function declaration part of a function template? 313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 314 return *FTD; 315 316 // Nothing to do if function is not an implicit instantiation. 317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 318 return D; 319 320 // Function is an implicit instantiation of a function template? 321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 322 return *FTD; 323 324 // Function is instantiated from a member definition of a class template? 325 if (const FunctionDecl *MemberDecl = 326 FD->getInstantiatedFromMemberFunction()) 327 return *MemberDecl; 328 329 return D; 330 } 331 if (const auto *VD = dyn_cast<VarDecl>(&D)) { 332 // Static data member is instantiated from a member definition of a class 333 // template? 334 if (VD->isStaticDataMember()) 335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 336 return *MemberDecl; 337 338 return D; 339 } 340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { 341 // Is this class declaration part of a class template? 342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 343 return *CTD; 344 345 // Class is an implicit instantiation of a class template or partial 346 // specialization? 347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 349 return D; 350 llvm::PointerUnion<ClassTemplateDecl *, 351 ClassTemplatePartialSpecializationDecl *> 352 PU = CTSD->getSpecializedTemplateOrPartial(); 353 return PU.is<ClassTemplateDecl *>() 354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) 355 : *static_cast<const Decl *>( 356 PU.get<ClassTemplatePartialSpecializationDecl *>()); 357 } 358 359 // Class is instantiated from a member definition of a class template? 360 if (const MemberSpecializationInfo *Info = 361 CRD->getMemberSpecializationInfo()) 362 return *Info->getInstantiatedFrom(); 363 364 return D; 365 } 366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) { 367 // Enum is instantiated from a member definition of a class template? 368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 369 return *MemberDecl; 370 371 return D; 372 } 373 // FIXME: Adjust alias templates? 374 return D; 375 } 376 377 const RawComment *ASTContext::getRawCommentForAnyRedecl( 378 const Decl *D, 379 const Decl **OriginalDecl) const { 380 if (!D) { 381 if (OriginalDecl) 382 OriginalDecl = nullptr; 383 return nullptr; 384 } 385 386 D = &adjustDeclToTemplate(*D); 387 388 // Any comment directly attached to D? 389 { 390 auto DeclComment = DeclRawComments.find(D); 391 if (DeclComment != DeclRawComments.end()) { 392 if (OriginalDecl) 393 *OriginalDecl = D; 394 return DeclComment->second; 395 } 396 } 397 398 // Any comment attached to any redeclaration of D? 399 const Decl *CanonicalD = D->getCanonicalDecl(); 400 if (!CanonicalD) 401 return nullptr; 402 403 { 404 auto RedeclComment = RedeclChainComments.find(CanonicalD); 405 if (RedeclComment != RedeclChainComments.end()) { 406 if (OriginalDecl) 407 *OriginalDecl = RedeclComment->second; 408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); 409 assert(CommentAtRedecl != DeclRawComments.end() && 410 "This decl is supposed to have comment attached."); 411 return CommentAtRedecl->second; 412 } 413 } 414 415 // Any redeclarations of D that we haven't checked for comments yet? 416 // We can't use DenseMap::iterator directly since it'd get invalid. 417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { 418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD); 419 if (LookupRes != CommentlessRedeclChains.end()) 420 return LookupRes->second; 421 return nullptr; 422 }(); 423 424 for (const auto Redecl : D->redecls()) { 425 assert(Redecl); 426 // Skip all redeclarations that have been checked previously. 427 if (LastCheckedRedecl) { 428 if (LastCheckedRedecl == Redecl) { 429 LastCheckedRedecl = nullptr; 430 } 431 continue; 432 } 433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); 434 if (RedeclComment) { 435 cacheRawCommentForDecl(*Redecl, *RedeclComment); 436 if (OriginalDecl) 437 *OriginalDecl = Redecl; 438 return RedeclComment; 439 } 440 CommentlessRedeclChains[CanonicalD] = Redecl; 441 } 442 443 if (OriginalDecl) 444 *OriginalDecl = nullptr; 445 return nullptr; 446 } 447 448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, 449 const RawComment &Comment) const { 450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 451 DeclRawComments.try_emplace(&OriginalD, &Comment); 452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); 453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); 454 CommentlessRedeclChains.erase(CanonicalDecl); 455 } 456 457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 458 SmallVectorImpl<const NamedDecl *> &Redeclared) { 459 const DeclContext *DC = ObjCMethod->getDeclContext(); 460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 461 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 462 if (!ID) 463 return; 464 // Add redeclared method here. 465 for (const auto *Ext : ID->known_extensions()) { 466 if (ObjCMethodDecl *RedeclaredMethod = 467 Ext->getMethod(ObjCMethod->getSelector(), 468 ObjCMethod->isInstanceMethod())) 469 Redeclared.push_back(RedeclaredMethod); 470 } 471 } 472 } 473 474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 475 const Preprocessor *PP) { 476 if (Comments.empty() || Decls.empty()) 477 return; 478 479 FileID File; 480 for (Decl *D : Decls) { 481 SourceLocation Loc = D->getLocation(); 482 if (Loc.isValid()) { 483 // See if there are any new comments that are not attached to a decl. 484 // The location doesn't have to be precise - we care only about the file. 485 File = SourceMgr.getDecomposedLoc(Loc).first; 486 break; 487 } 488 } 489 490 if (File.isInvalid()) 491 return; 492 493 auto CommentsInThisFile = Comments.getCommentsInFile(File); 494 if (!CommentsInThisFile || CommentsInThisFile->empty() || 495 CommentsInThisFile->rbegin()->second->isAttached()) 496 return; 497 498 // There is at least one comment not attached to a decl. 499 // Maybe it should be attached to one of Decls? 500 // 501 // Note that this way we pick up not only comments that precede the 502 // declaration, but also comments that *follow* the declaration -- thanks to 503 // the lookahead in the lexer: we've consumed the semicolon and looked 504 // ahead through comments. 505 506 for (const Decl *D : Decls) { 507 assert(D); 508 if (D->isInvalidDecl()) 509 continue; 510 511 D = &adjustDeclToTemplate(*D); 512 513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); 514 515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 516 continue; 517 518 if (DeclRawComments.count(D) > 0) 519 continue; 520 521 if (RawComment *const DocComment = 522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { 523 cacheRawCommentForDecl(*D, *DocComment); 524 comments::FullComment *FC = DocComment->parse(*this, PP, D); 525 ParsedComments[D->getCanonicalDecl()] = FC; 526 } 527 } 528 } 529 530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 531 const Decl *D) const { 532 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 533 ThisDeclInfo->CommentDecl = D; 534 ThisDeclInfo->IsFilled = false; 535 ThisDeclInfo->fill(); 536 ThisDeclInfo->CommentDecl = FC->getDecl(); 537 if (!ThisDeclInfo->TemplateParameters) 538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 539 comments::FullComment *CFC = 540 new (*this) comments::FullComment(FC->getBlocks(), 541 ThisDeclInfo); 542 return CFC; 543 } 544 545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 546 const RawComment *RC = getRawCommentForDeclNoCache(D); 547 return RC ? RC->parse(*this, nullptr, D) : nullptr; 548 } 549 550 comments::FullComment *ASTContext::getCommentForDecl( 551 const Decl *D, 552 const Preprocessor *PP) const { 553 if (!D || D->isInvalidDecl()) 554 return nullptr; 555 D = &adjustDeclToTemplate(*D); 556 557 const Decl *Canonical = D->getCanonicalDecl(); 558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 559 ParsedComments.find(Canonical); 560 561 if (Pos != ParsedComments.end()) { 562 if (Canonical != D) { 563 comments::FullComment *FC = Pos->second; 564 comments::FullComment *CFC = cloneFullComment(FC, D); 565 return CFC; 566 } 567 return Pos->second; 568 } 569 570 const Decl *OriginalDecl = nullptr; 571 572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 573 if (!RC) { 574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 575 SmallVector<const NamedDecl*, 8> Overridden; 576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 577 if (OMD && OMD->isPropertyAccessor()) 578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 580 return cloneFullComment(FC, D); 581 if (OMD) 582 addRedeclaredMethods(OMD, Overridden); 583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 584 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 586 return cloneFullComment(FC, D); 587 } 588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 589 // Attach any tag type's documentation to its typedef if latter 590 // does not have one of its own. 591 QualType QT = TD->getUnderlyingType(); 592 if (const auto *TT = QT->getAs<TagType>()) 593 if (const Decl *TD = TT->getDecl()) 594 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 595 return cloneFullComment(FC, D); 596 } 597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 598 while (IC->getSuperClass()) { 599 IC = IC->getSuperClass(); 600 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 601 return cloneFullComment(FC, D); 602 } 603 } 604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 606 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 607 return cloneFullComment(FC, D); 608 } 609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 610 if (!(RD = RD->getDefinition())) 611 return nullptr; 612 // Check non-virtual bases. 613 for (const auto &I : RD->bases()) { 614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 615 continue; 616 QualType Ty = I.getType(); 617 if (Ty.isNull()) 618 continue; 619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 620 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 621 continue; 622 623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 624 return cloneFullComment(FC, D); 625 } 626 } 627 // Check virtual bases. 628 for (const auto &I : RD->vbases()) { 629 if (I.getAccessSpecifier() != AS_public) 630 continue; 631 QualType Ty = I.getType(); 632 if (Ty.isNull()) 633 continue; 634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 635 if (!(VirtualBase= VirtualBase->getDefinition())) 636 continue; 637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 638 return cloneFullComment(FC, D); 639 } 640 } 641 } 642 return nullptr; 643 } 644 645 // If the RawComment was attached to other redeclaration of this Decl, we 646 // should parse the comment in context of that other Decl. This is important 647 // because comments can contain references to parameter names which can be 648 // different across redeclarations. 649 if (D != OriginalDecl && OriginalDecl) 650 return getCommentForDecl(OriginalDecl, PP); 651 652 comments::FullComment *FC = RC->parse(*this, PP, D); 653 ParsedComments[Canonical] = FC; 654 return FC; 655 } 656 657 void 658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 659 const ASTContext &C, 660 TemplateTemplateParmDecl *Parm) { 661 ID.AddInteger(Parm->getDepth()); 662 ID.AddInteger(Parm->getPosition()); 663 ID.AddBoolean(Parm->isParameterPack()); 664 665 TemplateParameterList *Params = Parm->getTemplateParameters(); 666 ID.AddInteger(Params->size()); 667 for (TemplateParameterList::const_iterator P = Params->begin(), 668 PEnd = Params->end(); 669 P != PEnd; ++P) { 670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 671 ID.AddInteger(0); 672 ID.AddBoolean(TTP->isParameterPack()); 673 const TypeConstraint *TC = TTP->getTypeConstraint(); 674 ID.AddBoolean(TC != nullptr); 675 if (TC) 676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, 677 /*Canonical=*/true); 678 if (TTP->isExpandedParameterPack()) { 679 ID.AddBoolean(true); 680 ID.AddInteger(TTP->getNumExpansionParameters()); 681 } else 682 ID.AddBoolean(false); 683 continue; 684 } 685 686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 687 ID.AddInteger(1); 688 ID.AddBoolean(NTTP->isParameterPack()); 689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 690 if (NTTP->isExpandedParameterPack()) { 691 ID.AddBoolean(true); 692 ID.AddInteger(NTTP->getNumExpansionTypes()); 693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 694 QualType T = NTTP->getExpansionType(I); 695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 696 } 697 } else 698 ID.AddBoolean(false); 699 continue; 700 } 701 702 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 703 ID.AddInteger(2); 704 Profile(ID, C, TTP); 705 } 706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); 707 ID.AddBoolean(RequiresClause != nullptr); 708 if (RequiresClause) 709 RequiresClause->Profile(ID, C, /*Canonical=*/true); 710 } 711 712 static Expr * 713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, 714 QualType ConstrainedType) { 715 // This is a bit ugly - we need to form a new immediately-declared 716 // constraint that references the new parameter; this would ideally 717 // require semantic analysis (e.g. template<C T> struct S {}; - the 718 // converted arguments of C<T> could be an argument pack if C is 719 // declared as template<typename... T> concept C = ...). 720 // We don't have semantic analysis here so we dig deep into the 721 // ready-made constraint expr and change the thing manually. 722 ConceptSpecializationExpr *CSE; 723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) 724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); 725 else 726 CSE = cast<ConceptSpecializationExpr>(IDC); 727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); 728 SmallVector<TemplateArgument, 3> NewConverted; 729 NewConverted.reserve(OldConverted.size()); 730 if (OldConverted.front().getKind() == TemplateArgument::Pack) { 731 // The case: 732 // template<typename... T> concept C = true; 733 // template<C<int> T> struct S; -> constraint is C<{T, int}> 734 NewConverted.push_back(ConstrainedType); 735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) 736 NewConverted.push_back(Arg); 737 TemplateArgument NewPack(NewConverted); 738 739 NewConverted.clear(); 740 NewConverted.push_back(NewPack); 741 assert(OldConverted.size() == 1 && 742 "Template parameter pack should be the last parameter"); 743 } else { 744 assert(OldConverted.front().getKind() == TemplateArgument::Type && 745 "Unexpected first argument kind for immediately-declared " 746 "constraint"); 747 NewConverted.push_back(ConstrainedType); 748 for (auto &Arg : OldConverted.drop_front(1)) 749 NewConverted.push_back(Arg); 750 } 751 Expr *NewIDC = ConceptSpecializationExpr::Create( 752 C, CSE->getNamedConcept(), NewConverted, nullptr, 753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); 754 755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) 756 NewIDC = new (C) CXXFoldExpr( 757 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, 758 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, 759 SourceLocation(), /*NumExpansions=*/None); 760 return NewIDC; 761 } 762 763 TemplateTemplateParmDecl * 764 ASTContext::getCanonicalTemplateTemplateParmDecl( 765 TemplateTemplateParmDecl *TTP) const { 766 // Check if we already have a canonical template template parameter. 767 llvm::FoldingSetNodeID ID; 768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); 769 void *InsertPos = nullptr; 770 CanonicalTemplateTemplateParm *Canonical 771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 772 if (Canonical) 773 return Canonical->getParam(); 774 775 // Build a canonical template parameter list. 776 TemplateParameterList *Params = TTP->getTemplateParameters(); 777 SmallVector<NamedDecl *, 4> CanonParams; 778 CanonParams.reserve(Params->size()); 779 for (TemplateParameterList::const_iterator P = Params->begin(), 780 PEnd = Params->end(); 781 P != PEnd; ++P) { 782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, 784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 785 TTP->getDepth(), TTP->getIndex(), nullptr, false, 786 TTP->isParameterPack(), TTP->hasTypeConstraint(), 787 TTP->isExpandedParameterPack() ? 788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); 789 if (const auto *TC = TTP->getTypeConstraint()) { 790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); 791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( 792 *this, TC->getImmediatelyDeclaredConstraint(), 793 ParamAsArgument); 794 TemplateArgumentListInfo CanonArgsAsWritten; 795 if (auto *Args = TC->getTemplateArgsAsWritten()) 796 for (const auto &ArgLoc : Args->arguments()) 797 CanonArgsAsWritten.addArgument( 798 TemplateArgumentLoc(ArgLoc.getArgument(), 799 TemplateArgumentLocInfo())); 800 NewTTP->setTypeConstraint( 801 NestedNameSpecifierLoc(), 802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), 803 SourceLocation()), /*FoundDecl=*/nullptr, 804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we 805 // simply omit the ArgsAsWritten 806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); 807 } 808 CanonParams.push_back(NewTTP); 809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 810 QualType T = getCanonicalType(NTTP->getType()); 811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 812 NonTypeTemplateParmDecl *Param; 813 if (NTTP->isExpandedParameterPack()) { 814 SmallVector<QualType, 2> ExpandedTypes; 815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 818 ExpandedTInfos.push_back( 819 getTrivialTypeSourceInfo(ExpandedTypes.back())); 820 } 821 822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 823 SourceLocation(), 824 SourceLocation(), 825 NTTP->getDepth(), 826 NTTP->getPosition(), nullptr, 827 T, 828 TInfo, 829 ExpandedTypes, 830 ExpandedTInfos); 831 } else { 832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 833 SourceLocation(), 834 SourceLocation(), 835 NTTP->getDepth(), 836 NTTP->getPosition(), nullptr, 837 T, 838 NTTP->isParameterPack(), 839 TInfo); 840 } 841 if (AutoType *AT = T->getContainedAutoType()) { 842 if (AT->isConstrained()) { 843 Param->setPlaceholderTypeConstraint( 844 canonicalizeImmediatelyDeclaredConstraint( 845 *this, NTTP->getPlaceholderTypeConstraint(), T)); 846 } 847 } 848 CanonParams.push_back(Param); 849 850 } else 851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 852 cast<TemplateTemplateParmDecl>(*P))); 853 } 854 855 Expr *CanonRequiresClause = nullptr; 856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) 857 CanonRequiresClause = RequiresClause; 858 859 TemplateTemplateParmDecl *CanonTTP 860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 861 SourceLocation(), TTP->getDepth(), 862 TTP->getPosition(), 863 TTP->isParameterPack(), 864 nullptr, 865 TemplateParameterList::Create(*this, SourceLocation(), 866 SourceLocation(), 867 CanonParams, 868 SourceLocation(), 869 CanonRequiresClause)); 870 871 // Get the new insert position for the node we care about. 872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 873 assert(!Canonical && "Shouldn't be in the map!"); 874 (void)Canonical; 875 876 // Create the canonical template template parameter entry. 877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 879 return CanonTTP; 880 } 881 882 TargetCXXABI::Kind ASTContext::getCXXABIKind() const { 883 auto Kind = getTargetInfo().getCXXABI().getKind(); 884 return getLangOpts().CXXABI.getValueOr(Kind); 885 } 886 887 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 888 if (!LangOpts.CPlusPlus) return nullptr; 889 890 switch (getCXXABIKind()) { 891 case TargetCXXABI::AppleARM64: 892 case TargetCXXABI::Fuchsia: 893 case TargetCXXABI::GenericARM: // Same as Itanium at this level 894 case TargetCXXABI::iOS: 895 case TargetCXXABI::WatchOS: 896 case TargetCXXABI::GenericAArch64: 897 case TargetCXXABI::GenericMIPS: 898 case TargetCXXABI::GenericItanium: 899 case TargetCXXABI::WebAssembly: 900 case TargetCXXABI::XL: 901 return CreateItaniumCXXABI(*this); 902 case TargetCXXABI::Microsoft: 903 return CreateMicrosoftCXXABI(*this); 904 } 905 llvm_unreachable("Invalid CXXABI type!"); 906 } 907 908 interp::Context &ASTContext::getInterpContext() { 909 if (!InterpContext) { 910 InterpContext.reset(new interp::Context(*this)); 911 } 912 return *InterpContext.get(); 913 } 914 915 ParentMapContext &ASTContext::getParentMapContext() { 916 if (!ParentMapCtx) 917 ParentMapCtx.reset(new ParentMapContext(*this)); 918 return *ParentMapCtx.get(); 919 } 920 921 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 922 const LangOptions &LOpts) { 923 if (LOpts.FakeAddressSpaceMap) { 924 // The fake address space map must have a distinct entry for each 925 // language-specific address space. 926 static const unsigned FakeAddrSpaceMap[] = { 927 0, // Default 928 1, // opencl_global 929 3, // opencl_local 930 2, // opencl_constant 931 0, // opencl_private 932 4, // opencl_generic 933 5, // opencl_global_device 934 6, // opencl_global_host 935 7, // cuda_device 936 8, // cuda_constant 937 9, // cuda_shared 938 1, // sycl_global 939 5, // sycl_global_device 940 6, // sycl_global_host 941 3, // sycl_local 942 0, // sycl_private 943 10, // ptr32_sptr 944 11, // ptr32_uptr 945 12 // ptr64 946 }; 947 return &FakeAddrSpaceMap; 948 } else { 949 return &T.getAddressSpaceMap(); 950 } 951 } 952 953 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 954 const LangOptions &LangOpts) { 955 switch (LangOpts.getAddressSpaceMapMangling()) { 956 case LangOptions::ASMM_Target: 957 return TI.useAddressSpaceMapMangling(); 958 case LangOptions::ASMM_On: 959 return true; 960 case LangOptions::ASMM_Off: 961 return false; 962 } 963 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 964 } 965 966 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 967 IdentifierTable &idents, SelectorTable &sels, 968 Builtin::Context &builtins, TranslationUnitKind TUKind) 969 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), 970 TemplateSpecializationTypes(this_()), 971 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), 972 SubstTemplateTemplateParmPacks(this_()), 973 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), 974 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)), 975 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 976 LangOpts.XRayNeverInstrumentFiles, 977 LangOpts.XRayAttrListFiles, SM)), 978 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)), 979 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 980 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this), 981 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 982 CompCategories(this_()), LastSDM(nullptr, 0) { 983 addTranslationUnitDecl(); 984 } 985 986 ASTContext::~ASTContext() { 987 // Release the DenseMaps associated with DeclContext objects. 988 // FIXME: Is this the ideal solution? 989 ReleaseDeclContextMaps(); 990 991 // Call all of the deallocation functions on all of their targets. 992 for (auto &Pair : Deallocations) 993 (Pair.first)(Pair.second); 994 995 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 996 // because they can contain DenseMaps. 997 for (llvm::DenseMap<const ObjCContainerDecl*, 998 const ASTRecordLayout*>::iterator 999 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 1000 // Increment in loop to prevent using deallocated memory. 1001 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1002 R->Destroy(*this); 1003 1004 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 1005 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 1006 // Increment in loop to prevent using deallocated memory. 1007 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 1008 R->Destroy(*this); 1009 } 1010 1011 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 1012 AEnd = DeclAttrs.end(); 1013 A != AEnd; ++A) 1014 A->second->~AttrVec(); 1015 1016 for (const auto &Value : ModuleInitializers) 1017 Value.second->~PerModuleInitializers(); 1018 } 1019 1020 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { 1021 TraversalScope = TopLevelDecls; 1022 getParentMapContext().clear(); 1023 } 1024 1025 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { 1026 Deallocations.push_back({Callback, Data}); 1027 } 1028 1029 void 1030 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 1031 ExternalSource = std::move(Source); 1032 } 1033 1034 void ASTContext::PrintStats() const { 1035 llvm::errs() << "\n*** AST Context Stats:\n"; 1036 llvm::errs() << " " << Types.size() << " types total.\n"; 1037 1038 unsigned counts[] = { 1039 #define TYPE(Name, Parent) 0, 1040 #define ABSTRACT_TYPE(Name, Parent) 1041 #include "clang/AST/TypeNodes.inc" 1042 0 // Extra 1043 }; 1044 1045 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 1046 Type *T = Types[i]; 1047 counts[(unsigned)T->getTypeClass()]++; 1048 } 1049 1050 unsigned Idx = 0; 1051 unsigned TotalBytes = 0; 1052 #define TYPE(Name, Parent) \ 1053 if (counts[Idx]) \ 1054 llvm::errs() << " " << counts[Idx] << " " << #Name \ 1055 << " types, " << sizeof(Name##Type) << " each " \ 1056 << "(" << counts[Idx] * sizeof(Name##Type) \ 1057 << " bytes)\n"; \ 1058 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 1059 ++Idx; 1060 #define ABSTRACT_TYPE(Name, Parent) 1061 #include "clang/AST/TypeNodes.inc" 1062 1063 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 1064 1065 // Implicit special member functions. 1066 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 1067 << NumImplicitDefaultConstructors 1068 << " implicit default constructors created\n"; 1069 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 1070 << NumImplicitCopyConstructors 1071 << " implicit copy constructors created\n"; 1072 if (getLangOpts().CPlusPlus) 1073 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 1074 << NumImplicitMoveConstructors 1075 << " implicit move constructors created\n"; 1076 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 1077 << NumImplicitCopyAssignmentOperators 1078 << " implicit copy assignment operators created\n"; 1079 if (getLangOpts().CPlusPlus) 1080 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 1081 << NumImplicitMoveAssignmentOperators 1082 << " implicit move assignment operators created\n"; 1083 llvm::errs() << NumImplicitDestructorsDeclared << "/" 1084 << NumImplicitDestructors 1085 << " implicit destructors created\n"; 1086 1087 if (ExternalSource) { 1088 llvm::errs() << "\n"; 1089 ExternalSource->PrintStats(); 1090 } 1091 1092 BumpAlloc.PrintStats(); 1093 } 1094 1095 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1096 bool NotifyListeners) { 1097 if (NotifyListeners) 1098 if (auto *Listener = getASTMutationListener()) 1099 Listener->RedefinedHiddenDefinition(ND, M); 1100 1101 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); 1102 } 1103 1104 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 1105 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); 1106 if (It == MergedDefModules.end()) 1107 return; 1108 1109 auto &Merged = It->second; 1110 llvm::DenseSet<Module*> Found; 1111 for (Module *&M : Merged) 1112 if (!Found.insert(M).second) 1113 M = nullptr; 1114 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 1115 } 1116 1117 ArrayRef<Module *> 1118 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { 1119 auto MergedIt = 1120 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl())); 1121 if (MergedIt == MergedDefModules.end()) 1122 return None; 1123 return MergedIt->second; 1124 } 1125 1126 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 1127 if (LazyInitializers.empty()) 1128 return; 1129 1130 auto *Source = Ctx.getExternalSource(); 1131 assert(Source && "lazy initializers but no external source"); 1132 1133 auto LazyInits = std::move(LazyInitializers); 1134 LazyInitializers.clear(); 1135 1136 for (auto ID : LazyInits) 1137 Initializers.push_back(Source->GetExternalDecl(ID)); 1138 1139 assert(LazyInitializers.empty() && 1140 "GetExternalDecl for lazy module initializer added more inits"); 1141 } 1142 1143 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 1144 // One special case: if we add a module initializer that imports another 1145 // module, and that module's only initializer is an ImportDecl, simplify. 1146 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 1147 auto It = ModuleInitializers.find(ID->getImportedModule()); 1148 1149 // Maybe the ImportDecl does nothing at all. (Common case.) 1150 if (It == ModuleInitializers.end()) 1151 return; 1152 1153 // Maybe the ImportDecl only imports another ImportDecl. 1154 auto &Imported = *It->second; 1155 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 1156 Imported.resolve(*this); 1157 auto *OnlyDecl = Imported.Initializers.front(); 1158 if (isa<ImportDecl>(OnlyDecl)) 1159 D = OnlyDecl; 1160 } 1161 } 1162 1163 auto *&Inits = ModuleInitializers[M]; 1164 if (!Inits) 1165 Inits = new (*this) PerModuleInitializers; 1166 Inits->Initializers.push_back(D); 1167 } 1168 1169 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 1170 auto *&Inits = ModuleInitializers[M]; 1171 if (!Inits) 1172 Inits = new (*this) PerModuleInitializers; 1173 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1174 IDs.begin(), IDs.end()); 1175 } 1176 1177 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1178 auto It = ModuleInitializers.find(M); 1179 if (It == ModuleInitializers.end()) 1180 return None; 1181 1182 auto *Inits = It->second; 1183 Inits->resolve(*this); 1184 return Inits->Initializers; 1185 } 1186 1187 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1188 if (!ExternCContext) 1189 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1190 1191 return ExternCContext; 1192 } 1193 1194 BuiltinTemplateDecl * 1195 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1196 const IdentifierInfo *II) const { 1197 auto *BuiltinTemplate = 1198 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); 1199 BuiltinTemplate->setImplicit(); 1200 getTranslationUnitDecl()->addDecl(BuiltinTemplate); 1201 1202 return BuiltinTemplate; 1203 } 1204 1205 BuiltinTemplateDecl * 1206 ASTContext::getMakeIntegerSeqDecl() const { 1207 if (!MakeIntegerSeqDecl) 1208 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1209 getMakeIntegerSeqName()); 1210 return MakeIntegerSeqDecl; 1211 } 1212 1213 BuiltinTemplateDecl * 1214 ASTContext::getTypePackElementDecl() const { 1215 if (!TypePackElementDecl) 1216 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1217 getTypePackElementName()); 1218 return TypePackElementDecl; 1219 } 1220 1221 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1222 RecordDecl::TagKind TK) const { 1223 SourceLocation Loc; 1224 RecordDecl *NewDecl; 1225 if (getLangOpts().CPlusPlus) 1226 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1227 Loc, &Idents.get(Name)); 1228 else 1229 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1230 &Idents.get(Name)); 1231 NewDecl->setImplicit(); 1232 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1233 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1234 return NewDecl; 1235 } 1236 1237 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1238 StringRef Name) const { 1239 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1240 TypedefDecl *NewDecl = TypedefDecl::Create( 1241 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1242 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1243 NewDecl->setImplicit(); 1244 return NewDecl; 1245 } 1246 1247 TypedefDecl *ASTContext::getInt128Decl() const { 1248 if (!Int128Decl) 1249 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1250 return Int128Decl; 1251 } 1252 1253 TypedefDecl *ASTContext::getUInt128Decl() const { 1254 if (!UInt128Decl) 1255 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1256 return UInt128Decl; 1257 } 1258 1259 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1260 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1261 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1262 Types.push_back(Ty); 1263 } 1264 1265 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1266 const TargetInfo *AuxTarget) { 1267 assert((!this->Target || this->Target == &Target) && 1268 "Incorrect target reinitialization"); 1269 assert(VoidTy.isNull() && "Context reinitialized?"); 1270 1271 this->Target = &Target; 1272 this->AuxTarget = AuxTarget; 1273 1274 ABI.reset(createCXXABI(Target)); 1275 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1276 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1277 1278 // C99 6.2.5p19. 1279 InitBuiltinType(VoidTy, BuiltinType::Void); 1280 1281 // C99 6.2.5p2. 1282 InitBuiltinType(BoolTy, BuiltinType::Bool); 1283 // C99 6.2.5p3. 1284 if (LangOpts.CharIsSigned) 1285 InitBuiltinType(CharTy, BuiltinType::Char_S); 1286 else 1287 InitBuiltinType(CharTy, BuiltinType::Char_U); 1288 // C99 6.2.5p4. 1289 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1290 InitBuiltinType(ShortTy, BuiltinType::Short); 1291 InitBuiltinType(IntTy, BuiltinType::Int); 1292 InitBuiltinType(LongTy, BuiltinType::Long); 1293 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1294 1295 // C99 6.2.5p6. 1296 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1297 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1298 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1299 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1300 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1301 1302 // C99 6.2.5p10. 1303 InitBuiltinType(FloatTy, BuiltinType::Float); 1304 InitBuiltinType(DoubleTy, BuiltinType::Double); 1305 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1306 1307 // GNU extension, __float128 for IEEE quadruple precision 1308 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1309 1310 // C11 extension ISO/IEC TS 18661-3 1311 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1312 1313 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1314 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1315 InitBuiltinType(AccumTy, BuiltinType::Accum); 1316 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1317 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1318 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1319 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1320 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1321 InitBuiltinType(FractTy, BuiltinType::Fract); 1322 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1323 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1324 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1325 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1326 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1327 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1328 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1329 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1330 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1331 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1332 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1333 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1334 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1335 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1336 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1337 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1338 1339 // GNU extension, 128-bit integers. 1340 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1341 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1342 1343 // C++ 3.9.1p5 1344 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1345 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1346 else // -fshort-wchar makes wchar_t be unsigned. 1347 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1348 if (LangOpts.CPlusPlus && LangOpts.WChar) 1349 WideCharTy = WCharTy; 1350 else { 1351 // C99 (or C++ using -fno-wchar). 1352 WideCharTy = getFromTargetType(Target.getWCharType()); 1353 } 1354 1355 WIntTy = getFromTargetType(Target.getWIntType()); 1356 1357 // C++20 (proposed) 1358 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1359 1360 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1361 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1362 else // C99 1363 Char16Ty = getFromTargetType(Target.getChar16Type()); 1364 1365 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1366 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1367 else // C99 1368 Char32Ty = getFromTargetType(Target.getChar32Type()); 1369 1370 // Placeholder type for type-dependent expressions whose type is 1371 // completely unknown. No code should ever check a type against 1372 // DependentTy and users should never see it; however, it is here to 1373 // help diagnose failures to properly check for type-dependent 1374 // expressions. 1375 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1376 1377 // Placeholder type for functions. 1378 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1379 1380 // Placeholder type for bound members. 1381 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1382 1383 // Placeholder type for pseudo-objects. 1384 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1385 1386 // "any" type; useful for debugger-like clients. 1387 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1388 1389 // Placeholder type for unbridged ARC casts. 1390 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1391 1392 // Placeholder type for builtin functions. 1393 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1394 1395 // Placeholder type for OMP array sections. 1396 if (LangOpts.OpenMP) { 1397 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1398 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping); 1399 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator); 1400 } 1401 if (LangOpts.MatrixTypes) 1402 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); 1403 1404 // C99 6.2.5p11. 1405 FloatComplexTy = getComplexType(FloatTy); 1406 DoubleComplexTy = getComplexType(DoubleTy); 1407 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1408 Float128ComplexTy = getComplexType(Float128Ty); 1409 1410 // Builtin types for 'id', 'Class', and 'SEL'. 1411 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1412 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1413 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1414 1415 if (LangOpts.OpenCL) { 1416 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1417 InitBuiltinType(SingletonId, BuiltinType::Id); 1418 #include "clang/Basic/OpenCLImageTypes.def" 1419 1420 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1421 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1422 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1423 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1424 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1425 1426 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1427 InitBuiltinType(Id##Ty, BuiltinType::Id); 1428 #include "clang/Basic/OpenCLExtensionTypes.def" 1429 } 1430 1431 if (Target.hasAArch64SVETypes()) { 1432 #define SVE_TYPE(Name, Id, SingletonId) \ 1433 InitBuiltinType(SingletonId, BuiltinType::Id); 1434 #include "clang/Basic/AArch64SVEACLETypes.def" 1435 } 1436 1437 if (Target.getTriple().isPPC64() && 1438 Target.hasFeature("paired-vector-memops")) { 1439 if (Target.hasFeature("mma")) { 1440 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 1441 InitBuiltinType(Id##Ty, BuiltinType::Id); 1442 #include "clang/Basic/PPCTypes.def" 1443 } 1444 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 1445 InitBuiltinType(Id##Ty, BuiltinType::Id); 1446 #include "clang/Basic/PPCTypes.def" 1447 } 1448 1449 if (Target.hasRISCVVTypes()) { 1450 #define RVV_TYPE(Name, Id, SingletonId) \ 1451 InitBuiltinType(SingletonId, BuiltinType::Id); 1452 #include "clang/Basic/RISCVVTypes.def" 1453 } 1454 1455 // Builtin type for __objc_yes and __objc_no 1456 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1457 SignedCharTy : BoolTy); 1458 1459 ObjCConstantStringType = QualType(); 1460 1461 ObjCSuperType = QualType(); 1462 1463 // void * type 1464 if (LangOpts.OpenCLGenericAddressSpace) { 1465 auto Q = VoidTy.getQualifiers(); 1466 Q.setAddressSpace(LangAS::opencl_generic); 1467 VoidPtrTy = getPointerType(getCanonicalType( 1468 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1469 } else { 1470 VoidPtrTy = getPointerType(VoidTy); 1471 } 1472 1473 // nullptr type (C++0x 2.14.7) 1474 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1475 1476 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1477 InitBuiltinType(HalfTy, BuiltinType::Half); 1478 1479 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16); 1480 1481 // Builtin type used to help define __builtin_va_list. 1482 VaListTagDecl = nullptr; 1483 1484 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls. 1485 if (LangOpts.MicrosoftExt || LangOpts.Borland) { 1486 MSGuidTagDecl = buildImplicitRecord("_GUID"); 1487 getTranslationUnitDecl()->addDecl(MSGuidTagDecl); 1488 } 1489 } 1490 1491 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1492 return SourceMgr.getDiagnostics(); 1493 } 1494 1495 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1496 AttrVec *&Result = DeclAttrs[D]; 1497 if (!Result) { 1498 void *Mem = Allocate(sizeof(AttrVec)); 1499 Result = new (Mem) AttrVec; 1500 } 1501 1502 return *Result; 1503 } 1504 1505 /// Erase the attributes corresponding to the given declaration. 1506 void ASTContext::eraseDeclAttrs(const Decl *D) { 1507 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1508 if (Pos != DeclAttrs.end()) { 1509 Pos->second->~AttrVec(); 1510 DeclAttrs.erase(Pos); 1511 } 1512 } 1513 1514 // FIXME: Remove ? 1515 MemberSpecializationInfo * 1516 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1517 assert(Var->isStaticDataMember() && "Not a static data member"); 1518 return getTemplateOrSpecializationInfo(Var) 1519 .dyn_cast<MemberSpecializationInfo *>(); 1520 } 1521 1522 ASTContext::TemplateOrSpecializationInfo 1523 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1524 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1525 TemplateOrInstantiation.find(Var); 1526 if (Pos == TemplateOrInstantiation.end()) 1527 return {}; 1528 1529 return Pos->second; 1530 } 1531 1532 void 1533 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1534 TemplateSpecializationKind TSK, 1535 SourceLocation PointOfInstantiation) { 1536 assert(Inst->isStaticDataMember() && "Not a static data member"); 1537 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1538 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1539 Tmpl, TSK, PointOfInstantiation)); 1540 } 1541 1542 void 1543 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1544 TemplateOrSpecializationInfo TSI) { 1545 assert(!TemplateOrInstantiation[Inst] && 1546 "Already noted what the variable was instantiated from"); 1547 TemplateOrInstantiation[Inst] = TSI; 1548 } 1549 1550 NamedDecl * 1551 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1552 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1553 if (Pos == InstantiatedFromUsingDecl.end()) 1554 return nullptr; 1555 1556 return Pos->second; 1557 } 1558 1559 void 1560 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1561 assert((isa<UsingDecl>(Pattern) || 1562 isa<UnresolvedUsingValueDecl>(Pattern) || 1563 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1564 "pattern decl is not a using decl"); 1565 assert((isa<UsingDecl>(Inst) || 1566 isa<UnresolvedUsingValueDecl>(Inst) || 1567 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1568 "instantiation did not produce a using decl"); 1569 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1570 InstantiatedFromUsingDecl[Inst] = Pattern; 1571 } 1572 1573 UsingEnumDecl * 1574 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) { 1575 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD); 1576 if (Pos == InstantiatedFromUsingEnumDecl.end()) 1577 return nullptr; 1578 1579 return Pos->second; 1580 } 1581 1582 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 1583 UsingEnumDecl *Pattern) { 1584 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists"); 1585 InstantiatedFromUsingEnumDecl[Inst] = Pattern; 1586 } 1587 1588 UsingShadowDecl * 1589 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1590 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1591 = InstantiatedFromUsingShadowDecl.find(Inst); 1592 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1593 return nullptr; 1594 1595 return Pos->second; 1596 } 1597 1598 void 1599 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1600 UsingShadowDecl *Pattern) { 1601 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1602 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1603 } 1604 1605 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1606 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1607 = InstantiatedFromUnnamedFieldDecl.find(Field); 1608 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1609 return nullptr; 1610 1611 return Pos->second; 1612 } 1613 1614 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1615 FieldDecl *Tmpl) { 1616 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1617 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1618 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1619 "Already noted what unnamed field was instantiated from"); 1620 1621 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1622 } 1623 1624 ASTContext::overridden_cxx_method_iterator 1625 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1626 return overridden_methods(Method).begin(); 1627 } 1628 1629 ASTContext::overridden_cxx_method_iterator 1630 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1631 return overridden_methods(Method).end(); 1632 } 1633 1634 unsigned 1635 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1636 auto Range = overridden_methods(Method); 1637 return Range.end() - Range.begin(); 1638 } 1639 1640 ASTContext::overridden_method_range 1641 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1642 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1643 OverriddenMethods.find(Method->getCanonicalDecl()); 1644 if (Pos == OverriddenMethods.end()) 1645 return overridden_method_range(nullptr, nullptr); 1646 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1647 } 1648 1649 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1650 const CXXMethodDecl *Overridden) { 1651 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1652 OverriddenMethods[Method].push_back(Overridden); 1653 } 1654 1655 void ASTContext::getOverriddenMethods( 1656 const NamedDecl *D, 1657 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1658 assert(D); 1659 1660 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1661 Overridden.append(overridden_methods_begin(CXXMethod), 1662 overridden_methods_end(CXXMethod)); 1663 return; 1664 } 1665 1666 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1667 if (!Method) 1668 return; 1669 1670 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1671 Method->getOverriddenMethods(OverDecls); 1672 Overridden.append(OverDecls.begin(), OverDecls.end()); 1673 } 1674 1675 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1676 assert(!Import->getNextLocalImport() && 1677 "Import declaration already in the chain"); 1678 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1679 if (!FirstLocalImport) { 1680 FirstLocalImport = Import; 1681 LastLocalImport = Import; 1682 return; 1683 } 1684 1685 LastLocalImport->setNextLocalImport(Import); 1686 LastLocalImport = Import; 1687 } 1688 1689 //===----------------------------------------------------------------------===// 1690 // Type Sizing and Analysis 1691 //===----------------------------------------------------------------------===// 1692 1693 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1694 /// scalar floating point type. 1695 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1696 switch (T->castAs<BuiltinType>()->getKind()) { 1697 default: 1698 llvm_unreachable("Not a floating point type!"); 1699 case BuiltinType::BFloat16: 1700 return Target->getBFloat16Format(); 1701 case BuiltinType::Float16: 1702 case BuiltinType::Half: 1703 return Target->getHalfFormat(); 1704 case BuiltinType::Float: return Target->getFloatFormat(); 1705 case BuiltinType::Double: return Target->getDoubleFormat(); 1706 case BuiltinType::LongDouble: 1707 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1708 return AuxTarget->getLongDoubleFormat(); 1709 return Target->getLongDoubleFormat(); 1710 case BuiltinType::Float128: 1711 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) 1712 return AuxTarget->getFloat128Format(); 1713 return Target->getFloat128Format(); 1714 } 1715 } 1716 1717 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1718 unsigned Align = Target->getCharWidth(); 1719 1720 bool UseAlignAttrOnly = false; 1721 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1722 Align = AlignFromAttr; 1723 1724 // __attribute__((aligned)) can increase or decrease alignment 1725 // *except* on a struct or struct member, where it only increases 1726 // alignment unless 'packed' is also specified. 1727 // 1728 // It is an error for alignas to decrease alignment, so we can 1729 // ignore that possibility; Sema should diagnose it. 1730 if (isa<FieldDecl>(D)) { 1731 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1732 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1733 } else { 1734 UseAlignAttrOnly = true; 1735 } 1736 } 1737 else if (isa<FieldDecl>(D)) 1738 UseAlignAttrOnly = 1739 D->hasAttr<PackedAttr>() || 1740 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1741 1742 // If we're using the align attribute only, just ignore everything 1743 // else about the declaration and its type. 1744 if (UseAlignAttrOnly) { 1745 // do nothing 1746 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1747 QualType T = VD->getType(); 1748 if (const auto *RT = T->getAs<ReferenceType>()) { 1749 if (ForAlignof) 1750 T = RT->getPointeeType(); 1751 else 1752 T = getPointerType(RT->getPointeeType()); 1753 } 1754 QualType BaseT = getBaseElementType(T); 1755 if (T->isFunctionType()) 1756 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1757 else if (!BaseT->isIncompleteType()) { 1758 // Adjust alignments of declarations with array type by the 1759 // large-array alignment on the target. 1760 if (const ArrayType *arrayType = getAsArrayType(T)) { 1761 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1762 if (!ForAlignof && MinWidth) { 1763 if (isa<VariableArrayType>(arrayType)) 1764 Align = std::max(Align, Target->getLargeArrayAlign()); 1765 else if (isa<ConstantArrayType>(arrayType) && 1766 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1767 Align = std::max(Align, Target->getLargeArrayAlign()); 1768 } 1769 } 1770 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1771 if (BaseT.getQualifiers().hasUnaligned()) 1772 Align = Target->getCharWidth(); 1773 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1774 if (VD->hasGlobalStorage() && !ForAlignof) { 1775 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 1776 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); 1777 } 1778 } 1779 } 1780 1781 // Fields can be subject to extra alignment constraints, like if 1782 // the field is packed, the struct is packed, or the struct has a 1783 // a max-field-alignment constraint (#pragma pack). So calculate 1784 // the actual alignment of the field within the struct, and then 1785 // (as we're expected to) constrain that by the alignment of the type. 1786 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1787 const RecordDecl *Parent = Field->getParent(); 1788 // We can only produce a sensible answer if the record is valid. 1789 if (!Parent->isInvalidDecl()) { 1790 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1791 1792 // Start with the record's overall alignment. 1793 unsigned FieldAlign = toBits(Layout.getAlignment()); 1794 1795 // Use the GCD of that and the offset within the record. 1796 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1797 if (Offset > 0) { 1798 // Alignment is always a power of 2, so the GCD will be a power of 2, 1799 // which means we get to do this crazy thing instead of Euclid's. 1800 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1801 if (LowBitOfOffset < FieldAlign) 1802 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1803 } 1804 1805 Align = std::min(Align, FieldAlign); 1806 } 1807 } 1808 } 1809 1810 // Some targets have hard limitation on the maximum requestable alignment in 1811 // aligned attribute for static variables. 1812 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); 1813 const auto *VD = dyn_cast<VarDecl>(D); 1814 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) 1815 Align = std::min(Align, MaxAlignedAttr); 1816 1817 return toCharUnitsFromBits(Align); 1818 } 1819 1820 CharUnits ASTContext::getExnObjectAlignment() const { 1821 return toCharUnitsFromBits(Target->getExnObjectAlignment()); 1822 } 1823 1824 // getTypeInfoDataSizeInChars - Return the size of a type, in 1825 // chars. If the type is a record, its data size is returned. This is 1826 // the size of the memcpy that's performed when assigning this type 1827 // using a trivial copy/move assignment operator. 1828 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1829 TypeInfoChars Info = getTypeInfoInChars(T); 1830 1831 // In C++, objects can sometimes be allocated into the tail padding 1832 // of a base-class subobject. We decide whether that's possible 1833 // during class layout, so here we can just trust the layout results. 1834 if (getLangOpts().CPlusPlus) { 1835 if (const auto *RT = T->getAs<RecordType>()) { 1836 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1837 Info.Width = layout.getDataSize(); 1838 } 1839 } 1840 1841 return Info; 1842 } 1843 1844 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1845 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1846 TypeInfoChars 1847 static getConstantArrayInfoInChars(const ASTContext &Context, 1848 const ConstantArrayType *CAT) { 1849 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); 1850 uint64_t Size = CAT->getSize().getZExtValue(); 1851 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= 1852 (uint64_t)(-1)/Size) && 1853 "Overflow in array type char size evaluation"); 1854 uint64_t Width = EltInfo.Width.getQuantity() * Size; 1855 unsigned Align = EltInfo.Align.getQuantity(); 1856 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1857 Context.getTargetInfo().getPointerWidth(0) == 64) 1858 Width = llvm::alignTo(Width, Align); 1859 return TypeInfoChars(CharUnits::fromQuantity(Width), 1860 CharUnits::fromQuantity(Align), 1861 EltInfo.AlignIsRequired); 1862 } 1863 1864 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { 1865 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1866 return getConstantArrayInfoInChars(*this, CAT); 1867 TypeInfo Info = getTypeInfo(T); 1868 return TypeInfoChars(toCharUnitsFromBits(Info.Width), 1869 toCharUnitsFromBits(Info.Align), 1870 Info.AlignIsRequired); 1871 } 1872 1873 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const { 1874 return getTypeInfoInChars(T.getTypePtr()); 1875 } 1876 1877 bool ASTContext::isAlignmentRequired(const Type *T) const { 1878 return getTypeInfo(T).AlignIsRequired; 1879 } 1880 1881 bool ASTContext::isAlignmentRequired(QualType T) const { 1882 return isAlignmentRequired(T.getTypePtr()); 1883 } 1884 1885 unsigned ASTContext::getTypeAlignIfKnown(QualType T, 1886 bool NeedsPreferredAlignment) const { 1887 // An alignment on a typedef overrides anything else. 1888 if (const auto *TT = T->getAs<TypedefType>()) 1889 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1890 return Align; 1891 1892 // If we have an (array of) complete type, we're done. 1893 T = getBaseElementType(T); 1894 if (!T->isIncompleteType()) 1895 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T); 1896 1897 // If we had an array type, its element type might be a typedef 1898 // type with an alignment attribute. 1899 if (const auto *TT = T->getAs<TypedefType>()) 1900 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1901 return Align; 1902 1903 // Otherwise, see if the declaration of the type had an attribute. 1904 if (const auto *TT = T->getAs<TagType>()) 1905 return TT->getDecl()->getMaxAlignment(); 1906 1907 return 0; 1908 } 1909 1910 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1911 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1912 if (I != MemoizedTypeInfo.end()) 1913 return I->second; 1914 1915 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1916 TypeInfo TI = getTypeInfoImpl(T); 1917 MemoizedTypeInfo[T] = TI; 1918 return TI; 1919 } 1920 1921 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1922 /// method does not work on incomplete types. 1923 /// 1924 /// FIXME: Pointers into different addr spaces could have different sizes and 1925 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1926 /// should take a QualType, &c. 1927 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1928 uint64_t Width = 0; 1929 unsigned Align = 8; 1930 bool AlignIsRequired = false; 1931 unsigned AS = 0; 1932 switch (T->getTypeClass()) { 1933 #define TYPE(Class, Base) 1934 #define ABSTRACT_TYPE(Class, Base) 1935 #define NON_CANONICAL_TYPE(Class, Base) 1936 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1937 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1938 case Type::Class: \ 1939 assert(!T->isDependentType() && "should not see dependent types here"); \ 1940 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1941 #include "clang/AST/TypeNodes.inc" 1942 llvm_unreachable("Should not see dependent types"); 1943 1944 case Type::FunctionNoProto: 1945 case Type::FunctionProto: 1946 // GCC extension: alignof(function) = 32 bits 1947 Width = 0; 1948 Align = 32; 1949 break; 1950 1951 case Type::IncompleteArray: 1952 case Type::VariableArray: 1953 case Type::ConstantArray: { 1954 // Model non-constant sized arrays as size zero, but track the alignment. 1955 uint64_t Size = 0; 1956 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1957 Size = CAT->getSize().getZExtValue(); 1958 1959 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType()); 1960 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1961 "Overflow in array type bit size evaluation"); 1962 Width = EltInfo.Width * Size; 1963 Align = EltInfo.Align; 1964 AlignIsRequired = EltInfo.AlignIsRequired; 1965 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1966 getTargetInfo().getPointerWidth(0) == 64) 1967 Width = llvm::alignTo(Width, Align); 1968 break; 1969 } 1970 1971 case Type::ExtVector: 1972 case Type::Vector: { 1973 const auto *VT = cast<VectorType>(T); 1974 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1975 Width = EltInfo.Width * VT->getNumElements(); 1976 Align = Width; 1977 // If the alignment is not a power of 2, round up to the next power of 2. 1978 // This happens for non-power-of-2 length vectors. 1979 if (Align & (Align-1)) { 1980 Align = llvm::NextPowerOf2(Align); 1981 Width = llvm::alignTo(Width, Align); 1982 } 1983 // Adjust the alignment based on the target max. 1984 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1985 if (TargetVectorAlign && TargetVectorAlign < Align) 1986 Align = TargetVectorAlign; 1987 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 1988 // Adjust the alignment for fixed-length SVE vectors. This is important 1989 // for non-power-of-2 vector lengths. 1990 Align = 128; 1991 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 1992 // Adjust the alignment for fixed-length SVE predicates. 1993 Align = 16; 1994 break; 1995 } 1996 1997 case Type::ConstantMatrix: { 1998 const auto *MT = cast<ConstantMatrixType>(T); 1999 TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); 2000 // The internal layout of a matrix value is implementation defined. 2001 // Initially be ABI compatible with arrays with respect to alignment and 2002 // size. 2003 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns(); 2004 Align = ElementInfo.Align; 2005 break; 2006 } 2007 2008 case Type::Builtin: 2009 switch (cast<BuiltinType>(T)->getKind()) { 2010 default: llvm_unreachable("Unknown builtin type!"); 2011 case BuiltinType::Void: 2012 // GCC extension: alignof(void) = 8 bits. 2013 Width = 0; 2014 Align = 8; 2015 break; 2016 case BuiltinType::Bool: 2017 Width = Target->getBoolWidth(); 2018 Align = Target->getBoolAlign(); 2019 break; 2020 case BuiltinType::Char_S: 2021 case BuiltinType::Char_U: 2022 case BuiltinType::UChar: 2023 case BuiltinType::SChar: 2024 case BuiltinType::Char8: 2025 Width = Target->getCharWidth(); 2026 Align = Target->getCharAlign(); 2027 break; 2028 case BuiltinType::WChar_S: 2029 case BuiltinType::WChar_U: 2030 Width = Target->getWCharWidth(); 2031 Align = Target->getWCharAlign(); 2032 break; 2033 case BuiltinType::Char16: 2034 Width = Target->getChar16Width(); 2035 Align = Target->getChar16Align(); 2036 break; 2037 case BuiltinType::Char32: 2038 Width = Target->getChar32Width(); 2039 Align = Target->getChar32Align(); 2040 break; 2041 case BuiltinType::UShort: 2042 case BuiltinType::Short: 2043 Width = Target->getShortWidth(); 2044 Align = Target->getShortAlign(); 2045 break; 2046 case BuiltinType::UInt: 2047 case BuiltinType::Int: 2048 Width = Target->getIntWidth(); 2049 Align = Target->getIntAlign(); 2050 break; 2051 case BuiltinType::ULong: 2052 case BuiltinType::Long: 2053 Width = Target->getLongWidth(); 2054 Align = Target->getLongAlign(); 2055 break; 2056 case BuiltinType::ULongLong: 2057 case BuiltinType::LongLong: 2058 Width = Target->getLongLongWidth(); 2059 Align = Target->getLongLongAlign(); 2060 break; 2061 case BuiltinType::Int128: 2062 case BuiltinType::UInt128: 2063 Width = 128; 2064 Align = 128; // int128_t is 128-bit aligned on all targets. 2065 break; 2066 case BuiltinType::ShortAccum: 2067 case BuiltinType::UShortAccum: 2068 case BuiltinType::SatShortAccum: 2069 case BuiltinType::SatUShortAccum: 2070 Width = Target->getShortAccumWidth(); 2071 Align = Target->getShortAccumAlign(); 2072 break; 2073 case BuiltinType::Accum: 2074 case BuiltinType::UAccum: 2075 case BuiltinType::SatAccum: 2076 case BuiltinType::SatUAccum: 2077 Width = Target->getAccumWidth(); 2078 Align = Target->getAccumAlign(); 2079 break; 2080 case BuiltinType::LongAccum: 2081 case BuiltinType::ULongAccum: 2082 case BuiltinType::SatLongAccum: 2083 case BuiltinType::SatULongAccum: 2084 Width = Target->getLongAccumWidth(); 2085 Align = Target->getLongAccumAlign(); 2086 break; 2087 case BuiltinType::ShortFract: 2088 case BuiltinType::UShortFract: 2089 case BuiltinType::SatShortFract: 2090 case BuiltinType::SatUShortFract: 2091 Width = Target->getShortFractWidth(); 2092 Align = Target->getShortFractAlign(); 2093 break; 2094 case BuiltinType::Fract: 2095 case BuiltinType::UFract: 2096 case BuiltinType::SatFract: 2097 case BuiltinType::SatUFract: 2098 Width = Target->getFractWidth(); 2099 Align = Target->getFractAlign(); 2100 break; 2101 case BuiltinType::LongFract: 2102 case BuiltinType::ULongFract: 2103 case BuiltinType::SatLongFract: 2104 case BuiltinType::SatULongFract: 2105 Width = Target->getLongFractWidth(); 2106 Align = Target->getLongFractAlign(); 2107 break; 2108 case BuiltinType::BFloat16: 2109 Width = Target->getBFloat16Width(); 2110 Align = Target->getBFloat16Align(); 2111 break; 2112 case BuiltinType::Float16: 2113 case BuiltinType::Half: 2114 if (Target->hasFloat16Type() || !getLangOpts().OpenMP || 2115 !getLangOpts().OpenMPIsDevice) { 2116 Width = Target->getHalfWidth(); 2117 Align = Target->getHalfAlign(); 2118 } else { 2119 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2120 "Expected OpenMP device compilation."); 2121 Width = AuxTarget->getHalfWidth(); 2122 Align = AuxTarget->getHalfAlign(); 2123 } 2124 break; 2125 case BuiltinType::Float: 2126 Width = Target->getFloatWidth(); 2127 Align = Target->getFloatAlign(); 2128 break; 2129 case BuiltinType::Double: 2130 Width = Target->getDoubleWidth(); 2131 Align = Target->getDoubleAlign(); 2132 break; 2133 case BuiltinType::LongDouble: 2134 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2135 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || 2136 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { 2137 Width = AuxTarget->getLongDoubleWidth(); 2138 Align = AuxTarget->getLongDoubleAlign(); 2139 } else { 2140 Width = Target->getLongDoubleWidth(); 2141 Align = Target->getLongDoubleAlign(); 2142 } 2143 break; 2144 case BuiltinType::Float128: 2145 if (Target->hasFloat128Type() || !getLangOpts().OpenMP || 2146 !getLangOpts().OpenMPIsDevice) { 2147 Width = Target->getFloat128Width(); 2148 Align = Target->getFloat128Align(); 2149 } else { 2150 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2151 "Expected OpenMP device compilation."); 2152 Width = AuxTarget->getFloat128Width(); 2153 Align = AuxTarget->getFloat128Align(); 2154 } 2155 break; 2156 case BuiltinType::NullPtr: 2157 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 2158 Align = Target->getPointerAlign(0); // == sizeof(void*) 2159 break; 2160 case BuiltinType::ObjCId: 2161 case BuiltinType::ObjCClass: 2162 case BuiltinType::ObjCSel: 2163 Width = Target->getPointerWidth(0); 2164 Align = Target->getPointerAlign(0); 2165 break; 2166 case BuiltinType::OCLSampler: 2167 case BuiltinType::OCLEvent: 2168 case BuiltinType::OCLClkEvent: 2169 case BuiltinType::OCLQueue: 2170 case BuiltinType::OCLReserveID: 2171 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2172 case BuiltinType::Id: 2173 #include "clang/Basic/OpenCLImageTypes.def" 2174 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2175 case BuiltinType::Id: 2176 #include "clang/Basic/OpenCLExtensionTypes.def" 2177 AS = getTargetAddressSpace( 2178 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 2179 Width = Target->getPointerWidth(AS); 2180 Align = Target->getPointerAlign(AS); 2181 break; 2182 // The SVE types are effectively target-specific. The length of an 2183 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple 2184 // of 128 bits. There is one predicate bit for each vector byte, so the 2185 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. 2186 // 2187 // Because the length is only known at runtime, we use a dummy value 2188 // of 0 for the static length. The alignment values are those defined 2189 // by the Procedure Call Standard for the Arm Architecture. 2190 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 2191 IsSigned, IsFP, IsBF) \ 2192 case BuiltinType::Id: \ 2193 Width = 0; \ 2194 Align = 128; \ 2195 break; 2196 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 2197 case BuiltinType::Id: \ 2198 Width = 0; \ 2199 Align = 16; \ 2200 break; 2201 #include "clang/Basic/AArch64SVEACLETypes.def" 2202 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2203 case BuiltinType::Id: \ 2204 Width = Size; \ 2205 Align = Size; \ 2206 break; 2207 #include "clang/Basic/PPCTypes.def" 2208 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \ 2209 IsFP) \ 2210 case BuiltinType::Id: \ 2211 Width = 0; \ 2212 Align = ElBits; \ 2213 break; 2214 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ 2215 case BuiltinType::Id: \ 2216 Width = 0; \ 2217 Align = 8; \ 2218 break; 2219 #include "clang/Basic/RISCVVTypes.def" 2220 } 2221 break; 2222 case Type::ObjCObjectPointer: 2223 Width = Target->getPointerWidth(0); 2224 Align = Target->getPointerAlign(0); 2225 break; 2226 case Type::BlockPointer: 2227 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 2228 Width = Target->getPointerWidth(AS); 2229 Align = Target->getPointerAlign(AS); 2230 break; 2231 case Type::LValueReference: 2232 case Type::RValueReference: 2233 // alignof and sizeof should never enter this code path here, so we go 2234 // the pointer route. 2235 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 2236 Width = Target->getPointerWidth(AS); 2237 Align = Target->getPointerAlign(AS); 2238 break; 2239 case Type::Pointer: 2240 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 2241 Width = Target->getPointerWidth(AS); 2242 Align = Target->getPointerAlign(AS); 2243 break; 2244 case Type::MemberPointer: { 2245 const auto *MPT = cast<MemberPointerType>(T); 2246 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 2247 Width = MPI.Width; 2248 Align = MPI.Align; 2249 break; 2250 } 2251 case Type::Complex: { 2252 // Complex types have the same alignment as their elements, but twice the 2253 // size. 2254 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 2255 Width = EltInfo.Width * 2; 2256 Align = EltInfo.Align; 2257 break; 2258 } 2259 case Type::ObjCObject: 2260 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 2261 case Type::Adjusted: 2262 case Type::Decayed: 2263 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 2264 case Type::ObjCInterface: { 2265 const auto *ObjCI = cast<ObjCInterfaceType>(T); 2266 if (ObjCI->getDecl()->isInvalidDecl()) { 2267 Width = 8; 2268 Align = 8; 2269 break; 2270 } 2271 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2272 Width = toBits(Layout.getSize()); 2273 Align = toBits(Layout.getAlignment()); 2274 break; 2275 } 2276 case Type::ExtInt: { 2277 const auto *EIT = cast<ExtIntType>(T); 2278 Align = 2279 std::min(static_cast<unsigned>(std::max( 2280 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), 2281 Target->getLongLongAlign()); 2282 Width = llvm::alignTo(EIT->getNumBits(), Align); 2283 break; 2284 } 2285 case Type::Record: 2286 case Type::Enum: { 2287 const auto *TT = cast<TagType>(T); 2288 2289 if (TT->getDecl()->isInvalidDecl()) { 2290 Width = 8; 2291 Align = 8; 2292 break; 2293 } 2294 2295 if (const auto *ET = dyn_cast<EnumType>(TT)) { 2296 const EnumDecl *ED = ET->getDecl(); 2297 TypeInfo Info = 2298 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 2299 if (unsigned AttrAlign = ED->getMaxAlignment()) { 2300 Info.Align = AttrAlign; 2301 Info.AlignIsRequired = true; 2302 } 2303 return Info; 2304 } 2305 2306 const auto *RT = cast<RecordType>(TT); 2307 const RecordDecl *RD = RT->getDecl(); 2308 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2309 Width = toBits(Layout.getSize()); 2310 Align = toBits(Layout.getAlignment()); 2311 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 2312 break; 2313 } 2314 2315 case Type::SubstTemplateTypeParm: 2316 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 2317 getReplacementType().getTypePtr()); 2318 2319 case Type::Auto: 2320 case Type::DeducedTemplateSpecialization: { 2321 const auto *A = cast<DeducedType>(T); 2322 assert(!A->getDeducedType().isNull() && 2323 "cannot request the size of an undeduced or dependent auto type"); 2324 return getTypeInfo(A->getDeducedType().getTypePtr()); 2325 } 2326 2327 case Type::Paren: 2328 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 2329 2330 case Type::MacroQualified: 2331 return getTypeInfo( 2332 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); 2333 2334 case Type::ObjCTypeParam: 2335 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2336 2337 case Type::Typedef: { 2338 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2339 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2340 // If the typedef has an aligned attribute on it, it overrides any computed 2341 // alignment we have. This violates the GCC documentation (which says that 2342 // attribute(aligned) can only round up) but matches its implementation. 2343 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2344 Align = AttrAlign; 2345 AlignIsRequired = true; 2346 } else { 2347 Align = Info.Align; 2348 AlignIsRequired = Info.AlignIsRequired; 2349 } 2350 Width = Info.Width; 2351 break; 2352 } 2353 2354 case Type::Elaborated: 2355 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2356 2357 case Type::Attributed: 2358 return getTypeInfo( 2359 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2360 2361 case Type::Atomic: { 2362 // Start with the base type information. 2363 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2364 Width = Info.Width; 2365 Align = Info.Align; 2366 2367 if (!Width) { 2368 // An otherwise zero-sized type should still generate an 2369 // atomic operation. 2370 Width = Target->getCharWidth(); 2371 assert(Align); 2372 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2373 // If the size of the type doesn't exceed the platform's max 2374 // atomic promotion width, make the size and alignment more 2375 // favorable to atomic operations: 2376 2377 // Round the size up to a power of 2. 2378 if (!llvm::isPowerOf2_64(Width)) 2379 Width = llvm::NextPowerOf2(Width); 2380 2381 // Set the alignment equal to the size. 2382 Align = static_cast<unsigned>(Width); 2383 } 2384 } 2385 break; 2386 2387 case Type::Pipe: 2388 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2389 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2390 break; 2391 } 2392 2393 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2394 return TypeInfo(Width, Align, AlignIsRequired); 2395 } 2396 2397 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2398 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2399 if (I != MemoizedUnadjustedAlign.end()) 2400 return I->second; 2401 2402 unsigned UnadjustedAlign; 2403 if (const auto *RT = T->getAs<RecordType>()) { 2404 const RecordDecl *RD = RT->getDecl(); 2405 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2406 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2407 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2408 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2409 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2410 } else { 2411 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); 2412 } 2413 2414 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2415 return UnadjustedAlign; 2416 } 2417 2418 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2419 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2420 return SimdAlign; 2421 } 2422 2423 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2424 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2425 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2426 } 2427 2428 /// toBits - Convert a size in characters to a size in characters. 2429 int64_t ASTContext::toBits(CharUnits CharSize) const { 2430 return CharSize.getQuantity() * getCharWidth(); 2431 } 2432 2433 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2434 /// This method does not work on incomplete types. 2435 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2436 return getTypeInfoInChars(T).Width; 2437 } 2438 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2439 return getTypeInfoInChars(T).Width; 2440 } 2441 2442 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2443 /// characters. This method does not work on incomplete types. 2444 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2445 return toCharUnitsFromBits(getTypeAlign(T)); 2446 } 2447 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2448 return toCharUnitsFromBits(getTypeAlign(T)); 2449 } 2450 2451 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2452 /// type, in characters, before alignment adustments. This method does 2453 /// not work on incomplete types. 2454 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2455 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2456 } 2457 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2458 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2459 } 2460 2461 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2462 /// type for the current target in bits. This can be different than the ABI 2463 /// alignment in cases where it is beneficial for performance or backwards 2464 /// compatibility preserving to overalign a data type. (Note: despite the name, 2465 /// the preferred alignment is ABI-impacting, and not an optimization.) 2466 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2467 TypeInfo TI = getTypeInfo(T); 2468 unsigned ABIAlign = TI.Align; 2469 2470 T = T->getBaseElementTypeUnsafe(); 2471 2472 // The preferred alignment of member pointers is that of a pointer. 2473 if (T->isMemberPointerType()) 2474 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2475 2476 if (!Target->allowsLargerPreferedTypeAlignment()) 2477 return ABIAlign; 2478 2479 if (const auto *RT = T->getAs<RecordType>()) { 2480 const RecordDecl *RD = RT->getDecl(); 2481 2482 // When used as part of a typedef, or together with a 'packed' attribute, 2483 // the 'aligned' attribute can be used to decrease alignment. 2484 if ((TI.AlignIsRequired && T->getAs<TypedefType>() != nullptr) || 2485 RD->isInvalidDecl()) 2486 return ABIAlign; 2487 2488 unsigned PreferredAlign = static_cast<unsigned>( 2489 toBits(getASTRecordLayout(RD).PreferredAlignment)); 2490 assert(PreferredAlign >= ABIAlign && 2491 "PreferredAlign should be at least as large as ABIAlign."); 2492 return PreferredAlign; 2493 } 2494 2495 // Double (and, for targets supporting AIX `power` alignment, long double) and 2496 // long long should be naturally aligned (despite requiring less alignment) if 2497 // possible. 2498 if (const auto *CT = T->getAs<ComplexType>()) 2499 T = CT->getElementType().getTypePtr(); 2500 if (const auto *ET = T->getAs<EnumType>()) 2501 T = ET->getDecl()->getIntegerType().getTypePtr(); 2502 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2503 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2504 T->isSpecificBuiltinType(BuiltinType::ULongLong) || 2505 (T->isSpecificBuiltinType(BuiltinType::LongDouble) && 2506 Target->defaultsToAIXPowerAlignment())) 2507 // Don't increase the alignment if an alignment attribute was specified on a 2508 // typedef declaration. 2509 if (!TI.AlignIsRequired) 2510 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2511 2512 return ABIAlign; 2513 } 2514 2515 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2516 /// for __attribute__((aligned)) on this target, to be used if no alignment 2517 /// value is specified. 2518 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2519 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2520 } 2521 2522 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2523 /// to a global variable of the specified type. 2524 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2525 uint64_t TypeSize = getTypeSize(T.getTypePtr()); 2526 return std::max(getPreferredTypeAlign(T), 2527 getTargetInfo().getMinGlobalAlign(TypeSize)); 2528 } 2529 2530 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2531 /// should be given to a global variable of the specified type. 2532 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2533 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2534 } 2535 2536 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2537 CharUnits Offset = CharUnits::Zero(); 2538 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2539 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2540 Offset += Layout->getBaseClassOffset(Base); 2541 Layout = &getASTRecordLayout(Base); 2542 } 2543 return Offset; 2544 } 2545 2546 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { 2547 const ValueDecl *MPD = MP.getMemberPointerDecl(); 2548 CharUnits ThisAdjustment = CharUnits::Zero(); 2549 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath(); 2550 bool DerivedMember = MP.isMemberPointerToDerivedMember(); 2551 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext()); 2552 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 2553 const CXXRecordDecl *Base = RD; 2554 const CXXRecordDecl *Derived = Path[I]; 2555 if (DerivedMember) 2556 std::swap(Base, Derived); 2557 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); 2558 RD = Path[I]; 2559 } 2560 if (DerivedMember) 2561 ThisAdjustment = -ThisAdjustment; 2562 return ThisAdjustment; 2563 } 2564 2565 /// DeepCollectObjCIvars - 2566 /// This routine first collects all declared, but not synthesized, ivars in 2567 /// super class and then collects all ivars, including those synthesized for 2568 /// current class. This routine is used for implementation of current class 2569 /// when all ivars, declared and synthesized are known. 2570 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2571 bool leafClass, 2572 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2573 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2574 DeepCollectObjCIvars(SuperClass, false, Ivars); 2575 if (!leafClass) { 2576 for (const auto *I : OI->ivars()) 2577 Ivars.push_back(I); 2578 } else { 2579 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2580 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2581 Iv= Iv->getNextIvar()) 2582 Ivars.push_back(Iv); 2583 } 2584 } 2585 2586 /// CollectInheritedProtocols - Collect all protocols in current class and 2587 /// those inherited by it. 2588 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2589 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2590 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2591 // We can use protocol_iterator here instead of 2592 // all_referenced_protocol_iterator since we are walking all categories. 2593 for (auto *Proto : OI->all_referenced_protocols()) { 2594 CollectInheritedProtocols(Proto, Protocols); 2595 } 2596 2597 // Categories of this Interface. 2598 for (const auto *Cat : OI->visible_categories()) 2599 CollectInheritedProtocols(Cat, Protocols); 2600 2601 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2602 while (SD) { 2603 CollectInheritedProtocols(SD, Protocols); 2604 SD = SD->getSuperClass(); 2605 } 2606 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2607 for (auto *Proto : OC->protocols()) { 2608 CollectInheritedProtocols(Proto, Protocols); 2609 } 2610 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2611 // Insert the protocol. 2612 if (!Protocols.insert( 2613 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2614 return; 2615 2616 for (auto *Proto : OP->protocols()) 2617 CollectInheritedProtocols(Proto, Protocols); 2618 } 2619 } 2620 2621 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2622 const RecordDecl *RD) { 2623 assert(RD->isUnion() && "Must be union type"); 2624 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2625 2626 for (const auto *Field : RD->fields()) { 2627 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2628 return false; 2629 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2630 if (FieldSize != UnionSize) 2631 return false; 2632 } 2633 return !RD->field_empty(); 2634 } 2635 2636 static bool isStructEmpty(QualType Ty) { 2637 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2638 2639 if (!RD->field_empty()) 2640 return false; 2641 2642 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2643 return ClassDecl->isEmpty(); 2644 2645 return true; 2646 } 2647 2648 static llvm::Optional<int64_t> 2649 structHasUniqueObjectRepresentations(const ASTContext &Context, 2650 const RecordDecl *RD) { 2651 assert(!RD->isUnion() && "Must be struct/class type"); 2652 const auto &Layout = Context.getASTRecordLayout(RD); 2653 2654 int64_t CurOffsetInBits = 0; 2655 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2656 if (ClassDecl->isDynamicClass()) 2657 return llvm::None; 2658 2659 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2660 for (const auto &Base : ClassDecl->bases()) { 2661 // Empty types can be inherited from, and non-empty types can potentially 2662 // have tail padding, so just make sure there isn't an error. 2663 if (!isStructEmpty(Base.getType())) { 2664 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2665 Context, Base.getType()->castAs<RecordType>()->getDecl()); 2666 if (!Size) 2667 return llvm::None; 2668 Bases.emplace_back(Base.getType(), Size.getValue()); 2669 } 2670 } 2671 2672 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, 2673 const std::pair<QualType, int64_t> &R) { 2674 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2675 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2676 }); 2677 2678 for (const auto &Base : Bases) { 2679 int64_t BaseOffset = Context.toBits( 2680 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2681 int64_t BaseSize = Base.second; 2682 if (BaseOffset != CurOffsetInBits) 2683 return llvm::None; 2684 CurOffsetInBits = BaseOffset + BaseSize; 2685 } 2686 } 2687 2688 for (const auto *Field : RD->fields()) { 2689 if (!Field->getType()->isReferenceType() && 2690 !Context.hasUniqueObjectRepresentations(Field->getType())) 2691 return llvm::None; 2692 2693 int64_t FieldSizeInBits = 2694 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2695 if (Field->isBitField()) { 2696 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2697 2698 if (BitfieldSize > FieldSizeInBits) 2699 return llvm::None; 2700 FieldSizeInBits = BitfieldSize; 2701 } 2702 2703 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2704 2705 if (FieldOffsetInBits != CurOffsetInBits) 2706 return llvm::None; 2707 2708 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2709 } 2710 2711 return CurOffsetInBits; 2712 } 2713 2714 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2715 // C++17 [meta.unary.prop]: 2716 // The predicate condition for a template specialization 2717 // has_unique_object_representations<T> shall be 2718 // satisfied if and only if: 2719 // (9.1) - T is trivially copyable, and 2720 // (9.2) - any two objects of type T with the same value have the same 2721 // object representation, where two objects 2722 // of array or non-union class type are considered to have the same value 2723 // if their respective sequences of 2724 // direct subobjects have the same values, and two objects of union type 2725 // are considered to have the same 2726 // value if they have the same active member and the corresponding members 2727 // have the same value. 2728 // The set of scalar types for which this condition holds is 2729 // implementation-defined. [ Note: If a type has padding 2730 // bits, the condition does not hold; otherwise, the condition holds true 2731 // for unsigned integral types. -- end note ] 2732 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2733 2734 // Arrays are unique only if their element type is unique. 2735 if (Ty->isArrayType()) 2736 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2737 2738 // (9.1) - T is trivially copyable... 2739 if (!Ty.isTriviallyCopyableType(*this)) 2740 return false; 2741 2742 // All integrals and enums are unique. 2743 if (Ty->isIntegralOrEnumerationType()) 2744 return true; 2745 2746 // All other pointers are unique. 2747 if (Ty->isPointerType()) 2748 return true; 2749 2750 if (Ty->isMemberPointerType()) { 2751 const auto *MPT = Ty->getAs<MemberPointerType>(); 2752 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2753 } 2754 2755 if (Ty->isRecordType()) { 2756 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); 2757 2758 if (Record->isInvalidDecl()) 2759 return false; 2760 2761 if (Record->isUnion()) 2762 return unionHasUniqueObjectRepresentations(*this, Record); 2763 2764 Optional<int64_t> StructSize = 2765 structHasUniqueObjectRepresentations(*this, Record); 2766 2767 return StructSize && 2768 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2769 } 2770 2771 // FIXME: More cases to handle here (list by rsmith): 2772 // vectors (careful about, eg, vector of 3 foo) 2773 // _Complex int and friends 2774 // _Atomic T 2775 // Obj-C block pointers 2776 // Obj-C object pointers 2777 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2778 // clk_event_t, queue_t, reserve_id_t) 2779 // There're also Obj-C class types and the Obj-C selector type, but I think it 2780 // makes sense for those to return false here. 2781 2782 return false; 2783 } 2784 2785 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2786 unsigned count = 0; 2787 // Count ivars declared in class extension. 2788 for (const auto *Ext : OI->known_extensions()) 2789 count += Ext->ivar_size(); 2790 2791 // Count ivar defined in this class's implementation. This 2792 // includes synthesized ivars. 2793 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2794 count += ImplDecl->ivar_size(); 2795 2796 return count; 2797 } 2798 2799 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2800 if (!E) 2801 return false; 2802 2803 // nullptr_t is always treated as null. 2804 if (E->getType()->isNullPtrType()) return true; 2805 2806 if (E->getType()->isAnyPointerType() && 2807 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2808 Expr::NPC_ValueDependentIsNull)) 2809 return true; 2810 2811 // Unfortunately, __null has type 'int'. 2812 if (isa<GNUNullExpr>(E)) return true; 2813 2814 return false; 2815 } 2816 2817 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2818 /// exists. 2819 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2820 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2821 I = ObjCImpls.find(D); 2822 if (I != ObjCImpls.end()) 2823 return cast<ObjCImplementationDecl>(I->second); 2824 return nullptr; 2825 } 2826 2827 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2828 /// exists. 2829 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2830 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2831 I = ObjCImpls.find(D); 2832 if (I != ObjCImpls.end()) 2833 return cast<ObjCCategoryImplDecl>(I->second); 2834 return nullptr; 2835 } 2836 2837 /// Set the implementation of ObjCInterfaceDecl. 2838 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2839 ObjCImplementationDecl *ImplD) { 2840 assert(IFaceD && ImplD && "Passed null params"); 2841 ObjCImpls[IFaceD] = ImplD; 2842 } 2843 2844 /// Set the implementation of ObjCCategoryDecl. 2845 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2846 ObjCCategoryImplDecl *ImplD) { 2847 assert(CatD && ImplD && "Passed null params"); 2848 ObjCImpls[CatD] = ImplD; 2849 } 2850 2851 const ObjCMethodDecl * 2852 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2853 return ObjCMethodRedecls.lookup(MD); 2854 } 2855 2856 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2857 const ObjCMethodDecl *Redecl) { 2858 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2859 ObjCMethodRedecls[MD] = Redecl; 2860 } 2861 2862 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2863 const NamedDecl *ND) const { 2864 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2865 return ID; 2866 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2867 return CD->getClassInterface(); 2868 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2869 return IMD->getClassInterface(); 2870 2871 return nullptr; 2872 } 2873 2874 /// Get the copy initialization expression of VarDecl, or nullptr if 2875 /// none exists. 2876 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { 2877 assert(VD && "Passed null params"); 2878 assert(VD->hasAttr<BlocksAttr>() && 2879 "getBlockVarCopyInits - not __block var"); 2880 auto I = BlockVarCopyInits.find(VD); 2881 if (I != BlockVarCopyInits.end()) 2882 return I->second; 2883 return {nullptr, false}; 2884 } 2885 2886 /// Set the copy initialization expression of a block var decl. 2887 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2888 bool CanThrow) { 2889 assert(VD && CopyExpr && "Passed null params"); 2890 assert(VD->hasAttr<BlocksAttr>() && 2891 "setBlockVarCopyInits - not __block var"); 2892 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2893 } 2894 2895 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2896 unsigned DataSize) const { 2897 if (!DataSize) 2898 DataSize = TypeLoc::getFullDataSizeForType(T); 2899 else 2900 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2901 "incorrect data size provided to CreateTypeSourceInfo!"); 2902 2903 auto *TInfo = 2904 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2905 new (TInfo) TypeSourceInfo(T); 2906 return TInfo; 2907 } 2908 2909 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2910 SourceLocation L) const { 2911 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2912 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2913 return DI; 2914 } 2915 2916 const ASTRecordLayout & 2917 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2918 return getObjCLayout(D, nullptr); 2919 } 2920 2921 const ASTRecordLayout & 2922 ASTContext::getASTObjCImplementationLayout( 2923 const ObjCImplementationDecl *D) const { 2924 return getObjCLayout(D->getClassInterface(), D); 2925 } 2926 2927 //===----------------------------------------------------------------------===// 2928 // Type creation/memoization methods 2929 //===----------------------------------------------------------------------===// 2930 2931 QualType 2932 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2933 unsigned fastQuals = quals.getFastQualifiers(); 2934 quals.removeFastQualifiers(); 2935 2936 // Check if we've already instantiated this type. 2937 llvm::FoldingSetNodeID ID; 2938 ExtQuals::Profile(ID, baseType, quals); 2939 void *insertPos = nullptr; 2940 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2941 assert(eq->getQualifiers() == quals); 2942 return QualType(eq, fastQuals); 2943 } 2944 2945 // If the base type is not canonical, make the appropriate canonical type. 2946 QualType canon; 2947 if (!baseType->isCanonicalUnqualified()) { 2948 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2949 canonSplit.Quals.addConsistentQualifiers(quals); 2950 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2951 2952 // Re-find the insert position. 2953 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2954 } 2955 2956 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2957 ExtQualNodes.InsertNode(eq, insertPos); 2958 return QualType(eq, fastQuals); 2959 } 2960 2961 QualType ASTContext::getAddrSpaceQualType(QualType T, 2962 LangAS AddressSpace) const { 2963 QualType CanT = getCanonicalType(T); 2964 if (CanT.getAddressSpace() == AddressSpace) 2965 return T; 2966 2967 // If we are composing extended qualifiers together, merge together 2968 // into one ExtQuals node. 2969 QualifierCollector Quals; 2970 const Type *TypeNode = Quals.strip(T); 2971 2972 // If this type already has an address space specified, it cannot get 2973 // another one. 2974 assert(!Quals.hasAddressSpace() && 2975 "Type cannot be in multiple addr spaces!"); 2976 Quals.addAddressSpace(AddressSpace); 2977 2978 return getExtQualType(TypeNode, Quals); 2979 } 2980 2981 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2982 // If the type is not qualified with an address space, just return it 2983 // immediately. 2984 if (!T.hasAddressSpace()) 2985 return T; 2986 2987 // If we are composing extended qualifiers together, merge together 2988 // into one ExtQuals node. 2989 QualifierCollector Quals; 2990 const Type *TypeNode; 2991 2992 while (T.hasAddressSpace()) { 2993 TypeNode = Quals.strip(T); 2994 2995 // If the type no longer has an address space after stripping qualifiers, 2996 // jump out. 2997 if (!QualType(TypeNode, 0).hasAddressSpace()) 2998 break; 2999 3000 // There might be sugar in the way. Strip it and try again. 3001 T = T.getSingleStepDesugaredType(*this); 3002 } 3003 3004 Quals.removeAddressSpace(); 3005 3006 // Removal of the address space can mean there are no longer any 3007 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 3008 // or required. 3009 if (Quals.hasNonFastQualifiers()) 3010 return getExtQualType(TypeNode, Quals); 3011 else 3012 return QualType(TypeNode, Quals.getFastQualifiers()); 3013 } 3014 3015 QualType ASTContext::getObjCGCQualType(QualType T, 3016 Qualifiers::GC GCAttr) const { 3017 QualType CanT = getCanonicalType(T); 3018 if (CanT.getObjCGCAttr() == GCAttr) 3019 return T; 3020 3021 if (const auto *ptr = T->getAs<PointerType>()) { 3022 QualType Pointee = ptr->getPointeeType(); 3023 if (Pointee->isAnyPointerType()) { 3024 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 3025 return getPointerType(ResultType); 3026 } 3027 } 3028 3029 // If we are composing extended qualifiers together, merge together 3030 // into one ExtQuals node. 3031 QualifierCollector Quals; 3032 const Type *TypeNode = Quals.strip(T); 3033 3034 // If this type already has an ObjCGC specified, it cannot get 3035 // another one. 3036 assert(!Quals.hasObjCGCAttr() && 3037 "Type cannot have multiple ObjCGCs!"); 3038 Quals.addObjCGCAttr(GCAttr); 3039 3040 return getExtQualType(TypeNode, Quals); 3041 } 3042 3043 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { 3044 if (const PointerType *Ptr = T->getAs<PointerType>()) { 3045 QualType Pointee = Ptr->getPointeeType(); 3046 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { 3047 return getPointerType(removeAddrSpaceQualType(Pointee)); 3048 } 3049 } 3050 return T; 3051 } 3052 3053 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 3054 FunctionType::ExtInfo Info) { 3055 if (T->getExtInfo() == Info) 3056 return T; 3057 3058 QualType Result; 3059 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 3060 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 3061 } else { 3062 const auto *FPT = cast<FunctionProtoType>(T); 3063 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3064 EPI.ExtInfo = Info; 3065 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 3066 } 3067 3068 return cast<FunctionType>(Result.getTypePtr()); 3069 } 3070 3071 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 3072 QualType ResultType) { 3073 FD = FD->getMostRecentDecl(); 3074 while (true) { 3075 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3076 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3077 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 3078 if (FunctionDecl *Next = FD->getPreviousDecl()) 3079 FD = Next; 3080 else 3081 break; 3082 } 3083 if (ASTMutationListener *L = getASTMutationListener()) 3084 L->DeducedReturnType(FD, ResultType); 3085 } 3086 3087 /// Get a function type and produce the equivalent function type with the 3088 /// specified exception specification. Type sugar that can be present on a 3089 /// declaration of a function with an exception specification is permitted 3090 /// and preserved. Other type sugar (for instance, typedefs) is not. 3091 QualType ASTContext::getFunctionTypeWithExceptionSpec( 3092 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 3093 // Might have some parens. 3094 if (const auto *PT = dyn_cast<ParenType>(Orig)) 3095 return getParenType( 3096 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 3097 3098 // Might be wrapped in a macro qualified type. 3099 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) 3100 return getMacroQualifiedType( 3101 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), 3102 MQT->getMacroIdentifier()); 3103 3104 // Might have a calling-convention attribute. 3105 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 3106 return getAttributedType( 3107 AT->getAttrKind(), 3108 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 3109 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 3110 3111 // Anything else must be a function type. Rebuild it with the new exception 3112 // specification. 3113 const auto *Proto = Orig->castAs<FunctionProtoType>(); 3114 return getFunctionType( 3115 Proto->getReturnType(), Proto->getParamTypes(), 3116 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 3117 } 3118 3119 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 3120 QualType U) { 3121 return hasSameType(T, U) || 3122 (getLangOpts().CPlusPlus17 && 3123 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 3124 getFunctionTypeWithExceptionSpec(U, EST_None))); 3125 } 3126 3127 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { 3128 if (const auto *Proto = T->getAs<FunctionProtoType>()) { 3129 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3130 SmallVector<QualType, 16> Args(Proto->param_types()); 3131 for (unsigned i = 0, n = Args.size(); i != n; ++i) 3132 Args[i] = removePtrSizeAddrSpace(Args[i]); 3133 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); 3134 } 3135 3136 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { 3137 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); 3138 return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); 3139 } 3140 3141 return T; 3142 } 3143 3144 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { 3145 return hasSameType(T, U) || 3146 hasSameType(getFunctionTypeWithoutPtrSizes(T), 3147 getFunctionTypeWithoutPtrSizes(U)); 3148 } 3149 3150 void ASTContext::adjustExceptionSpec( 3151 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 3152 bool AsWritten) { 3153 // Update the type. 3154 QualType Updated = 3155 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 3156 FD->setType(Updated); 3157 3158 if (!AsWritten) 3159 return; 3160 3161 // Update the type in the type source information too. 3162 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 3163 // If the type and the type-as-written differ, we may need to update 3164 // the type-as-written too. 3165 if (TSInfo->getType() != FD->getType()) 3166 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 3167 3168 // FIXME: When we get proper type location information for exceptions, 3169 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 3170 // up the TypeSourceInfo; 3171 assert(TypeLoc::getFullDataSizeForType(Updated) == 3172 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 3173 "TypeLoc size mismatch from updating exception specification"); 3174 TSInfo->overrideType(Updated); 3175 } 3176 } 3177 3178 /// getComplexType - Return the uniqued reference to the type for a complex 3179 /// number with the specified element type. 3180 QualType ASTContext::getComplexType(QualType T) const { 3181 // Unique pointers, to guarantee there is only one pointer of a particular 3182 // structure. 3183 llvm::FoldingSetNodeID ID; 3184 ComplexType::Profile(ID, T); 3185 3186 void *InsertPos = nullptr; 3187 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 3188 return QualType(CT, 0); 3189 3190 // If the pointee type isn't canonical, this won't be a canonical type either, 3191 // so fill in the canonical type field. 3192 QualType Canonical; 3193 if (!T.isCanonical()) { 3194 Canonical = getComplexType(getCanonicalType(T)); 3195 3196 // Get the new insert position for the node we care about. 3197 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 3198 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3199 } 3200 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 3201 Types.push_back(New); 3202 ComplexTypes.InsertNode(New, InsertPos); 3203 return QualType(New, 0); 3204 } 3205 3206 /// getPointerType - Return the uniqued reference to the type for a pointer to 3207 /// the specified type. 3208 QualType ASTContext::getPointerType(QualType T) const { 3209 // Unique pointers, to guarantee there is only one pointer of a particular 3210 // structure. 3211 llvm::FoldingSetNodeID ID; 3212 PointerType::Profile(ID, T); 3213 3214 void *InsertPos = nullptr; 3215 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3216 return QualType(PT, 0); 3217 3218 // If the pointee type isn't canonical, this won't be a canonical type either, 3219 // so fill in the canonical type field. 3220 QualType Canonical; 3221 if (!T.isCanonical()) { 3222 Canonical = getPointerType(getCanonicalType(T)); 3223 3224 // Get the new insert position for the node we care about. 3225 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3226 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3227 } 3228 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 3229 Types.push_back(New); 3230 PointerTypes.InsertNode(New, InsertPos); 3231 return QualType(New, 0); 3232 } 3233 3234 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 3235 llvm::FoldingSetNodeID ID; 3236 AdjustedType::Profile(ID, Orig, New); 3237 void *InsertPos = nullptr; 3238 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3239 if (AT) 3240 return QualType(AT, 0); 3241 3242 QualType Canonical = getCanonicalType(New); 3243 3244 // Get the new insert position for the node we care about. 3245 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3246 assert(!AT && "Shouldn't be in the map!"); 3247 3248 AT = new (*this, TypeAlignment) 3249 AdjustedType(Type::Adjusted, Orig, New, Canonical); 3250 Types.push_back(AT); 3251 AdjustedTypes.InsertNode(AT, InsertPos); 3252 return QualType(AT, 0); 3253 } 3254 3255 QualType ASTContext::getDecayedType(QualType T) const { 3256 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 3257 3258 QualType Decayed; 3259 3260 // C99 6.7.5.3p7: 3261 // A declaration of a parameter as "array of type" shall be 3262 // adjusted to "qualified pointer to type", where the type 3263 // qualifiers (if any) are those specified within the [ and ] of 3264 // the array type derivation. 3265 if (T->isArrayType()) 3266 Decayed = getArrayDecayedType(T); 3267 3268 // C99 6.7.5.3p8: 3269 // A declaration of a parameter as "function returning type" 3270 // shall be adjusted to "pointer to function returning type", as 3271 // in 6.3.2.1. 3272 if (T->isFunctionType()) 3273 Decayed = getPointerType(T); 3274 3275 llvm::FoldingSetNodeID ID; 3276 AdjustedType::Profile(ID, T, Decayed); 3277 void *InsertPos = nullptr; 3278 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3279 if (AT) 3280 return QualType(AT, 0); 3281 3282 QualType Canonical = getCanonicalType(Decayed); 3283 3284 // Get the new insert position for the node we care about. 3285 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 3286 assert(!AT && "Shouldn't be in the map!"); 3287 3288 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 3289 Types.push_back(AT); 3290 AdjustedTypes.InsertNode(AT, InsertPos); 3291 return QualType(AT, 0); 3292 } 3293 3294 /// getBlockPointerType - Return the uniqued reference to the type for 3295 /// a pointer to the specified block. 3296 QualType ASTContext::getBlockPointerType(QualType T) const { 3297 assert(T->isFunctionType() && "block of function types only"); 3298 // Unique pointers, to guarantee there is only one block of a particular 3299 // structure. 3300 llvm::FoldingSetNodeID ID; 3301 BlockPointerType::Profile(ID, T); 3302 3303 void *InsertPos = nullptr; 3304 if (BlockPointerType *PT = 3305 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3306 return QualType(PT, 0); 3307 3308 // If the block pointee type isn't canonical, this won't be a canonical 3309 // type either so fill in the canonical type field. 3310 QualType Canonical; 3311 if (!T.isCanonical()) { 3312 Canonical = getBlockPointerType(getCanonicalType(T)); 3313 3314 // Get the new insert position for the node we care about. 3315 BlockPointerType *NewIP = 3316 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3317 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3318 } 3319 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 3320 Types.push_back(New); 3321 BlockPointerTypes.InsertNode(New, InsertPos); 3322 return QualType(New, 0); 3323 } 3324 3325 /// getLValueReferenceType - Return the uniqued reference to the type for an 3326 /// lvalue reference to the specified type. 3327 QualType 3328 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 3329 assert(getCanonicalType(T) != OverloadTy && 3330 "Unresolved overloaded function type"); 3331 3332 // Unique pointers, to guarantee there is only one pointer of a particular 3333 // structure. 3334 llvm::FoldingSetNodeID ID; 3335 ReferenceType::Profile(ID, T, SpelledAsLValue); 3336 3337 void *InsertPos = nullptr; 3338 if (LValueReferenceType *RT = 3339 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3340 return QualType(RT, 0); 3341 3342 const auto *InnerRef = T->getAs<ReferenceType>(); 3343 3344 // If the referencee type isn't canonical, this won't be a canonical type 3345 // either, so fill in the canonical type field. 3346 QualType Canonical; 3347 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 3348 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3349 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 3350 3351 // Get the new insert position for the node we care about. 3352 LValueReferenceType *NewIP = 3353 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3354 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3355 } 3356 3357 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 3358 SpelledAsLValue); 3359 Types.push_back(New); 3360 LValueReferenceTypes.InsertNode(New, InsertPos); 3361 3362 return QualType(New, 0); 3363 } 3364 3365 /// getRValueReferenceType - Return the uniqued reference to the type for an 3366 /// rvalue reference to the specified type. 3367 QualType ASTContext::getRValueReferenceType(QualType T) const { 3368 // Unique pointers, to guarantee there is only one pointer of a particular 3369 // structure. 3370 llvm::FoldingSetNodeID ID; 3371 ReferenceType::Profile(ID, T, false); 3372 3373 void *InsertPos = nullptr; 3374 if (RValueReferenceType *RT = 3375 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 3376 return QualType(RT, 0); 3377 3378 const auto *InnerRef = T->getAs<ReferenceType>(); 3379 3380 // If the referencee type isn't canonical, this won't be a canonical type 3381 // either, so fill in the canonical type field. 3382 QualType Canonical; 3383 if (InnerRef || !T.isCanonical()) { 3384 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 3385 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 3386 3387 // Get the new insert position for the node we care about. 3388 RValueReferenceType *NewIP = 3389 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 3390 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3391 } 3392 3393 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 3394 Types.push_back(New); 3395 RValueReferenceTypes.InsertNode(New, InsertPos); 3396 return QualType(New, 0); 3397 } 3398 3399 /// getMemberPointerType - Return the uniqued reference to the type for a 3400 /// member pointer to the specified type, in the specified class. 3401 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 3402 // Unique pointers, to guarantee there is only one pointer of a particular 3403 // structure. 3404 llvm::FoldingSetNodeID ID; 3405 MemberPointerType::Profile(ID, T, Cls); 3406 3407 void *InsertPos = nullptr; 3408 if (MemberPointerType *PT = 3409 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3410 return QualType(PT, 0); 3411 3412 // If the pointee or class type isn't canonical, this won't be a canonical 3413 // type either, so fill in the canonical type field. 3414 QualType Canonical; 3415 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 3416 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 3417 3418 // Get the new insert position for the node we care about. 3419 MemberPointerType *NewIP = 3420 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3421 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3422 } 3423 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3424 Types.push_back(New); 3425 MemberPointerTypes.InsertNode(New, InsertPos); 3426 return QualType(New, 0); 3427 } 3428 3429 /// getConstantArrayType - Return the unique reference to the type for an 3430 /// array of the specified element type. 3431 QualType ASTContext::getConstantArrayType(QualType EltTy, 3432 const llvm::APInt &ArySizeIn, 3433 const Expr *SizeExpr, 3434 ArrayType::ArraySizeModifier ASM, 3435 unsigned IndexTypeQuals) const { 3436 assert((EltTy->isDependentType() || 3437 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3438 "Constant array of VLAs is illegal!"); 3439 3440 // We only need the size as part of the type if it's instantiation-dependent. 3441 if (SizeExpr && !SizeExpr->isInstantiationDependent()) 3442 SizeExpr = nullptr; 3443 3444 // Convert the array size into a canonical width matching the pointer size for 3445 // the target. 3446 llvm::APInt ArySize(ArySizeIn); 3447 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3448 3449 llvm::FoldingSetNodeID ID; 3450 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, 3451 IndexTypeQuals); 3452 3453 void *InsertPos = nullptr; 3454 if (ConstantArrayType *ATP = 3455 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3456 return QualType(ATP, 0); 3457 3458 // If the element type isn't canonical or has qualifiers, or the array bound 3459 // is instantiation-dependent, this won't be a canonical type either, so fill 3460 // in the canonical type field. 3461 QualType Canon; 3462 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { 3463 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3464 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, 3465 ASM, IndexTypeQuals); 3466 Canon = getQualifiedType(Canon, canonSplit.Quals); 3467 3468 // Get the new insert position for the node we care about. 3469 ConstantArrayType *NewIP = 3470 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3471 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3472 } 3473 3474 void *Mem = Allocate( 3475 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), 3476 TypeAlignment); 3477 auto *New = new (Mem) 3478 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); 3479 ConstantArrayTypes.InsertNode(New, InsertPos); 3480 Types.push_back(New); 3481 return QualType(New, 0); 3482 } 3483 3484 /// getVariableArrayDecayedType - Turns the given type, which may be 3485 /// variably-modified, into the corresponding type with all the known 3486 /// sizes replaced with [*]. 3487 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3488 // Vastly most common case. 3489 if (!type->isVariablyModifiedType()) return type; 3490 3491 QualType result; 3492 3493 SplitQualType split = type.getSplitDesugaredType(); 3494 const Type *ty = split.Ty; 3495 switch (ty->getTypeClass()) { 3496 #define TYPE(Class, Base) 3497 #define ABSTRACT_TYPE(Class, Base) 3498 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3499 #include "clang/AST/TypeNodes.inc" 3500 llvm_unreachable("didn't desugar past all non-canonical types?"); 3501 3502 // These types should never be variably-modified. 3503 case Type::Builtin: 3504 case Type::Complex: 3505 case Type::Vector: 3506 case Type::DependentVector: 3507 case Type::ExtVector: 3508 case Type::DependentSizedExtVector: 3509 case Type::ConstantMatrix: 3510 case Type::DependentSizedMatrix: 3511 case Type::DependentAddressSpace: 3512 case Type::ObjCObject: 3513 case Type::ObjCInterface: 3514 case Type::ObjCObjectPointer: 3515 case Type::Record: 3516 case Type::Enum: 3517 case Type::UnresolvedUsing: 3518 case Type::TypeOfExpr: 3519 case Type::TypeOf: 3520 case Type::Decltype: 3521 case Type::UnaryTransform: 3522 case Type::DependentName: 3523 case Type::InjectedClassName: 3524 case Type::TemplateSpecialization: 3525 case Type::DependentTemplateSpecialization: 3526 case Type::TemplateTypeParm: 3527 case Type::SubstTemplateTypeParmPack: 3528 case Type::Auto: 3529 case Type::DeducedTemplateSpecialization: 3530 case Type::PackExpansion: 3531 case Type::ExtInt: 3532 case Type::DependentExtInt: 3533 llvm_unreachable("type should never be variably-modified"); 3534 3535 // These types can be variably-modified but should never need to 3536 // further decay. 3537 case Type::FunctionNoProto: 3538 case Type::FunctionProto: 3539 case Type::BlockPointer: 3540 case Type::MemberPointer: 3541 case Type::Pipe: 3542 return type; 3543 3544 // These types can be variably-modified. All these modifications 3545 // preserve structure except as noted by comments. 3546 // TODO: if we ever care about optimizing VLAs, there are no-op 3547 // optimizations available here. 3548 case Type::Pointer: 3549 result = getPointerType(getVariableArrayDecayedType( 3550 cast<PointerType>(ty)->getPointeeType())); 3551 break; 3552 3553 case Type::LValueReference: { 3554 const auto *lv = cast<LValueReferenceType>(ty); 3555 result = getLValueReferenceType( 3556 getVariableArrayDecayedType(lv->getPointeeType()), 3557 lv->isSpelledAsLValue()); 3558 break; 3559 } 3560 3561 case Type::RValueReference: { 3562 const auto *lv = cast<RValueReferenceType>(ty); 3563 result = getRValueReferenceType( 3564 getVariableArrayDecayedType(lv->getPointeeType())); 3565 break; 3566 } 3567 3568 case Type::Atomic: { 3569 const auto *at = cast<AtomicType>(ty); 3570 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3571 break; 3572 } 3573 3574 case Type::ConstantArray: { 3575 const auto *cat = cast<ConstantArrayType>(ty); 3576 result = getConstantArrayType( 3577 getVariableArrayDecayedType(cat->getElementType()), 3578 cat->getSize(), 3579 cat->getSizeExpr(), 3580 cat->getSizeModifier(), 3581 cat->getIndexTypeCVRQualifiers()); 3582 break; 3583 } 3584 3585 case Type::DependentSizedArray: { 3586 const auto *dat = cast<DependentSizedArrayType>(ty); 3587 result = getDependentSizedArrayType( 3588 getVariableArrayDecayedType(dat->getElementType()), 3589 dat->getSizeExpr(), 3590 dat->getSizeModifier(), 3591 dat->getIndexTypeCVRQualifiers(), 3592 dat->getBracketsRange()); 3593 break; 3594 } 3595 3596 // Turn incomplete types into [*] types. 3597 case Type::IncompleteArray: { 3598 const auto *iat = cast<IncompleteArrayType>(ty); 3599 result = getVariableArrayType( 3600 getVariableArrayDecayedType(iat->getElementType()), 3601 /*size*/ nullptr, 3602 ArrayType::Normal, 3603 iat->getIndexTypeCVRQualifiers(), 3604 SourceRange()); 3605 break; 3606 } 3607 3608 // Turn VLA types into [*] types. 3609 case Type::VariableArray: { 3610 const auto *vat = cast<VariableArrayType>(ty); 3611 result = getVariableArrayType( 3612 getVariableArrayDecayedType(vat->getElementType()), 3613 /*size*/ nullptr, 3614 ArrayType::Star, 3615 vat->getIndexTypeCVRQualifiers(), 3616 vat->getBracketsRange()); 3617 break; 3618 } 3619 } 3620 3621 // Apply the top-level qualifiers from the original. 3622 return getQualifiedType(result, split.Quals); 3623 } 3624 3625 /// getVariableArrayType - Returns a non-unique reference to the type for a 3626 /// variable array of the specified element type. 3627 QualType ASTContext::getVariableArrayType(QualType EltTy, 3628 Expr *NumElts, 3629 ArrayType::ArraySizeModifier ASM, 3630 unsigned IndexTypeQuals, 3631 SourceRange Brackets) const { 3632 // Since we don't unique expressions, it isn't possible to unique VLA's 3633 // that have an expression provided for their size. 3634 QualType Canon; 3635 3636 // Be sure to pull qualifiers off the element type. 3637 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3638 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3639 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3640 IndexTypeQuals, Brackets); 3641 Canon = getQualifiedType(Canon, canonSplit.Quals); 3642 } 3643 3644 auto *New = new (*this, TypeAlignment) 3645 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3646 3647 VariableArrayTypes.push_back(New); 3648 Types.push_back(New); 3649 return QualType(New, 0); 3650 } 3651 3652 /// getDependentSizedArrayType - Returns a non-unique reference to 3653 /// the type for a dependently-sized array of the specified element 3654 /// type. 3655 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3656 Expr *numElements, 3657 ArrayType::ArraySizeModifier ASM, 3658 unsigned elementTypeQuals, 3659 SourceRange brackets) const { 3660 assert((!numElements || numElements->isTypeDependent() || 3661 numElements->isValueDependent()) && 3662 "Size must be type- or value-dependent!"); 3663 3664 // Dependently-sized array types that do not have a specified number 3665 // of elements will have their sizes deduced from a dependent 3666 // initializer. We do no canonicalization here at all, which is okay 3667 // because they can't be used in most locations. 3668 if (!numElements) { 3669 auto *newType 3670 = new (*this, TypeAlignment) 3671 DependentSizedArrayType(*this, elementType, QualType(), 3672 numElements, ASM, elementTypeQuals, 3673 brackets); 3674 Types.push_back(newType); 3675 return QualType(newType, 0); 3676 } 3677 3678 // Otherwise, we actually build a new type every time, but we 3679 // also build a canonical type. 3680 3681 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3682 3683 void *insertPos = nullptr; 3684 llvm::FoldingSetNodeID ID; 3685 DependentSizedArrayType::Profile(ID, *this, 3686 QualType(canonElementType.Ty, 0), 3687 ASM, elementTypeQuals, numElements); 3688 3689 // Look for an existing type with these properties. 3690 DependentSizedArrayType *canonTy = 3691 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3692 3693 // If we don't have one, build one. 3694 if (!canonTy) { 3695 canonTy = new (*this, TypeAlignment) 3696 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3697 QualType(), numElements, ASM, elementTypeQuals, 3698 brackets); 3699 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3700 Types.push_back(canonTy); 3701 } 3702 3703 // Apply qualifiers from the element type to the array. 3704 QualType canon = getQualifiedType(QualType(canonTy,0), 3705 canonElementType.Quals); 3706 3707 // If we didn't need extra canonicalization for the element type or the size 3708 // expression, then just use that as our result. 3709 if (QualType(canonElementType.Ty, 0) == elementType && 3710 canonTy->getSizeExpr() == numElements) 3711 return canon; 3712 3713 // Otherwise, we need to build a type which follows the spelling 3714 // of the element type. 3715 auto *sugaredType 3716 = new (*this, TypeAlignment) 3717 DependentSizedArrayType(*this, elementType, canon, numElements, 3718 ASM, elementTypeQuals, brackets); 3719 Types.push_back(sugaredType); 3720 return QualType(sugaredType, 0); 3721 } 3722 3723 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3724 ArrayType::ArraySizeModifier ASM, 3725 unsigned elementTypeQuals) const { 3726 llvm::FoldingSetNodeID ID; 3727 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3728 3729 void *insertPos = nullptr; 3730 if (IncompleteArrayType *iat = 3731 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3732 return QualType(iat, 0); 3733 3734 // If the element type isn't canonical, this won't be a canonical type 3735 // either, so fill in the canonical type field. We also have to pull 3736 // qualifiers off the element type. 3737 QualType canon; 3738 3739 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3740 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3741 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3742 ASM, elementTypeQuals); 3743 canon = getQualifiedType(canon, canonSplit.Quals); 3744 3745 // Get the new insert position for the node we care about. 3746 IncompleteArrayType *existing = 3747 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3748 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3749 } 3750 3751 auto *newType = new (*this, TypeAlignment) 3752 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3753 3754 IncompleteArrayTypes.InsertNode(newType, insertPos); 3755 Types.push_back(newType); 3756 return QualType(newType, 0); 3757 } 3758 3759 ASTContext::BuiltinVectorTypeInfo 3760 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { 3761 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ 3762 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ 3763 NUMVECTORS}; 3764 3765 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \ 3766 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; 3767 3768 switch (Ty->getKind()) { 3769 default: 3770 llvm_unreachable("Unsupported builtin vector type"); 3771 case BuiltinType::SveInt8: 3772 return SVE_INT_ELTTY(8, 16, true, 1); 3773 case BuiltinType::SveUint8: 3774 return SVE_INT_ELTTY(8, 16, false, 1); 3775 case BuiltinType::SveInt8x2: 3776 return SVE_INT_ELTTY(8, 16, true, 2); 3777 case BuiltinType::SveUint8x2: 3778 return SVE_INT_ELTTY(8, 16, false, 2); 3779 case BuiltinType::SveInt8x3: 3780 return SVE_INT_ELTTY(8, 16, true, 3); 3781 case BuiltinType::SveUint8x3: 3782 return SVE_INT_ELTTY(8, 16, false, 3); 3783 case BuiltinType::SveInt8x4: 3784 return SVE_INT_ELTTY(8, 16, true, 4); 3785 case BuiltinType::SveUint8x4: 3786 return SVE_INT_ELTTY(8, 16, false, 4); 3787 case BuiltinType::SveInt16: 3788 return SVE_INT_ELTTY(16, 8, true, 1); 3789 case BuiltinType::SveUint16: 3790 return SVE_INT_ELTTY(16, 8, false, 1); 3791 case BuiltinType::SveInt16x2: 3792 return SVE_INT_ELTTY(16, 8, true, 2); 3793 case BuiltinType::SveUint16x2: 3794 return SVE_INT_ELTTY(16, 8, false, 2); 3795 case BuiltinType::SveInt16x3: 3796 return SVE_INT_ELTTY(16, 8, true, 3); 3797 case BuiltinType::SveUint16x3: 3798 return SVE_INT_ELTTY(16, 8, false, 3); 3799 case BuiltinType::SveInt16x4: 3800 return SVE_INT_ELTTY(16, 8, true, 4); 3801 case BuiltinType::SveUint16x4: 3802 return SVE_INT_ELTTY(16, 8, false, 4); 3803 case BuiltinType::SveInt32: 3804 return SVE_INT_ELTTY(32, 4, true, 1); 3805 case BuiltinType::SveUint32: 3806 return SVE_INT_ELTTY(32, 4, false, 1); 3807 case BuiltinType::SveInt32x2: 3808 return SVE_INT_ELTTY(32, 4, true, 2); 3809 case BuiltinType::SveUint32x2: 3810 return SVE_INT_ELTTY(32, 4, false, 2); 3811 case BuiltinType::SveInt32x3: 3812 return SVE_INT_ELTTY(32, 4, true, 3); 3813 case BuiltinType::SveUint32x3: 3814 return SVE_INT_ELTTY(32, 4, false, 3); 3815 case BuiltinType::SveInt32x4: 3816 return SVE_INT_ELTTY(32, 4, true, 4); 3817 case BuiltinType::SveUint32x4: 3818 return SVE_INT_ELTTY(32, 4, false, 4); 3819 case BuiltinType::SveInt64: 3820 return SVE_INT_ELTTY(64, 2, true, 1); 3821 case BuiltinType::SveUint64: 3822 return SVE_INT_ELTTY(64, 2, false, 1); 3823 case BuiltinType::SveInt64x2: 3824 return SVE_INT_ELTTY(64, 2, true, 2); 3825 case BuiltinType::SveUint64x2: 3826 return SVE_INT_ELTTY(64, 2, false, 2); 3827 case BuiltinType::SveInt64x3: 3828 return SVE_INT_ELTTY(64, 2, true, 3); 3829 case BuiltinType::SveUint64x3: 3830 return SVE_INT_ELTTY(64, 2, false, 3); 3831 case BuiltinType::SveInt64x4: 3832 return SVE_INT_ELTTY(64, 2, true, 4); 3833 case BuiltinType::SveUint64x4: 3834 return SVE_INT_ELTTY(64, 2, false, 4); 3835 case BuiltinType::SveBool: 3836 return SVE_ELTTY(BoolTy, 16, 1); 3837 case BuiltinType::SveFloat16: 3838 return SVE_ELTTY(HalfTy, 8, 1); 3839 case BuiltinType::SveFloat16x2: 3840 return SVE_ELTTY(HalfTy, 8, 2); 3841 case BuiltinType::SveFloat16x3: 3842 return SVE_ELTTY(HalfTy, 8, 3); 3843 case BuiltinType::SveFloat16x4: 3844 return SVE_ELTTY(HalfTy, 8, 4); 3845 case BuiltinType::SveFloat32: 3846 return SVE_ELTTY(FloatTy, 4, 1); 3847 case BuiltinType::SveFloat32x2: 3848 return SVE_ELTTY(FloatTy, 4, 2); 3849 case BuiltinType::SveFloat32x3: 3850 return SVE_ELTTY(FloatTy, 4, 3); 3851 case BuiltinType::SveFloat32x4: 3852 return SVE_ELTTY(FloatTy, 4, 4); 3853 case BuiltinType::SveFloat64: 3854 return SVE_ELTTY(DoubleTy, 2, 1); 3855 case BuiltinType::SveFloat64x2: 3856 return SVE_ELTTY(DoubleTy, 2, 2); 3857 case BuiltinType::SveFloat64x3: 3858 return SVE_ELTTY(DoubleTy, 2, 3); 3859 case BuiltinType::SveFloat64x4: 3860 return SVE_ELTTY(DoubleTy, 2, 4); 3861 case BuiltinType::SveBFloat16: 3862 return SVE_ELTTY(BFloat16Ty, 8, 1); 3863 case BuiltinType::SveBFloat16x2: 3864 return SVE_ELTTY(BFloat16Ty, 8, 2); 3865 case BuiltinType::SveBFloat16x3: 3866 return SVE_ELTTY(BFloat16Ty, 8, 3); 3867 case BuiltinType::SveBFloat16x4: 3868 return SVE_ELTTY(BFloat16Ty, 8, 4); 3869 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \ 3870 IsSigned) \ 3871 case BuiltinType::Id: \ 3872 return {getIntTypeForBitwidth(ElBits, IsSigned), \ 3873 llvm::ElementCount::getScalable(NumEls), NF}; 3874 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \ 3875 case BuiltinType::Id: \ 3876 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \ 3877 llvm::ElementCount::getScalable(NumEls), NF}; 3878 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3879 case BuiltinType::Id: \ 3880 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1}; 3881 #include "clang/Basic/RISCVVTypes.def" 3882 } 3883 } 3884 3885 /// getScalableVectorType - Return the unique reference to a scalable vector 3886 /// type of the specified element type and size. VectorType must be a built-in 3887 /// type. 3888 QualType ASTContext::getScalableVectorType(QualType EltTy, 3889 unsigned NumElts) const { 3890 if (Target->hasAArch64SVETypes()) { 3891 uint64_t EltTySize = getTypeSize(EltTy); 3892 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ 3893 IsSigned, IsFP, IsBF) \ 3894 if (!EltTy->isBooleanType() && \ 3895 ((EltTy->hasIntegerRepresentation() && \ 3896 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3897 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \ 3898 IsFP && !IsBF) || \ 3899 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \ 3900 IsBF && !IsFP)) && \ 3901 EltTySize == ElBits && NumElts == NumEls) { \ 3902 return SingletonId; \ 3903 } 3904 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \ 3905 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3906 return SingletonId; 3907 #include "clang/Basic/AArch64SVEACLETypes.def" 3908 } else if (Target->hasRISCVVTypes()) { 3909 uint64_t EltTySize = getTypeSize(EltTy); 3910 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ 3911 IsFP) \ 3912 if (!EltTy->isBooleanType() && \ 3913 ((EltTy->hasIntegerRepresentation() && \ 3914 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ 3915 (EltTy->hasFloatingRepresentation() && IsFP)) && \ 3916 EltTySize == ElBits && NumElts == NumEls) \ 3917 return SingletonId; 3918 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ 3919 if (EltTy->isBooleanType() && NumElts == NumEls) \ 3920 return SingletonId; 3921 #include "clang/Basic/RISCVVTypes.def" 3922 } 3923 return QualType(); 3924 } 3925 3926 /// getVectorType - Return the unique reference to a vector type of 3927 /// the specified element type and size. VectorType must be a built-in type. 3928 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3929 VectorType::VectorKind VecKind) const { 3930 assert(vecType->isBuiltinType()); 3931 3932 // Check if we've already instantiated a vector of this type. 3933 llvm::FoldingSetNodeID ID; 3934 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3935 3936 void *InsertPos = nullptr; 3937 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3938 return QualType(VTP, 0); 3939 3940 // If the element type isn't canonical, this won't be a canonical type either, 3941 // so fill in the canonical type field. 3942 QualType Canonical; 3943 if (!vecType.isCanonical()) { 3944 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3945 3946 // Get the new insert position for the node we care about. 3947 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3948 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3949 } 3950 auto *New = new (*this, TypeAlignment) 3951 VectorType(vecType, NumElts, Canonical, VecKind); 3952 VectorTypes.InsertNode(New, InsertPos); 3953 Types.push_back(New); 3954 return QualType(New, 0); 3955 } 3956 3957 QualType 3958 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3959 SourceLocation AttrLoc, 3960 VectorType::VectorKind VecKind) const { 3961 llvm::FoldingSetNodeID ID; 3962 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3963 VecKind); 3964 void *InsertPos = nullptr; 3965 DependentVectorType *Canon = 3966 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3967 DependentVectorType *New; 3968 3969 if (Canon) { 3970 New = new (*this, TypeAlignment) DependentVectorType( 3971 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3972 } else { 3973 QualType CanonVecTy = getCanonicalType(VecType); 3974 if (CanonVecTy == VecType) { 3975 New = new (*this, TypeAlignment) DependentVectorType( 3976 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3977 3978 DependentVectorType *CanonCheck = 3979 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3980 assert(!CanonCheck && 3981 "Dependent-sized vector_size canonical type broken"); 3982 (void)CanonCheck; 3983 DependentVectorTypes.InsertNode(New, InsertPos); 3984 } else { 3985 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr, 3986 SourceLocation(), VecKind); 3987 New = new (*this, TypeAlignment) DependentVectorType( 3988 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind); 3989 } 3990 } 3991 3992 Types.push_back(New); 3993 return QualType(New, 0); 3994 } 3995 3996 /// getExtVectorType - Return the unique reference to an extended vector type of 3997 /// the specified element type and size. VectorType must be a built-in type. 3998 QualType 3999 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 4000 assert(vecType->isBuiltinType() || vecType->isDependentType()); 4001 4002 // Check if we've already instantiated a vector of this type. 4003 llvm::FoldingSetNodeID ID; 4004 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 4005 VectorType::GenericVector); 4006 void *InsertPos = nullptr; 4007 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 4008 return QualType(VTP, 0); 4009 4010 // If the element type isn't canonical, this won't be a canonical type either, 4011 // so fill in the canonical type field. 4012 QualType Canonical; 4013 if (!vecType.isCanonical()) { 4014 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 4015 4016 // Get the new insert position for the node we care about. 4017 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4018 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4019 } 4020 auto *New = new (*this, TypeAlignment) 4021 ExtVectorType(vecType, NumElts, Canonical); 4022 VectorTypes.InsertNode(New, InsertPos); 4023 Types.push_back(New); 4024 return QualType(New, 0); 4025 } 4026 4027 QualType 4028 ASTContext::getDependentSizedExtVectorType(QualType vecType, 4029 Expr *SizeExpr, 4030 SourceLocation AttrLoc) const { 4031 llvm::FoldingSetNodeID ID; 4032 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 4033 SizeExpr); 4034 4035 void *InsertPos = nullptr; 4036 DependentSizedExtVectorType *Canon 4037 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4038 DependentSizedExtVectorType *New; 4039 if (Canon) { 4040 // We already have a canonical version of this array type; use it as 4041 // the canonical type for a newly-built type. 4042 New = new (*this, TypeAlignment) 4043 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 4044 SizeExpr, AttrLoc); 4045 } else { 4046 QualType CanonVecTy = getCanonicalType(vecType); 4047 if (CanonVecTy == vecType) { 4048 New = new (*this, TypeAlignment) 4049 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 4050 AttrLoc); 4051 4052 DependentSizedExtVectorType *CanonCheck 4053 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 4054 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 4055 (void)CanonCheck; 4056 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 4057 } else { 4058 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 4059 SourceLocation()); 4060 New = new (*this, TypeAlignment) DependentSizedExtVectorType( 4061 *this, vecType, CanonExtTy, SizeExpr, AttrLoc); 4062 } 4063 } 4064 4065 Types.push_back(New); 4066 return QualType(New, 0); 4067 } 4068 4069 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows, 4070 unsigned NumColumns) const { 4071 llvm::FoldingSetNodeID ID; 4072 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, 4073 Type::ConstantMatrix); 4074 4075 assert(MatrixType::isValidElementType(ElementTy) && 4076 "need a valid element type"); 4077 assert(ConstantMatrixType::isDimensionValid(NumRows) && 4078 ConstantMatrixType::isDimensionValid(NumColumns) && 4079 "need valid matrix dimensions"); 4080 void *InsertPos = nullptr; 4081 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos)) 4082 return QualType(MTP, 0); 4083 4084 QualType Canonical; 4085 if (!ElementTy.isCanonical()) { 4086 Canonical = 4087 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns); 4088 4089 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4090 assert(!NewIP && "Matrix type shouldn't already exist in the map"); 4091 (void)NewIP; 4092 } 4093 4094 auto *New = new (*this, TypeAlignment) 4095 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical); 4096 MatrixTypes.InsertNode(New, InsertPos); 4097 Types.push_back(New); 4098 return QualType(New, 0); 4099 } 4100 4101 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy, 4102 Expr *RowExpr, 4103 Expr *ColumnExpr, 4104 SourceLocation AttrLoc) const { 4105 QualType CanonElementTy = getCanonicalType(ElementTy); 4106 llvm::FoldingSetNodeID ID; 4107 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr, 4108 ColumnExpr); 4109 4110 void *InsertPos = nullptr; 4111 DependentSizedMatrixType *Canon = 4112 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4113 4114 if (!Canon) { 4115 Canon = new (*this, TypeAlignment) DependentSizedMatrixType( 4116 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc); 4117 #ifndef NDEBUG 4118 DependentSizedMatrixType *CanonCheck = 4119 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos); 4120 assert(!CanonCheck && "Dependent-sized matrix canonical type broken"); 4121 #endif 4122 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos); 4123 Types.push_back(Canon); 4124 } 4125 4126 // Already have a canonical version of the matrix type 4127 // 4128 // If it exactly matches the requested type, use it directly. 4129 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr && 4130 Canon->getRowExpr() == ColumnExpr) 4131 return QualType(Canon, 0); 4132 4133 // Use Canon as the canonical type for newly-built type. 4134 DependentSizedMatrixType *New = new (*this, TypeAlignment) 4135 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr, 4136 ColumnExpr, AttrLoc); 4137 Types.push_back(New); 4138 return QualType(New, 0); 4139 } 4140 4141 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 4142 Expr *AddrSpaceExpr, 4143 SourceLocation AttrLoc) const { 4144 assert(AddrSpaceExpr->isInstantiationDependent()); 4145 4146 QualType canonPointeeType = getCanonicalType(PointeeType); 4147 4148 void *insertPos = nullptr; 4149 llvm::FoldingSetNodeID ID; 4150 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 4151 AddrSpaceExpr); 4152 4153 DependentAddressSpaceType *canonTy = 4154 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 4155 4156 if (!canonTy) { 4157 canonTy = new (*this, TypeAlignment) 4158 DependentAddressSpaceType(*this, canonPointeeType, 4159 QualType(), AddrSpaceExpr, AttrLoc); 4160 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 4161 Types.push_back(canonTy); 4162 } 4163 4164 if (canonPointeeType == PointeeType && 4165 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 4166 return QualType(canonTy, 0); 4167 4168 auto *sugaredType 4169 = new (*this, TypeAlignment) 4170 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 4171 AddrSpaceExpr, AttrLoc); 4172 Types.push_back(sugaredType); 4173 return QualType(sugaredType, 0); 4174 } 4175 4176 /// Determine whether \p T is canonical as the result type of a function. 4177 static bool isCanonicalResultType(QualType T) { 4178 return T.isCanonical() && 4179 (T.getObjCLifetime() == Qualifiers::OCL_None || 4180 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 4181 } 4182 4183 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 4184 QualType 4185 ASTContext::getFunctionNoProtoType(QualType ResultTy, 4186 const FunctionType::ExtInfo &Info) const { 4187 // Unique functions, to guarantee there is only one function of a particular 4188 // structure. 4189 llvm::FoldingSetNodeID ID; 4190 FunctionNoProtoType::Profile(ID, ResultTy, Info); 4191 4192 void *InsertPos = nullptr; 4193 if (FunctionNoProtoType *FT = 4194 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4195 return QualType(FT, 0); 4196 4197 QualType Canonical; 4198 if (!isCanonicalResultType(ResultTy)) { 4199 Canonical = 4200 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 4201 4202 // Get the new insert position for the node we care about. 4203 FunctionNoProtoType *NewIP = 4204 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4205 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4206 } 4207 4208 auto *New = new (*this, TypeAlignment) 4209 FunctionNoProtoType(ResultTy, Canonical, Info); 4210 Types.push_back(New); 4211 FunctionNoProtoTypes.InsertNode(New, InsertPos); 4212 return QualType(New, 0); 4213 } 4214 4215 CanQualType 4216 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 4217 CanQualType CanResultType = getCanonicalType(ResultType); 4218 4219 // Canonical result types do not have ARC lifetime qualifiers. 4220 if (CanResultType.getQualifiers().hasObjCLifetime()) { 4221 Qualifiers Qs = CanResultType.getQualifiers(); 4222 Qs.removeObjCLifetime(); 4223 return CanQualType::CreateUnsafe( 4224 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 4225 } 4226 4227 return CanResultType; 4228 } 4229 4230 static bool isCanonicalExceptionSpecification( 4231 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 4232 if (ESI.Type == EST_None) 4233 return true; 4234 if (!NoexceptInType) 4235 return false; 4236 4237 // C++17 onwards: exception specification is part of the type, as a simple 4238 // boolean "can this function type throw". 4239 if (ESI.Type == EST_BasicNoexcept) 4240 return true; 4241 4242 // A noexcept(expr) specification is (possibly) canonical if expr is 4243 // value-dependent. 4244 if (ESI.Type == EST_DependentNoexcept) 4245 return true; 4246 4247 // A dynamic exception specification is canonical if it only contains pack 4248 // expansions (so we can't tell whether it's non-throwing) and all its 4249 // contained types are canonical. 4250 if (ESI.Type == EST_Dynamic) { 4251 bool AnyPackExpansions = false; 4252 for (QualType ET : ESI.Exceptions) { 4253 if (!ET.isCanonical()) 4254 return false; 4255 if (ET->getAs<PackExpansionType>()) 4256 AnyPackExpansions = true; 4257 } 4258 return AnyPackExpansions; 4259 } 4260 4261 return false; 4262 } 4263 4264 QualType ASTContext::getFunctionTypeInternal( 4265 QualType ResultTy, ArrayRef<QualType> ArgArray, 4266 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 4267 size_t NumArgs = ArgArray.size(); 4268 4269 // Unique functions, to guarantee there is only one function of a particular 4270 // structure. 4271 llvm::FoldingSetNodeID ID; 4272 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 4273 *this, true); 4274 4275 QualType Canonical; 4276 bool Unique = false; 4277 4278 void *InsertPos = nullptr; 4279 if (FunctionProtoType *FPT = 4280 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 4281 QualType Existing = QualType(FPT, 0); 4282 4283 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 4284 // it so long as our exception specification doesn't contain a dependent 4285 // noexcept expression, or we're just looking for a canonical type. 4286 // Otherwise, we're going to need to create a type 4287 // sugar node to hold the concrete expression. 4288 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 4289 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 4290 return Existing; 4291 4292 // We need a new type sugar node for this one, to hold the new noexcept 4293 // expression. We do no canonicalization here, but that's OK since we don't 4294 // expect to see the same noexcept expression much more than once. 4295 Canonical = getCanonicalType(Existing); 4296 Unique = true; 4297 } 4298 4299 bool NoexceptInType = getLangOpts().CPlusPlus17; 4300 bool IsCanonicalExceptionSpec = 4301 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 4302 4303 // Determine whether the type being created is already canonical or not. 4304 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 4305 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 4306 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 4307 if (!ArgArray[i].isCanonicalAsParam()) 4308 isCanonical = false; 4309 4310 if (OnlyWantCanonical) 4311 assert(isCanonical && 4312 "given non-canonical parameters constructing canonical type"); 4313 4314 // If this type isn't canonical, get the canonical version of it if we don't 4315 // already have it. The exception spec is only partially part of the 4316 // canonical type, and only in C++17 onwards. 4317 if (!isCanonical && Canonical.isNull()) { 4318 SmallVector<QualType, 16> CanonicalArgs; 4319 CanonicalArgs.reserve(NumArgs); 4320 for (unsigned i = 0; i != NumArgs; ++i) 4321 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 4322 4323 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 4324 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 4325 CanonicalEPI.HasTrailingReturn = false; 4326 4327 if (IsCanonicalExceptionSpec) { 4328 // Exception spec is already OK. 4329 } else if (NoexceptInType) { 4330 switch (EPI.ExceptionSpec.Type) { 4331 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 4332 // We don't know yet. It shouldn't matter what we pick here; no-one 4333 // should ever look at this. 4334 LLVM_FALLTHROUGH; 4335 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 4336 CanonicalEPI.ExceptionSpec.Type = EST_None; 4337 break; 4338 4339 // A dynamic exception specification is almost always "not noexcept", 4340 // with the exception that a pack expansion might expand to no types. 4341 case EST_Dynamic: { 4342 bool AnyPacks = false; 4343 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 4344 if (ET->getAs<PackExpansionType>()) 4345 AnyPacks = true; 4346 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 4347 } 4348 if (!AnyPacks) 4349 CanonicalEPI.ExceptionSpec.Type = EST_None; 4350 else { 4351 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 4352 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 4353 } 4354 break; 4355 } 4356 4357 case EST_DynamicNone: 4358 case EST_BasicNoexcept: 4359 case EST_NoexceptTrue: 4360 case EST_NoThrow: 4361 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 4362 break; 4363 4364 case EST_DependentNoexcept: 4365 llvm_unreachable("dependent noexcept is already canonical"); 4366 } 4367 } else { 4368 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 4369 } 4370 4371 // Adjust the canonical function result type. 4372 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 4373 Canonical = 4374 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 4375 4376 // Get the new insert position for the node we care about. 4377 FunctionProtoType *NewIP = 4378 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 4379 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4380 } 4381 4382 // Compute the needed size to hold this FunctionProtoType and the 4383 // various trailing objects. 4384 auto ESH = FunctionProtoType::getExceptionSpecSize( 4385 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 4386 size_t Size = FunctionProtoType::totalSizeToAlloc< 4387 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, 4388 FunctionType::ExceptionType, Expr *, FunctionDecl *, 4389 FunctionProtoType::ExtParameterInfo, Qualifiers>( 4390 NumArgs, EPI.Variadic, 4391 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), 4392 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, 4393 EPI.ExtParameterInfos ? NumArgs : 0, 4394 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); 4395 4396 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); 4397 FunctionProtoType::ExtProtoInfo newEPI = EPI; 4398 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 4399 Types.push_back(FTP); 4400 if (!Unique) 4401 FunctionProtoTypes.InsertNode(FTP, InsertPos); 4402 return QualType(FTP, 0); 4403 } 4404 4405 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 4406 llvm::FoldingSetNodeID ID; 4407 PipeType::Profile(ID, T, ReadOnly); 4408 4409 void *InsertPos = nullptr; 4410 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 4411 return QualType(PT, 0); 4412 4413 // If the pipe element type isn't canonical, this won't be a canonical type 4414 // either, so fill in the canonical type field. 4415 QualType Canonical; 4416 if (!T.isCanonical()) { 4417 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 4418 4419 // Get the new insert position for the node we care about. 4420 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 4421 assert(!NewIP && "Shouldn't be in the map!"); 4422 (void)NewIP; 4423 } 4424 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 4425 Types.push_back(New); 4426 PipeTypes.InsertNode(New, InsertPos); 4427 return QualType(New, 0); 4428 } 4429 4430 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 4431 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 4432 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 4433 : Ty; 4434 } 4435 4436 QualType ASTContext::getReadPipeType(QualType T) const { 4437 return getPipeType(T, true); 4438 } 4439 4440 QualType ASTContext::getWritePipeType(QualType T) const { 4441 return getPipeType(T, false); 4442 } 4443 4444 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const { 4445 llvm::FoldingSetNodeID ID; 4446 ExtIntType::Profile(ID, IsUnsigned, NumBits); 4447 4448 void *InsertPos = nullptr; 4449 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4450 return QualType(EIT, 0); 4451 4452 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits); 4453 ExtIntTypes.InsertNode(New, InsertPos); 4454 Types.push_back(New); 4455 return QualType(New, 0); 4456 } 4457 4458 QualType ASTContext::getDependentExtIntType(bool IsUnsigned, 4459 Expr *NumBitsExpr) const { 4460 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent"); 4461 llvm::FoldingSetNodeID ID; 4462 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr); 4463 4464 void *InsertPos = nullptr; 4465 if (DependentExtIntType *Existing = 4466 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos)) 4467 return QualType(Existing, 0); 4468 4469 auto *New = new (*this, TypeAlignment) 4470 DependentExtIntType(*this, IsUnsigned, NumBitsExpr); 4471 DependentExtIntTypes.InsertNode(New, InsertPos); 4472 4473 Types.push_back(New); 4474 return QualType(New, 0); 4475 } 4476 4477 #ifndef NDEBUG 4478 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 4479 if (!isa<CXXRecordDecl>(D)) return false; 4480 const auto *RD = cast<CXXRecordDecl>(D); 4481 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 4482 return true; 4483 if (RD->getDescribedClassTemplate() && 4484 !isa<ClassTemplateSpecializationDecl>(RD)) 4485 return true; 4486 return false; 4487 } 4488 #endif 4489 4490 /// getInjectedClassNameType - Return the unique reference to the 4491 /// injected class name type for the specified templated declaration. 4492 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 4493 QualType TST) const { 4494 assert(NeedsInjectedClassNameType(Decl)); 4495 if (Decl->TypeForDecl) { 4496 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4497 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 4498 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 4499 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4500 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 4501 } else { 4502 Type *newType = 4503 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 4504 Decl->TypeForDecl = newType; 4505 Types.push_back(newType); 4506 } 4507 return QualType(Decl->TypeForDecl, 0); 4508 } 4509 4510 /// getTypeDeclType - Return the unique reference to the type for the 4511 /// specified type declaration. 4512 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 4513 assert(Decl && "Passed null for Decl param"); 4514 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 4515 4516 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 4517 return getTypedefType(Typedef); 4518 4519 assert(!isa<TemplateTypeParmDecl>(Decl) && 4520 "Template type parameter types are always available."); 4521 4522 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 4523 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 4524 assert(!NeedsInjectedClassNameType(Record)); 4525 return getRecordType(Record); 4526 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 4527 assert(Enum->isFirstDecl() && "enum has previous declaration"); 4528 return getEnumType(Enum); 4529 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 4530 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 4531 Decl->TypeForDecl = newType; 4532 Types.push_back(newType); 4533 } else 4534 llvm_unreachable("TypeDecl without a type?"); 4535 4536 return QualType(Decl->TypeForDecl, 0); 4537 } 4538 4539 /// getTypedefType - Return the unique reference to the type for the 4540 /// specified typedef name decl. 4541 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, 4542 QualType Underlying) const { 4543 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4544 4545 if (Underlying.isNull()) 4546 Underlying = Decl->getUnderlyingType(); 4547 QualType Canonical = getCanonicalType(Underlying); 4548 auto *newType = new (*this, TypeAlignment) 4549 TypedefType(Type::Typedef, Decl, Underlying, Canonical); 4550 Decl->TypeForDecl = newType; 4551 Types.push_back(newType); 4552 return QualType(newType, 0); 4553 } 4554 4555 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 4556 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4557 4558 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 4559 if (PrevDecl->TypeForDecl) 4560 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4561 4562 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 4563 Decl->TypeForDecl = newType; 4564 Types.push_back(newType); 4565 return QualType(newType, 0); 4566 } 4567 4568 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 4569 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 4570 4571 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 4572 if (PrevDecl->TypeForDecl) 4573 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 4574 4575 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 4576 Decl->TypeForDecl = newType; 4577 Types.push_back(newType); 4578 return QualType(newType, 0); 4579 } 4580 4581 QualType ASTContext::getAttributedType(attr::Kind attrKind, 4582 QualType modifiedType, 4583 QualType equivalentType) { 4584 llvm::FoldingSetNodeID id; 4585 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 4586 4587 void *insertPos = nullptr; 4588 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 4589 if (type) return QualType(type, 0); 4590 4591 QualType canon = getCanonicalType(equivalentType); 4592 type = new (*this, TypeAlignment) 4593 AttributedType(canon, attrKind, modifiedType, equivalentType); 4594 4595 Types.push_back(type); 4596 AttributedTypes.InsertNode(type, insertPos); 4597 4598 return QualType(type, 0); 4599 } 4600 4601 /// Retrieve a substitution-result type. 4602 QualType 4603 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 4604 QualType Replacement) const { 4605 assert(Replacement.isCanonical() 4606 && "replacement types must always be canonical"); 4607 4608 llvm::FoldingSetNodeID ID; 4609 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 4610 void *InsertPos = nullptr; 4611 SubstTemplateTypeParmType *SubstParm 4612 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4613 4614 if (!SubstParm) { 4615 SubstParm = new (*this, TypeAlignment) 4616 SubstTemplateTypeParmType(Parm, Replacement); 4617 Types.push_back(SubstParm); 4618 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 4619 } 4620 4621 return QualType(SubstParm, 0); 4622 } 4623 4624 /// Retrieve a 4625 QualType ASTContext::getSubstTemplateTypeParmPackType( 4626 const TemplateTypeParmType *Parm, 4627 const TemplateArgument &ArgPack) { 4628 #ifndef NDEBUG 4629 for (const auto &P : ArgPack.pack_elements()) { 4630 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 4631 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 4632 } 4633 #endif 4634 4635 llvm::FoldingSetNodeID ID; 4636 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 4637 void *InsertPos = nullptr; 4638 if (SubstTemplateTypeParmPackType *SubstParm 4639 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 4640 return QualType(SubstParm, 0); 4641 4642 QualType Canon; 4643 if (!Parm->isCanonicalUnqualified()) { 4644 Canon = getCanonicalType(QualType(Parm, 0)); 4645 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 4646 ArgPack); 4647 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 4648 } 4649 4650 auto *SubstParm 4651 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 4652 ArgPack); 4653 Types.push_back(SubstParm); 4654 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 4655 return QualType(SubstParm, 0); 4656 } 4657 4658 /// Retrieve the template type parameter type for a template 4659 /// parameter or parameter pack with the given depth, index, and (optionally) 4660 /// name. 4661 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 4662 bool ParameterPack, 4663 TemplateTypeParmDecl *TTPDecl) const { 4664 llvm::FoldingSetNodeID ID; 4665 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 4666 void *InsertPos = nullptr; 4667 TemplateTypeParmType *TypeParm 4668 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4669 4670 if (TypeParm) 4671 return QualType(TypeParm, 0); 4672 4673 if (TTPDecl) { 4674 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 4675 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 4676 4677 TemplateTypeParmType *TypeCheck 4678 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 4679 assert(!TypeCheck && "Template type parameter canonical type broken"); 4680 (void)TypeCheck; 4681 } else 4682 TypeParm = new (*this, TypeAlignment) 4683 TemplateTypeParmType(Depth, Index, ParameterPack); 4684 4685 Types.push_back(TypeParm); 4686 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 4687 4688 return QualType(TypeParm, 0); 4689 } 4690 4691 TypeSourceInfo * 4692 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 4693 SourceLocation NameLoc, 4694 const TemplateArgumentListInfo &Args, 4695 QualType Underlying) const { 4696 assert(!Name.getAsDependentTemplateName() && 4697 "No dependent template names here!"); 4698 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 4699 4700 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 4701 TemplateSpecializationTypeLoc TL = 4702 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4703 TL.setTemplateKeywordLoc(SourceLocation()); 4704 TL.setTemplateNameLoc(NameLoc); 4705 TL.setLAngleLoc(Args.getLAngleLoc()); 4706 TL.setRAngleLoc(Args.getRAngleLoc()); 4707 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4708 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4709 return DI; 4710 } 4711 4712 QualType 4713 ASTContext::getTemplateSpecializationType(TemplateName Template, 4714 const TemplateArgumentListInfo &Args, 4715 QualType Underlying) const { 4716 assert(!Template.getAsDependentTemplateName() && 4717 "No dependent template names here!"); 4718 4719 SmallVector<TemplateArgument, 4> ArgVec; 4720 ArgVec.reserve(Args.size()); 4721 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4722 ArgVec.push_back(Arg.getArgument()); 4723 4724 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4725 } 4726 4727 #ifndef NDEBUG 4728 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4729 for (const TemplateArgument &Arg : Args) 4730 if (Arg.isPackExpansion()) 4731 return true; 4732 4733 return true; 4734 } 4735 #endif 4736 4737 QualType 4738 ASTContext::getTemplateSpecializationType(TemplateName Template, 4739 ArrayRef<TemplateArgument> Args, 4740 QualType Underlying) const { 4741 assert(!Template.getAsDependentTemplateName() && 4742 "No dependent template names here!"); 4743 // Look through qualified template names. 4744 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4745 Template = TemplateName(QTN->getTemplateDecl()); 4746 4747 bool IsTypeAlias = 4748 Template.getAsTemplateDecl() && 4749 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4750 QualType CanonType; 4751 if (!Underlying.isNull()) 4752 CanonType = getCanonicalType(Underlying); 4753 else { 4754 // We can get here with an alias template when the specialization contains 4755 // a pack expansion that does not match up with a parameter pack. 4756 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4757 "Caller must compute aliased type"); 4758 IsTypeAlias = false; 4759 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4760 } 4761 4762 // Allocate the (non-canonical) template specialization type, but don't 4763 // try to unique it: these types typically have location information that 4764 // we don't unique and don't want to lose. 4765 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4766 sizeof(TemplateArgument) * Args.size() + 4767 (IsTypeAlias? sizeof(QualType) : 0), 4768 TypeAlignment); 4769 auto *Spec 4770 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4771 IsTypeAlias ? Underlying : QualType()); 4772 4773 Types.push_back(Spec); 4774 return QualType(Spec, 0); 4775 } 4776 4777 QualType ASTContext::getCanonicalTemplateSpecializationType( 4778 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4779 assert(!Template.getAsDependentTemplateName() && 4780 "No dependent template names here!"); 4781 4782 // Look through qualified template names. 4783 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4784 Template = TemplateName(QTN->getTemplateDecl()); 4785 4786 // Build the canonical template specialization type. 4787 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4788 SmallVector<TemplateArgument, 4> CanonArgs; 4789 unsigned NumArgs = Args.size(); 4790 CanonArgs.reserve(NumArgs); 4791 for (const TemplateArgument &Arg : Args) 4792 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4793 4794 // Determine whether this canonical template specialization type already 4795 // exists. 4796 llvm::FoldingSetNodeID ID; 4797 TemplateSpecializationType::Profile(ID, CanonTemplate, 4798 CanonArgs, *this); 4799 4800 void *InsertPos = nullptr; 4801 TemplateSpecializationType *Spec 4802 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4803 4804 if (!Spec) { 4805 // Allocate a new canonical template specialization type. 4806 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4807 sizeof(TemplateArgument) * NumArgs), 4808 TypeAlignment); 4809 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4810 CanonArgs, 4811 QualType(), QualType()); 4812 Types.push_back(Spec); 4813 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4814 } 4815 4816 assert(Spec->isDependentType() && 4817 "Non-dependent template-id type must have a canonical type"); 4818 return QualType(Spec, 0); 4819 } 4820 4821 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4822 NestedNameSpecifier *NNS, 4823 QualType NamedType, 4824 TagDecl *OwnedTagDecl) const { 4825 llvm::FoldingSetNodeID ID; 4826 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4827 4828 void *InsertPos = nullptr; 4829 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4830 if (T) 4831 return QualType(T, 0); 4832 4833 QualType Canon = NamedType; 4834 if (!Canon.isCanonical()) { 4835 Canon = getCanonicalType(NamedType); 4836 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4837 assert(!CheckT && "Elaborated canonical type broken"); 4838 (void)CheckT; 4839 } 4840 4841 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), 4842 TypeAlignment); 4843 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4844 4845 Types.push_back(T); 4846 ElaboratedTypes.InsertNode(T, InsertPos); 4847 return QualType(T, 0); 4848 } 4849 4850 QualType 4851 ASTContext::getParenType(QualType InnerType) const { 4852 llvm::FoldingSetNodeID ID; 4853 ParenType::Profile(ID, InnerType); 4854 4855 void *InsertPos = nullptr; 4856 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4857 if (T) 4858 return QualType(T, 0); 4859 4860 QualType Canon = InnerType; 4861 if (!Canon.isCanonical()) { 4862 Canon = getCanonicalType(InnerType); 4863 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4864 assert(!CheckT && "Paren canonical type broken"); 4865 (void)CheckT; 4866 } 4867 4868 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4869 Types.push_back(T); 4870 ParenTypes.InsertNode(T, InsertPos); 4871 return QualType(T, 0); 4872 } 4873 4874 QualType 4875 ASTContext::getMacroQualifiedType(QualType UnderlyingTy, 4876 const IdentifierInfo *MacroII) const { 4877 QualType Canon = UnderlyingTy; 4878 if (!Canon.isCanonical()) 4879 Canon = getCanonicalType(UnderlyingTy); 4880 4881 auto *newType = new (*this, TypeAlignment) 4882 MacroQualifiedType(UnderlyingTy, Canon, MacroII); 4883 Types.push_back(newType); 4884 return QualType(newType, 0); 4885 } 4886 4887 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4888 NestedNameSpecifier *NNS, 4889 const IdentifierInfo *Name, 4890 QualType Canon) const { 4891 if (Canon.isNull()) { 4892 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4893 if (CanonNNS != NNS) 4894 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4895 } 4896 4897 llvm::FoldingSetNodeID ID; 4898 DependentNameType::Profile(ID, Keyword, NNS, Name); 4899 4900 void *InsertPos = nullptr; 4901 DependentNameType *T 4902 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4903 if (T) 4904 return QualType(T, 0); 4905 4906 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4907 Types.push_back(T); 4908 DependentNameTypes.InsertNode(T, InsertPos); 4909 return QualType(T, 0); 4910 } 4911 4912 QualType 4913 ASTContext::getDependentTemplateSpecializationType( 4914 ElaboratedTypeKeyword Keyword, 4915 NestedNameSpecifier *NNS, 4916 const IdentifierInfo *Name, 4917 const TemplateArgumentListInfo &Args) const { 4918 // TODO: avoid this copy 4919 SmallVector<TemplateArgument, 16> ArgCopy; 4920 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4921 ArgCopy.push_back(Args[I].getArgument()); 4922 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4923 } 4924 4925 QualType 4926 ASTContext::getDependentTemplateSpecializationType( 4927 ElaboratedTypeKeyword Keyword, 4928 NestedNameSpecifier *NNS, 4929 const IdentifierInfo *Name, 4930 ArrayRef<TemplateArgument> Args) const { 4931 assert((!NNS || NNS->isDependent()) && 4932 "nested-name-specifier must be dependent"); 4933 4934 llvm::FoldingSetNodeID ID; 4935 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4936 Name, Args); 4937 4938 void *InsertPos = nullptr; 4939 DependentTemplateSpecializationType *T 4940 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4941 if (T) 4942 return QualType(T, 0); 4943 4944 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4945 4946 ElaboratedTypeKeyword CanonKeyword = Keyword; 4947 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4948 4949 bool AnyNonCanonArgs = false; 4950 unsigned NumArgs = Args.size(); 4951 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4952 for (unsigned I = 0; I != NumArgs; ++I) { 4953 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4954 if (!CanonArgs[I].structurallyEquals(Args[I])) 4955 AnyNonCanonArgs = true; 4956 } 4957 4958 QualType Canon; 4959 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4960 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4961 Name, 4962 CanonArgs); 4963 4964 // Find the insert position again. 4965 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4966 } 4967 4968 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4969 sizeof(TemplateArgument) * NumArgs), 4970 TypeAlignment); 4971 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4972 Name, Args, Canon); 4973 Types.push_back(T); 4974 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4975 return QualType(T, 0); 4976 } 4977 4978 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4979 TemplateArgument Arg; 4980 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4981 QualType ArgType = getTypeDeclType(TTP); 4982 if (TTP->isParameterPack()) 4983 ArgType = getPackExpansionType(ArgType, None); 4984 4985 Arg = TemplateArgument(ArgType); 4986 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4987 QualType T = 4988 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this); 4989 // For class NTTPs, ensure we include the 'const' so the type matches that 4990 // of a real template argument. 4991 // FIXME: It would be more faithful to model this as something like an 4992 // lvalue-to-rvalue conversion applied to a const-qualified lvalue. 4993 if (T->isRecordType()) 4994 T.addConst(); 4995 Expr *E = new (*this) DeclRefExpr( 4996 *this, NTTP, /*enclosing*/ false, T, 4997 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4998 4999 if (NTTP->isParameterPack()) 5000 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 5001 None); 5002 Arg = TemplateArgument(E); 5003 } else { 5004 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5005 if (TTP->isParameterPack()) 5006 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 5007 else 5008 Arg = TemplateArgument(TemplateName(TTP)); 5009 } 5010 5011 if (Param->isTemplateParameterPack()) 5012 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 5013 5014 return Arg; 5015 } 5016 5017 void 5018 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 5019 SmallVectorImpl<TemplateArgument> &Args) { 5020 Args.reserve(Args.size() + Params->size()); 5021 5022 for (NamedDecl *Param : *Params) 5023 Args.push_back(getInjectedTemplateArg(Param)); 5024 } 5025 5026 QualType ASTContext::getPackExpansionType(QualType Pattern, 5027 Optional<unsigned> NumExpansions, 5028 bool ExpectPackInType) { 5029 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && 5030 "Pack expansions must expand one or more parameter packs"); 5031 5032 llvm::FoldingSetNodeID ID; 5033 PackExpansionType::Profile(ID, Pattern, NumExpansions); 5034 5035 void *InsertPos = nullptr; 5036 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5037 if (T) 5038 return QualType(T, 0); 5039 5040 QualType Canon; 5041 if (!Pattern.isCanonical()) { 5042 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions, 5043 /*ExpectPackInType=*/false); 5044 5045 // Find the insert position again, in case we inserted an element into 5046 // PackExpansionTypes and invalidated our insert position. 5047 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 5048 } 5049 5050 T = new (*this, TypeAlignment) 5051 PackExpansionType(Pattern, Canon, NumExpansions); 5052 Types.push_back(T); 5053 PackExpansionTypes.InsertNode(T, InsertPos); 5054 return QualType(T, 0); 5055 } 5056 5057 /// CmpProtocolNames - Comparison predicate for sorting protocols 5058 /// alphabetically. 5059 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 5060 ObjCProtocolDecl *const *RHS) { 5061 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 5062 } 5063 5064 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 5065 if (Protocols.empty()) return true; 5066 5067 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 5068 return false; 5069 5070 for (unsigned i = 1; i != Protocols.size(); ++i) 5071 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 5072 Protocols[i]->getCanonicalDecl() != Protocols[i]) 5073 return false; 5074 return true; 5075 } 5076 5077 static void 5078 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 5079 // Sort protocols, keyed by name. 5080 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 5081 5082 // Canonicalize. 5083 for (ObjCProtocolDecl *&P : Protocols) 5084 P = P->getCanonicalDecl(); 5085 5086 // Remove duplicates. 5087 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 5088 Protocols.erase(ProtocolsEnd, Protocols.end()); 5089 } 5090 5091 QualType ASTContext::getObjCObjectType(QualType BaseType, 5092 ObjCProtocolDecl * const *Protocols, 5093 unsigned NumProtocols) const { 5094 return getObjCObjectType(BaseType, {}, 5095 llvm::makeArrayRef(Protocols, NumProtocols), 5096 /*isKindOf=*/false); 5097 } 5098 5099 QualType ASTContext::getObjCObjectType( 5100 QualType baseType, 5101 ArrayRef<QualType> typeArgs, 5102 ArrayRef<ObjCProtocolDecl *> protocols, 5103 bool isKindOf) const { 5104 // If the base type is an interface and there aren't any protocols or 5105 // type arguments to add, then the interface type will do just fine. 5106 if (typeArgs.empty() && protocols.empty() && !isKindOf && 5107 isa<ObjCInterfaceType>(baseType)) 5108 return baseType; 5109 5110 // Look in the folding set for an existing type. 5111 llvm::FoldingSetNodeID ID; 5112 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 5113 void *InsertPos = nullptr; 5114 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 5115 return QualType(QT, 0); 5116 5117 // Determine the type arguments to be used for canonicalization, 5118 // which may be explicitly specified here or written on the base 5119 // type. 5120 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 5121 if (effectiveTypeArgs.empty()) { 5122 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 5123 effectiveTypeArgs = baseObject->getTypeArgs(); 5124 } 5125 5126 // Build the canonical type, which has the canonical base type and a 5127 // sorted-and-uniqued list of protocols and the type arguments 5128 // canonicalized. 5129 QualType canonical; 5130 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 5131 effectiveTypeArgs.end(), 5132 [&](QualType type) { 5133 return type.isCanonical(); 5134 }); 5135 bool protocolsSorted = areSortedAndUniqued(protocols); 5136 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 5137 // Determine the canonical type arguments. 5138 ArrayRef<QualType> canonTypeArgs; 5139 SmallVector<QualType, 4> canonTypeArgsVec; 5140 if (!typeArgsAreCanonical) { 5141 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 5142 for (auto typeArg : effectiveTypeArgs) 5143 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 5144 canonTypeArgs = canonTypeArgsVec; 5145 } else { 5146 canonTypeArgs = effectiveTypeArgs; 5147 } 5148 5149 ArrayRef<ObjCProtocolDecl *> canonProtocols; 5150 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 5151 if (!protocolsSorted) { 5152 canonProtocolsVec.append(protocols.begin(), protocols.end()); 5153 SortAndUniqueProtocols(canonProtocolsVec); 5154 canonProtocols = canonProtocolsVec; 5155 } else { 5156 canonProtocols = protocols; 5157 } 5158 5159 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 5160 canonProtocols, isKindOf); 5161 5162 // Regenerate InsertPos. 5163 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 5164 } 5165 5166 unsigned size = sizeof(ObjCObjectTypeImpl); 5167 size += typeArgs.size() * sizeof(QualType); 5168 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5169 void *mem = Allocate(size, TypeAlignment); 5170 auto *T = 5171 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 5172 isKindOf); 5173 5174 Types.push_back(T); 5175 ObjCObjectTypes.InsertNode(T, InsertPos); 5176 return QualType(T, 0); 5177 } 5178 5179 /// Apply Objective-C protocol qualifiers to the given type. 5180 /// If this is for the canonical type of a type parameter, we can apply 5181 /// protocol qualifiers on the ObjCObjectPointerType. 5182 QualType 5183 ASTContext::applyObjCProtocolQualifiers(QualType type, 5184 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 5185 bool allowOnPointerType) const { 5186 hasError = false; 5187 5188 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 5189 return getObjCTypeParamType(objT->getDecl(), protocols); 5190 } 5191 5192 // Apply protocol qualifiers to ObjCObjectPointerType. 5193 if (allowOnPointerType) { 5194 if (const auto *objPtr = 5195 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 5196 const ObjCObjectType *objT = objPtr->getObjectType(); 5197 // Merge protocol lists and construct ObjCObjectType. 5198 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 5199 protocolsVec.append(objT->qual_begin(), 5200 objT->qual_end()); 5201 protocolsVec.append(protocols.begin(), protocols.end()); 5202 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 5203 type = getObjCObjectType( 5204 objT->getBaseType(), 5205 objT->getTypeArgsAsWritten(), 5206 protocols, 5207 objT->isKindOfTypeAsWritten()); 5208 return getObjCObjectPointerType(type); 5209 } 5210 } 5211 5212 // Apply protocol qualifiers to ObjCObjectType. 5213 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 5214 // FIXME: Check for protocols to which the class type is already 5215 // known to conform. 5216 5217 return getObjCObjectType(objT->getBaseType(), 5218 objT->getTypeArgsAsWritten(), 5219 protocols, 5220 objT->isKindOfTypeAsWritten()); 5221 } 5222 5223 // If the canonical type is ObjCObjectType, ... 5224 if (type->isObjCObjectType()) { 5225 // Silently overwrite any existing protocol qualifiers. 5226 // TODO: determine whether that's the right thing to do. 5227 5228 // FIXME: Check for protocols to which the class type is already 5229 // known to conform. 5230 return getObjCObjectType(type, {}, protocols, false); 5231 } 5232 5233 // id<protocol-list> 5234 if (type->isObjCIdType()) { 5235 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5236 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 5237 objPtr->isKindOfType()); 5238 return getObjCObjectPointerType(type); 5239 } 5240 5241 // Class<protocol-list> 5242 if (type->isObjCClassType()) { 5243 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 5244 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 5245 objPtr->isKindOfType()); 5246 return getObjCObjectPointerType(type); 5247 } 5248 5249 hasError = true; 5250 return type; 5251 } 5252 5253 QualType 5254 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 5255 ArrayRef<ObjCProtocolDecl *> protocols) const { 5256 // Look in the folding set for an existing type. 5257 llvm::FoldingSetNodeID ID; 5258 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); 5259 void *InsertPos = nullptr; 5260 if (ObjCTypeParamType *TypeParam = 5261 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 5262 return QualType(TypeParam, 0); 5263 5264 // We canonicalize to the underlying type. 5265 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 5266 if (!protocols.empty()) { 5267 // Apply the protocol qualifers. 5268 bool hasError; 5269 Canonical = getCanonicalType(applyObjCProtocolQualifiers( 5270 Canonical, protocols, hasError, true /*allowOnPointerType*/)); 5271 assert(!hasError && "Error when apply protocol qualifier to bound type"); 5272 } 5273 5274 unsigned size = sizeof(ObjCTypeParamType); 5275 size += protocols.size() * sizeof(ObjCProtocolDecl *); 5276 void *mem = Allocate(size, TypeAlignment); 5277 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 5278 5279 Types.push_back(newType); 5280 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 5281 return QualType(newType, 0); 5282 } 5283 5284 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 5285 ObjCTypeParamDecl *New) const { 5286 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); 5287 // Update TypeForDecl after updating TypeSourceInfo. 5288 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl()); 5289 SmallVector<ObjCProtocolDecl *, 8> protocols; 5290 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end()); 5291 QualType UpdatedTy = getObjCTypeParamType(New, protocols); 5292 New->setTypeForDecl(UpdatedTy.getTypePtr()); 5293 } 5294 5295 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 5296 /// protocol list adopt all protocols in QT's qualified-id protocol 5297 /// list. 5298 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 5299 ObjCInterfaceDecl *IC) { 5300 if (!QT->isObjCQualifiedIdType()) 5301 return false; 5302 5303 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 5304 // If both the right and left sides have qualifiers. 5305 for (auto *Proto : OPT->quals()) { 5306 if (!IC->ClassImplementsProtocol(Proto, false)) 5307 return false; 5308 } 5309 return true; 5310 } 5311 return false; 5312 } 5313 5314 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 5315 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 5316 /// of protocols. 5317 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 5318 ObjCInterfaceDecl *IDecl) { 5319 if (!QT->isObjCQualifiedIdType()) 5320 return false; 5321 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 5322 if (!OPT) 5323 return false; 5324 if (!IDecl->hasDefinition()) 5325 return false; 5326 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 5327 CollectInheritedProtocols(IDecl, InheritedProtocols); 5328 if (InheritedProtocols.empty()) 5329 return false; 5330 // Check that if every protocol in list of id<plist> conforms to a protocol 5331 // of IDecl's, then bridge casting is ok. 5332 bool Conforms = false; 5333 for (auto *Proto : OPT->quals()) { 5334 Conforms = false; 5335 for (auto *PI : InheritedProtocols) { 5336 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 5337 Conforms = true; 5338 break; 5339 } 5340 } 5341 if (!Conforms) 5342 break; 5343 } 5344 if (Conforms) 5345 return true; 5346 5347 for (auto *PI : InheritedProtocols) { 5348 // If both the right and left sides have qualifiers. 5349 bool Adopts = false; 5350 for (auto *Proto : OPT->quals()) { 5351 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 5352 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 5353 break; 5354 } 5355 if (!Adopts) 5356 return false; 5357 } 5358 return true; 5359 } 5360 5361 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 5362 /// the given object type. 5363 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 5364 llvm::FoldingSetNodeID ID; 5365 ObjCObjectPointerType::Profile(ID, ObjectT); 5366 5367 void *InsertPos = nullptr; 5368 if (ObjCObjectPointerType *QT = 5369 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 5370 return QualType(QT, 0); 5371 5372 // Find the canonical object type. 5373 QualType Canonical; 5374 if (!ObjectT.isCanonical()) { 5375 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 5376 5377 // Regenerate InsertPos. 5378 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 5379 } 5380 5381 // No match. 5382 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 5383 auto *QType = 5384 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 5385 5386 Types.push_back(QType); 5387 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 5388 return QualType(QType, 0); 5389 } 5390 5391 /// getObjCInterfaceType - Return the unique reference to the type for the 5392 /// specified ObjC interface decl. The list of protocols is optional. 5393 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 5394 ObjCInterfaceDecl *PrevDecl) const { 5395 if (Decl->TypeForDecl) 5396 return QualType(Decl->TypeForDecl, 0); 5397 5398 if (PrevDecl) { 5399 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 5400 Decl->TypeForDecl = PrevDecl->TypeForDecl; 5401 return QualType(PrevDecl->TypeForDecl, 0); 5402 } 5403 5404 // Prefer the definition, if there is one. 5405 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 5406 Decl = Def; 5407 5408 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 5409 auto *T = new (Mem) ObjCInterfaceType(Decl); 5410 Decl->TypeForDecl = T; 5411 Types.push_back(T); 5412 return QualType(T, 0); 5413 } 5414 5415 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 5416 /// TypeOfExprType AST's (since expression's are never shared). For example, 5417 /// multiple declarations that refer to "typeof(x)" all contain different 5418 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 5419 /// on canonical type's (which are always unique). 5420 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 5421 TypeOfExprType *toe; 5422 if (tofExpr->isTypeDependent()) { 5423 llvm::FoldingSetNodeID ID; 5424 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 5425 5426 void *InsertPos = nullptr; 5427 DependentTypeOfExprType *Canon 5428 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 5429 if (Canon) { 5430 // We already have a "canonical" version of an identical, dependent 5431 // typeof(expr) type. Use that as our canonical type. 5432 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 5433 QualType((TypeOfExprType*)Canon, 0)); 5434 } else { 5435 // Build a new, canonical typeof(expr) type. 5436 Canon 5437 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 5438 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 5439 toe = Canon; 5440 } 5441 } else { 5442 QualType Canonical = getCanonicalType(tofExpr->getType()); 5443 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 5444 } 5445 Types.push_back(toe); 5446 return QualType(toe, 0); 5447 } 5448 5449 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 5450 /// TypeOfType nodes. The only motivation to unique these nodes would be 5451 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 5452 /// an issue. This doesn't affect the type checker, since it operates 5453 /// on canonical types (which are always unique). 5454 QualType ASTContext::getTypeOfType(QualType tofType) const { 5455 QualType Canonical = getCanonicalType(tofType); 5456 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 5457 Types.push_back(tot); 5458 return QualType(tot, 0); 5459 } 5460 5461 /// getReferenceQualifiedType - Given an expr, will return the type for 5462 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions 5463 /// and class member access into account. 5464 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { 5465 // C++11 [dcl.type.simple]p4: 5466 // [...] 5467 QualType T = E->getType(); 5468 switch (E->getValueKind()) { 5469 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5470 // type of e; 5471 case VK_XValue: 5472 return getRValueReferenceType(T); 5473 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5474 // type of e; 5475 case VK_LValue: 5476 return getLValueReferenceType(T); 5477 // - otherwise, decltype(e) is the type of e. 5478 case VK_PRValue: 5479 return T; 5480 } 5481 llvm_unreachable("Unknown value kind"); 5482 } 5483 5484 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 5485 /// nodes. This would never be helpful, since each such type has its own 5486 /// expression, and would not give a significant memory saving, since there 5487 /// is an Expr tree under each such type. 5488 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 5489 DecltypeType *dt; 5490 5491 // C++11 [temp.type]p2: 5492 // If an expression e involves a template parameter, decltype(e) denotes a 5493 // unique dependent type. Two such decltype-specifiers refer to the same 5494 // type only if their expressions are equivalent (14.5.6.1). 5495 if (e->isInstantiationDependent()) { 5496 llvm::FoldingSetNodeID ID; 5497 DependentDecltypeType::Profile(ID, *this, e); 5498 5499 void *InsertPos = nullptr; 5500 DependentDecltypeType *Canon 5501 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 5502 if (!Canon) { 5503 // Build a new, canonical decltype(expr) type. 5504 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 5505 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 5506 } 5507 dt = new (*this, TypeAlignment) 5508 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 5509 } else { 5510 dt = new (*this, TypeAlignment) 5511 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 5512 } 5513 Types.push_back(dt); 5514 return QualType(dt, 0); 5515 } 5516 5517 /// getUnaryTransformationType - We don't unique these, since the memory 5518 /// savings are minimal and these are rare. 5519 QualType ASTContext::getUnaryTransformType(QualType BaseType, 5520 QualType UnderlyingType, 5521 UnaryTransformType::UTTKind Kind) 5522 const { 5523 UnaryTransformType *ut = nullptr; 5524 5525 if (BaseType->isDependentType()) { 5526 // Look in the folding set for an existing type. 5527 llvm::FoldingSetNodeID ID; 5528 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 5529 5530 void *InsertPos = nullptr; 5531 DependentUnaryTransformType *Canon 5532 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 5533 5534 if (!Canon) { 5535 // Build a new, canonical __underlying_type(type) type. 5536 Canon = new (*this, TypeAlignment) 5537 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 5538 Kind); 5539 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 5540 } 5541 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5542 QualType(), Kind, 5543 QualType(Canon, 0)); 5544 } else { 5545 QualType CanonType = getCanonicalType(UnderlyingType); 5546 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 5547 UnderlyingType, Kind, 5548 CanonType); 5549 } 5550 Types.push_back(ut); 5551 return QualType(ut, 0); 5552 } 5553 5554 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 5555 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 5556 /// canonical deduced-but-dependent 'auto' type. 5557 QualType 5558 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 5559 bool IsDependent, bool IsPack, 5560 ConceptDecl *TypeConstraintConcept, 5561 ArrayRef<TemplateArgument> TypeConstraintArgs) const { 5562 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); 5563 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && 5564 !TypeConstraintConcept && !IsDependent) 5565 return getAutoDeductType(); 5566 5567 // Look in the folding set for an existing type. 5568 void *InsertPos = nullptr; 5569 llvm::FoldingSetNodeID ID; 5570 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, 5571 TypeConstraintConcept, TypeConstraintArgs); 5572 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 5573 return QualType(AT, 0); 5574 5575 void *Mem = Allocate(sizeof(AutoType) + 5576 sizeof(TemplateArgument) * TypeConstraintArgs.size(), 5577 TypeAlignment); 5578 auto *AT = new (Mem) AutoType( 5579 DeducedType, Keyword, 5580 (IsDependent ? TypeDependence::DependentInstantiation 5581 : TypeDependence::None) | 5582 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None), 5583 TypeConstraintConcept, TypeConstraintArgs); 5584 Types.push_back(AT); 5585 if (InsertPos) 5586 AutoTypes.InsertNode(AT, InsertPos); 5587 return QualType(AT, 0); 5588 } 5589 5590 /// Return the uniqued reference to the deduced template specialization type 5591 /// which has been deduced to the given type, or to the canonical undeduced 5592 /// such type, or the canonical deduced-but-dependent such type. 5593 QualType ASTContext::getDeducedTemplateSpecializationType( 5594 TemplateName Template, QualType DeducedType, bool IsDependent) const { 5595 // Look in the folding set for an existing type. 5596 void *InsertPos = nullptr; 5597 llvm::FoldingSetNodeID ID; 5598 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 5599 IsDependent); 5600 if (DeducedTemplateSpecializationType *DTST = 5601 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 5602 return QualType(DTST, 0); 5603 5604 auto *DTST = new (*this, TypeAlignment) 5605 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 5606 Types.push_back(DTST); 5607 if (InsertPos) 5608 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 5609 return QualType(DTST, 0); 5610 } 5611 5612 /// getAtomicType - Return the uniqued reference to the atomic type for 5613 /// the given value type. 5614 QualType ASTContext::getAtomicType(QualType T) const { 5615 // Unique pointers, to guarantee there is only one pointer of a particular 5616 // structure. 5617 llvm::FoldingSetNodeID ID; 5618 AtomicType::Profile(ID, T); 5619 5620 void *InsertPos = nullptr; 5621 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 5622 return QualType(AT, 0); 5623 5624 // If the atomic value type isn't canonical, this won't be a canonical type 5625 // either, so fill in the canonical type field. 5626 QualType Canonical; 5627 if (!T.isCanonical()) { 5628 Canonical = getAtomicType(getCanonicalType(T)); 5629 5630 // Get the new insert position for the node we care about. 5631 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 5632 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 5633 } 5634 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 5635 Types.push_back(New); 5636 AtomicTypes.InsertNode(New, InsertPos); 5637 return QualType(New, 0); 5638 } 5639 5640 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 5641 QualType ASTContext::getAutoDeductType() const { 5642 if (AutoDeductTy.isNull()) 5643 AutoDeductTy = QualType(new (*this, TypeAlignment) 5644 AutoType(QualType(), AutoTypeKeyword::Auto, 5645 TypeDependence::None, 5646 /*concept*/ nullptr, /*args*/ {}), 5647 0); 5648 return AutoDeductTy; 5649 } 5650 5651 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 5652 QualType ASTContext::getAutoRRefDeductType() const { 5653 if (AutoRRefDeductTy.isNull()) 5654 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 5655 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 5656 return AutoRRefDeductTy; 5657 } 5658 5659 /// getTagDeclType - Return the unique reference to the type for the 5660 /// specified TagDecl (struct/union/class/enum) decl. 5661 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 5662 assert(Decl); 5663 // FIXME: What is the design on getTagDeclType when it requires casting 5664 // away const? mutable? 5665 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 5666 } 5667 5668 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 5669 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 5670 /// needs to agree with the definition in <stddef.h>. 5671 CanQualType ASTContext::getSizeType() const { 5672 return getFromTargetType(Target->getSizeType()); 5673 } 5674 5675 /// Return the unique signed counterpart of the integer type 5676 /// corresponding to size_t. 5677 CanQualType ASTContext::getSignedSizeType() const { 5678 return getFromTargetType(Target->getSignedSizeType()); 5679 } 5680 5681 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 5682 CanQualType ASTContext::getIntMaxType() const { 5683 return getFromTargetType(Target->getIntMaxType()); 5684 } 5685 5686 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 5687 CanQualType ASTContext::getUIntMaxType() const { 5688 return getFromTargetType(Target->getUIntMaxType()); 5689 } 5690 5691 /// getSignedWCharType - Return the type of "signed wchar_t". 5692 /// Used when in C++, as a GCC extension. 5693 QualType ASTContext::getSignedWCharType() const { 5694 // FIXME: derive from "Target" ? 5695 return WCharTy; 5696 } 5697 5698 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 5699 /// Used when in C++, as a GCC extension. 5700 QualType ASTContext::getUnsignedWCharType() const { 5701 // FIXME: derive from "Target" ? 5702 return UnsignedIntTy; 5703 } 5704 5705 QualType ASTContext::getIntPtrType() const { 5706 return getFromTargetType(Target->getIntPtrType()); 5707 } 5708 5709 QualType ASTContext::getUIntPtrType() const { 5710 return getCorrespondingUnsignedType(getIntPtrType()); 5711 } 5712 5713 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 5714 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 5715 QualType ASTContext::getPointerDiffType() const { 5716 return getFromTargetType(Target->getPtrDiffType(0)); 5717 } 5718 5719 /// Return the unique unsigned counterpart of "ptrdiff_t" 5720 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 5721 /// in the definition of %tu format specifier. 5722 QualType ASTContext::getUnsignedPointerDiffType() const { 5723 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 5724 } 5725 5726 /// Return the unique type for "pid_t" defined in 5727 /// <sys/types.h>. We need this to compute the correct type for vfork(). 5728 QualType ASTContext::getProcessIDType() const { 5729 return getFromTargetType(Target->getProcessIDType()); 5730 } 5731 5732 //===----------------------------------------------------------------------===// 5733 // Type Operators 5734 //===----------------------------------------------------------------------===// 5735 5736 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 5737 // Push qualifiers into arrays, and then discard any remaining 5738 // qualifiers. 5739 T = getCanonicalType(T); 5740 T = getVariableArrayDecayedType(T); 5741 const Type *Ty = T.getTypePtr(); 5742 QualType Result; 5743 if (isa<ArrayType>(Ty)) { 5744 Result = getArrayDecayedType(QualType(Ty,0)); 5745 } else if (isa<FunctionType>(Ty)) { 5746 Result = getPointerType(QualType(Ty, 0)); 5747 } else { 5748 Result = QualType(Ty, 0); 5749 } 5750 5751 return CanQualType::CreateUnsafe(Result); 5752 } 5753 5754 QualType ASTContext::getUnqualifiedArrayType(QualType type, 5755 Qualifiers &quals) { 5756 SplitQualType splitType = type.getSplitUnqualifiedType(); 5757 5758 // FIXME: getSplitUnqualifiedType() actually walks all the way to 5759 // the unqualified desugared type and then drops it on the floor. 5760 // We then have to strip that sugar back off with 5761 // getUnqualifiedDesugaredType(), which is silly. 5762 const auto *AT = 5763 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 5764 5765 // If we don't have an array, just use the results in splitType. 5766 if (!AT) { 5767 quals = splitType.Quals; 5768 return QualType(splitType.Ty, 0); 5769 } 5770 5771 // Otherwise, recurse on the array's element type. 5772 QualType elementType = AT->getElementType(); 5773 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5774 5775 // If that didn't change the element type, AT has no qualifiers, so we 5776 // can just use the results in splitType. 5777 if (elementType == unqualElementType) { 5778 assert(quals.empty()); // from the recursive call 5779 quals = splitType.Quals; 5780 return QualType(splitType.Ty, 0); 5781 } 5782 5783 // Otherwise, add in the qualifiers from the outermost type, then 5784 // build the type back up. 5785 quals.addConsistentQualifiers(splitType.Quals); 5786 5787 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5788 return getConstantArrayType(unqualElementType, CAT->getSize(), 5789 CAT->getSizeExpr(), CAT->getSizeModifier(), 0); 5790 } 5791 5792 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5793 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5794 } 5795 5796 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5797 return getVariableArrayType(unqualElementType, 5798 VAT->getSizeExpr(), 5799 VAT->getSizeModifier(), 5800 VAT->getIndexTypeCVRQualifiers(), 5801 VAT->getBracketsRange()); 5802 } 5803 5804 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5805 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5806 DSAT->getSizeModifier(), 0, 5807 SourceRange()); 5808 } 5809 5810 /// Attempt to unwrap two types that may both be array types with the same bound 5811 /// (or both be array types of unknown bound) for the purpose of comparing the 5812 /// cv-decomposition of two types per C++ [conv.qual]. 5813 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5814 while (true) { 5815 auto *AT1 = getAsArrayType(T1); 5816 if (!AT1) 5817 return; 5818 5819 auto *AT2 = getAsArrayType(T2); 5820 if (!AT2) 5821 return; 5822 5823 // If we don't have two array types with the same constant bound nor two 5824 // incomplete array types, we've unwrapped everything we can. 5825 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5826 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5827 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5828 return; 5829 } else if (!isa<IncompleteArrayType>(AT1) || 5830 !isa<IncompleteArrayType>(AT2)) { 5831 return; 5832 } 5833 5834 T1 = AT1->getElementType(); 5835 T2 = AT2->getElementType(); 5836 } 5837 } 5838 5839 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5840 /// 5841 /// If T1 and T2 are both pointer types of the same kind, or both array types 5842 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5843 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5844 /// 5845 /// This function will typically be called in a loop that successively 5846 /// "unwraps" pointer and pointer-to-member types to compare them at each 5847 /// level. 5848 /// 5849 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5850 /// pair of types that can't be unwrapped further. 5851 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5852 UnwrapSimilarArrayTypes(T1, T2); 5853 5854 const auto *T1PtrType = T1->getAs<PointerType>(); 5855 const auto *T2PtrType = T2->getAs<PointerType>(); 5856 if (T1PtrType && T2PtrType) { 5857 T1 = T1PtrType->getPointeeType(); 5858 T2 = T2PtrType->getPointeeType(); 5859 return true; 5860 } 5861 5862 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5863 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5864 if (T1MPType && T2MPType && 5865 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5866 QualType(T2MPType->getClass(), 0))) { 5867 T1 = T1MPType->getPointeeType(); 5868 T2 = T2MPType->getPointeeType(); 5869 return true; 5870 } 5871 5872 if (getLangOpts().ObjC) { 5873 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5874 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5875 if (T1OPType && T2OPType) { 5876 T1 = T1OPType->getPointeeType(); 5877 T2 = T2OPType->getPointeeType(); 5878 return true; 5879 } 5880 } 5881 5882 // FIXME: Block pointers, too? 5883 5884 return false; 5885 } 5886 5887 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5888 while (true) { 5889 Qualifiers Quals; 5890 T1 = getUnqualifiedArrayType(T1, Quals); 5891 T2 = getUnqualifiedArrayType(T2, Quals); 5892 if (hasSameType(T1, T2)) 5893 return true; 5894 if (!UnwrapSimilarTypes(T1, T2)) 5895 return false; 5896 } 5897 } 5898 5899 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5900 while (true) { 5901 Qualifiers Quals1, Quals2; 5902 T1 = getUnqualifiedArrayType(T1, Quals1); 5903 T2 = getUnqualifiedArrayType(T2, Quals2); 5904 5905 Quals1.removeCVRQualifiers(); 5906 Quals2.removeCVRQualifiers(); 5907 if (Quals1 != Quals2) 5908 return false; 5909 5910 if (hasSameType(T1, T2)) 5911 return true; 5912 5913 if (!UnwrapSimilarTypes(T1, T2)) 5914 return false; 5915 } 5916 } 5917 5918 DeclarationNameInfo 5919 ASTContext::getNameForTemplate(TemplateName Name, 5920 SourceLocation NameLoc) const { 5921 switch (Name.getKind()) { 5922 case TemplateName::QualifiedTemplate: 5923 case TemplateName::Template: 5924 // DNInfo work in progress: CHECKME: what about DNLoc? 5925 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5926 NameLoc); 5927 5928 case TemplateName::OverloadedTemplate: { 5929 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5930 // DNInfo work in progress: CHECKME: what about DNLoc? 5931 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5932 } 5933 5934 case TemplateName::AssumedTemplate: { 5935 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); 5936 return DeclarationNameInfo(Storage->getDeclName(), NameLoc); 5937 } 5938 5939 case TemplateName::DependentTemplate: { 5940 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5941 DeclarationName DName; 5942 if (DTN->isIdentifier()) { 5943 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5944 return DeclarationNameInfo(DName, NameLoc); 5945 } else { 5946 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5947 // DNInfo work in progress: FIXME: source locations? 5948 DeclarationNameLoc DNLoc = 5949 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange()); 5950 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5951 } 5952 } 5953 5954 case TemplateName::SubstTemplateTemplateParm: { 5955 SubstTemplateTemplateParmStorage *subst 5956 = Name.getAsSubstTemplateTemplateParm(); 5957 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5958 NameLoc); 5959 } 5960 5961 case TemplateName::SubstTemplateTemplateParmPack: { 5962 SubstTemplateTemplateParmPackStorage *subst 5963 = Name.getAsSubstTemplateTemplateParmPack(); 5964 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5965 NameLoc); 5966 } 5967 } 5968 5969 llvm_unreachable("bad template name kind!"); 5970 } 5971 5972 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5973 switch (Name.getKind()) { 5974 case TemplateName::QualifiedTemplate: 5975 case TemplateName::Template: { 5976 TemplateDecl *Template = Name.getAsTemplateDecl(); 5977 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5978 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5979 5980 // The canonical template name is the canonical template declaration. 5981 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5982 } 5983 5984 case TemplateName::OverloadedTemplate: 5985 case TemplateName::AssumedTemplate: 5986 llvm_unreachable("cannot canonicalize unresolved template"); 5987 5988 case TemplateName::DependentTemplate: { 5989 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5990 assert(DTN && "Non-dependent template names must refer to template decls."); 5991 return DTN->CanonicalTemplateName; 5992 } 5993 5994 case TemplateName::SubstTemplateTemplateParm: { 5995 SubstTemplateTemplateParmStorage *subst 5996 = Name.getAsSubstTemplateTemplateParm(); 5997 return getCanonicalTemplateName(subst->getReplacement()); 5998 } 5999 6000 case TemplateName::SubstTemplateTemplateParmPack: { 6001 SubstTemplateTemplateParmPackStorage *subst 6002 = Name.getAsSubstTemplateTemplateParmPack(); 6003 TemplateTemplateParmDecl *canonParameter 6004 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 6005 TemplateArgument canonArgPack 6006 = getCanonicalTemplateArgument(subst->getArgumentPack()); 6007 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 6008 } 6009 } 6010 6011 llvm_unreachable("bad template name!"); 6012 } 6013 6014 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 6015 X = getCanonicalTemplateName(X); 6016 Y = getCanonicalTemplateName(Y); 6017 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 6018 } 6019 6020 TemplateArgument 6021 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 6022 switch (Arg.getKind()) { 6023 case TemplateArgument::Null: 6024 return Arg; 6025 6026 case TemplateArgument::Expression: 6027 return Arg; 6028 6029 case TemplateArgument::Declaration: { 6030 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 6031 return TemplateArgument(D, Arg.getParamTypeForDecl()); 6032 } 6033 6034 case TemplateArgument::NullPtr: 6035 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 6036 /*isNullPtr*/true); 6037 6038 case TemplateArgument::Template: 6039 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 6040 6041 case TemplateArgument::TemplateExpansion: 6042 return TemplateArgument(getCanonicalTemplateName( 6043 Arg.getAsTemplateOrTemplatePattern()), 6044 Arg.getNumTemplateExpansions()); 6045 6046 case TemplateArgument::Integral: 6047 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 6048 6049 case TemplateArgument::Type: 6050 return TemplateArgument(getCanonicalType(Arg.getAsType())); 6051 6052 case TemplateArgument::Pack: { 6053 if (Arg.pack_size() == 0) 6054 return Arg; 6055 6056 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 6057 unsigned Idx = 0; 6058 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 6059 AEnd = Arg.pack_end(); 6060 A != AEnd; (void)++A, ++Idx) 6061 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 6062 6063 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 6064 } 6065 } 6066 6067 // Silence GCC warning 6068 llvm_unreachable("Unhandled template argument kind"); 6069 } 6070 6071 NestedNameSpecifier * 6072 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 6073 if (!NNS) 6074 return nullptr; 6075 6076 switch (NNS->getKind()) { 6077 case NestedNameSpecifier::Identifier: 6078 // Canonicalize the prefix but keep the identifier the same. 6079 return NestedNameSpecifier::Create(*this, 6080 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 6081 NNS->getAsIdentifier()); 6082 6083 case NestedNameSpecifier::Namespace: 6084 // A namespace is canonical; build a nested-name-specifier with 6085 // this namespace and no prefix. 6086 return NestedNameSpecifier::Create(*this, nullptr, 6087 NNS->getAsNamespace()->getOriginalNamespace()); 6088 6089 case NestedNameSpecifier::NamespaceAlias: 6090 // A namespace is canonical; build a nested-name-specifier with 6091 // this namespace and no prefix. 6092 return NestedNameSpecifier::Create(*this, nullptr, 6093 NNS->getAsNamespaceAlias()->getNamespace() 6094 ->getOriginalNamespace()); 6095 6096 // The difference between TypeSpec and TypeSpecWithTemplate is that the 6097 // latter will have the 'template' keyword when printed. 6098 case NestedNameSpecifier::TypeSpec: 6099 case NestedNameSpecifier::TypeSpecWithTemplate: { 6100 const Type *T = getCanonicalType(NNS->getAsType()); 6101 6102 // If we have some kind of dependent-named type (e.g., "typename T::type"), 6103 // break it apart into its prefix and identifier, then reconsititute those 6104 // as the canonical nested-name-specifier. This is required to canonicalize 6105 // a dependent nested-name-specifier involving typedefs of dependent-name 6106 // types, e.g., 6107 // typedef typename T::type T1; 6108 // typedef typename T1::type T2; 6109 if (const auto *DNT = T->getAs<DependentNameType>()) 6110 return NestedNameSpecifier::Create( 6111 *this, DNT->getQualifier(), 6112 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 6113 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>()) 6114 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, 6115 const_cast<Type *>(T)); 6116 6117 // TODO: Set 'Template' parameter to true for other template types. 6118 return NestedNameSpecifier::Create(*this, nullptr, false, 6119 const_cast<Type *>(T)); 6120 } 6121 6122 case NestedNameSpecifier::Global: 6123 case NestedNameSpecifier::Super: 6124 // The global specifier and __super specifer are canonical and unique. 6125 return NNS; 6126 } 6127 6128 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6129 } 6130 6131 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 6132 // Handle the non-qualified case efficiently. 6133 if (!T.hasLocalQualifiers()) { 6134 // Handle the common positive case fast. 6135 if (const auto *AT = dyn_cast<ArrayType>(T)) 6136 return AT; 6137 } 6138 6139 // Handle the common negative case fast. 6140 if (!isa<ArrayType>(T.getCanonicalType())) 6141 return nullptr; 6142 6143 // Apply any qualifiers from the array type to the element type. This 6144 // implements C99 6.7.3p8: "If the specification of an array type includes 6145 // any type qualifiers, the element type is so qualified, not the array type." 6146 6147 // If we get here, we either have type qualifiers on the type, or we have 6148 // sugar such as a typedef in the way. If we have type qualifiers on the type 6149 // we must propagate them down into the element type. 6150 6151 SplitQualType split = T.getSplitDesugaredType(); 6152 Qualifiers qs = split.Quals; 6153 6154 // If we have a simple case, just return now. 6155 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 6156 if (!ATy || qs.empty()) 6157 return ATy; 6158 6159 // Otherwise, we have an array and we have qualifiers on it. Push the 6160 // qualifiers into the array element type and return a new array type. 6161 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 6162 6163 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 6164 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 6165 CAT->getSizeExpr(), 6166 CAT->getSizeModifier(), 6167 CAT->getIndexTypeCVRQualifiers())); 6168 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 6169 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 6170 IAT->getSizeModifier(), 6171 IAT->getIndexTypeCVRQualifiers())); 6172 6173 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 6174 return cast<ArrayType>( 6175 getDependentSizedArrayType(NewEltTy, 6176 DSAT->getSizeExpr(), 6177 DSAT->getSizeModifier(), 6178 DSAT->getIndexTypeCVRQualifiers(), 6179 DSAT->getBracketsRange())); 6180 6181 const auto *VAT = cast<VariableArrayType>(ATy); 6182 return cast<ArrayType>(getVariableArrayType(NewEltTy, 6183 VAT->getSizeExpr(), 6184 VAT->getSizeModifier(), 6185 VAT->getIndexTypeCVRQualifiers(), 6186 VAT->getBracketsRange())); 6187 } 6188 6189 QualType ASTContext::getAdjustedParameterType(QualType T) const { 6190 if (T->isArrayType() || T->isFunctionType()) 6191 return getDecayedType(T); 6192 return T; 6193 } 6194 6195 QualType ASTContext::getSignatureParameterType(QualType T) const { 6196 T = getVariableArrayDecayedType(T); 6197 T = getAdjustedParameterType(T); 6198 return T.getUnqualifiedType(); 6199 } 6200 6201 QualType ASTContext::getExceptionObjectType(QualType T) const { 6202 // C++ [except.throw]p3: 6203 // A throw-expression initializes a temporary object, called the exception 6204 // object, the type of which is determined by removing any top-level 6205 // cv-qualifiers from the static type of the operand of throw and adjusting 6206 // the type from "array of T" or "function returning T" to "pointer to T" 6207 // or "pointer to function returning T", [...] 6208 T = getVariableArrayDecayedType(T); 6209 if (T->isArrayType() || T->isFunctionType()) 6210 T = getDecayedType(T); 6211 return T.getUnqualifiedType(); 6212 } 6213 6214 /// getArrayDecayedType - Return the properly qualified result of decaying the 6215 /// specified array type to a pointer. This operation is non-trivial when 6216 /// handling typedefs etc. The canonical type of "T" must be an array type, 6217 /// this returns a pointer to a properly qualified element of the array. 6218 /// 6219 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 6220 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 6221 // Get the element type with 'getAsArrayType' so that we don't lose any 6222 // typedefs in the element type of the array. This also handles propagation 6223 // of type qualifiers from the array type into the element type if present 6224 // (C99 6.7.3p8). 6225 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 6226 assert(PrettyArrayType && "Not an array type!"); 6227 6228 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 6229 6230 // int x[restrict 4] -> int *restrict 6231 QualType Result = getQualifiedType(PtrTy, 6232 PrettyArrayType->getIndexTypeQualifiers()); 6233 6234 // int x[_Nullable] -> int * _Nullable 6235 if (auto Nullability = Ty->getNullability(*this)) { 6236 Result = const_cast<ASTContext *>(this)->getAttributedType( 6237 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 6238 } 6239 return Result; 6240 } 6241 6242 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 6243 return getBaseElementType(array->getElementType()); 6244 } 6245 6246 QualType ASTContext::getBaseElementType(QualType type) const { 6247 Qualifiers qs; 6248 while (true) { 6249 SplitQualType split = type.getSplitDesugaredType(); 6250 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 6251 if (!array) break; 6252 6253 type = array->getElementType(); 6254 qs.addConsistentQualifiers(split.Quals); 6255 } 6256 6257 return getQualifiedType(type, qs); 6258 } 6259 6260 /// getConstantArrayElementCount - Returns number of constant array elements. 6261 uint64_t 6262 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 6263 uint64_t ElementCount = 1; 6264 do { 6265 ElementCount *= CA->getSize().getZExtValue(); 6266 CA = dyn_cast_or_null<ConstantArrayType>( 6267 CA->getElementType()->getAsArrayTypeUnsafe()); 6268 } while (CA); 6269 return ElementCount; 6270 } 6271 6272 /// getFloatingRank - Return a relative rank for floating point types. 6273 /// This routine will assert if passed a built-in type that isn't a float. 6274 static FloatingRank getFloatingRank(QualType T) { 6275 if (const auto *CT = T->getAs<ComplexType>()) 6276 return getFloatingRank(CT->getElementType()); 6277 6278 switch (T->castAs<BuiltinType>()->getKind()) { 6279 default: llvm_unreachable("getFloatingRank(): not a floating type"); 6280 case BuiltinType::Float16: return Float16Rank; 6281 case BuiltinType::Half: return HalfRank; 6282 case BuiltinType::Float: return FloatRank; 6283 case BuiltinType::Double: return DoubleRank; 6284 case BuiltinType::LongDouble: return LongDoubleRank; 6285 case BuiltinType::Float128: return Float128Rank; 6286 case BuiltinType::BFloat16: return BFloat16Rank; 6287 } 6288 } 6289 6290 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 6291 /// point or a complex type (based on typeDomain/typeSize). 6292 /// 'typeDomain' is a real floating point or complex type. 6293 /// 'typeSize' is a real floating point or complex type. 6294 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 6295 QualType Domain) const { 6296 FloatingRank EltRank = getFloatingRank(Size); 6297 if (Domain->isComplexType()) { 6298 switch (EltRank) { 6299 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); 6300 case Float16Rank: 6301 case HalfRank: llvm_unreachable("Complex half is not supported"); 6302 case FloatRank: return FloatComplexTy; 6303 case DoubleRank: return DoubleComplexTy; 6304 case LongDoubleRank: return LongDoubleComplexTy; 6305 case Float128Rank: return Float128ComplexTy; 6306 } 6307 } 6308 6309 assert(Domain->isRealFloatingType() && "Unknown domain!"); 6310 switch (EltRank) { 6311 case Float16Rank: return HalfTy; 6312 case BFloat16Rank: return BFloat16Ty; 6313 case HalfRank: return HalfTy; 6314 case FloatRank: return FloatTy; 6315 case DoubleRank: return DoubleTy; 6316 case LongDoubleRank: return LongDoubleTy; 6317 case Float128Rank: return Float128Ty; 6318 } 6319 llvm_unreachable("getFloatingRank(): illegal value for rank"); 6320 } 6321 6322 /// getFloatingTypeOrder - Compare the rank of the two specified floating 6323 /// point types, ignoring the domain of the type (i.e. 'double' == 6324 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 6325 /// LHS < RHS, return -1. 6326 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 6327 FloatingRank LHSR = getFloatingRank(LHS); 6328 FloatingRank RHSR = getFloatingRank(RHS); 6329 6330 if (LHSR == RHSR) 6331 return 0; 6332 if (LHSR > RHSR) 6333 return 1; 6334 return -1; 6335 } 6336 6337 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { 6338 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) 6339 return 0; 6340 return getFloatingTypeOrder(LHS, RHS); 6341 } 6342 6343 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 6344 /// routine will assert if passed a built-in type that isn't an integer or enum, 6345 /// or if it is not canonicalized. 6346 unsigned ASTContext::getIntegerRank(const Type *T) const { 6347 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 6348 6349 // Results in this 'losing' to any type of the same size, but winning if 6350 // larger. 6351 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 6352 return 0 + (EIT->getNumBits() << 3); 6353 6354 switch (cast<BuiltinType>(T)->getKind()) { 6355 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 6356 case BuiltinType::Bool: 6357 return 1 + (getIntWidth(BoolTy) << 3); 6358 case BuiltinType::Char_S: 6359 case BuiltinType::Char_U: 6360 case BuiltinType::SChar: 6361 case BuiltinType::UChar: 6362 return 2 + (getIntWidth(CharTy) << 3); 6363 case BuiltinType::Short: 6364 case BuiltinType::UShort: 6365 return 3 + (getIntWidth(ShortTy) << 3); 6366 case BuiltinType::Int: 6367 case BuiltinType::UInt: 6368 return 4 + (getIntWidth(IntTy) << 3); 6369 case BuiltinType::Long: 6370 case BuiltinType::ULong: 6371 return 5 + (getIntWidth(LongTy) << 3); 6372 case BuiltinType::LongLong: 6373 case BuiltinType::ULongLong: 6374 return 6 + (getIntWidth(LongLongTy) << 3); 6375 case BuiltinType::Int128: 6376 case BuiltinType::UInt128: 6377 return 7 + (getIntWidth(Int128Ty) << 3); 6378 } 6379 } 6380 6381 /// Whether this is a promotable bitfield reference according 6382 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 6383 /// 6384 /// \returns the type this bit-field will promote to, or NULL if no 6385 /// promotion occurs. 6386 QualType ASTContext::isPromotableBitField(Expr *E) const { 6387 if (E->isTypeDependent() || E->isValueDependent()) 6388 return {}; 6389 6390 // C++ [conv.prom]p5: 6391 // If the bit-field has an enumerated type, it is treated as any other 6392 // value of that type for promotion purposes. 6393 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 6394 return {}; 6395 6396 // FIXME: We should not do this unless E->refersToBitField() is true. This 6397 // matters in C where getSourceBitField() will find bit-fields for various 6398 // cases where the source expression is not a bit-field designator. 6399 6400 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 6401 if (!Field) 6402 return {}; 6403 6404 QualType FT = Field->getType(); 6405 6406 uint64_t BitWidth = Field->getBitWidthValue(*this); 6407 uint64_t IntSize = getTypeSize(IntTy); 6408 // C++ [conv.prom]p5: 6409 // A prvalue for an integral bit-field can be converted to a prvalue of type 6410 // int if int can represent all the values of the bit-field; otherwise, it 6411 // can be converted to unsigned int if unsigned int can represent all the 6412 // values of the bit-field. If the bit-field is larger yet, no integral 6413 // promotion applies to it. 6414 // C11 6.3.1.1/2: 6415 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 6416 // If an int can represent all values of the original type (as restricted by 6417 // the width, for a bit-field), the value is converted to an int; otherwise, 6418 // it is converted to an unsigned int. 6419 // 6420 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 6421 // We perform that promotion here to match GCC and C++. 6422 // FIXME: C does not permit promotion of an enum bit-field whose rank is 6423 // greater than that of 'int'. We perform that promotion to match GCC. 6424 if (BitWidth < IntSize) 6425 return IntTy; 6426 6427 if (BitWidth == IntSize) 6428 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 6429 6430 // Bit-fields wider than int are not subject to promotions, and therefore act 6431 // like the base type. GCC has some weird bugs in this area that we 6432 // deliberately do not follow (GCC follows a pre-standard resolution to 6433 // C's DR315 which treats bit-width as being part of the type, and this leaks 6434 // into their semantics in some cases). 6435 return {}; 6436 } 6437 6438 /// getPromotedIntegerType - Returns the type that Promotable will 6439 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 6440 /// integer type. 6441 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 6442 assert(!Promotable.isNull()); 6443 assert(Promotable->isPromotableIntegerType()); 6444 if (const auto *ET = Promotable->getAs<EnumType>()) 6445 return ET->getDecl()->getPromotionType(); 6446 6447 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 6448 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 6449 // (3.9.1) can be converted to a prvalue of the first of the following 6450 // types that can represent all the values of its underlying type: 6451 // int, unsigned int, long int, unsigned long int, long long int, or 6452 // unsigned long long int [...] 6453 // FIXME: Is there some better way to compute this? 6454 if (BT->getKind() == BuiltinType::WChar_S || 6455 BT->getKind() == BuiltinType::WChar_U || 6456 BT->getKind() == BuiltinType::Char8 || 6457 BT->getKind() == BuiltinType::Char16 || 6458 BT->getKind() == BuiltinType::Char32) { 6459 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 6460 uint64_t FromSize = getTypeSize(BT); 6461 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 6462 LongLongTy, UnsignedLongLongTy }; 6463 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 6464 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 6465 if (FromSize < ToSize || 6466 (FromSize == ToSize && 6467 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 6468 return PromoteTypes[Idx]; 6469 } 6470 llvm_unreachable("char type should fit into long long"); 6471 } 6472 } 6473 6474 // At this point, we should have a signed or unsigned integer type. 6475 if (Promotable->isSignedIntegerType()) 6476 return IntTy; 6477 uint64_t PromotableSize = getIntWidth(Promotable); 6478 uint64_t IntSize = getIntWidth(IntTy); 6479 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 6480 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 6481 } 6482 6483 /// Recurses in pointer/array types until it finds an objc retainable 6484 /// type and returns its ownership. 6485 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 6486 while (!T.isNull()) { 6487 if (T.getObjCLifetime() != Qualifiers::OCL_None) 6488 return T.getObjCLifetime(); 6489 if (T->isArrayType()) 6490 T = getBaseElementType(T); 6491 else if (const auto *PT = T->getAs<PointerType>()) 6492 T = PT->getPointeeType(); 6493 else if (const auto *RT = T->getAs<ReferenceType>()) 6494 T = RT->getPointeeType(); 6495 else 6496 break; 6497 } 6498 6499 return Qualifiers::OCL_None; 6500 } 6501 6502 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 6503 // Incomplete enum types are not treated as integer types. 6504 // FIXME: In C++, enum types are never integer types. 6505 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 6506 return ET->getDecl()->getIntegerType().getTypePtr(); 6507 return nullptr; 6508 } 6509 6510 /// getIntegerTypeOrder - Returns the highest ranked integer type: 6511 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 6512 /// LHS < RHS, return -1. 6513 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 6514 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 6515 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 6516 6517 // Unwrap enums to their underlying type. 6518 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 6519 LHSC = getIntegerTypeForEnum(ET); 6520 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 6521 RHSC = getIntegerTypeForEnum(ET); 6522 6523 if (LHSC == RHSC) return 0; 6524 6525 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 6526 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 6527 6528 unsigned LHSRank = getIntegerRank(LHSC); 6529 unsigned RHSRank = getIntegerRank(RHSC); 6530 6531 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 6532 if (LHSRank == RHSRank) return 0; 6533 return LHSRank > RHSRank ? 1 : -1; 6534 } 6535 6536 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 6537 if (LHSUnsigned) { 6538 // If the unsigned [LHS] type is larger, return it. 6539 if (LHSRank >= RHSRank) 6540 return 1; 6541 6542 // If the signed type can represent all values of the unsigned type, it 6543 // wins. Because we are dealing with 2's complement and types that are 6544 // powers of two larger than each other, this is always safe. 6545 return -1; 6546 } 6547 6548 // If the unsigned [RHS] type is larger, return it. 6549 if (RHSRank >= LHSRank) 6550 return -1; 6551 6552 // If the signed type can represent all values of the unsigned type, it 6553 // wins. Because we are dealing with 2's complement and types that are 6554 // powers of two larger than each other, this is always safe. 6555 return 1; 6556 } 6557 6558 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 6559 if (CFConstantStringTypeDecl) 6560 return CFConstantStringTypeDecl; 6561 6562 assert(!CFConstantStringTagDecl && 6563 "tag and typedef should be initialized together"); 6564 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 6565 CFConstantStringTagDecl->startDefinition(); 6566 6567 struct { 6568 QualType Type; 6569 const char *Name; 6570 } Fields[5]; 6571 unsigned Count = 0; 6572 6573 /// Objective-C ABI 6574 /// 6575 /// typedef struct __NSConstantString_tag { 6576 /// const int *isa; 6577 /// int flags; 6578 /// const char *str; 6579 /// long length; 6580 /// } __NSConstantString; 6581 /// 6582 /// Swift ABI (4.1, 4.2) 6583 /// 6584 /// typedef struct __NSConstantString_tag { 6585 /// uintptr_t _cfisa; 6586 /// uintptr_t _swift_rc; 6587 /// _Atomic(uint64_t) _cfinfoa; 6588 /// const char *_ptr; 6589 /// uint32_t _length; 6590 /// } __NSConstantString; 6591 /// 6592 /// Swift ABI (5.0) 6593 /// 6594 /// typedef struct __NSConstantString_tag { 6595 /// uintptr_t _cfisa; 6596 /// uintptr_t _swift_rc; 6597 /// _Atomic(uint64_t) _cfinfoa; 6598 /// const char *_ptr; 6599 /// uintptr_t _length; 6600 /// } __NSConstantString; 6601 6602 const auto CFRuntime = getLangOpts().CFRuntime; 6603 if (static_cast<unsigned>(CFRuntime) < 6604 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { 6605 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; 6606 Fields[Count++] = { IntTy, "flags" }; 6607 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; 6608 Fields[Count++] = { LongTy, "length" }; 6609 } else { 6610 Fields[Count++] = { getUIntPtrType(), "_cfisa" }; 6611 Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; 6612 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; 6613 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; 6614 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6615 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6616 Fields[Count++] = { IntTy, "_ptr" }; 6617 else 6618 Fields[Count++] = { getUIntPtrType(), "_ptr" }; 6619 } 6620 6621 // Create fields 6622 for (unsigned i = 0; i < Count; ++i) { 6623 FieldDecl *Field = 6624 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), 6625 SourceLocation(), &Idents.get(Fields[i].Name), 6626 Fields[i].Type, /*TInfo=*/nullptr, 6627 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6628 Field->setAccess(AS_public); 6629 CFConstantStringTagDecl->addDecl(Field); 6630 } 6631 6632 CFConstantStringTagDecl->completeDefinition(); 6633 // This type is designed to be compatible with NSConstantString, but cannot 6634 // use the same name, since NSConstantString is an interface. 6635 auto tagType = getTagDeclType(CFConstantStringTagDecl); 6636 CFConstantStringTypeDecl = 6637 buildImplicitTypedef(tagType, "__NSConstantString"); 6638 6639 return CFConstantStringTypeDecl; 6640 } 6641 6642 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 6643 if (!CFConstantStringTagDecl) 6644 getCFConstantStringDecl(); // Build the tag and the typedef. 6645 return CFConstantStringTagDecl; 6646 } 6647 6648 // getCFConstantStringType - Return the type used for constant CFStrings. 6649 QualType ASTContext::getCFConstantStringType() const { 6650 return getTypedefType(getCFConstantStringDecl()); 6651 } 6652 6653 QualType ASTContext::getObjCSuperType() const { 6654 if (ObjCSuperType.isNull()) { 6655 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 6656 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl); 6657 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 6658 } 6659 return ObjCSuperType; 6660 } 6661 6662 void ASTContext::setCFConstantStringType(QualType T) { 6663 const auto *TD = T->castAs<TypedefType>(); 6664 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 6665 const auto *TagType = 6666 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); 6667 CFConstantStringTagDecl = TagType->getDecl(); 6668 } 6669 6670 QualType ASTContext::getBlockDescriptorType() const { 6671 if (BlockDescriptorType) 6672 return getTagDeclType(BlockDescriptorType); 6673 6674 RecordDecl *RD; 6675 // FIXME: Needs the FlagAppleBlock bit. 6676 RD = buildImplicitRecord("__block_descriptor"); 6677 RD->startDefinition(); 6678 6679 QualType FieldTypes[] = { 6680 UnsignedLongTy, 6681 UnsignedLongTy, 6682 }; 6683 6684 static const char *const FieldNames[] = { 6685 "reserved", 6686 "Size" 6687 }; 6688 6689 for (size_t i = 0; i < 2; ++i) { 6690 FieldDecl *Field = FieldDecl::Create( 6691 *this, RD, SourceLocation(), SourceLocation(), 6692 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6693 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 6694 Field->setAccess(AS_public); 6695 RD->addDecl(Field); 6696 } 6697 6698 RD->completeDefinition(); 6699 6700 BlockDescriptorType = RD; 6701 6702 return getTagDeclType(BlockDescriptorType); 6703 } 6704 6705 QualType ASTContext::getBlockDescriptorExtendedType() const { 6706 if (BlockDescriptorExtendedType) 6707 return getTagDeclType(BlockDescriptorExtendedType); 6708 6709 RecordDecl *RD; 6710 // FIXME: Needs the FlagAppleBlock bit. 6711 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 6712 RD->startDefinition(); 6713 6714 QualType FieldTypes[] = { 6715 UnsignedLongTy, 6716 UnsignedLongTy, 6717 getPointerType(VoidPtrTy), 6718 getPointerType(VoidPtrTy) 6719 }; 6720 6721 static const char *const FieldNames[] = { 6722 "reserved", 6723 "Size", 6724 "CopyFuncPtr", 6725 "DestroyFuncPtr" 6726 }; 6727 6728 for (size_t i = 0; i < 4; ++i) { 6729 FieldDecl *Field = FieldDecl::Create( 6730 *this, RD, SourceLocation(), SourceLocation(), 6731 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 6732 /*BitWidth=*/nullptr, 6733 /*Mutable=*/false, ICIS_NoInit); 6734 Field->setAccess(AS_public); 6735 RD->addDecl(Field); 6736 } 6737 6738 RD->completeDefinition(); 6739 6740 BlockDescriptorExtendedType = RD; 6741 return getTagDeclType(BlockDescriptorExtendedType); 6742 } 6743 6744 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 6745 const auto *BT = dyn_cast<BuiltinType>(T); 6746 6747 if (!BT) { 6748 if (isa<PipeType>(T)) 6749 return OCLTK_Pipe; 6750 6751 return OCLTK_Default; 6752 } 6753 6754 switch (BT->getKind()) { 6755 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6756 case BuiltinType::Id: \ 6757 return OCLTK_Image; 6758 #include "clang/Basic/OpenCLImageTypes.def" 6759 6760 case BuiltinType::OCLClkEvent: 6761 return OCLTK_ClkEvent; 6762 6763 case BuiltinType::OCLEvent: 6764 return OCLTK_Event; 6765 6766 case BuiltinType::OCLQueue: 6767 return OCLTK_Queue; 6768 6769 case BuiltinType::OCLReserveID: 6770 return OCLTK_ReserveID; 6771 6772 case BuiltinType::OCLSampler: 6773 return OCLTK_Sampler; 6774 6775 default: 6776 return OCLTK_Default; 6777 } 6778 } 6779 6780 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 6781 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 6782 } 6783 6784 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 6785 /// requires copy/dispose. Note that this must match the logic 6786 /// in buildByrefHelpers. 6787 bool ASTContext::BlockRequiresCopying(QualType Ty, 6788 const VarDecl *D) { 6789 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 6790 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 6791 if (!copyExpr && record->hasTrivialDestructor()) return false; 6792 6793 return true; 6794 } 6795 6796 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 6797 // move or destroy. 6798 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 6799 return true; 6800 6801 if (!Ty->isObjCRetainableType()) return false; 6802 6803 Qualifiers qs = Ty.getQualifiers(); 6804 6805 // If we have lifetime, that dominates. 6806 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 6807 switch (lifetime) { 6808 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 6809 6810 // These are just bits as far as the runtime is concerned. 6811 case Qualifiers::OCL_ExplicitNone: 6812 case Qualifiers::OCL_Autoreleasing: 6813 return false; 6814 6815 // These cases should have been taken care of when checking the type's 6816 // non-triviality. 6817 case Qualifiers::OCL_Weak: 6818 case Qualifiers::OCL_Strong: 6819 llvm_unreachable("impossible"); 6820 } 6821 llvm_unreachable("fell out of lifetime switch!"); 6822 } 6823 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6824 Ty->isObjCObjectPointerType()); 6825 } 6826 6827 bool ASTContext::getByrefLifetime(QualType Ty, 6828 Qualifiers::ObjCLifetime &LifeTime, 6829 bool &HasByrefExtendedLayout) const { 6830 if (!getLangOpts().ObjC || 6831 getLangOpts().getGC() != LangOptions::NonGC) 6832 return false; 6833 6834 HasByrefExtendedLayout = false; 6835 if (Ty->isRecordType()) { 6836 HasByrefExtendedLayout = true; 6837 LifeTime = Qualifiers::OCL_None; 6838 } else if ((LifeTime = Ty.getObjCLifetime())) { 6839 // Honor the ARC qualifiers. 6840 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6841 // The MRR rule. 6842 LifeTime = Qualifiers::OCL_ExplicitNone; 6843 } else { 6844 LifeTime = Qualifiers::OCL_None; 6845 } 6846 return true; 6847 } 6848 6849 CanQualType ASTContext::getNSUIntegerType() const { 6850 assert(Target && "Expected target to be initialized"); 6851 const llvm::Triple &T = Target->getTriple(); 6852 // Windows is LLP64 rather than LP64 6853 if (T.isOSWindows() && T.isArch64Bit()) 6854 return UnsignedLongLongTy; 6855 return UnsignedLongTy; 6856 } 6857 6858 CanQualType ASTContext::getNSIntegerType() const { 6859 assert(Target && "Expected target to be initialized"); 6860 const llvm::Triple &T = Target->getTriple(); 6861 // Windows is LLP64 rather than LP64 6862 if (T.isOSWindows() && T.isArch64Bit()) 6863 return LongLongTy; 6864 return LongTy; 6865 } 6866 6867 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6868 if (!ObjCInstanceTypeDecl) 6869 ObjCInstanceTypeDecl = 6870 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6871 return ObjCInstanceTypeDecl; 6872 } 6873 6874 // This returns true if a type has been typedefed to BOOL: 6875 // typedef <type> BOOL; 6876 static bool isTypeTypedefedAsBOOL(QualType T) { 6877 if (const auto *TT = dyn_cast<TypedefType>(T)) 6878 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6879 return II->isStr("BOOL"); 6880 6881 return false; 6882 } 6883 6884 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6885 /// purpose. 6886 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6887 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6888 return CharUnits::Zero(); 6889 6890 CharUnits sz = getTypeSizeInChars(type); 6891 6892 // Make all integer and enum types at least as large as an int 6893 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6894 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6895 // Treat arrays as pointers, since that's how they're passed in. 6896 else if (type->isArrayType()) 6897 sz = getTypeSizeInChars(VoidPtrTy); 6898 return sz; 6899 } 6900 6901 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6902 return getTargetInfo().getCXXABI().isMicrosoft() && 6903 VD->isStaticDataMember() && 6904 VD->getType()->isIntegralOrEnumerationType() && 6905 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6906 } 6907 6908 ASTContext::InlineVariableDefinitionKind 6909 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6910 if (!VD->isInline()) 6911 return InlineVariableDefinitionKind::None; 6912 6913 // In almost all cases, it's a weak definition. 6914 auto *First = VD->getFirstDecl(); 6915 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6916 return InlineVariableDefinitionKind::Weak; 6917 6918 // If there's a file-context declaration in this translation unit, it's a 6919 // non-discardable definition. 6920 for (auto *D : VD->redecls()) 6921 if (D->getLexicalDeclContext()->isFileContext() && 6922 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6923 return InlineVariableDefinitionKind::Strong; 6924 6925 // If we've not seen one yet, we don't know. 6926 return InlineVariableDefinitionKind::WeakUnknown; 6927 } 6928 6929 static std::string charUnitsToString(const CharUnits &CU) { 6930 return llvm::itostr(CU.getQuantity()); 6931 } 6932 6933 /// getObjCEncodingForBlock - Return the encoded type for this block 6934 /// declaration. 6935 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6936 std::string S; 6937 6938 const BlockDecl *Decl = Expr->getBlockDecl(); 6939 QualType BlockTy = 6940 Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); 6941 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); 6942 // Encode result type. 6943 if (getLangOpts().EncodeExtendedBlockSig) 6944 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, 6945 true /*Extended*/); 6946 else 6947 getObjCEncodingForType(BlockReturnTy, S); 6948 // Compute size of all parameters. 6949 // Start with computing size of a pointer in number of bytes. 6950 // FIXME: There might(should) be a better way of doing this computation! 6951 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6952 CharUnits ParmOffset = PtrSize; 6953 for (auto PI : Decl->parameters()) { 6954 QualType PType = PI->getType(); 6955 CharUnits sz = getObjCEncodingTypeSize(PType); 6956 if (sz.isZero()) 6957 continue; 6958 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6959 ParmOffset += sz; 6960 } 6961 // Size of the argument frame 6962 S += charUnitsToString(ParmOffset); 6963 // Block pointer and offset. 6964 S += "@?0"; 6965 6966 // Argument types. 6967 ParmOffset = PtrSize; 6968 for (auto PVDecl : Decl->parameters()) { 6969 QualType PType = PVDecl->getOriginalType(); 6970 if (const auto *AT = 6971 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6972 // Use array's original type only if it has known number of 6973 // elements. 6974 if (!isa<ConstantArrayType>(AT)) 6975 PType = PVDecl->getType(); 6976 } else if (PType->isFunctionType()) 6977 PType = PVDecl->getType(); 6978 if (getLangOpts().EncodeExtendedBlockSig) 6979 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6980 S, true /*Extended*/); 6981 else 6982 getObjCEncodingForType(PType, S); 6983 S += charUnitsToString(ParmOffset); 6984 ParmOffset += getObjCEncodingTypeSize(PType); 6985 } 6986 6987 return S; 6988 } 6989 6990 std::string 6991 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6992 std::string S; 6993 // Encode result type. 6994 getObjCEncodingForType(Decl->getReturnType(), S); 6995 CharUnits ParmOffset; 6996 // Compute size of all parameters. 6997 for (auto PI : Decl->parameters()) { 6998 QualType PType = PI->getType(); 6999 CharUnits sz = getObjCEncodingTypeSize(PType); 7000 if (sz.isZero()) 7001 continue; 7002 7003 assert(sz.isPositive() && 7004 "getObjCEncodingForFunctionDecl - Incomplete param type"); 7005 ParmOffset += sz; 7006 } 7007 S += charUnitsToString(ParmOffset); 7008 ParmOffset = CharUnits::Zero(); 7009 7010 // Argument types. 7011 for (auto PVDecl : Decl->parameters()) { 7012 QualType PType = PVDecl->getOriginalType(); 7013 if (const auto *AT = 7014 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7015 // Use array's original type only if it has known number of 7016 // elements. 7017 if (!isa<ConstantArrayType>(AT)) 7018 PType = PVDecl->getType(); 7019 } else if (PType->isFunctionType()) 7020 PType = PVDecl->getType(); 7021 getObjCEncodingForType(PType, S); 7022 S += charUnitsToString(ParmOffset); 7023 ParmOffset += getObjCEncodingTypeSize(PType); 7024 } 7025 7026 return S; 7027 } 7028 7029 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 7030 /// method parameter or return type. If Extended, include class names and 7031 /// block object types. 7032 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 7033 QualType T, std::string& S, 7034 bool Extended) const { 7035 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 7036 getObjCEncodingForTypeQualifier(QT, S); 7037 // Encode parameter type. 7038 ObjCEncOptions Options = ObjCEncOptions() 7039 .setExpandPointedToStructures() 7040 .setExpandStructures() 7041 .setIsOutermostType(); 7042 if (Extended) 7043 Options.setEncodeBlockParameters().setEncodeClassNames(); 7044 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); 7045 } 7046 7047 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 7048 /// declaration. 7049 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 7050 bool Extended) const { 7051 // FIXME: This is not very efficient. 7052 // Encode return type. 7053 std::string S; 7054 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 7055 Decl->getReturnType(), S, Extended); 7056 // Compute size of all parameters. 7057 // Start with computing size of a pointer in number of bytes. 7058 // FIXME: There might(should) be a better way of doing this computation! 7059 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 7060 // The first two arguments (self and _cmd) are pointers; account for 7061 // their size. 7062 CharUnits ParmOffset = 2 * PtrSize; 7063 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7064 E = Decl->sel_param_end(); PI != E; ++PI) { 7065 QualType PType = (*PI)->getType(); 7066 CharUnits sz = getObjCEncodingTypeSize(PType); 7067 if (sz.isZero()) 7068 continue; 7069 7070 assert(sz.isPositive() && 7071 "getObjCEncodingForMethodDecl - Incomplete param type"); 7072 ParmOffset += sz; 7073 } 7074 S += charUnitsToString(ParmOffset); 7075 S += "@0:"; 7076 S += charUnitsToString(PtrSize); 7077 7078 // Argument types. 7079 ParmOffset = 2 * PtrSize; 7080 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 7081 E = Decl->sel_param_end(); PI != E; ++PI) { 7082 const ParmVarDecl *PVDecl = *PI; 7083 QualType PType = PVDecl->getOriginalType(); 7084 if (const auto *AT = 7085 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 7086 // Use array's original type only if it has known number of 7087 // elements. 7088 if (!isa<ConstantArrayType>(AT)) 7089 PType = PVDecl->getType(); 7090 } else if (PType->isFunctionType()) 7091 PType = PVDecl->getType(); 7092 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 7093 PType, S, Extended); 7094 S += charUnitsToString(ParmOffset); 7095 ParmOffset += getObjCEncodingTypeSize(PType); 7096 } 7097 7098 return S; 7099 } 7100 7101 ObjCPropertyImplDecl * 7102 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 7103 const ObjCPropertyDecl *PD, 7104 const Decl *Container) const { 7105 if (!Container) 7106 return nullptr; 7107 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 7108 for (auto *PID : CID->property_impls()) 7109 if (PID->getPropertyDecl() == PD) 7110 return PID; 7111 } else { 7112 const auto *OID = cast<ObjCImplementationDecl>(Container); 7113 for (auto *PID : OID->property_impls()) 7114 if (PID->getPropertyDecl() == PD) 7115 return PID; 7116 } 7117 return nullptr; 7118 } 7119 7120 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 7121 /// property declaration. If non-NULL, Container must be either an 7122 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 7123 /// NULL when getting encodings for protocol properties. 7124 /// Property attributes are stored as a comma-delimited C string. The simple 7125 /// attributes readonly and bycopy are encoded as single characters. The 7126 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 7127 /// encoded as single characters, followed by an identifier. Property types 7128 /// are also encoded as a parametrized attribute. The characters used to encode 7129 /// these attributes are defined by the following enumeration: 7130 /// @code 7131 /// enum PropertyAttributes { 7132 /// kPropertyReadOnly = 'R', // property is read-only. 7133 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 7134 /// kPropertyByref = '&', // property is a reference to the value last assigned 7135 /// kPropertyDynamic = 'D', // property is dynamic 7136 /// kPropertyGetter = 'G', // followed by getter selector name 7137 /// kPropertySetter = 'S', // followed by setter selector name 7138 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 7139 /// kPropertyType = 'T' // followed by old-style type encoding. 7140 /// kPropertyWeak = 'W' // 'weak' property 7141 /// kPropertyStrong = 'P' // property GC'able 7142 /// kPropertyNonAtomic = 'N' // property non-atomic 7143 /// }; 7144 /// @endcode 7145 std::string 7146 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 7147 const Decl *Container) const { 7148 // Collect information from the property implementation decl(s). 7149 bool Dynamic = false; 7150 ObjCPropertyImplDecl *SynthesizePID = nullptr; 7151 7152 if (ObjCPropertyImplDecl *PropertyImpDecl = 7153 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 7154 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7155 Dynamic = true; 7156 else 7157 SynthesizePID = PropertyImpDecl; 7158 } 7159 7160 // FIXME: This is not very efficient. 7161 std::string S = "T"; 7162 7163 // Encode result type. 7164 // GCC has some special rules regarding encoding of properties which 7165 // closely resembles encoding of ivars. 7166 getObjCEncodingForPropertyType(PD->getType(), S); 7167 7168 if (PD->isReadOnly()) { 7169 S += ",R"; 7170 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) 7171 S += ",C"; 7172 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) 7173 S += ",&"; 7174 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) 7175 S += ",W"; 7176 } else { 7177 switch (PD->getSetterKind()) { 7178 case ObjCPropertyDecl::Assign: break; 7179 case ObjCPropertyDecl::Copy: S += ",C"; break; 7180 case ObjCPropertyDecl::Retain: S += ",&"; break; 7181 case ObjCPropertyDecl::Weak: S += ",W"; break; 7182 } 7183 } 7184 7185 // It really isn't clear at all what this means, since properties 7186 // are "dynamic by default". 7187 if (Dynamic) 7188 S += ",D"; 7189 7190 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic) 7191 S += ",N"; 7192 7193 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 7194 S += ",G"; 7195 S += PD->getGetterName().getAsString(); 7196 } 7197 7198 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 7199 S += ",S"; 7200 S += PD->getSetterName().getAsString(); 7201 } 7202 7203 if (SynthesizePID) { 7204 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 7205 S += ",V"; 7206 S += OID->getNameAsString(); 7207 } 7208 7209 // FIXME: OBJCGC: weak & strong 7210 return S; 7211 } 7212 7213 /// getLegacyIntegralTypeEncoding - 7214 /// Another legacy compatibility encoding: 32-bit longs are encoded as 7215 /// 'l' or 'L' , but not always. For typedefs, we need to use 7216 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 7217 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 7218 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 7219 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 7220 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 7221 PointeeTy = UnsignedIntTy; 7222 else 7223 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 7224 PointeeTy = IntTy; 7225 } 7226 } 7227 } 7228 7229 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 7230 const FieldDecl *Field, 7231 QualType *NotEncodedT) const { 7232 // We follow the behavior of gcc, expanding structures which are 7233 // directly pointed to, and expanding embedded structures. Note that 7234 // these rules are sufficient to prevent recursive encoding of the 7235 // same type. 7236 getObjCEncodingForTypeImpl(T, S, 7237 ObjCEncOptions() 7238 .setExpandPointedToStructures() 7239 .setExpandStructures() 7240 .setIsOutermostType(), 7241 Field, NotEncodedT); 7242 } 7243 7244 void ASTContext::getObjCEncodingForPropertyType(QualType T, 7245 std::string& S) const { 7246 // Encode result type. 7247 // GCC has some special rules regarding encoding of properties which 7248 // closely resembles encoding of ivars. 7249 getObjCEncodingForTypeImpl(T, S, 7250 ObjCEncOptions() 7251 .setExpandPointedToStructures() 7252 .setExpandStructures() 7253 .setIsOutermostType() 7254 .setEncodingProperty(), 7255 /*Field=*/nullptr); 7256 } 7257 7258 static char getObjCEncodingForPrimitiveType(const ASTContext *C, 7259 const BuiltinType *BT) { 7260 BuiltinType::Kind kind = BT->getKind(); 7261 switch (kind) { 7262 case BuiltinType::Void: return 'v'; 7263 case BuiltinType::Bool: return 'B'; 7264 case BuiltinType::Char8: 7265 case BuiltinType::Char_U: 7266 case BuiltinType::UChar: return 'C'; 7267 case BuiltinType::Char16: 7268 case BuiltinType::UShort: return 'S'; 7269 case BuiltinType::Char32: 7270 case BuiltinType::UInt: return 'I'; 7271 case BuiltinType::ULong: 7272 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 7273 case BuiltinType::UInt128: return 'T'; 7274 case BuiltinType::ULongLong: return 'Q'; 7275 case BuiltinType::Char_S: 7276 case BuiltinType::SChar: return 'c'; 7277 case BuiltinType::Short: return 's'; 7278 case BuiltinType::WChar_S: 7279 case BuiltinType::WChar_U: 7280 case BuiltinType::Int: return 'i'; 7281 case BuiltinType::Long: 7282 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 7283 case BuiltinType::LongLong: return 'q'; 7284 case BuiltinType::Int128: return 't'; 7285 case BuiltinType::Float: return 'f'; 7286 case BuiltinType::Double: return 'd'; 7287 case BuiltinType::LongDouble: return 'D'; 7288 case BuiltinType::NullPtr: return '*'; // like char* 7289 7290 case BuiltinType::BFloat16: 7291 case BuiltinType::Float16: 7292 case BuiltinType::Float128: 7293 case BuiltinType::Half: 7294 case BuiltinType::ShortAccum: 7295 case BuiltinType::Accum: 7296 case BuiltinType::LongAccum: 7297 case BuiltinType::UShortAccum: 7298 case BuiltinType::UAccum: 7299 case BuiltinType::ULongAccum: 7300 case BuiltinType::ShortFract: 7301 case BuiltinType::Fract: 7302 case BuiltinType::LongFract: 7303 case BuiltinType::UShortFract: 7304 case BuiltinType::UFract: 7305 case BuiltinType::ULongFract: 7306 case BuiltinType::SatShortAccum: 7307 case BuiltinType::SatAccum: 7308 case BuiltinType::SatLongAccum: 7309 case BuiltinType::SatUShortAccum: 7310 case BuiltinType::SatUAccum: 7311 case BuiltinType::SatULongAccum: 7312 case BuiltinType::SatShortFract: 7313 case BuiltinType::SatFract: 7314 case BuiltinType::SatLongFract: 7315 case BuiltinType::SatUShortFract: 7316 case BuiltinType::SatUFract: 7317 case BuiltinType::SatULongFract: 7318 // FIXME: potentially need @encodes for these! 7319 return ' '; 7320 7321 #define SVE_TYPE(Name, Id, SingletonId) \ 7322 case BuiltinType::Id: 7323 #include "clang/Basic/AArch64SVEACLETypes.def" 7324 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 7325 #include "clang/Basic/RISCVVTypes.def" 7326 { 7327 DiagnosticsEngine &Diags = C->getDiagnostics(); 7328 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 7329 "cannot yet @encode type %0"); 7330 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); 7331 return ' '; 7332 } 7333 7334 case BuiltinType::ObjCId: 7335 case BuiltinType::ObjCClass: 7336 case BuiltinType::ObjCSel: 7337 llvm_unreachable("@encoding ObjC primitive type"); 7338 7339 // OpenCL and placeholder types don't need @encodings. 7340 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7341 case BuiltinType::Id: 7342 #include "clang/Basic/OpenCLImageTypes.def" 7343 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7344 case BuiltinType::Id: 7345 #include "clang/Basic/OpenCLExtensionTypes.def" 7346 case BuiltinType::OCLEvent: 7347 case BuiltinType::OCLClkEvent: 7348 case BuiltinType::OCLQueue: 7349 case BuiltinType::OCLReserveID: 7350 case BuiltinType::OCLSampler: 7351 case BuiltinType::Dependent: 7352 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7353 case BuiltinType::Id: 7354 #include "clang/Basic/PPCTypes.def" 7355 #define BUILTIN_TYPE(KIND, ID) 7356 #define PLACEHOLDER_TYPE(KIND, ID) \ 7357 case BuiltinType::KIND: 7358 #include "clang/AST/BuiltinTypes.def" 7359 llvm_unreachable("invalid builtin type for @encode"); 7360 } 7361 llvm_unreachable("invalid BuiltinType::Kind value"); 7362 } 7363 7364 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 7365 EnumDecl *Enum = ET->getDecl(); 7366 7367 // The encoding of an non-fixed enum type is always 'i', regardless of size. 7368 if (!Enum->isFixed()) 7369 return 'i'; 7370 7371 // The encoding of a fixed enum type matches its fixed underlying type. 7372 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 7373 return getObjCEncodingForPrimitiveType(C, BT); 7374 } 7375 7376 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 7377 QualType T, const FieldDecl *FD) { 7378 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 7379 S += 'b'; 7380 // The NeXT runtime encodes bit fields as b followed by the number of bits. 7381 // The GNU runtime requires more information; bitfields are encoded as b, 7382 // then the offset (in bits) of the first element, then the type of the 7383 // bitfield, then the size in bits. For example, in this structure: 7384 // 7385 // struct 7386 // { 7387 // int integer; 7388 // int flags:2; 7389 // }; 7390 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 7391 // runtime, but b32i2 for the GNU runtime. The reason for this extra 7392 // information is not especially sensible, but we're stuck with it for 7393 // compatibility with GCC, although providing it breaks anything that 7394 // actually uses runtime introspection and wants to work on both runtimes... 7395 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 7396 uint64_t Offset; 7397 7398 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 7399 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 7400 IVD); 7401 } else { 7402 const RecordDecl *RD = FD->getParent(); 7403 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 7404 Offset = RL.getFieldOffset(FD->getFieldIndex()); 7405 } 7406 7407 S += llvm::utostr(Offset); 7408 7409 if (const auto *ET = T->getAs<EnumType>()) 7410 S += ObjCEncodingForEnumType(Ctx, ET); 7411 else { 7412 const auto *BT = T->castAs<BuiltinType>(); 7413 S += getObjCEncodingForPrimitiveType(Ctx, BT); 7414 } 7415 } 7416 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 7417 } 7418 7419 // Helper function for determining whether the encoded type string would include 7420 // a template specialization type. 7421 static bool hasTemplateSpecializationInEncodedString(const Type *T, 7422 bool VisitBasesAndFields) { 7423 T = T->getBaseElementTypeUnsafe(); 7424 7425 if (auto *PT = T->getAs<PointerType>()) 7426 return hasTemplateSpecializationInEncodedString( 7427 PT->getPointeeType().getTypePtr(), false); 7428 7429 auto *CXXRD = T->getAsCXXRecordDecl(); 7430 7431 if (!CXXRD) 7432 return false; 7433 7434 if (isa<ClassTemplateSpecializationDecl>(CXXRD)) 7435 return true; 7436 7437 if (!CXXRD->hasDefinition() || !VisitBasesAndFields) 7438 return false; 7439 7440 for (auto B : CXXRD->bases()) 7441 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(), 7442 true)) 7443 return true; 7444 7445 for (auto *FD : CXXRD->fields()) 7446 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(), 7447 true)) 7448 return true; 7449 7450 return false; 7451 } 7452 7453 // FIXME: Use SmallString for accumulating string. 7454 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, 7455 const ObjCEncOptions Options, 7456 const FieldDecl *FD, 7457 QualType *NotEncodedT) const { 7458 CanQualType CT = getCanonicalType(T); 7459 switch (CT->getTypeClass()) { 7460 case Type::Builtin: 7461 case Type::Enum: 7462 if (FD && FD->isBitField()) 7463 return EncodeBitField(this, S, T, FD); 7464 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 7465 S += getObjCEncodingForPrimitiveType(this, BT); 7466 else 7467 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 7468 return; 7469 7470 case Type::Complex: 7471 S += 'j'; 7472 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, 7473 ObjCEncOptions(), 7474 /*Field=*/nullptr); 7475 return; 7476 7477 case Type::Atomic: 7478 S += 'A'; 7479 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, 7480 ObjCEncOptions(), 7481 /*Field=*/nullptr); 7482 return; 7483 7484 // encoding for pointer or reference types. 7485 case Type::Pointer: 7486 case Type::LValueReference: 7487 case Type::RValueReference: { 7488 QualType PointeeTy; 7489 if (isa<PointerType>(CT)) { 7490 const auto *PT = T->castAs<PointerType>(); 7491 if (PT->isObjCSelType()) { 7492 S += ':'; 7493 return; 7494 } 7495 PointeeTy = PT->getPointeeType(); 7496 } else { 7497 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 7498 } 7499 7500 bool isReadOnly = false; 7501 // For historical/compatibility reasons, the read-only qualifier of the 7502 // pointee gets emitted _before_ the '^'. The read-only qualifier of 7503 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 7504 // Also, do not emit the 'r' for anything but the outermost type! 7505 if (isa<TypedefType>(T.getTypePtr())) { 7506 if (Options.IsOutermostType() && T.isConstQualified()) { 7507 isReadOnly = true; 7508 S += 'r'; 7509 } 7510 } else if (Options.IsOutermostType()) { 7511 QualType P = PointeeTy; 7512 while (auto PT = P->getAs<PointerType>()) 7513 P = PT->getPointeeType(); 7514 if (P.isConstQualified()) { 7515 isReadOnly = true; 7516 S += 'r'; 7517 } 7518 } 7519 if (isReadOnly) { 7520 // Another legacy compatibility encoding. Some ObjC qualifier and type 7521 // combinations need to be rearranged. 7522 // Rewrite "in const" from "nr" to "rn" 7523 if (StringRef(S).endswith("nr")) 7524 S.replace(S.end()-2, S.end(), "rn"); 7525 } 7526 7527 if (PointeeTy->isCharType()) { 7528 // char pointer types should be encoded as '*' unless it is a 7529 // type that has been typedef'd to 'BOOL'. 7530 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 7531 S += '*'; 7532 return; 7533 } 7534 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 7535 // GCC binary compat: Need to convert "struct objc_class *" to "#". 7536 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 7537 S += '#'; 7538 return; 7539 } 7540 // GCC binary compat: Need to convert "struct objc_object *" to "@". 7541 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 7542 S += '@'; 7543 return; 7544 } 7545 // If the encoded string for the class includes template names, just emit 7546 // "^v" for pointers to the class. 7547 if (getLangOpts().CPlusPlus && 7548 (!getLangOpts().EncodeCXXClassTemplateSpec && 7549 hasTemplateSpecializationInEncodedString( 7550 RTy, Options.ExpandPointedToStructures()))) { 7551 S += "^v"; 7552 return; 7553 } 7554 // fall through... 7555 } 7556 S += '^'; 7557 getLegacyIntegralTypeEncoding(PointeeTy); 7558 7559 ObjCEncOptions NewOptions; 7560 if (Options.ExpandPointedToStructures()) 7561 NewOptions.setExpandStructures(); 7562 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, 7563 /*Field=*/nullptr, NotEncodedT); 7564 return; 7565 } 7566 7567 case Type::ConstantArray: 7568 case Type::IncompleteArray: 7569 case Type::VariableArray: { 7570 const auto *AT = cast<ArrayType>(CT); 7571 7572 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { 7573 // Incomplete arrays are encoded as a pointer to the array element. 7574 S += '^'; 7575 7576 getObjCEncodingForTypeImpl( 7577 AT->getElementType(), S, 7578 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); 7579 } else { 7580 S += '['; 7581 7582 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7583 S += llvm::utostr(CAT->getSize().getZExtValue()); 7584 else { 7585 //Variable length arrays are encoded as a regular array with 0 elements. 7586 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 7587 "Unknown array type!"); 7588 S += '0'; 7589 } 7590 7591 getObjCEncodingForTypeImpl( 7592 AT->getElementType(), S, 7593 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, 7594 NotEncodedT); 7595 S += ']'; 7596 } 7597 return; 7598 } 7599 7600 case Type::FunctionNoProto: 7601 case Type::FunctionProto: 7602 S += '?'; 7603 return; 7604 7605 case Type::Record: { 7606 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 7607 S += RDecl->isUnion() ? '(' : '{'; 7608 // Anonymous structures print as '?' 7609 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 7610 S += II->getName(); 7611 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 7612 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 7613 llvm::raw_string_ostream OS(S); 7614 printTemplateArgumentList(OS, TemplateArgs.asArray(), 7615 getPrintingPolicy()); 7616 } 7617 } else { 7618 S += '?'; 7619 } 7620 if (Options.ExpandStructures()) { 7621 S += '='; 7622 if (!RDecl->isUnion()) { 7623 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 7624 } else { 7625 for (const auto *Field : RDecl->fields()) { 7626 if (FD) { 7627 S += '"'; 7628 S += Field->getNameAsString(); 7629 S += '"'; 7630 } 7631 7632 // Special case bit-fields. 7633 if (Field->isBitField()) { 7634 getObjCEncodingForTypeImpl(Field->getType(), S, 7635 ObjCEncOptions().setExpandStructures(), 7636 Field); 7637 } else { 7638 QualType qt = Field->getType(); 7639 getLegacyIntegralTypeEncoding(qt); 7640 getObjCEncodingForTypeImpl( 7641 qt, S, 7642 ObjCEncOptions().setExpandStructures().setIsStructField(), FD, 7643 NotEncodedT); 7644 } 7645 } 7646 } 7647 } 7648 S += RDecl->isUnion() ? ')' : '}'; 7649 return; 7650 } 7651 7652 case Type::BlockPointer: { 7653 const auto *BT = T->castAs<BlockPointerType>(); 7654 S += "@?"; // Unlike a pointer-to-function, which is "^?". 7655 if (Options.EncodeBlockParameters()) { 7656 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 7657 7658 S += '<'; 7659 // Block return type 7660 getObjCEncodingForTypeImpl(FT->getReturnType(), S, 7661 Options.forComponentType(), FD, NotEncodedT); 7662 // Block self 7663 S += "@?"; 7664 // Block parameters 7665 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 7666 for (const auto &I : FPT->param_types()) 7667 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, 7668 NotEncodedT); 7669 } 7670 S += '>'; 7671 } 7672 return; 7673 } 7674 7675 case Type::ObjCObject: { 7676 // hack to match legacy encoding of *id and *Class 7677 QualType Ty = getObjCObjectPointerType(CT); 7678 if (Ty->isObjCIdType()) { 7679 S += "{objc_object=}"; 7680 return; 7681 } 7682 else if (Ty->isObjCClassType()) { 7683 S += "{objc_class=}"; 7684 return; 7685 } 7686 // TODO: Double check to make sure this intentionally falls through. 7687 LLVM_FALLTHROUGH; 7688 } 7689 7690 case Type::ObjCInterface: { 7691 // Ignore protocol qualifiers when mangling at this level. 7692 // @encode(class_name) 7693 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 7694 S += '{'; 7695 S += OI->getObjCRuntimeNameAsString(); 7696 if (Options.ExpandStructures()) { 7697 S += '='; 7698 SmallVector<const ObjCIvarDecl*, 32> Ivars; 7699 DeepCollectObjCIvars(OI, true, Ivars); 7700 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 7701 const FieldDecl *Field = Ivars[i]; 7702 if (Field->isBitField()) 7703 getObjCEncodingForTypeImpl(Field->getType(), S, 7704 ObjCEncOptions().setExpandStructures(), 7705 Field); 7706 else 7707 getObjCEncodingForTypeImpl(Field->getType(), S, 7708 ObjCEncOptions().setExpandStructures(), FD, 7709 NotEncodedT); 7710 } 7711 } 7712 S += '}'; 7713 return; 7714 } 7715 7716 case Type::ObjCObjectPointer: { 7717 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 7718 if (OPT->isObjCIdType()) { 7719 S += '@'; 7720 return; 7721 } 7722 7723 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 7724 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 7725 // Since this is a binary compatibility issue, need to consult with 7726 // runtime folks. Fortunately, this is a *very* obscure construct. 7727 S += '#'; 7728 return; 7729 } 7730 7731 if (OPT->isObjCQualifiedIdType()) { 7732 getObjCEncodingForTypeImpl( 7733 getObjCIdType(), S, 7734 Options.keepingOnly(ObjCEncOptions() 7735 .setExpandPointedToStructures() 7736 .setExpandStructures()), 7737 FD); 7738 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { 7739 // Note that we do extended encoding of protocol qualifer list 7740 // Only when doing ivar or property encoding. 7741 S += '"'; 7742 for (const auto *I : OPT->quals()) { 7743 S += '<'; 7744 S += I->getObjCRuntimeNameAsString(); 7745 S += '>'; 7746 } 7747 S += '"'; 7748 } 7749 return; 7750 } 7751 7752 S += '@'; 7753 if (OPT->getInterfaceDecl() && 7754 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { 7755 S += '"'; 7756 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 7757 for (const auto *I : OPT->quals()) { 7758 S += '<'; 7759 S += I->getObjCRuntimeNameAsString(); 7760 S += '>'; 7761 } 7762 S += '"'; 7763 } 7764 return; 7765 } 7766 7767 // gcc just blithely ignores member pointers. 7768 // FIXME: we should do better than that. 'M' is available. 7769 case Type::MemberPointer: 7770 // This matches gcc's encoding, even though technically it is insufficient. 7771 //FIXME. We should do a better job than gcc. 7772 case Type::Vector: 7773 case Type::ExtVector: 7774 // Until we have a coherent encoding of these three types, issue warning. 7775 if (NotEncodedT) 7776 *NotEncodedT = T; 7777 return; 7778 7779 case Type::ConstantMatrix: 7780 if (NotEncodedT) 7781 *NotEncodedT = T; 7782 return; 7783 7784 // We could see an undeduced auto type here during error recovery. 7785 // Just ignore it. 7786 case Type::Auto: 7787 case Type::DeducedTemplateSpecialization: 7788 return; 7789 7790 case Type::Pipe: 7791 case Type::ExtInt: 7792 #define ABSTRACT_TYPE(KIND, BASE) 7793 #define TYPE(KIND, BASE) 7794 #define DEPENDENT_TYPE(KIND, BASE) \ 7795 case Type::KIND: 7796 #define NON_CANONICAL_TYPE(KIND, BASE) \ 7797 case Type::KIND: 7798 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 7799 case Type::KIND: 7800 #include "clang/AST/TypeNodes.inc" 7801 llvm_unreachable("@encode for dependent type!"); 7802 } 7803 llvm_unreachable("bad type kind!"); 7804 } 7805 7806 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 7807 std::string &S, 7808 const FieldDecl *FD, 7809 bool includeVBases, 7810 QualType *NotEncodedT) const { 7811 assert(RDecl && "Expected non-null RecordDecl"); 7812 assert(!RDecl->isUnion() && "Should not be called for unions"); 7813 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 7814 return; 7815 7816 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 7817 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 7818 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 7819 7820 if (CXXRec) { 7821 for (const auto &BI : CXXRec->bases()) { 7822 if (!BI.isVirtual()) { 7823 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7824 if (base->isEmpty()) 7825 continue; 7826 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 7827 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7828 std::make_pair(offs, base)); 7829 } 7830 } 7831 } 7832 7833 unsigned i = 0; 7834 for (FieldDecl *Field : RDecl->fields()) { 7835 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this)) 7836 continue; 7837 uint64_t offs = layout.getFieldOffset(i); 7838 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7839 std::make_pair(offs, Field)); 7840 ++i; 7841 } 7842 7843 if (CXXRec && includeVBases) { 7844 for (const auto &BI : CXXRec->vbases()) { 7845 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 7846 if (base->isEmpty()) 7847 continue; 7848 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 7849 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 7850 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 7851 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 7852 std::make_pair(offs, base)); 7853 } 7854 } 7855 7856 CharUnits size; 7857 if (CXXRec) { 7858 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 7859 } else { 7860 size = layout.getSize(); 7861 } 7862 7863 #ifndef NDEBUG 7864 uint64_t CurOffs = 0; 7865 #endif 7866 std::multimap<uint64_t, NamedDecl *>::iterator 7867 CurLayObj = FieldOrBaseOffsets.begin(); 7868 7869 if (CXXRec && CXXRec->isDynamicClass() && 7870 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 7871 if (FD) { 7872 S += "\"_vptr$"; 7873 std::string recname = CXXRec->getNameAsString(); 7874 if (recname.empty()) recname = "?"; 7875 S += recname; 7876 S += '"'; 7877 } 7878 S += "^^?"; 7879 #ifndef NDEBUG 7880 CurOffs += getTypeSize(VoidPtrTy); 7881 #endif 7882 } 7883 7884 if (!RDecl->hasFlexibleArrayMember()) { 7885 // Mark the end of the structure. 7886 uint64_t offs = toBits(size); 7887 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7888 std::make_pair(offs, nullptr)); 7889 } 7890 7891 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7892 #ifndef NDEBUG 7893 assert(CurOffs <= CurLayObj->first); 7894 if (CurOffs < CurLayObj->first) { 7895 uint64_t padding = CurLayObj->first - CurOffs; 7896 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7897 // packing/alignment of members is different that normal, in which case 7898 // the encoding will be out-of-sync with the real layout. 7899 // If the runtime switches to just consider the size of types without 7900 // taking into account alignment, we could make padding explicit in the 7901 // encoding (e.g. using arrays of chars). The encoding strings would be 7902 // longer then though. 7903 CurOffs += padding; 7904 } 7905 #endif 7906 7907 NamedDecl *dcl = CurLayObj->second; 7908 if (!dcl) 7909 break; // reached end of structure. 7910 7911 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7912 // We expand the bases without their virtual bases since those are going 7913 // in the initial structure. Note that this differs from gcc which 7914 // expands virtual bases each time one is encountered in the hierarchy, 7915 // making the encoding type bigger than it really is. 7916 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7917 NotEncodedT); 7918 assert(!base->isEmpty()); 7919 #ifndef NDEBUG 7920 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7921 #endif 7922 } else { 7923 const auto *field = cast<FieldDecl>(dcl); 7924 if (FD) { 7925 S += '"'; 7926 S += field->getNameAsString(); 7927 S += '"'; 7928 } 7929 7930 if (field->isBitField()) { 7931 EncodeBitField(this, S, field->getType(), field); 7932 #ifndef NDEBUG 7933 CurOffs += field->getBitWidthValue(*this); 7934 #endif 7935 } else { 7936 QualType qt = field->getType(); 7937 getLegacyIntegralTypeEncoding(qt); 7938 getObjCEncodingForTypeImpl( 7939 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), 7940 FD, NotEncodedT); 7941 #ifndef NDEBUG 7942 CurOffs += getTypeSize(field->getType()); 7943 #endif 7944 } 7945 } 7946 } 7947 } 7948 7949 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7950 std::string& S) const { 7951 if (QT & Decl::OBJC_TQ_In) 7952 S += 'n'; 7953 if (QT & Decl::OBJC_TQ_Inout) 7954 S += 'N'; 7955 if (QT & Decl::OBJC_TQ_Out) 7956 S += 'o'; 7957 if (QT & Decl::OBJC_TQ_Bycopy) 7958 S += 'O'; 7959 if (QT & Decl::OBJC_TQ_Byref) 7960 S += 'R'; 7961 if (QT & Decl::OBJC_TQ_Oneway) 7962 S += 'V'; 7963 } 7964 7965 TypedefDecl *ASTContext::getObjCIdDecl() const { 7966 if (!ObjCIdDecl) { 7967 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7968 T = getObjCObjectPointerType(T); 7969 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7970 } 7971 return ObjCIdDecl; 7972 } 7973 7974 TypedefDecl *ASTContext::getObjCSelDecl() const { 7975 if (!ObjCSelDecl) { 7976 QualType T = getPointerType(ObjCBuiltinSelTy); 7977 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7978 } 7979 return ObjCSelDecl; 7980 } 7981 7982 TypedefDecl *ASTContext::getObjCClassDecl() const { 7983 if (!ObjCClassDecl) { 7984 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7985 T = getObjCObjectPointerType(T); 7986 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7987 } 7988 return ObjCClassDecl; 7989 } 7990 7991 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7992 if (!ObjCProtocolClassDecl) { 7993 ObjCProtocolClassDecl 7994 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7995 SourceLocation(), 7996 &Idents.get("Protocol"), 7997 /*typeParamList=*/nullptr, 7998 /*PrevDecl=*/nullptr, 7999 SourceLocation(), true); 8000 } 8001 8002 return ObjCProtocolClassDecl; 8003 } 8004 8005 //===----------------------------------------------------------------------===// 8006 // __builtin_va_list Construction Functions 8007 //===----------------------------------------------------------------------===// 8008 8009 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 8010 StringRef Name) { 8011 // typedef char* __builtin[_ms]_va_list; 8012 QualType T = Context->getPointerType(Context->CharTy); 8013 return Context->buildImplicitTypedef(T, Name); 8014 } 8015 8016 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 8017 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 8018 } 8019 8020 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 8021 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 8022 } 8023 8024 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 8025 // typedef void* __builtin_va_list; 8026 QualType T = Context->getPointerType(Context->VoidTy); 8027 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8028 } 8029 8030 static TypedefDecl * 8031 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 8032 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 8033 // namespace std { struct __va_list { 8034 // Note that we create the namespace even in C. This is intentional so that 8035 // the type is consistent between C and C++, which is important in cases where 8036 // the types need to match between translation units (e.g. with 8037 // -fsanitize=cfi-icall). Ideally we wouldn't have created this namespace at 8038 // all, but it's now part of the ABI (e.g. in mangled names), so we can't 8039 // change it. 8040 auto *NS = NamespaceDecl::Create( 8041 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), 8042 /*Inline*/ false, SourceLocation(), SourceLocation(), 8043 &Context->Idents.get("std"), 8044 /*PrevDecl*/ nullptr); 8045 NS->setImplicit(); 8046 VaListTagDecl->setDeclContext(NS); 8047 8048 VaListTagDecl->startDefinition(); 8049 8050 const size_t NumFields = 5; 8051 QualType FieldTypes[NumFields]; 8052 const char *FieldNames[NumFields]; 8053 8054 // void *__stack; 8055 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8056 FieldNames[0] = "__stack"; 8057 8058 // void *__gr_top; 8059 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8060 FieldNames[1] = "__gr_top"; 8061 8062 // void *__vr_top; 8063 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8064 FieldNames[2] = "__vr_top"; 8065 8066 // int __gr_offs; 8067 FieldTypes[3] = Context->IntTy; 8068 FieldNames[3] = "__gr_offs"; 8069 8070 // int __vr_offs; 8071 FieldTypes[4] = Context->IntTy; 8072 FieldNames[4] = "__vr_offs"; 8073 8074 // Create fields 8075 for (unsigned i = 0; i < NumFields; ++i) { 8076 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8077 VaListTagDecl, 8078 SourceLocation(), 8079 SourceLocation(), 8080 &Context->Idents.get(FieldNames[i]), 8081 FieldTypes[i], /*TInfo=*/nullptr, 8082 /*BitWidth=*/nullptr, 8083 /*Mutable=*/false, 8084 ICIS_NoInit); 8085 Field->setAccess(AS_public); 8086 VaListTagDecl->addDecl(Field); 8087 } 8088 VaListTagDecl->completeDefinition(); 8089 Context->VaListTagDecl = VaListTagDecl; 8090 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8091 8092 // } __builtin_va_list; 8093 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 8094 } 8095 8096 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 8097 // typedef struct __va_list_tag { 8098 RecordDecl *VaListTagDecl; 8099 8100 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8101 VaListTagDecl->startDefinition(); 8102 8103 const size_t NumFields = 5; 8104 QualType FieldTypes[NumFields]; 8105 const char *FieldNames[NumFields]; 8106 8107 // unsigned char gpr; 8108 FieldTypes[0] = Context->UnsignedCharTy; 8109 FieldNames[0] = "gpr"; 8110 8111 // unsigned char fpr; 8112 FieldTypes[1] = Context->UnsignedCharTy; 8113 FieldNames[1] = "fpr"; 8114 8115 // unsigned short reserved; 8116 FieldTypes[2] = Context->UnsignedShortTy; 8117 FieldNames[2] = "reserved"; 8118 8119 // void* overflow_arg_area; 8120 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8121 FieldNames[3] = "overflow_arg_area"; 8122 8123 // void* reg_save_area; 8124 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 8125 FieldNames[4] = "reg_save_area"; 8126 8127 // Create fields 8128 for (unsigned i = 0; i < NumFields; ++i) { 8129 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 8130 SourceLocation(), 8131 SourceLocation(), 8132 &Context->Idents.get(FieldNames[i]), 8133 FieldTypes[i], /*TInfo=*/nullptr, 8134 /*BitWidth=*/nullptr, 8135 /*Mutable=*/false, 8136 ICIS_NoInit); 8137 Field->setAccess(AS_public); 8138 VaListTagDecl->addDecl(Field); 8139 } 8140 VaListTagDecl->completeDefinition(); 8141 Context->VaListTagDecl = VaListTagDecl; 8142 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8143 8144 // } __va_list_tag; 8145 TypedefDecl *VaListTagTypedefDecl = 8146 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8147 8148 QualType VaListTagTypedefType = 8149 Context->getTypedefType(VaListTagTypedefDecl); 8150 8151 // typedef __va_list_tag __builtin_va_list[1]; 8152 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8153 QualType VaListTagArrayType 8154 = Context->getConstantArrayType(VaListTagTypedefType, 8155 Size, nullptr, ArrayType::Normal, 0); 8156 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8157 } 8158 8159 static TypedefDecl * 8160 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 8161 // struct __va_list_tag { 8162 RecordDecl *VaListTagDecl; 8163 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8164 VaListTagDecl->startDefinition(); 8165 8166 const size_t NumFields = 4; 8167 QualType FieldTypes[NumFields]; 8168 const char *FieldNames[NumFields]; 8169 8170 // unsigned gp_offset; 8171 FieldTypes[0] = Context->UnsignedIntTy; 8172 FieldNames[0] = "gp_offset"; 8173 8174 // unsigned fp_offset; 8175 FieldTypes[1] = Context->UnsignedIntTy; 8176 FieldNames[1] = "fp_offset"; 8177 8178 // void* overflow_arg_area; 8179 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8180 FieldNames[2] = "overflow_arg_area"; 8181 8182 // void* reg_save_area; 8183 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8184 FieldNames[3] = "reg_save_area"; 8185 8186 // Create fields 8187 for (unsigned i = 0; i < NumFields; ++i) { 8188 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8189 VaListTagDecl, 8190 SourceLocation(), 8191 SourceLocation(), 8192 &Context->Idents.get(FieldNames[i]), 8193 FieldTypes[i], /*TInfo=*/nullptr, 8194 /*BitWidth=*/nullptr, 8195 /*Mutable=*/false, 8196 ICIS_NoInit); 8197 Field->setAccess(AS_public); 8198 VaListTagDecl->addDecl(Field); 8199 } 8200 VaListTagDecl->completeDefinition(); 8201 Context->VaListTagDecl = VaListTagDecl; 8202 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8203 8204 // }; 8205 8206 // typedef struct __va_list_tag __builtin_va_list[1]; 8207 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8208 QualType VaListTagArrayType = Context->getConstantArrayType( 8209 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8210 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8211 } 8212 8213 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 8214 // typedef int __builtin_va_list[4]; 8215 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 8216 QualType IntArrayType = Context->getConstantArrayType( 8217 Context->IntTy, Size, nullptr, ArrayType::Normal, 0); 8218 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 8219 } 8220 8221 static TypedefDecl * 8222 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 8223 // struct __va_list 8224 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 8225 if (Context->getLangOpts().CPlusPlus) { 8226 // namespace std { struct __va_list { 8227 NamespaceDecl *NS; 8228 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 8229 Context->getTranslationUnitDecl(), 8230 /*Inline*/false, SourceLocation(), 8231 SourceLocation(), &Context->Idents.get("std"), 8232 /*PrevDecl*/ nullptr); 8233 NS->setImplicit(); 8234 VaListDecl->setDeclContext(NS); 8235 } 8236 8237 VaListDecl->startDefinition(); 8238 8239 // void * __ap; 8240 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8241 VaListDecl, 8242 SourceLocation(), 8243 SourceLocation(), 8244 &Context->Idents.get("__ap"), 8245 Context->getPointerType(Context->VoidTy), 8246 /*TInfo=*/nullptr, 8247 /*BitWidth=*/nullptr, 8248 /*Mutable=*/false, 8249 ICIS_NoInit); 8250 Field->setAccess(AS_public); 8251 VaListDecl->addDecl(Field); 8252 8253 // }; 8254 VaListDecl->completeDefinition(); 8255 Context->VaListTagDecl = VaListDecl; 8256 8257 // typedef struct __va_list __builtin_va_list; 8258 QualType T = Context->getRecordType(VaListDecl); 8259 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 8260 } 8261 8262 static TypedefDecl * 8263 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 8264 // struct __va_list_tag { 8265 RecordDecl *VaListTagDecl; 8266 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8267 VaListTagDecl->startDefinition(); 8268 8269 const size_t NumFields = 4; 8270 QualType FieldTypes[NumFields]; 8271 const char *FieldNames[NumFields]; 8272 8273 // long __gpr; 8274 FieldTypes[0] = Context->LongTy; 8275 FieldNames[0] = "__gpr"; 8276 8277 // long __fpr; 8278 FieldTypes[1] = Context->LongTy; 8279 FieldNames[1] = "__fpr"; 8280 8281 // void *__overflow_arg_area; 8282 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8283 FieldNames[2] = "__overflow_arg_area"; 8284 8285 // void *__reg_save_area; 8286 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 8287 FieldNames[3] = "__reg_save_area"; 8288 8289 // Create fields 8290 for (unsigned i = 0; i < NumFields; ++i) { 8291 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 8292 VaListTagDecl, 8293 SourceLocation(), 8294 SourceLocation(), 8295 &Context->Idents.get(FieldNames[i]), 8296 FieldTypes[i], /*TInfo=*/nullptr, 8297 /*BitWidth=*/nullptr, 8298 /*Mutable=*/false, 8299 ICIS_NoInit); 8300 Field->setAccess(AS_public); 8301 VaListTagDecl->addDecl(Field); 8302 } 8303 VaListTagDecl->completeDefinition(); 8304 Context->VaListTagDecl = VaListTagDecl; 8305 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8306 8307 // }; 8308 8309 // typedef __va_list_tag __builtin_va_list[1]; 8310 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8311 QualType VaListTagArrayType = Context->getConstantArrayType( 8312 VaListTagType, Size, nullptr, ArrayType::Normal, 0); 8313 8314 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8315 } 8316 8317 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { 8318 // typedef struct __va_list_tag { 8319 RecordDecl *VaListTagDecl; 8320 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 8321 VaListTagDecl->startDefinition(); 8322 8323 const size_t NumFields = 3; 8324 QualType FieldTypes[NumFields]; 8325 const char *FieldNames[NumFields]; 8326 8327 // void *CurrentSavedRegisterArea; 8328 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 8329 FieldNames[0] = "__current_saved_reg_area_pointer"; 8330 8331 // void *SavedRegAreaEnd; 8332 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 8333 FieldNames[1] = "__saved_reg_area_end_pointer"; 8334 8335 // void *OverflowArea; 8336 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 8337 FieldNames[2] = "__overflow_area_pointer"; 8338 8339 // Create fields 8340 for (unsigned i = 0; i < NumFields; ++i) { 8341 FieldDecl *Field = FieldDecl::Create( 8342 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), 8343 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], 8344 /*TInfo=*/0, 8345 /*BitWidth=*/0, 8346 /*Mutable=*/false, ICIS_NoInit); 8347 Field->setAccess(AS_public); 8348 VaListTagDecl->addDecl(Field); 8349 } 8350 VaListTagDecl->completeDefinition(); 8351 Context->VaListTagDecl = VaListTagDecl; 8352 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 8353 8354 // } __va_list_tag; 8355 TypedefDecl *VaListTagTypedefDecl = 8356 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 8357 8358 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); 8359 8360 // typedef __va_list_tag __builtin_va_list[1]; 8361 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 8362 QualType VaListTagArrayType = Context->getConstantArrayType( 8363 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); 8364 8365 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 8366 } 8367 8368 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 8369 TargetInfo::BuiltinVaListKind Kind) { 8370 switch (Kind) { 8371 case TargetInfo::CharPtrBuiltinVaList: 8372 return CreateCharPtrBuiltinVaListDecl(Context); 8373 case TargetInfo::VoidPtrBuiltinVaList: 8374 return CreateVoidPtrBuiltinVaListDecl(Context); 8375 case TargetInfo::AArch64ABIBuiltinVaList: 8376 return CreateAArch64ABIBuiltinVaListDecl(Context); 8377 case TargetInfo::PowerABIBuiltinVaList: 8378 return CreatePowerABIBuiltinVaListDecl(Context); 8379 case TargetInfo::X86_64ABIBuiltinVaList: 8380 return CreateX86_64ABIBuiltinVaListDecl(Context); 8381 case TargetInfo::PNaClABIBuiltinVaList: 8382 return CreatePNaClABIBuiltinVaListDecl(Context); 8383 case TargetInfo::AAPCSABIBuiltinVaList: 8384 return CreateAAPCSABIBuiltinVaListDecl(Context); 8385 case TargetInfo::SystemZBuiltinVaList: 8386 return CreateSystemZBuiltinVaListDecl(Context); 8387 case TargetInfo::HexagonBuiltinVaList: 8388 return CreateHexagonBuiltinVaListDecl(Context); 8389 } 8390 8391 llvm_unreachable("Unhandled __builtin_va_list type kind"); 8392 } 8393 8394 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 8395 if (!BuiltinVaListDecl) { 8396 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 8397 assert(BuiltinVaListDecl->isImplicit()); 8398 } 8399 8400 return BuiltinVaListDecl; 8401 } 8402 8403 Decl *ASTContext::getVaListTagDecl() const { 8404 // Force the creation of VaListTagDecl by building the __builtin_va_list 8405 // declaration. 8406 if (!VaListTagDecl) 8407 (void)getBuiltinVaListDecl(); 8408 8409 return VaListTagDecl; 8410 } 8411 8412 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 8413 if (!BuiltinMSVaListDecl) 8414 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 8415 8416 return BuiltinMSVaListDecl; 8417 } 8418 8419 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 8420 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 8421 } 8422 8423 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 8424 assert(ObjCConstantStringType.isNull() && 8425 "'NSConstantString' type already set!"); 8426 8427 ObjCConstantStringType = getObjCInterfaceType(Decl); 8428 } 8429 8430 /// Retrieve the template name that corresponds to a non-empty 8431 /// lookup. 8432 TemplateName 8433 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 8434 UnresolvedSetIterator End) const { 8435 unsigned size = End - Begin; 8436 assert(size > 1 && "set is not overloaded!"); 8437 8438 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 8439 size * sizeof(FunctionTemplateDecl*)); 8440 auto *OT = new (memory) OverloadedTemplateStorage(size); 8441 8442 NamedDecl **Storage = OT->getStorage(); 8443 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 8444 NamedDecl *D = *I; 8445 assert(isa<FunctionTemplateDecl>(D) || 8446 isa<UnresolvedUsingValueDecl>(D) || 8447 (isa<UsingShadowDecl>(D) && 8448 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 8449 *Storage++ = D; 8450 } 8451 8452 return TemplateName(OT); 8453 } 8454 8455 /// Retrieve a template name representing an unqualified-id that has been 8456 /// assumed to name a template for ADL purposes. 8457 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { 8458 auto *OT = new (*this) AssumedTemplateStorage(Name); 8459 return TemplateName(OT); 8460 } 8461 8462 /// Retrieve the template name that represents a qualified 8463 /// template name such as \c std::vector. 8464 TemplateName 8465 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 8466 bool TemplateKeyword, 8467 TemplateDecl *Template) const { 8468 assert(NNS && "Missing nested-name-specifier in qualified template name"); 8469 8470 // FIXME: Canonicalization? 8471 llvm::FoldingSetNodeID ID; 8472 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 8473 8474 void *InsertPos = nullptr; 8475 QualifiedTemplateName *QTN = 8476 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8477 if (!QTN) { 8478 QTN = new (*this, alignof(QualifiedTemplateName)) 8479 QualifiedTemplateName(NNS, TemplateKeyword, Template); 8480 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 8481 } 8482 8483 return TemplateName(QTN); 8484 } 8485 8486 /// Retrieve the template name that represents a dependent 8487 /// template name such as \c MetaFun::template apply. 8488 TemplateName 8489 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8490 const IdentifierInfo *Name) const { 8491 assert((!NNS || NNS->isDependent()) && 8492 "Nested name specifier must be dependent"); 8493 8494 llvm::FoldingSetNodeID ID; 8495 DependentTemplateName::Profile(ID, NNS, Name); 8496 8497 void *InsertPos = nullptr; 8498 DependentTemplateName *QTN = 8499 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8500 8501 if (QTN) 8502 return TemplateName(QTN); 8503 8504 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8505 if (CanonNNS == NNS) { 8506 QTN = new (*this, alignof(DependentTemplateName)) 8507 DependentTemplateName(NNS, Name); 8508 } else { 8509 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 8510 QTN = new (*this, alignof(DependentTemplateName)) 8511 DependentTemplateName(NNS, Name, Canon); 8512 DependentTemplateName *CheckQTN = 8513 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8514 assert(!CheckQTN && "Dependent type name canonicalization broken"); 8515 (void)CheckQTN; 8516 } 8517 8518 DependentTemplateNames.InsertNode(QTN, InsertPos); 8519 return TemplateName(QTN); 8520 } 8521 8522 /// Retrieve the template name that represents a dependent 8523 /// template name such as \c MetaFun::template operator+. 8524 TemplateName 8525 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 8526 OverloadedOperatorKind Operator) const { 8527 assert((!NNS || NNS->isDependent()) && 8528 "Nested name specifier must be dependent"); 8529 8530 llvm::FoldingSetNodeID ID; 8531 DependentTemplateName::Profile(ID, NNS, Operator); 8532 8533 void *InsertPos = nullptr; 8534 DependentTemplateName *QTN 8535 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8536 8537 if (QTN) 8538 return TemplateName(QTN); 8539 8540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 8541 if (CanonNNS == NNS) { 8542 QTN = new (*this, alignof(DependentTemplateName)) 8543 DependentTemplateName(NNS, Operator); 8544 } else { 8545 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 8546 QTN = new (*this, alignof(DependentTemplateName)) 8547 DependentTemplateName(NNS, Operator, Canon); 8548 8549 DependentTemplateName *CheckQTN 8550 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 8551 assert(!CheckQTN && "Dependent template name canonicalization broken"); 8552 (void)CheckQTN; 8553 } 8554 8555 DependentTemplateNames.InsertNode(QTN, InsertPos); 8556 return TemplateName(QTN); 8557 } 8558 8559 TemplateName 8560 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 8561 TemplateName replacement) const { 8562 llvm::FoldingSetNodeID ID; 8563 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 8564 8565 void *insertPos = nullptr; 8566 SubstTemplateTemplateParmStorage *subst 8567 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 8568 8569 if (!subst) { 8570 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 8571 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 8572 } 8573 8574 return TemplateName(subst); 8575 } 8576 8577 TemplateName 8578 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 8579 const TemplateArgument &ArgPack) const { 8580 auto &Self = const_cast<ASTContext &>(*this); 8581 llvm::FoldingSetNodeID ID; 8582 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 8583 8584 void *InsertPos = nullptr; 8585 SubstTemplateTemplateParmPackStorage *Subst 8586 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 8587 8588 if (!Subst) { 8589 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 8590 ArgPack.pack_size(), 8591 ArgPack.pack_begin()); 8592 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 8593 } 8594 8595 return TemplateName(Subst); 8596 } 8597 8598 /// getFromTargetType - Given one of the integer types provided by 8599 /// TargetInfo, produce the corresponding type. The unsigned @p Type 8600 /// is actually a value of type @c TargetInfo::IntType. 8601 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 8602 switch (Type) { 8603 case TargetInfo::NoInt: return {}; 8604 case TargetInfo::SignedChar: return SignedCharTy; 8605 case TargetInfo::UnsignedChar: return UnsignedCharTy; 8606 case TargetInfo::SignedShort: return ShortTy; 8607 case TargetInfo::UnsignedShort: return UnsignedShortTy; 8608 case TargetInfo::SignedInt: return IntTy; 8609 case TargetInfo::UnsignedInt: return UnsignedIntTy; 8610 case TargetInfo::SignedLong: return LongTy; 8611 case TargetInfo::UnsignedLong: return UnsignedLongTy; 8612 case TargetInfo::SignedLongLong: return LongLongTy; 8613 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 8614 } 8615 8616 llvm_unreachable("Unhandled TargetInfo::IntType value"); 8617 } 8618 8619 //===----------------------------------------------------------------------===// 8620 // Type Predicates. 8621 //===----------------------------------------------------------------------===// 8622 8623 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 8624 /// garbage collection attribute. 8625 /// 8626 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 8627 if (getLangOpts().getGC() == LangOptions::NonGC) 8628 return Qualifiers::GCNone; 8629 8630 assert(getLangOpts().ObjC); 8631 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 8632 8633 // Default behaviour under objective-C's gc is for ObjC pointers 8634 // (or pointers to them) be treated as though they were declared 8635 // as __strong. 8636 if (GCAttrs == Qualifiers::GCNone) { 8637 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 8638 return Qualifiers::Strong; 8639 else if (Ty->isPointerType()) 8640 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); 8641 } else { 8642 // It's not valid to set GC attributes on anything that isn't a 8643 // pointer. 8644 #ifndef NDEBUG 8645 QualType CT = Ty->getCanonicalTypeInternal(); 8646 while (const auto *AT = dyn_cast<ArrayType>(CT)) 8647 CT = AT->getElementType(); 8648 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 8649 #endif 8650 } 8651 return GCAttrs; 8652 } 8653 8654 //===----------------------------------------------------------------------===// 8655 // Type Compatibility Testing 8656 //===----------------------------------------------------------------------===// 8657 8658 /// areCompatVectorTypes - Return true if the two specified vector types are 8659 /// compatible. 8660 static bool areCompatVectorTypes(const VectorType *LHS, 8661 const VectorType *RHS) { 8662 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8663 return LHS->getElementType() == RHS->getElementType() && 8664 LHS->getNumElements() == RHS->getNumElements(); 8665 } 8666 8667 /// areCompatMatrixTypes - Return true if the two specified matrix types are 8668 /// compatible. 8669 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, 8670 const ConstantMatrixType *RHS) { 8671 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 8672 return LHS->getElementType() == RHS->getElementType() && 8673 LHS->getNumRows() == RHS->getNumRows() && 8674 LHS->getNumColumns() == RHS->getNumColumns(); 8675 } 8676 8677 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 8678 QualType SecondVec) { 8679 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 8680 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 8681 8682 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 8683 return true; 8684 8685 // Treat Neon vector types and most AltiVec vector types as if they are the 8686 // equivalent GCC vector types. 8687 const auto *First = FirstVec->castAs<VectorType>(); 8688 const auto *Second = SecondVec->castAs<VectorType>(); 8689 if (First->getNumElements() == Second->getNumElements() && 8690 hasSameType(First->getElementType(), Second->getElementType()) && 8691 First->getVectorKind() != VectorType::AltiVecPixel && 8692 First->getVectorKind() != VectorType::AltiVecBool && 8693 Second->getVectorKind() != VectorType::AltiVecPixel && 8694 Second->getVectorKind() != VectorType::AltiVecBool && 8695 First->getVectorKind() != VectorType::SveFixedLengthDataVector && 8696 First->getVectorKind() != VectorType::SveFixedLengthPredicateVector && 8697 Second->getVectorKind() != VectorType::SveFixedLengthDataVector && 8698 Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector) 8699 return true; 8700 8701 return false; 8702 } 8703 8704 /// getSVETypeSize - Return SVE vector or predicate register size. 8705 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { 8706 assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); 8707 return Ty->getKind() == BuiltinType::SveBool 8708 ? Context.getLangOpts().ArmSveVectorBits / Context.getCharWidth() 8709 : Context.getLangOpts().ArmSveVectorBits; 8710 } 8711 8712 bool ASTContext::areCompatibleSveTypes(QualType FirstType, 8713 QualType SecondType) { 8714 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8715 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8716 "Expected SVE builtin type and vector type!"); 8717 8718 auto IsValidCast = [this](QualType FirstType, QualType SecondType) { 8719 if (const auto *BT = FirstType->getAs<BuiltinType>()) { 8720 if (const auto *VT = SecondType->getAs<VectorType>()) { 8721 // Predicates have the same representation as uint8 so we also have to 8722 // check the kind to make these types incompatible. 8723 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 8724 return BT->getKind() == BuiltinType::SveBool; 8725 else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) 8726 return VT->getElementType().getCanonicalType() == 8727 FirstType->getSveEltType(*this); 8728 else if (VT->getVectorKind() == VectorType::GenericVector) 8729 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) && 8730 hasSameType(VT->getElementType(), 8731 getBuiltinVectorTypeInfo(BT).ElementType); 8732 } 8733 } 8734 return false; 8735 }; 8736 8737 return IsValidCast(FirstType, SecondType) || 8738 IsValidCast(SecondType, FirstType); 8739 } 8740 8741 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType, 8742 QualType SecondType) { 8743 assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) || 8744 (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) && 8745 "Expected SVE builtin type and vector type!"); 8746 8747 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) { 8748 const auto *BT = FirstType->getAs<BuiltinType>(); 8749 if (!BT) 8750 return false; 8751 8752 const auto *VecTy = SecondType->getAs<VectorType>(); 8753 if (VecTy && 8754 (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector || 8755 VecTy->getVectorKind() == VectorType::GenericVector)) { 8756 const LangOptions::LaxVectorConversionKind LVCKind = 8757 getLangOpts().getLaxVectorConversions(); 8758 8759 // Can not convert between sve predicates and sve vectors because of 8760 // different size. 8761 if (BT->getKind() == BuiltinType::SveBool && 8762 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector) 8763 return false; 8764 8765 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion. 8766 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly 8767 // converts to VLAT and VLAT implicitly converts to GNUT." 8768 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and 8769 // predicates. 8770 if (VecTy->getVectorKind() == VectorType::GenericVector && 8771 getTypeSize(SecondType) != getSVETypeSize(*this, BT)) 8772 return false; 8773 8774 // If -flax-vector-conversions=all is specified, the types are 8775 // certainly compatible. 8776 if (LVCKind == LangOptions::LaxVectorConversionKind::All) 8777 return true; 8778 8779 // If -flax-vector-conversions=integer is specified, the types are 8780 // compatible if the elements are integer types. 8781 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer) 8782 return VecTy->getElementType().getCanonicalType()->isIntegerType() && 8783 FirstType->getSveEltType(*this)->isIntegerType(); 8784 } 8785 8786 return false; 8787 }; 8788 8789 return IsLaxCompatible(FirstType, SecondType) || 8790 IsLaxCompatible(SecondType, FirstType); 8791 } 8792 8793 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { 8794 while (true) { 8795 // __strong id 8796 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { 8797 if (Attr->getAttrKind() == attr::ObjCOwnership) 8798 return true; 8799 8800 Ty = Attr->getModifiedType(); 8801 8802 // X *__strong (...) 8803 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { 8804 Ty = Paren->getInnerType(); 8805 8806 // We do not want to look through typedefs, typeof(expr), 8807 // typeof(type), or any other way that the type is somehow 8808 // abstracted. 8809 } else { 8810 return false; 8811 } 8812 } 8813 } 8814 8815 //===----------------------------------------------------------------------===// 8816 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 8817 //===----------------------------------------------------------------------===// 8818 8819 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 8820 /// inheritance hierarchy of 'rProto'. 8821 bool 8822 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 8823 ObjCProtocolDecl *rProto) const { 8824 if (declaresSameEntity(lProto, rProto)) 8825 return true; 8826 for (auto *PI : rProto->protocols()) 8827 if (ProtocolCompatibleWithProtocol(lProto, PI)) 8828 return true; 8829 return false; 8830 } 8831 8832 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 8833 /// Class<pr1, ...>. 8834 bool ASTContext::ObjCQualifiedClassTypesAreCompatible( 8835 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { 8836 for (auto *lhsProto : lhs->quals()) { 8837 bool match = false; 8838 for (auto *rhsProto : rhs->quals()) { 8839 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 8840 match = true; 8841 break; 8842 } 8843 } 8844 if (!match) 8845 return false; 8846 } 8847 return true; 8848 } 8849 8850 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 8851 /// ObjCQualifiedIDType. 8852 bool ASTContext::ObjCQualifiedIdTypesAreCompatible( 8853 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, 8854 bool compare) { 8855 // Allow id<P..> and an 'id' in all cases. 8856 if (lhs->isObjCIdType() || rhs->isObjCIdType()) 8857 return true; 8858 8859 // Don't allow id<P..> to convert to Class or Class<P..> in either direction. 8860 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || 8861 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) 8862 return false; 8863 8864 if (lhs->isObjCQualifiedIdType()) { 8865 if (rhs->qual_empty()) { 8866 // If the RHS is a unqualified interface pointer "NSString*", 8867 // make sure we check the class hierarchy. 8868 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8869 for (auto *I : lhs->quals()) { 8870 // when comparing an id<P> on lhs with a static type on rhs, 8871 // see if static class implements all of id's protocols, directly or 8872 // through its super class and categories. 8873 if (!rhsID->ClassImplementsProtocol(I, true)) 8874 return false; 8875 } 8876 } 8877 // If there are no qualifiers and no interface, we have an 'id'. 8878 return true; 8879 } 8880 // Both the right and left sides have qualifiers. 8881 for (auto *lhsProto : lhs->quals()) { 8882 bool match = false; 8883 8884 // when comparing an id<P> on lhs with a static type on rhs, 8885 // see if static class implements all of id's protocols, directly or 8886 // through its super class and categories. 8887 for (auto *rhsProto : rhs->quals()) { 8888 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8889 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8890 match = true; 8891 break; 8892 } 8893 } 8894 // If the RHS is a qualified interface pointer "NSString<P>*", 8895 // make sure we check the class hierarchy. 8896 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { 8897 for (auto *I : lhs->quals()) { 8898 // when comparing an id<P> on lhs with a static type on rhs, 8899 // see if static class implements all of id's protocols, directly or 8900 // through its super class and categories. 8901 if (rhsID->ClassImplementsProtocol(I, true)) { 8902 match = true; 8903 break; 8904 } 8905 } 8906 } 8907 if (!match) 8908 return false; 8909 } 8910 8911 return true; 8912 } 8913 8914 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); 8915 8916 if (lhs->getInterfaceType()) { 8917 // If both the right and left sides have qualifiers. 8918 for (auto *lhsProto : lhs->quals()) { 8919 bool match = false; 8920 8921 // when comparing an id<P> on rhs with a static type on lhs, 8922 // see if static class implements all of id's protocols, directly or 8923 // through its super class and categories. 8924 // First, lhs protocols in the qualifier list must be found, direct 8925 // or indirect in rhs's qualifier list or it is a mismatch. 8926 for (auto *rhsProto : rhs->quals()) { 8927 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8928 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8929 match = true; 8930 break; 8931 } 8932 } 8933 if (!match) 8934 return false; 8935 } 8936 8937 // Static class's protocols, or its super class or category protocols 8938 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 8939 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { 8940 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 8941 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 8942 // This is rather dubious but matches gcc's behavior. If lhs has 8943 // no type qualifier and its class has no static protocol(s) 8944 // assume that it is mismatch. 8945 if (LHSInheritedProtocols.empty() && lhs->qual_empty()) 8946 return false; 8947 for (auto *lhsProto : LHSInheritedProtocols) { 8948 bool match = false; 8949 for (auto *rhsProto : rhs->quals()) { 8950 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 8951 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 8952 match = true; 8953 break; 8954 } 8955 } 8956 if (!match) 8957 return false; 8958 } 8959 } 8960 return true; 8961 } 8962 return false; 8963 } 8964 8965 /// canAssignObjCInterfaces - Return true if the two interface types are 8966 /// compatible for assignment from RHS to LHS. This handles validation of any 8967 /// protocol qualifiers on the LHS or RHS. 8968 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 8969 const ObjCObjectPointerType *RHSOPT) { 8970 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8971 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8972 8973 // If either type represents the built-in 'id' type, return true. 8974 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) 8975 return true; 8976 8977 // Function object that propagates a successful result or handles 8978 // __kindof types. 8979 auto finish = [&](bool succeeded) -> bool { 8980 if (succeeded) 8981 return true; 8982 8983 if (!RHS->isKindOfType()) 8984 return false; 8985 8986 // Strip off __kindof and protocol qualifiers, then check whether 8987 // we can assign the other way. 8988 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 8989 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 8990 }; 8991 8992 // Casts from or to id<P> are allowed when the other side has compatible 8993 // protocols. 8994 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 8995 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); 8996 } 8997 8998 // Verify protocol compatibility for casts from Class<P1> to Class<P2>. 8999 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 9000 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); 9001 } 9002 9003 // Casts from Class to Class<Foo>, or vice-versa, are allowed. 9004 if (LHS->isObjCClass() && RHS->isObjCClass()) { 9005 return true; 9006 } 9007 9008 // If we have 2 user-defined types, fall into that path. 9009 if (LHS->getInterface() && RHS->getInterface()) { 9010 return finish(canAssignObjCInterfaces(LHS, RHS)); 9011 } 9012 9013 return false; 9014 } 9015 9016 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 9017 /// for providing type-safety for objective-c pointers used to pass/return 9018 /// arguments in block literals. When passed as arguments, passing 'A*' where 9019 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 9020 /// not OK. For the return type, the opposite is not OK. 9021 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 9022 const ObjCObjectPointerType *LHSOPT, 9023 const ObjCObjectPointerType *RHSOPT, 9024 bool BlockReturnType) { 9025 9026 // Function object that propagates a successful result or handles 9027 // __kindof types. 9028 auto finish = [&](bool succeeded) -> bool { 9029 if (succeeded) 9030 return true; 9031 9032 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 9033 if (!Expected->isKindOfType()) 9034 return false; 9035 9036 // Strip off __kindof and protocol qualifiers, then check whether 9037 // we can assign the other way. 9038 return canAssignObjCInterfacesInBlockPointer( 9039 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 9040 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 9041 BlockReturnType); 9042 }; 9043 9044 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 9045 return true; 9046 9047 if (LHSOPT->isObjCBuiltinType()) { 9048 return finish(RHSOPT->isObjCBuiltinType() || 9049 RHSOPT->isObjCQualifiedIdType()); 9050 } 9051 9052 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) { 9053 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking) 9054 // Use for block parameters previous type checking for compatibility. 9055 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) || 9056 // Or corrected type checking as in non-compat mode. 9057 (!BlockReturnType && 9058 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false))); 9059 else 9060 return finish(ObjCQualifiedIdTypesAreCompatible( 9061 (BlockReturnType ? LHSOPT : RHSOPT), 9062 (BlockReturnType ? RHSOPT : LHSOPT), false)); 9063 } 9064 9065 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 9066 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 9067 if (LHS && RHS) { // We have 2 user-defined types. 9068 if (LHS != RHS) { 9069 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 9070 return finish(BlockReturnType); 9071 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 9072 return finish(!BlockReturnType); 9073 } 9074 else 9075 return true; 9076 } 9077 return false; 9078 } 9079 9080 /// Comparison routine for Objective-C protocols to be used with 9081 /// llvm::array_pod_sort. 9082 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 9083 ObjCProtocolDecl * const *rhs) { 9084 return (*lhs)->getName().compare((*rhs)->getName()); 9085 } 9086 9087 /// getIntersectionOfProtocols - This routine finds the intersection of set 9088 /// of protocols inherited from two distinct objective-c pointer objects with 9089 /// the given common base. 9090 /// It is used to build composite qualifier list of the composite type of 9091 /// the conditional expression involving two objective-c pointer objects. 9092 static 9093 void getIntersectionOfProtocols(ASTContext &Context, 9094 const ObjCInterfaceDecl *CommonBase, 9095 const ObjCObjectPointerType *LHSOPT, 9096 const ObjCObjectPointerType *RHSOPT, 9097 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 9098 9099 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 9100 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 9101 assert(LHS->getInterface() && "LHS must have an interface base"); 9102 assert(RHS->getInterface() && "RHS must have an interface base"); 9103 9104 // Add all of the protocols for the LHS. 9105 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 9106 9107 // Start with the protocol qualifiers. 9108 for (auto proto : LHS->quals()) { 9109 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 9110 } 9111 9112 // Also add the protocols associated with the LHS interface. 9113 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 9114 9115 // Add all of the protocols for the RHS. 9116 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 9117 9118 // Start with the protocol qualifiers. 9119 for (auto proto : RHS->quals()) { 9120 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 9121 } 9122 9123 // Also add the protocols associated with the RHS interface. 9124 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 9125 9126 // Compute the intersection of the collected protocol sets. 9127 for (auto proto : LHSProtocolSet) { 9128 if (RHSProtocolSet.count(proto)) 9129 IntersectionSet.push_back(proto); 9130 } 9131 9132 // Compute the set of protocols that is implied by either the common type or 9133 // the protocols within the intersection. 9134 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 9135 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 9136 9137 // Remove any implied protocols from the list of inherited protocols. 9138 if (!ImpliedProtocols.empty()) { 9139 IntersectionSet.erase( 9140 std::remove_if(IntersectionSet.begin(), 9141 IntersectionSet.end(), 9142 [&](ObjCProtocolDecl *proto) -> bool { 9143 return ImpliedProtocols.count(proto) > 0; 9144 }), 9145 IntersectionSet.end()); 9146 } 9147 9148 // Sort the remaining protocols by name. 9149 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 9150 compareObjCProtocolsByName); 9151 } 9152 9153 /// Determine whether the first type is a subtype of the second. 9154 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 9155 QualType rhs) { 9156 // Common case: two object pointers. 9157 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 9158 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 9159 if (lhsOPT && rhsOPT) 9160 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 9161 9162 // Two block pointers. 9163 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 9164 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 9165 if (lhsBlock && rhsBlock) 9166 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 9167 9168 // If either is an unqualified 'id' and the other is a block, it's 9169 // acceptable. 9170 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 9171 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 9172 return true; 9173 9174 return false; 9175 } 9176 9177 // Check that the given Objective-C type argument lists are equivalent. 9178 static bool sameObjCTypeArgs(ASTContext &ctx, 9179 const ObjCInterfaceDecl *iface, 9180 ArrayRef<QualType> lhsArgs, 9181 ArrayRef<QualType> rhsArgs, 9182 bool stripKindOf) { 9183 if (lhsArgs.size() != rhsArgs.size()) 9184 return false; 9185 9186 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 9187 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 9188 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 9189 continue; 9190 9191 switch (typeParams->begin()[i]->getVariance()) { 9192 case ObjCTypeParamVariance::Invariant: 9193 if (!stripKindOf || 9194 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 9195 rhsArgs[i].stripObjCKindOfType(ctx))) { 9196 return false; 9197 } 9198 break; 9199 9200 case ObjCTypeParamVariance::Covariant: 9201 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 9202 return false; 9203 break; 9204 9205 case ObjCTypeParamVariance::Contravariant: 9206 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 9207 return false; 9208 break; 9209 } 9210 } 9211 9212 return true; 9213 } 9214 9215 QualType ASTContext::areCommonBaseCompatible( 9216 const ObjCObjectPointerType *Lptr, 9217 const ObjCObjectPointerType *Rptr) { 9218 const ObjCObjectType *LHS = Lptr->getObjectType(); 9219 const ObjCObjectType *RHS = Rptr->getObjectType(); 9220 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 9221 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 9222 9223 if (!LDecl || !RDecl) 9224 return {}; 9225 9226 // When either LHS or RHS is a kindof type, we should return a kindof type. 9227 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 9228 // kindof(A). 9229 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 9230 9231 // Follow the left-hand side up the class hierarchy until we either hit a 9232 // root or find the RHS. Record the ancestors in case we don't find it. 9233 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 9234 LHSAncestors; 9235 while (true) { 9236 // Record this ancestor. We'll need this if the common type isn't in the 9237 // path from the LHS to the root. 9238 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 9239 9240 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 9241 // Get the type arguments. 9242 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 9243 bool anyChanges = false; 9244 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9245 // Both have type arguments, compare them. 9246 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9247 LHS->getTypeArgs(), RHS->getTypeArgs(), 9248 /*stripKindOf=*/true)) 9249 return {}; 9250 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9251 // If only one has type arguments, the result will not have type 9252 // arguments. 9253 LHSTypeArgs = {}; 9254 anyChanges = true; 9255 } 9256 9257 // Compute the intersection of protocols. 9258 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9259 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 9260 Protocols); 9261 if (!Protocols.empty()) 9262 anyChanges = true; 9263 9264 // If anything in the LHS will have changed, build a new result type. 9265 // If we need to return a kindof type but LHS is not a kindof type, we 9266 // build a new result type. 9267 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 9268 QualType Result = getObjCInterfaceType(LHS->getInterface()); 9269 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 9270 anyKindOf || LHS->isKindOfType()); 9271 return getObjCObjectPointerType(Result); 9272 } 9273 9274 return getObjCObjectPointerType(QualType(LHS, 0)); 9275 } 9276 9277 // Find the superclass. 9278 QualType LHSSuperType = LHS->getSuperClassType(); 9279 if (LHSSuperType.isNull()) 9280 break; 9281 9282 LHS = LHSSuperType->castAs<ObjCObjectType>(); 9283 } 9284 9285 // We didn't find anything by following the LHS to its root; now check 9286 // the RHS against the cached set of ancestors. 9287 while (true) { 9288 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 9289 if (KnownLHS != LHSAncestors.end()) { 9290 LHS = KnownLHS->second; 9291 9292 // Get the type arguments. 9293 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 9294 bool anyChanges = false; 9295 if (LHS->isSpecialized() && RHS->isSpecialized()) { 9296 // Both have type arguments, compare them. 9297 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 9298 LHS->getTypeArgs(), RHS->getTypeArgs(), 9299 /*stripKindOf=*/true)) 9300 return {}; 9301 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 9302 // If only one has type arguments, the result will not have type 9303 // arguments. 9304 RHSTypeArgs = {}; 9305 anyChanges = true; 9306 } 9307 9308 // Compute the intersection of protocols. 9309 SmallVector<ObjCProtocolDecl *, 8> Protocols; 9310 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 9311 Protocols); 9312 if (!Protocols.empty()) 9313 anyChanges = true; 9314 9315 // If we need to return a kindof type but RHS is not a kindof type, we 9316 // build a new result type. 9317 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 9318 QualType Result = getObjCInterfaceType(RHS->getInterface()); 9319 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 9320 anyKindOf || RHS->isKindOfType()); 9321 return getObjCObjectPointerType(Result); 9322 } 9323 9324 return getObjCObjectPointerType(QualType(RHS, 0)); 9325 } 9326 9327 // Find the superclass of the RHS. 9328 QualType RHSSuperType = RHS->getSuperClassType(); 9329 if (RHSSuperType.isNull()) 9330 break; 9331 9332 RHS = RHSSuperType->castAs<ObjCObjectType>(); 9333 } 9334 9335 return {}; 9336 } 9337 9338 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 9339 const ObjCObjectType *RHS) { 9340 assert(LHS->getInterface() && "LHS is not an interface type"); 9341 assert(RHS->getInterface() && "RHS is not an interface type"); 9342 9343 // Verify that the base decls are compatible: the RHS must be a subclass of 9344 // the LHS. 9345 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 9346 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 9347 if (!IsSuperClass) 9348 return false; 9349 9350 // If the LHS has protocol qualifiers, determine whether all of them are 9351 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 9352 // LHS). 9353 if (LHS->getNumProtocols() > 0) { 9354 // OK if conversion of LHS to SuperClass results in narrowing of types 9355 // ; i.e., SuperClass may implement at least one of the protocols 9356 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 9357 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 9358 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 9359 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 9360 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 9361 // qualifiers. 9362 for (auto *RHSPI : RHS->quals()) 9363 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 9364 // If there is no protocols associated with RHS, it is not a match. 9365 if (SuperClassInheritedProtocols.empty()) 9366 return false; 9367 9368 for (const auto *LHSProto : LHS->quals()) { 9369 bool SuperImplementsProtocol = false; 9370 for (auto *SuperClassProto : SuperClassInheritedProtocols) 9371 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 9372 SuperImplementsProtocol = true; 9373 break; 9374 } 9375 if (!SuperImplementsProtocol) 9376 return false; 9377 } 9378 } 9379 9380 // If the LHS is specialized, we may need to check type arguments. 9381 if (LHS->isSpecialized()) { 9382 // Follow the superclass chain until we've matched the LHS class in the 9383 // hierarchy. This substitutes type arguments through. 9384 const ObjCObjectType *RHSSuper = RHS; 9385 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 9386 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 9387 9388 // If the RHS is specializd, compare type arguments. 9389 if (RHSSuper->isSpecialized() && 9390 !sameObjCTypeArgs(*this, LHS->getInterface(), 9391 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 9392 /*stripKindOf=*/true)) { 9393 return false; 9394 } 9395 } 9396 9397 return true; 9398 } 9399 9400 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 9401 // get the "pointed to" types 9402 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 9403 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 9404 9405 if (!LHSOPT || !RHSOPT) 9406 return false; 9407 9408 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 9409 canAssignObjCInterfaces(RHSOPT, LHSOPT); 9410 } 9411 9412 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 9413 return canAssignObjCInterfaces( 9414 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(), 9415 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>()); 9416 } 9417 9418 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 9419 /// both shall have the identically qualified version of a compatible type. 9420 /// C99 6.2.7p1: Two types have compatible types if their types are the 9421 /// same. See 6.7.[2,3,5] for additional rules. 9422 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 9423 bool CompareUnqualified) { 9424 if (getLangOpts().CPlusPlus) 9425 return hasSameType(LHS, RHS); 9426 9427 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 9428 } 9429 9430 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 9431 return typesAreCompatible(LHS, RHS); 9432 } 9433 9434 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 9435 return !mergeTypes(LHS, RHS, true).isNull(); 9436 } 9437 9438 /// mergeTransparentUnionType - if T is a transparent union type and a member 9439 /// of T is compatible with SubType, return the merged type, else return 9440 /// QualType() 9441 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 9442 bool OfBlockPointer, 9443 bool Unqualified) { 9444 if (const RecordType *UT = T->getAsUnionType()) { 9445 RecordDecl *UD = UT->getDecl(); 9446 if (UD->hasAttr<TransparentUnionAttr>()) { 9447 for (const auto *I : UD->fields()) { 9448 QualType ET = I->getType().getUnqualifiedType(); 9449 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 9450 if (!MT.isNull()) 9451 return MT; 9452 } 9453 } 9454 } 9455 9456 return {}; 9457 } 9458 9459 /// mergeFunctionParameterTypes - merge two types which appear as function 9460 /// parameter types 9461 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 9462 bool OfBlockPointer, 9463 bool Unqualified) { 9464 // GNU extension: two types are compatible if they appear as a function 9465 // argument, one of the types is a transparent union type and the other 9466 // type is compatible with a union member 9467 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 9468 Unqualified); 9469 if (!lmerge.isNull()) 9470 return lmerge; 9471 9472 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 9473 Unqualified); 9474 if (!rmerge.isNull()) 9475 return rmerge; 9476 9477 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 9478 } 9479 9480 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 9481 bool OfBlockPointer, bool Unqualified, 9482 bool AllowCXX) { 9483 const auto *lbase = lhs->castAs<FunctionType>(); 9484 const auto *rbase = rhs->castAs<FunctionType>(); 9485 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 9486 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 9487 bool allLTypes = true; 9488 bool allRTypes = true; 9489 9490 // Check return type 9491 QualType retType; 9492 if (OfBlockPointer) { 9493 QualType RHS = rbase->getReturnType(); 9494 QualType LHS = lbase->getReturnType(); 9495 bool UnqualifiedResult = Unqualified; 9496 if (!UnqualifiedResult) 9497 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 9498 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 9499 } 9500 else 9501 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 9502 Unqualified); 9503 if (retType.isNull()) 9504 return {}; 9505 9506 if (Unqualified) 9507 retType = retType.getUnqualifiedType(); 9508 9509 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 9510 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 9511 if (Unqualified) { 9512 LRetType = LRetType.getUnqualifiedType(); 9513 RRetType = RRetType.getUnqualifiedType(); 9514 } 9515 9516 if (getCanonicalType(retType) != LRetType) 9517 allLTypes = false; 9518 if (getCanonicalType(retType) != RRetType) 9519 allRTypes = false; 9520 9521 // FIXME: double check this 9522 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 9523 // rbase->getRegParmAttr() != 0 && 9524 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 9525 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 9526 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 9527 9528 // Compatible functions must have compatible calling conventions 9529 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 9530 return {}; 9531 9532 // Regparm is part of the calling convention. 9533 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 9534 return {}; 9535 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 9536 return {}; 9537 9538 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 9539 return {}; 9540 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 9541 return {}; 9542 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 9543 return {}; 9544 9545 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 9546 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 9547 9548 if (lbaseInfo.getNoReturn() != NoReturn) 9549 allLTypes = false; 9550 if (rbaseInfo.getNoReturn() != NoReturn) 9551 allRTypes = false; 9552 9553 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 9554 9555 if (lproto && rproto) { // two C99 style function prototypes 9556 assert((AllowCXX || 9557 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) && 9558 "C++ shouldn't be here"); 9559 // Compatible functions must have the same number of parameters 9560 if (lproto->getNumParams() != rproto->getNumParams()) 9561 return {}; 9562 9563 // Variadic and non-variadic functions aren't compatible 9564 if (lproto->isVariadic() != rproto->isVariadic()) 9565 return {}; 9566 9567 if (lproto->getMethodQuals() != rproto->getMethodQuals()) 9568 return {}; 9569 9570 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 9571 bool canUseLeft, canUseRight; 9572 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 9573 newParamInfos)) 9574 return {}; 9575 9576 if (!canUseLeft) 9577 allLTypes = false; 9578 if (!canUseRight) 9579 allRTypes = false; 9580 9581 // Check parameter type compatibility 9582 SmallVector<QualType, 10> types; 9583 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 9584 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 9585 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 9586 QualType paramType = mergeFunctionParameterTypes( 9587 lParamType, rParamType, OfBlockPointer, Unqualified); 9588 if (paramType.isNull()) 9589 return {}; 9590 9591 if (Unqualified) 9592 paramType = paramType.getUnqualifiedType(); 9593 9594 types.push_back(paramType); 9595 if (Unqualified) { 9596 lParamType = lParamType.getUnqualifiedType(); 9597 rParamType = rParamType.getUnqualifiedType(); 9598 } 9599 9600 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 9601 allLTypes = false; 9602 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 9603 allRTypes = false; 9604 } 9605 9606 if (allLTypes) return lhs; 9607 if (allRTypes) return rhs; 9608 9609 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 9610 EPI.ExtInfo = einfo; 9611 EPI.ExtParameterInfos = 9612 newParamInfos.empty() ? nullptr : newParamInfos.data(); 9613 return getFunctionType(retType, types, EPI); 9614 } 9615 9616 if (lproto) allRTypes = false; 9617 if (rproto) allLTypes = false; 9618 9619 const FunctionProtoType *proto = lproto ? lproto : rproto; 9620 if (proto) { 9621 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); 9622 if (proto->isVariadic()) 9623 return {}; 9624 // Check that the types are compatible with the types that 9625 // would result from default argument promotions (C99 6.7.5.3p15). 9626 // The only types actually affected are promotable integer 9627 // types and floats, which would be passed as a different 9628 // type depending on whether the prototype is visible. 9629 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 9630 QualType paramTy = proto->getParamType(i); 9631 9632 // Look at the converted type of enum types, since that is the type used 9633 // to pass enum values. 9634 if (const auto *Enum = paramTy->getAs<EnumType>()) { 9635 paramTy = Enum->getDecl()->getIntegerType(); 9636 if (paramTy.isNull()) 9637 return {}; 9638 } 9639 9640 if (paramTy->isPromotableIntegerType() || 9641 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 9642 return {}; 9643 } 9644 9645 if (allLTypes) return lhs; 9646 if (allRTypes) return rhs; 9647 9648 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 9649 EPI.ExtInfo = einfo; 9650 return getFunctionType(retType, proto->getParamTypes(), EPI); 9651 } 9652 9653 if (allLTypes) return lhs; 9654 if (allRTypes) return rhs; 9655 return getFunctionNoProtoType(retType, einfo); 9656 } 9657 9658 /// Given that we have an enum type and a non-enum type, try to merge them. 9659 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 9660 QualType other, bool isBlockReturnType) { 9661 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 9662 // a signed integer type, or an unsigned integer type. 9663 // Compatibility is based on the underlying type, not the promotion 9664 // type. 9665 QualType underlyingType = ET->getDecl()->getIntegerType(); 9666 if (underlyingType.isNull()) 9667 return {}; 9668 if (Context.hasSameType(underlyingType, other)) 9669 return other; 9670 9671 // In block return types, we're more permissive and accept any 9672 // integral type of the same size. 9673 if (isBlockReturnType && other->isIntegerType() && 9674 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 9675 return other; 9676 9677 return {}; 9678 } 9679 9680 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 9681 bool OfBlockPointer, 9682 bool Unqualified, bool BlockReturnType) { 9683 // C++ [expr]: If an expression initially has the type "reference to T", the 9684 // type is adjusted to "T" prior to any further analysis, the expression 9685 // designates the object or function denoted by the reference, and the 9686 // expression is an lvalue unless the reference is an rvalue reference and 9687 // the expression is a function call (possibly inside parentheses). 9688 if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>()) 9689 return {}; 9690 9691 if (Unqualified) { 9692 LHS = LHS.getUnqualifiedType(); 9693 RHS = RHS.getUnqualifiedType(); 9694 } 9695 9696 QualType LHSCan = getCanonicalType(LHS), 9697 RHSCan = getCanonicalType(RHS); 9698 9699 // If two types are identical, they are compatible. 9700 if (LHSCan == RHSCan) 9701 return LHS; 9702 9703 // If the qualifiers are different, the types aren't compatible... mostly. 9704 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9705 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9706 if (LQuals != RQuals) { 9707 // If any of these qualifiers are different, we have a type 9708 // mismatch. 9709 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9710 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 9711 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 9712 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 9713 return {}; 9714 9715 // Exactly one GC qualifier difference is allowed: __strong is 9716 // okay if the other type has no GC qualifier but is an Objective 9717 // C object pointer (i.e. implicitly strong by default). We fix 9718 // this by pretending that the unqualified type was actually 9719 // qualified __strong. 9720 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9721 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9722 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9723 9724 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9725 return {}; 9726 9727 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 9728 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 9729 } 9730 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 9731 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 9732 } 9733 return {}; 9734 } 9735 9736 // Okay, qualifiers are equal. 9737 9738 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 9739 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 9740 9741 // We want to consider the two function types to be the same for these 9742 // comparisons, just force one to the other. 9743 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 9744 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 9745 9746 // Same as above for arrays 9747 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 9748 LHSClass = Type::ConstantArray; 9749 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 9750 RHSClass = Type::ConstantArray; 9751 9752 // ObjCInterfaces are just specialized ObjCObjects. 9753 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 9754 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 9755 9756 // Canonicalize ExtVector -> Vector. 9757 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 9758 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 9759 9760 // If the canonical type classes don't match. 9761 if (LHSClass != RHSClass) { 9762 // Note that we only have special rules for turning block enum 9763 // returns into block int returns, not vice-versa. 9764 if (const auto *ETy = LHS->getAs<EnumType>()) { 9765 return mergeEnumWithInteger(*this, ETy, RHS, false); 9766 } 9767 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 9768 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 9769 } 9770 // allow block pointer type to match an 'id' type. 9771 if (OfBlockPointer && !BlockReturnType) { 9772 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 9773 return LHS; 9774 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 9775 return RHS; 9776 } 9777 9778 return {}; 9779 } 9780 9781 // The canonical type classes match. 9782 switch (LHSClass) { 9783 #define TYPE(Class, Base) 9784 #define ABSTRACT_TYPE(Class, Base) 9785 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 9786 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 9787 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 9788 #include "clang/AST/TypeNodes.inc" 9789 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 9790 9791 case Type::Auto: 9792 case Type::DeducedTemplateSpecialization: 9793 case Type::LValueReference: 9794 case Type::RValueReference: 9795 case Type::MemberPointer: 9796 llvm_unreachable("C++ should never be in mergeTypes"); 9797 9798 case Type::ObjCInterface: 9799 case Type::IncompleteArray: 9800 case Type::VariableArray: 9801 case Type::FunctionProto: 9802 case Type::ExtVector: 9803 llvm_unreachable("Types are eliminated above"); 9804 9805 case Type::Pointer: 9806 { 9807 // Merge two pointer types, while trying to preserve typedef info 9808 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); 9809 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); 9810 if (Unqualified) { 9811 LHSPointee = LHSPointee.getUnqualifiedType(); 9812 RHSPointee = RHSPointee.getUnqualifiedType(); 9813 } 9814 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 9815 Unqualified); 9816 if (ResultType.isNull()) 9817 return {}; 9818 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9819 return LHS; 9820 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9821 return RHS; 9822 return getPointerType(ResultType); 9823 } 9824 case Type::BlockPointer: 9825 { 9826 // Merge two block pointer types, while trying to preserve typedef info 9827 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); 9828 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); 9829 if (Unqualified) { 9830 LHSPointee = LHSPointee.getUnqualifiedType(); 9831 RHSPointee = RHSPointee.getUnqualifiedType(); 9832 } 9833 if (getLangOpts().OpenCL) { 9834 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 9835 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 9836 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 9837 // 6.12.5) thus the following check is asymmetric. 9838 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 9839 return {}; 9840 LHSPteeQual.removeAddressSpace(); 9841 RHSPteeQual.removeAddressSpace(); 9842 LHSPointee = 9843 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 9844 RHSPointee = 9845 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 9846 } 9847 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 9848 Unqualified); 9849 if (ResultType.isNull()) 9850 return {}; 9851 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 9852 return LHS; 9853 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 9854 return RHS; 9855 return getBlockPointerType(ResultType); 9856 } 9857 case Type::Atomic: 9858 { 9859 // Merge two pointer types, while trying to preserve typedef info 9860 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); 9861 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); 9862 if (Unqualified) { 9863 LHSValue = LHSValue.getUnqualifiedType(); 9864 RHSValue = RHSValue.getUnqualifiedType(); 9865 } 9866 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 9867 Unqualified); 9868 if (ResultType.isNull()) 9869 return {}; 9870 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 9871 return LHS; 9872 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 9873 return RHS; 9874 return getAtomicType(ResultType); 9875 } 9876 case Type::ConstantArray: 9877 { 9878 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 9879 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 9880 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 9881 return {}; 9882 9883 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 9884 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 9885 if (Unqualified) { 9886 LHSElem = LHSElem.getUnqualifiedType(); 9887 RHSElem = RHSElem.getUnqualifiedType(); 9888 } 9889 9890 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 9891 if (ResultType.isNull()) 9892 return {}; 9893 9894 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 9895 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 9896 9897 // If either side is a variable array, and both are complete, check whether 9898 // the current dimension is definite. 9899 if (LVAT || RVAT) { 9900 auto SizeFetch = [this](const VariableArrayType* VAT, 9901 const ConstantArrayType* CAT) 9902 -> std::pair<bool,llvm::APInt> { 9903 if (VAT) { 9904 Optional<llvm::APSInt> TheInt; 9905 Expr *E = VAT->getSizeExpr(); 9906 if (E && (TheInt = E->getIntegerConstantExpr(*this))) 9907 return std::make_pair(true, *TheInt); 9908 return std::make_pair(false, llvm::APSInt()); 9909 } 9910 if (CAT) 9911 return std::make_pair(true, CAT->getSize()); 9912 return std::make_pair(false, llvm::APInt()); 9913 }; 9914 9915 bool HaveLSize, HaveRSize; 9916 llvm::APInt LSize, RSize; 9917 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 9918 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 9919 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 9920 return {}; // Definite, but unequal, array dimension 9921 } 9922 9923 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9924 return LHS; 9925 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9926 return RHS; 9927 if (LCAT) 9928 return getConstantArrayType(ResultType, LCAT->getSize(), 9929 LCAT->getSizeExpr(), 9930 ArrayType::ArraySizeModifier(), 0); 9931 if (RCAT) 9932 return getConstantArrayType(ResultType, RCAT->getSize(), 9933 RCAT->getSizeExpr(), 9934 ArrayType::ArraySizeModifier(), 0); 9935 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 9936 return LHS; 9937 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 9938 return RHS; 9939 if (LVAT) { 9940 // FIXME: This isn't correct! But tricky to implement because 9941 // the array's size has to be the size of LHS, but the type 9942 // has to be different. 9943 return LHS; 9944 } 9945 if (RVAT) { 9946 // FIXME: This isn't correct! But tricky to implement because 9947 // the array's size has to be the size of RHS, but the type 9948 // has to be different. 9949 return RHS; 9950 } 9951 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 9952 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 9953 return getIncompleteArrayType(ResultType, 9954 ArrayType::ArraySizeModifier(), 0); 9955 } 9956 case Type::FunctionNoProto: 9957 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 9958 case Type::Record: 9959 case Type::Enum: 9960 return {}; 9961 case Type::Builtin: 9962 // Only exactly equal builtin types are compatible, which is tested above. 9963 return {}; 9964 case Type::Complex: 9965 // Distinct complex types are incompatible. 9966 return {}; 9967 case Type::Vector: 9968 // FIXME: The merged type should be an ExtVector! 9969 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), 9970 RHSCan->castAs<VectorType>())) 9971 return LHS; 9972 return {}; 9973 case Type::ConstantMatrix: 9974 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(), 9975 RHSCan->castAs<ConstantMatrixType>())) 9976 return LHS; 9977 return {}; 9978 case Type::ObjCObject: { 9979 // Check if the types are assignment compatible. 9980 // FIXME: This should be type compatibility, e.g. whether 9981 // "LHS x; RHS x;" at global scope is legal. 9982 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), 9983 RHS->castAs<ObjCObjectType>())) 9984 return LHS; 9985 return {}; 9986 } 9987 case Type::ObjCObjectPointer: 9988 if (OfBlockPointer) { 9989 if (canAssignObjCInterfacesInBlockPointer( 9990 LHS->castAs<ObjCObjectPointerType>(), 9991 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) 9992 return LHS; 9993 return {}; 9994 } 9995 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), 9996 RHS->castAs<ObjCObjectPointerType>())) 9997 return LHS; 9998 return {}; 9999 case Type::Pipe: 10000 assert(LHS != RHS && 10001 "Equivalent pipe types should have already been handled!"); 10002 return {}; 10003 case Type::ExtInt: { 10004 // Merge two ext-int types, while trying to preserve typedef info. 10005 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned(); 10006 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned(); 10007 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits(); 10008 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits(); 10009 10010 // Like unsigned/int, shouldn't have a type if they dont match. 10011 if (LHSUnsigned != RHSUnsigned) 10012 return {}; 10013 10014 if (LHSBits != RHSBits) 10015 return {}; 10016 return LHS; 10017 } 10018 } 10019 10020 llvm_unreachable("Invalid Type::Class!"); 10021 } 10022 10023 bool ASTContext::mergeExtParameterInfo( 10024 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 10025 bool &CanUseFirst, bool &CanUseSecond, 10026 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 10027 assert(NewParamInfos.empty() && "param info list not empty"); 10028 CanUseFirst = CanUseSecond = true; 10029 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 10030 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 10031 10032 // Fast path: if the first type doesn't have ext parameter infos, 10033 // we match if and only if the second type also doesn't have them. 10034 if (!FirstHasInfo && !SecondHasInfo) 10035 return true; 10036 10037 bool NeedParamInfo = false; 10038 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 10039 : SecondFnType->getExtParameterInfos().size(); 10040 10041 for (size_t I = 0; I < E; ++I) { 10042 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 10043 if (FirstHasInfo) 10044 FirstParam = FirstFnType->getExtParameterInfo(I); 10045 if (SecondHasInfo) 10046 SecondParam = SecondFnType->getExtParameterInfo(I); 10047 10048 // Cannot merge unless everything except the noescape flag matches. 10049 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 10050 return false; 10051 10052 bool FirstNoEscape = FirstParam.isNoEscape(); 10053 bool SecondNoEscape = SecondParam.isNoEscape(); 10054 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 10055 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 10056 if (NewParamInfos.back().getOpaqueValue()) 10057 NeedParamInfo = true; 10058 if (FirstNoEscape != IsNoEscape) 10059 CanUseFirst = false; 10060 if (SecondNoEscape != IsNoEscape) 10061 CanUseSecond = false; 10062 } 10063 10064 if (!NeedParamInfo) 10065 NewParamInfos.clear(); 10066 10067 return true; 10068 } 10069 10070 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 10071 ObjCLayouts[CD] = nullptr; 10072 } 10073 10074 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 10075 /// 'RHS' attributes and returns the merged version; including for function 10076 /// return types. 10077 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 10078 QualType LHSCan = getCanonicalType(LHS), 10079 RHSCan = getCanonicalType(RHS); 10080 // If two types are identical, they are compatible. 10081 if (LHSCan == RHSCan) 10082 return LHS; 10083 if (RHSCan->isFunctionType()) { 10084 if (!LHSCan->isFunctionType()) 10085 return {}; 10086 QualType OldReturnType = 10087 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 10088 QualType NewReturnType = 10089 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 10090 QualType ResReturnType = 10091 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 10092 if (ResReturnType.isNull()) 10093 return {}; 10094 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 10095 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 10096 // In either case, use OldReturnType to build the new function type. 10097 const auto *F = LHS->castAs<FunctionType>(); 10098 if (const auto *FPT = cast<FunctionProtoType>(F)) { 10099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10100 EPI.ExtInfo = getFunctionExtInfo(LHS); 10101 QualType ResultType = 10102 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 10103 return ResultType; 10104 } 10105 } 10106 return {}; 10107 } 10108 10109 // If the qualifiers are different, the types can still be merged. 10110 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 10111 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 10112 if (LQuals != RQuals) { 10113 // If any of these qualifiers are different, we have a type mismatch. 10114 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 10115 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 10116 return {}; 10117 10118 // Exactly one GC qualifier difference is allowed: __strong is 10119 // okay if the other type has no GC qualifier but is an Objective 10120 // C object pointer (i.e. implicitly strong by default). We fix 10121 // this by pretending that the unqualified type was actually 10122 // qualified __strong. 10123 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 10124 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 10125 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 10126 10127 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 10128 return {}; 10129 10130 if (GC_L == Qualifiers::Strong) 10131 return LHS; 10132 if (GC_R == Qualifiers::Strong) 10133 return RHS; 10134 return {}; 10135 } 10136 10137 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 10138 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10139 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); 10140 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 10141 if (ResQT == LHSBaseQT) 10142 return LHS; 10143 if (ResQT == RHSBaseQT) 10144 return RHS; 10145 } 10146 return {}; 10147 } 10148 10149 //===----------------------------------------------------------------------===// 10150 // Integer Predicates 10151 //===----------------------------------------------------------------------===// 10152 10153 unsigned ASTContext::getIntWidth(QualType T) const { 10154 if (const auto *ET = T->getAs<EnumType>()) 10155 T = ET->getDecl()->getIntegerType(); 10156 if (T->isBooleanType()) 10157 return 1; 10158 if(const auto *EIT = T->getAs<ExtIntType>()) 10159 return EIT->getNumBits(); 10160 // For builtin types, just use the standard type sizing method 10161 return (unsigned)getTypeSize(T); 10162 } 10163 10164 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 10165 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 10166 "Unexpected type"); 10167 10168 // Turn <4 x signed int> -> <4 x unsigned int> 10169 if (const auto *VTy = T->getAs<VectorType>()) 10170 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 10171 VTy->getNumElements(), VTy->getVectorKind()); 10172 10173 // For _ExtInt, return an unsigned _ExtInt with same width. 10174 if (const auto *EITy = T->getAs<ExtIntType>()) 10175 return getExtIntType(/*IsUnsigned=*/true, EITy->getNumBits()); 10176 10177 // For enums, get the underlying integer type of the enum, and let the general 10178 // integer type signchanging code handle it. 10179 if (const auto *ETy = T->getAs<EnumType>()) 10180 T = ETy->getDecl()->getIntegerType(); 10181 10182 switch (T->castAs<BuiltinType>()->getKind()) { 10183 case BuiltinType::Char_S: 10184 case BuiltinType::SChar: 10185 return UnsignedCharTy; 10186 case BuiltinType::Short: 10187 return UnsignedShortTy; 10188 case BuiltinType::Int: 10189 return UnsignedIntTy; 10190 case BuiltinType::Long: 10191 return UnsignedLongTy; 10192 case BuiltinType::LongLong: 10193 return UnsignedLongLongTy; 10194 case BuiltinType::Int128: 10195 return UnsignedInt128Ty; 10196 // wchar_t is special. It is either signed or not, but when it's signed, 10197 // there's no matching "unsigned wchar_t". Therefore we return the unsigned 10198 // version of it's underlying type instead. 10199 case BuiltinType::WChar_S: 10200 return getUnsignedWCharType(); 10201 10202 case BuiltinType::ShortAccum: 10203 return UnsignedShortAccumTy; 10204 case BuiltinType::Accum: 10205 return UnsignedAccumTy; 10206 case BuiltinType::LongAccum: 10207 return UnsignedLongAccumTy; 10208 case BuiltinType::SatShortAccum: 10209 return SatUnsignedShortAccumTy; 10210 case BuiltinType::SatAccum: 10211 return SatUnsignedAccumTy; 10212 case BuiltinType::SatLongAccum: 10213 return SatUnsignedLongAccumTy; 10214 case BuiltinType::ShortFract: 10215 return UnsignedShortFractTy; 10216 case BuiltinType::Fract: 10217 return UnsignedFractTy; 10218 case BuiltinType::LongFract: 10219 return UnsignedLongFractTy; 10220 case BuiltinType::SatShortFract: 10221 return SatUnsignedShortFractTy; 10222 case BuiltinType::SatFract: 10223 return SatUnsignedFractTy; 10224 case BuiltinType::SatLongFract: 10225 return SatUnsignedLongFractTy; 10226 default: 10227 llvm_unreachable("Unexpected signed integer or fixed point type"); 10228 } 10229 } 10230 10231 QualType ASTContext::getCorrespondingSignedType(QualType T) const { 10232 assert((T->hasUnsignedIntegerRepresentation() || 10233 T->isUnsignedFixedPointType()) && 10234 "Unexpected type"); 10235 10236 // Turn <4 x unsigned int> -> <4 x signed int> 10237 if (const auto *VTy = T->getAs<VectorType>()) 10238 return getVectorType(getCorrespondingSignedType(VTy->getElementType()), 10239 VTy->getNumElements(), VTy->getVectorKind()); 10240 10241 // For _ExtInt, return a signed _ExtInt with same width. 10242 if (const auto *EITy = T->getAs<ExtIntType>()) 10243 return getExtIntType(/*IsUnsigned=*/false, EITy->getNumBits()); 10244 10245 // For enums, get the underlying integer type of the enum, and let the general 10246 // integer type signchanging code handle it. 10247 if (const auto *ETy = T->getAs<EnumType>()) 10248 T = ETy->getDecl()->getIntegerType(); 10249 10250 switch (T->castAs<BuiltinType>()->getKind()) { 10251 case BuiltinType::Char_U: 10252 case BuiltinType::UChar: 10253 return SignedCharTy; 10254 case BuiltinType::UShort: 10255 return ShortTy; 10256 case BuiltinType::UInt: 10257 return IntTy; 10258 case BuiltinType::ULong: 10259 return LongTy; 10260 case BuiltinType::ULongLong: 10261 return LongLongTy; 10262 case BuiltinType::UInt128: 10263 return Int128Ty; 10264 // wchar_t is special. It is either unsigned or not, but when it's unsigned, 10265 // there's no matching "signed wchar_t". Therefore we return the signed 10266 // version of it's underlying type instead. 10267 case BuiltinType::WChar_U: 10268 return getSignedWCharType(); 10269 10270 case BuiltinType::UShortAccum: 10271 return ShortAccumTy; 10272 case BuiltinType::UAccum: 10273 return AccumTy; 10274 case BuiltinType::ULongAccum: 10275 return LongAccumTy; 10276 case BuiltinType::SatUShortAccum: 10277 return SatShortAccumTy; 10278 case BuiltinType::SatUAccum: 10279 return SatAccumTy; 10280 case BuiltinType::SatULongAccum: 10281 return SatLongAccumTy; 10282 case BuiltinType::UShortFract: 10283 return ShortFractTy; 10284 case BuiltinType::UFract: 10285 return FractTy; 10286 case BuiltinType::ULongFract: 10287 return LongFractTy; 10288 case BuiltinType::SatUShortFract: 10289 return SatShortFractTy; 10290 case BuiltinType::SatUFract: 10291 return SatFractTy; 10292 case BuiltinType::SatULongFract: 10293 return SatLongFractTy; 10294 default: 10295 llvm_unreachable("Unexpected unsigned integer or fixed point type"); 10296 } 10297 } 10298 10299 ASTMutationListener::~ASTMutationListener() = default; 10300 10301 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 10302 QualType ReturnType) {} 10303 10304 //===----------------------------------------------------------------------===// 10305 // Builtin Type Computation 10306 //===----------------------------------------------------------------------===// 10307 10308 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 10309 /// pointer over the consumed characters. This returns the resultant type. If 10310 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 10311 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 10312 /// a vector of "i*". 10313 /// 10314 /// RequiresICE is filled in on return to indicate whether the value is required 10315 /// to be an Integer Constant Expression. 10316 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 10317 ASTContext::GetBuiltinTypeError &Error, 10318 bool &RequiresICE, 10319 bool AllowTypeModifiers) { 10320 // Modifiers. 10321 int HowLong = 0; 10322 bool Signed = false, Unsigned = false; 10323 RequiresICE = false; 10324 10325 // Read the prefixed modifiers first. 10326 bool Done = false; 10327 #ifndef NDEBUG 10328 bool IsSpecial = false; 10329 #endif 10330 while (!Done) { 10331 switch (*Str++) { 10332 default: Done = true; --Str; break; 10333 case 'I': 10334 RequiresICE = true; 10335 break; 10336 case 'S': 10337 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 10338 assert(!Signed && "Can't use 'S' modifier multiple times!"); 10339 Signed = true; 10340 break; 10341 case 'U': 10342 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 10343 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 10344 Unsigned = true; 10345 break; 10346 case 'L': 10347 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); 10348 assert(HowLong <= 2 && "Can't have LLLL modifier"); 10349 ++HowLong; 10350 break; 10351 case 'N': 10352 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 10353 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10354 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 10355 #ifndef NDEBUG 10356 IsSpecial = true; 10357 #endif 10358 if (Context.getTargetInfo().getLongWidth() == 32) 10359 ++HowLong; 10360 break; 10361 case 'W': 10362 // This modifier represents int64 type. 10363 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10364 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 10365 #ifndef NDEBUG 10366 IsSpecial = true; 10367 #endif 10368 switch (Context.getTargetInfo().getInt64Type()) { 10369 default: 10370 llvm_unreachable("Unexpected integer type"); 10371 case TargetInfo::SignedLong: 10372 HowLong = 1; 10373 break; 10374 case TargetInfo::SignedLongLong: 10375 HowLong = 2; 10376 break; 10377 } 10378 break; 10379 case 'Z': 10380 // This modifier represents int32 type. 10381 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10382 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); 10383 #ifndef NDEBUG 10384 IsSpecial = true; 10385 #endif 10386 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { 10387 default: 10388 llvm_unreachable("Unexpected integer type"); 10389 case TargetInfo::SignedInt: 10390 HowLong = 0; 10391 break; 10392 case TargetInfo::SignedLong: 10393 HowLong = 1; 10394 break; 10395 case TargetInfo::SignedLongLong: 10396 HowLong = 2; 10397 break; 10398 } 10399 break; 10400 case 'O': 10401 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); 10402 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); 10403 #ifndef NDEBUG 10404 IsSpecial = true; 10405 #endif 10406 if (Context.getLangOpts().OpenCL) 10407 HowLong = 1; 10408 else 10409 HowLong = 2; 10410 break; 10411 } 10412 } 10413 10414 QualType Type; 10415 10416 // Read the base type. 10417 switch (*Str++) { 10418 default: llvm_unreachable("Unknown builtin type letter!"); 10419 case 'x': 10420 assert(HowLong == 0 && !Signed && !Unsigned && 10421 "Bad modifiers used with 'x'!"); 10422 Type = Context.Float16Ty; 10423 break; 10424 case 'y': 10425 assert(HowLong == 0 && !Signed && !Unsigned && 10426 "Bad modifiers used with 'y'!"); 10427 Type = Context.BFloat16Ty; 10428 break; 10429 case 'v': 10430 assert(HowLong == 0 && !Signed && !Unsigned && 10431 "Bad modifiers used with 'v'!"); 10432 Type = Context.VoidTy; 10433 break; 10434 case 'h': 10435 assert(HowLong == 0 && !Signed && !Unsigned && 10436 "Bad modifiers used with 'h'!"); 10437 Type = Context.HalfTy; 10438 break; 10439 case 'f': 10440 assert(HowLong == 0 && !Signed && !Unsigned && 10441 "Bad modifiers used with 'f'!"); 10442 Type = Context.FloatTy; 10443 break; 10444 case 'd': 10445 assert(HowLong < 3 && !Signed && !Unsigned && 10446 "Bad modifiers used with 'd'!"); 10447 if (HowLong == 1) 10448 Type = Context.LongDoubleTy; 10449 else if (HowLong == 2) 10450 Type = Context.Float128Ty; 10451 else 10452 Type = Context.DoubleTy; 10453 break; 10454 case 's': 10455 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 10456 if (Unsigned) 10457 Type = Context.UnsignedShortTy; 10458 else 10459 Type = Context.ShortTy; 10460 break; 10461 case 'i': 10462 if (HowLong == 3) 10463 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 10464 else if (HowLong == 2) 10465 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 10466 else if (HowLong == 1) 10467 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 10468 else 10469 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 10470 break; 10471 case 'c': 10472 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 10473 if (Signed) 10474 Type = Context.SignedCharTy; 10475 else if (Unsigned) 10476 Type = Context.UnsignedCharTy; 10477 else 10478 Type = Context.CharTy; 10479 break; 10480 case 'b': // boolean 10481 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 10482 Type = Context.BoolTy; 10483 break; 10484 case 'z': // size_t. 10485 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 10486 Type = Context.getSizeType(); 10487 break; 10488 case 'w': // wchar_t. 10489 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 10490 Type = Context.getWideCharType(); 10491 break; 10492 case 'F': 10493 Type = Context.getCFConstantStringType(); 10494 break; 10495 case 'G': 10496 Type = Context.getObjCIdType(); 10497 break; 10498 case 'H': 10499 Type = Context.getObjCSelType(); 10500 break; 10501 case 'M': 10502 Type = Context.getObjCSuperType(); 10503 break; 10504 case 'a': 10505 Type = Context.getBuiltinVaListType(); 10506 assert(!Type.isNull() && "builtin va list type not initialized!"); 10507 break; 10508 case 'A': 10509 // This is a "reference" to a va_list; however, what exactly 10510 // this means depends on how va_list is defined. There are two 10511 // different kinds of va_list: ones passed by value, and ones 10512 // passed by reference. An example of a by-value va_list is 10513 // x86, where va_list is a char*. An example of by-ref va_list 10514 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 10515 // we want this argument to be a char*&; for x86-64, we want 10516 // it to be a __va_list_tag*. 10517 Type = Context.getBuiltinVaListType(); 10518 assert(!Type.isNull() && "builtin va list type not initialized!"); 10519 if (Type->isArrayType()) 10520 Type = Context.getArrayDecayedType(Type); 10521 else 10522 Type = Context.getLValueReferenceType(Type); 10523 break; 10524 case 'q': { 10525 char *End; 10526 unsigned NumElements = strtoul(Str, &End, 10); 10527 assert(End != Str && "Missing vector size"); 10528 Str = End; 10529 10530 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10531 RequiresICE, false); 10532 assert(!RequiresICE && "Can't require vector ICE"); 10533 10534 Type = Context.getScalableVectorType(ElementType, NumElements); 10535 break; 10536 } 10537 case 'V': { 10538 char *End; 10539 unsigned NumElements = strtoul(Str, &End, 10); 10540 assert(End != Str && "Missing vector size"); 10541 Str = End; 10542 10543 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 10544 RequiresICE, false); 10545 assert(!RequiresICE && "Can't require vector ICE"); 10546 10547 // TODO: No way to make AltiVec vectors in builtins yet. 10548 Type = Context.getVectorType(ElementType, NumElements, 10549 VectorType::GenericVector); 10550 break; 10551 } 10552 case 'E': { 10553 char *End; 10554 10555 unsigned NumElements = strtoul(Str, &End, 10); 10556 assert(End != Str && "Missing vector size"); 10557 10558 Str = End; 10559 10560 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10561 false); 10562 Type = Context.getExtVectorType(ElementType, NumElements); 10563 break; 10564 } 10565 case 'X': { 10566 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 10567 false); 10568 assert(!RequiresICE && "Can't require complex ICE"); 10569 Type = Context.getComplexType(ElementType); 10570 break; 10571 } 10572 case 'Y': 10573 Type = Context.getPointerDiffType(); 10574 break; 10575 case 'P': 10576 Type = Context.getFILEType(); 10577 if (Type.isNull()) { 10578 Error = ASTContext::GE_Missing_stdio; 10579 return {}; 10580 } 10581 break; 10582 case 'J': 10583 if (Signed) 10584 Type = Context.getsigjmp_bufType(); 10585 else 10586 Type = Context.getjmp_bufType(); 10587 10588 if (Type.isNull()) { 10589 Error = ASTContext::GE_Missing_setjmp; 10590 return {}; 10591 } 10592 break; 10593 case 'K': 10594 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 10595 Type = Context.getucontext_tType(); 10596 10597 if (Type.isNull()) { 10598 Error = ASTContext::GE_Missing_ucontext; 10599 return {}; 10600 } 10601 break; 10602 case 'p': 10603 Type = Context.getProcessIDType(); 10604 break; 10605 } 10606 10607 // If there are modifiers and if we're allowed to parse them, go for it. 10608 Done = !AllowTypeModifiers; 10609 while (!Done) { 10610 switch (char c = *Str++) { 10611 default: Done = true; --Str; break; 10612 case '*': 10613 case '&': { 10614 // Both pointers and references can have their pointee types 10615 // qualified with an address space. 10616 char *End; 10617 unsigned AddrSpace = strtoul(Str, &End, 10); 10618 if (End != Str) { 10619 // Note AddrSpace == 0 is not the same as an unspecified address space. 10620 Type = Context.getAddrSpaceQualType( 10621 Type, 10622 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 10623 Str = End; 10624 } 10625 if (c == '*') 10626 Type = Context.getPointerType(Type); 10627 else 10628 Type = Context.getLValueReferenceType(Type); 10629 break; 10630 } 10631 // FIXME: There's no way to have a built-in with an rvalue ref arg. 10632 case 'C': 10633 Type = Type.withConst(); 10634 break; 10635 case 'D': 10636 Type = Context.getVolatileType(Type); 10637 break; 10638 case 'R': 10639 Type = Type.withRestrict(); 10640 break; 10641 } 10642 } 10643 10644 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 10645 "Integer constant 'I' type must be an integer"); 10646 10647 return Type; 10648 } 10649 10650 // On some targets such as PowerPC, some of the builtins are defined with custom 10651 // type decriptors for target-dependent types. These descriptors are decoded in 10652 // other functions, but it may be useful to be able to fall back to default 10653 // descriptor decoding to define builtins mixing target-dependent and target- 10654 // independent types. This function allows decoding one type descriptor with 10655 // default decoding. 10656 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, 10657 GetBuiltinTypeError &Error, bool &RequireICE, 10658 bool AllowTypeModifiers) const { 10659 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); 10660 } 10661 10662 /// GetBuiltinType - Return the type for the specified builtin. 10663 QualType ASTContext::GetBuiltinType(unsigned Id, 10664 GetBuiltinTypeError &Error, 10665 unsigned *IntegerConstantArgs) const { 10666 const char *TypeStr = BuiltinInfo.getTypeString(Id); 10667 if (TypeStr[0] == '\0') { 10668 Error = GE_Missing_type; 10669 return {}; 10670 } 10671 10672 SmallVector<QualType, 8> ArgTypes; 10673 10674 bool RequiresICE = false; 10675 Error = GE_None; 10676 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 10677 RequiresICE, true); 10678 if (Error != GE_None) 10679 return {}; 10680 10681 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 10682 10683 while (TypeStr[0] && TypeStr[0] != '.') { 10684 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 10685 if (Error != GE_None) 10686 return {}; 10687 10688 // If this argument is required to be an IntegerConstantExpression and the 10689 // caller cares, fill in the bitmask we return. 10690 if (RequiresICE && IntegerConstantArgs) 10691 *IntegerConstantArgs |= 1 << ArgTypes.size(); 10692 10693 // Do array -> pointer decay. The builtin should use the decayed type. 10694 if (Ty->isArrayType()) 10695 Ty = getArrayDecayedType(Ty); 10696 10697 ArgTypes.push_back(Ty); 10698 } 10699 10700 if (Id == Builtin::BI__GetExceptionInfo) 10701 return {}; 10702 10703 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 10704 "'.' should only occur at end of builtin type list!"); 10705 10706 bool Variadic = (TypeStr[0] == '.'); 10707 10708 FunctionType::ExtInfo EI(getDefaultCallingConvention( 10709 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 10710 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 10711 10712 10713 // We really shouldn't be making a no-proto type here. 10714 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 10715 return getFunctionNoProtoType(ResType, EI); 10716 10717 FunctionProtoType::ExtProtoInfo EPI; 10718 EPI.ExtInfo = EI; 10719 EPI.Variadic = Variadic; 10720 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 10721 EPI.ExceptionSpec.Type = 10722 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 10723 10724 return getFunctionType(ResType, ArgTypes, EPI); 10725 } 10726 10727 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 10728 const FunctionDecl *FD) { 10729 if (!FD->isExternallyVisible()) 10730 return GVA_Internal; 10731 10732 // Non-user-provided functions get emitted as weak definitions with every 10733 // use, no matter whether they've been explicitly instantiated etc. 10734 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 10735 if (!MD->isUserProvided()) 10736 return GVA_DiscardableODR; 10737 10738 GVALinkage External; 10739 switch (FD->getTemplateSpecializationKind()) { 10740 case TSK_Undeclared: 10741 case TSK_ExplicitSpecialization: 10742 External = GVA_StrongExternal; 10743 break; 10744 10745 case TSK_ExplicitInstantiationDefinition: 10746 return GVA_StrongODR; 10747 10748 // C++11 [temp.explicit]p10: 10749 // [ Note: The intent is that an inline function that is the subject of 10750 // an explicit instantiation declaration will still be implicitly 10751 // instantiated when used so that the body can be considered for 10752 // inlining, but that no out-of-line copy of the inline function would be 10753 // generated in the translation unit. -- end note ] 10754 case TSK_ExplicitInstantiationDeclaration: 10755 return GVA_AvailableExternally; 10756 10757 case TSK_ImplicitInstantiation: 10758 External = GVA_DiscardableODR; 10759 break; 10760 } 10761 10762 if (!FD->isInlined()) 10763 return External; 10764 10765 if ((!Context.getLangOpts().CPlusPlus && 10766 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 10767 !FD->hasAttr<DLLExportAttr>()) || 10768 FD->hasAttr<GNUInlineAttr>()) { 10769 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 10770 10771 // GNU or C99 inline semantics. Determine whether this symbol should be 10772 // externally visible. 10773 if (FD->isInlineDefinitionExternallyVisible()) 10774 return External; 10775 10776 // C99 inline semantics, where the symbol is not externally visible. 10777 return GVA_AvailableExternally; 10778 } 10779 10780 // Functions specified with extern and inline in -fms-compatibility mode 10781 // forcibly get emitted. While the body of the function cannot be later 10782 // replaced, the function definition cannot be discarded. 10783 if (FD->isMSExternInline()) 10784 return GVA_StrongODR; 10785 10786 return GVA_DiscardableODR; 10787 } 10788 10789 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 10790 const Decl *D, GVALinkage L) { 10791 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 10792 // dllexport/dllimport on inline functions. 10793 if (D->hasAttr<DLLImportAttr>()) { 10794 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 10795 return GVA_AvailableExternally; 10796 } else if (D->hasAttr<DLLExportAttr>()) { 10797 if (L == GVA_DiscardableODR) 10798 return GVA_StrongODR; 10799 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) { 10800 // Device-side functions with __global__ attribute must always be 10801 // visible externally so they can be launched from host. 10802 if (D->hasAttr<CUDAGlobalAttr>() && 10803 (L == GVA_DiscardableODR || L == GVA_Internal)) 10804 return GVA_StrongODR; 10805 // Single source offloading languages like CUDA/HIP need to be able to 10806 // access static device variables from host code of the same compilation 10807 // unit. This is done by externalizing the static variable with a shared 10808 // name between the host and device compilation which is the same for the 10809 // same compilation unit whereas different among different compilation 10810 // units. 10811 if (Context.shouldExternalizeStaticVar(D)) 10812 return GVA_StrongExternal; 10813 } 10814 return L; 10815 } 10816 10817 /// Adjust the GVALinkage for a declaration based on what an external AST source 10818 /// knows about whether there can be other definitions of this declaration. 10819 static GVALinkage 10820 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 10821 GVALinkage L) { 10822 ExternalASTSource *Source = Ctx.getExternalSource(); 10823 if (!Source) 10824 return L; 10825 10826 switch (Source->hasExternalDefinitions(D)) { 10827 case ExternalASTSource::EK_Never: 10828 // Other translation units rely on us to provide the definition. 10829 if (L == GVA_DiscardableODR) 10830 return GVA_StrongODR; 10831 break; 10832 10833 case ExternalASTSource::EK_Always: 10834 return GVA_AvailableExternally; 10835 10836 case ExternalASTSource::EK_ReplyHazy: 10837 break; 10838 } 10839 return L; 10840 } 10841 10842 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 10843 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 10844 adjustGVALinkageForAttributes(*this, FD, 10845 basicGVALinkageForFunction(*this, FD))); 10846 } 10847 10848 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 10849 const VarDecl *VD) { 10850 if (!VD->isExternallyVisible()) 10851 return GVA_Internal; 10852 10853 if (VD->isStaticLocal()) { 10854 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 10855 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 10856 LexicalContext = LexicalContext->getLexicalParent(); 10857 10858 // ObjC Blocks can create local variables that don't have a FunctionDecl 10859 // LexicalContext. 10860 if (!LexicalContext) 10861 return GVA_DiscardableODR; 10862 10863 // Otherwise, let the static local variable inherit its linkage from the 10864 // nearest enclosing function. 10865 auto StaticLocalLinkage = 10866 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 10867 10868 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 10869 // be emitted in any object with references to the symbol for the object it 10870 // contains, whether inline or out-of-line." 10871 // Similar behavior is observed with MSVC. An alternative ABI could use 10872 // StrongODR/AvailableExternally to match the function, but none are 10873 // known/supported currently. 10874 if (StaticLocalLinkage == GVA_StrongODR || 10875 StaticLocalLinkage == GVA_AvailableExternally) 10876 return GVA_DiscardableODR; 10877 return StaticLocalLinkage; 10878 } 10879 10880 // MSVC treats in-class initialized static data members as definitions. 10881 // By giving them non-strong linkage, out-of-line definitions won't 10882 // cause link errors. 10883 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 10884 return GVA_DiscardableODR; 10885 10886 // Most non-template variables have strong linkage; inline variables are 10887 // linkonce_odr or (occasionally, for compatibility) weak_odr. 10888 GVALinkage StrongLinkage; 10889 switch (Context.getInlineVariableDefinitionKind(VD)) { 10890 case ASTContext::InlineVariableDefinitionKind::None: 10891 StrongLinkage = GVA_StrongExternal; 10892 break; 10893 case ASTContext::InlineVariableDefinitionKind::Weak: 10894 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 10895 StrongLinkage = GVA_DiscardableODR; 10896 break; 10897 case ASTContext::InlineVariableDefinitionKind::Strong: 10898 StrongLinkage = GVA_StrongODR; 10899 break; 10900 } 10901 10902 switch (VD->getTemplateSpecializationKind()) { 10903 case TSK_Undeclared: 10904 return StrongLinkage; 10905 10906 case TSK_ExplicitSpecialization: 10907 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 10908 VD->isStaticDataMember() 10909 ? GVA_StrongODR 10910 : StrongLinkage; 10911 10912 case TSK_ExplicitInstantiationDefinition: 10913 return GVA_StrongODR; 10914 10915 case TSK_ExplicitInstantiationDeclaration: 10916 return GVA_AvailableExternally; 10917 10918 case TSK_ImplicitInstantiation: 10919 return GVA_DiscardableODR; 10920 } 10921 10922 llvm_unreachable("Invalid Linkage!"); 10923 } 10924 10925 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 10926 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 10927 adjustGVALinkageForAttributes(*this, VD, 10928 basicGVALinkageForVariable(*this, VD))); 10929 } 10930 10931 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 10932 if (const auto *VD = dyn_cast<VarDecl>(D)) { 10933 if (!VD->isFileVarDecl()) 10934 return false; 10935 // Global named register variables (GNU extension) are never emitted. 10936 if (VD->getStorageClass() == SC_Register) 10937 return false; 10938 if (VD->getDescribedVarTemplate() || 10939 isa<VarTemplatePartialSpecializationDecl>(VD)) 10940 return false; 10941 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10942 // We never need to emit an uninstantiated function template. 10943 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10944 return false; 10945 } else if (isa<PragmaCommentDecl>(D)) 10946 return true; 10947 else if (isa<PragmaDetectMismatchDecl>(D)) 10948 return true; 10949 else if (isa<OMPRequiresDecl>(D)) 10950 return true; 10951 else if (isa<OMPThreadPrivateDecl>(D)) 10952 return !D->getDeclContext()->isDependentContext(); 10953 else if (isa<OMPAllocateDecl>(D)) 10954 return !D->getDeclContext()->isDependentContext(); 10955 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) 10956 return !D->getDeclContext()->isDependentContext(); 10957 else if (isa<ImportDecl>(D)) 10958 return true; 10959 else 10960 return false; 10961 10962 // If this is a member of a class template, we do not need to emit it. 10963 if (D->getDeclContext()->isDependentContext()) 10964 return false; 10965 10966 // Weak references don't produce any output by themselves. 10967 if (D->hasAttr<WeakRefAttr>()) 10968 return false; 10969 10970 // Aliases and used decls are required. 10971 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 10972 return true; 10973 10974 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 10975 // Forward declarations aren't required. 10976 if (!FD->doesThisDeclarationHaveABody()) 10977 return FD->doesDeclarationForceExternallyVisibleDefinition(); 10978 10979 // Constructors and destructors are required. 10980 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 10981 return true; 10982 10983 // The key function for a class is required. This rule only comes 10984 // into play when inline functions can be key functions, though. 10985 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10986 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10987 const CXXRecordDecl *RD = MD->getParent(); 10988 if (MD->isOutOfLine() && RD->isDynamicClass()) { 10989 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 10990 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 10991 return true; 10992 } 10993 } 10994 } 10995 10996 GVALinkage Linkage = GetGVALinkageForFunction(FD); 10997 10998 // static, static inline, always_inline, and extern inline functions can 10999 // always be deferred. Normal inline functions can be deferred in C99/C++. 11000 // Implicit template instantiations can also be deferred in C++. 11001 return !isDiscardableGVALinkage(Linkage); 11002 } 11003 11004 const auto *VD = cast<VarDecl>(D); 11005 assert(VD->isFileVarDecl() && "Expected file scoped var"); 11006 11007 // If the decl is marked as `declare target to`, it should be emitted for the 11008 // host and for the device. 11009 if (LangOpts.OpenMP && 11010 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 11011 return true; 11012 11013 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 11014 !isMSStaticDataMemberInlineDefinition(VD)) 11015 return false; 11016 11017 // Variables that can be needed in other TUs are required. 11018 auto Linkage = GetGVALinkageForVariable(VD); 11019 if (!isDiscardableGVALinkage(Linkage)) 11020 return true; 11021 11022 // We never need to emit a variable that is available in another TU. 11023 if (Linkage == GVA_AvailableExternally) 11024 return false; 11025 11026 // Variables that have destruction with side-effects are required. 11027 if (VD->needsDestruction(*this)) 11028 return true; 11029 11030 // Variables that have initialization with side-effects are required. 11031 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 11032 // We can get a value-dependent initializer during error recovery. 11033 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 11034 return true; 11035 11036 // Likewise, variables with tuple-like bindings are required if their 11037 // bindings have side-effects. 11038 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 11039 for (const auto *BD : DD->bindings()) 11040 if (const auto *BindingVD = BD->getHoldingVar()) 11041 if (DeclMustBeEmitted(BindingVD)) 11042 return true; 11043 11044 return false; 11045 } 11046 11047 void ASTContext::forEachMultiversionedFunctionVersion( 11048 const FunctionDecl *FD, 11049 llvm::function_ref<void(FunctionDecl *)> Pred) const { 11050 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 11051 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 11052 FD = FD->getMostRecentDecl(); 11053 // FIXME: The order of traversal here matters and depends on the order of 11054 // lookup results, which happens to be (mostly) oldest-to-newest, but we 11055 // shouldn't rely on that. 11056 for (auto *CurDecl : 11057 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 11058 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); 11059 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 11060 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 11061 SeenDecls.insert(CurFD); 11062 Pred(CurFD); 11063 } 11064 } 11065 } 11066 11067 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 11068 bool IsCXXMethod, 11069 bool IsBuiltin) const { 11070 // Pass through to the C++ ABI object 11071 if (IsCXXMethod) 11072 return ABI->getDefaultMethodCallConv(IsVariadic); 11073 11074 // Builtins ignore user-specified default calling convention and remain the 11075 // Target's default calling convention. 11076 if (!IsBuiltin) { 11077 switch (LangOpts.getDefaultCallingConv()) { 11078 case LangOptions::DCC_None: 11079 break; 11080 case LangOptions::DCC_CDecl: 11081 return CC_C; 11082 case LangOptions::DCC_FastCall: 11083 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 11084 return CC_X86FastCall; 11085 break; 11086 case LangOptions::DCC_StdCall: 11087 if (!IsVariadic) 11088 return CC_X86StdCall; 11089 break; 11090 case LangOptions::DCC_VectorCall: 11091 // __vectorcall cannot be applied to variadic functions. 11092 if (!IsVariadic) 11093 return CC_X86VectorCall; 11094 break; 11095 case LangOptions::DCC_RegCall: 11096 // __regcall cannot be applied to variadic functions. 11097 if (!IsVariadic) 11098 return CC_X86RegCall; 11099 break; 11100 } 11101 } 11102 return Target->getDefaultCallingConv(); 11103 } 11104 11105 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 11106 // Pass through to the C++ ABI object 11107 return ABI->isNearlyEmpty(RD); 11108 } 11109 11110 VTableContextBase *ASTContext::getVTableContext() { 11111 if (!VTContext.get()) { 11112 auto ABI = Target->getCXXABI(); 11113 if (ABI.isMicrosoft()) 11114 VTContext.reset(new MicrosoftVTableContext(*this)); 11115 else { 11116 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables 11117 ? ItaniumVTableContext::Relative 11118 : ItaniumVTableContext::Pointer; 11119 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout)); 11120 } 11121 } 11122 return VTContext.get(); 11123 } 11124 11125 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { 11126 if (!T) 11127 T = Target; 11128 switch (T->getCXXABI().getKind()) { 11129 case TargetCXXABI::AppleARM64: 11130 case TargetCXXABI::Fuchsia: 11131 case TargetCXXABI::GenericAArch64: 11132 case TargetCXXABI::GenericItanium: 11133 case TargetCXXABI::GenericARM: 11134 case TargetCXXABI::GenericMIPS: 11135 case TargetCXXABI::iOS: 11136 case TargetCXXABI::WebAssembly: 11137 case TargetCXXABI::WatchOS: 11138 case TargetCXXABI::XL: 11139 return ItaniumMangleContext::create(*this, getDiagnostics()); 11140 case TargetCXXABI::Microsoft: 11141 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11142 } 11143 llvm_unreachable("Unsupported ABI"); 11144 } 11145 11146 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { 11147 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && 11148 "Device mangle context does not support Microsoft mangling."); 11149 switch (T.getCXXABI().getKind()) { 11150 case TargetCXXABI::AppleARM64: 11151 case TargetCXXABI::Fuchsia: 11152 case TargetCXXABI::GenericAArch64: 11153 case TargetCXXABI::GenericItanium: 11154 case TargetCXXABI::GenericARM: 11155 case TargetCXXABI::GenericMIPS: 11156 case TargetCXXABI::iOS: 11157 case TargetCXXABI::WebAssembly: 11158 case TargetCXXABI::WatchOS: 11159 case TargetCXXABI::XL: 11160 return ItaniumMangleContext::create( 11161 *this, getDiagnostics(), 11162 [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> { 11163 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11164 return RD->getDeviceLambdaManglingNumber(); 11165 return llvm::None; 11166 }); 11167 case TargetCXXABI::Microsoft: 11168 return MicrosoftMangleContext::create(*this, getDiagnostics()); 11169 } 11170 llvm_unreachable("Unsupported ABI"); 11171 } 11172 11173 CXXABI::~CXXABI() = default; 11174 11175 size_t ASTContext::getSideTableAllocatedMemory() const { 11176 return ASTRecordLayouts.getMemorySize() + 11177 llvm::capacity_in_bytes(ObjCLayouts) + 11178 llvm::capacity_in_bytes(KeyFunctions) + 11179 llvm::capacity_in_bytes(ObjCImpls) + 11180 llvm::capacity_in_bytes(BlockVarCopyInits) + 11181 llvm::capacity_in_bytes(DeclAttrs) + 11182 llvm::capacity_in_bytes(TemplateOrInstantiation) + 11183 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 11184 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 11185 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 11186 llvm::capacity_in_bytes(OverriddenMethods) + 11187 llvm::capacity_in_bytes(Types) + 11188 llvm::capacity_in_bytes(VariableArrayTypes); 11189 } 11190 11191 /// getIntTypeForBitwidth - 11192 /// sets integer QualTy according to specified details: 11193 /// bitwidth, signed/unsigned. 11194 /// Returns empty type if there is no appropriate target types. 11195 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 11196 unsigned Signed) const { 11197 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 11198 CanQualType QualTy = getFromTargetType(Ty); 11199 if (!QualTy && DestWidth == 128) 11200 return Signed ? Int128Ty : UnsignedInt128Ty; 11201 return QualTy; 11202 } 11203 11204 /// getRealTypeForBitwidth - 11205 /// sets floating point QualTy according to specified bitwidth. 11206 /// Returns empty type if there is no appropriate target types. 11207 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth, 11208 bool ExplicitIEEE) const { 11209 TargetInfo::RealType Ty = 11210 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE); 11211 switch (Ty) { 11212 case TargetInfo::Float: 11213 return FloatTy; 11214 case TargetInfo::Double: 11215 return DoubleTy; 11216 case TargetInfo::LongDouble: 11217 return LongDoubleTy; 11218 case TargetInfo::Float128: 11219 return Float128Ty; 11220 case TargetInfo::NoFloat: 11221 return {}; 11222 } 11223 11224 llvm_unreachable("Unhandled TargetInfo::RealType value"); 11225 } 11226 11227 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 11228 if (Number > 1) 11229 MangleNumbers[ND] = Number; 11230 } 11231 11232 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 11233 auto I = MangleNumbers.find(ND); 11234 return I != MangleNumbers.end() ? I->second : 1; 11235 } 11236 11237 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 11238 if (Number > 1) 11239 StaticLocalNumbers[VD] = Number; 11240 } 11241 11242 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 11243 auto I = StaticLocalNumbers.find(VD); 11244 return I != StaticLocalNumbers.end() ? I->second : 1; 11245 } 11246 11247 MangleNumberingContext & 11248 ASTContext::getManglingNumberContext(const DeclContext *DC) { 11249 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11250 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 11251 if (!MCtx) 11252 MCtx = createMangleNumberingContext(); 11253 return *MCtx; 11254 } 11255 11256 MangleNumberingContext & 11257 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { 11258 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 11259 std::unique_ptr<MangleNumberingContext> &MCtx = 11260 ExtraMangleNumberingContexts[D]; 11261 if (!MCtx) 11262 MCtx = createMangleNumberingContext(); 11263 return *MCtx; 11264 } 11265 11266 std::unique_ptr<MangleNumberingContext> 11267 ASTContext::createMangleNumberingContext() const { 11268 return ABI->createMangleNumberingContext(); 11269 } 11270 11271 const CXXConstructorDecl * 11272 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 11273 return ABI->getCopyConstructorForExceptionObject( 11274 cast<CXXRecordDecl>(RD->getFirstDecl())); 11275 } 11276 11277 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 11278 CXXConstructorDecl *CD) { 11279 return ABI->addCopyConstructorForExceptionObject( 11280 cast<CXXRecordDecl>(RD->getFirstDecl()), 11281 cast<CXXConstructorDecl>(CD->getFirstDecl())); 11282 } 11283 11284 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 11285 TypedefNameDecl *DD) { 11286 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 11287 } 11288 11289 TypedefNameDecl * 11290 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 11291 return ABI->getTypedefNameForUnnamedTagDecl(TD); 11292 } 11293 11294 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 11295 DeclaratorDecl *DD) { 11296 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 11297 } 11298 11299 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 11300 return ABI->getDeclaratorForUnnamedTagDecl(TD); 11301 } 11302 11303 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 11304 ParamIndices[D] = index; 11305 } 11306 11307 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 11308 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 11309 assert(I != ParamIndices.end() && 11310 "ParmIndices lacks entry set by ParmVarDecl"); 11311 return I->second; 11312 } 11313 11314 QualType ASTContext::getStringLiteralArrayType(QualType EltTy, 11315 unsigned Length) const { 11316 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 11317 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 11318 EltTy = EltTy.withConst(); 11319 11320 EltTy = adjustStringLiteralBaseType(EltTy); 11321 11322 // Get an array type for the string, according to C99 6.4.5. This includes 11323 // the null terminator character. 11324 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, 11325 ArrayType::Normal, /*IndexTypeQuals*/ 0); 11326 } 11327 11328 StringLiteral * 11329 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { 11330 StringLiteral *&Result = StringLiteralCache[Key]; 11331 if (!Result) 11332 Result = StringLiteral::Create( 11333 *this, Key, StringLiteral::Ascii, 11334 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), 11335 SourceLocation()); 11336 return Result; 11337 } 11338 11339 MSGuidDecl * 11340 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { 11341 assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); 11342 11343 llvm::FoldingSetNodeID ID; 11344 MSGuidDecl::Profile(ID, Parts); 11345 11346 void *InsertPos; 11347 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos)) 11348 return Existing; 11349 11350 QualType GUIDType = getMSGuidType().withConst(); 11351 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts); 11352 MSGuidDecls.InsertNode(New, InsertPos); 11353 return New; 11354 } 11355 11356 TemplateParamObjectDecl * 11357 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { 11358 assert(T->isRecordType() && "template param object of unexpected type"); 11359 11360 // C++ [temp.param]p8: 11361 // [...] a static storage duration object of type 'const T' [...] 11362 T.addConst(); 11363 11364 llvm::FoldingSetNodeID ID; 11365 TemplateParamObjectDecl::Profile(ID, T, V); 11366 11367 void *InsertPos; 11368 if (TemplateParamObjectDecl *Existing = 11369 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos)) 11370 return Existing; 11371 11372 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V); 11373 TemplateParamObjectDecls.InsertNode(New, InsertPos); 11374 return New; 11375 } 11376 11377 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 11378 const llvm::Triple &T = getTargetInfo().getTriple(); 11379 if (!T.isOSDarwin()) 11380 return false; 11381 11382 if (!(T.isiOS() && T.isOSVersionLT(7)) && 11383 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 11384 return false; 11385 11386 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 11387 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 11388 uint64_t Size = sizeChars.getQuantity(); 11389 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 11390 unsigned Align = alignChars.getQuantity(); 11391 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 11392 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 11393 } 11394 11395 bool 11396 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 11397 const ObjCMethodDecl *MethodImpl) { 11398 // No point trying to match an unavailable/deprecated mothod. 11399 if (MethodDecl->hasAttr<UnavailableAttr>() 11400 || MethodDecl->hasAttr<DeprecatedAttr>()) 11401 return false; 11402 if (MethodDecl->getObjCDeclQualifier() != 11403 MethodImpl->getObjCDeclQualifier()) 11404 return false; 11405 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 11406 return false; 11407 11408 if (MethodDecl->param_size() != MethodImpl->param_size()) 11409 return false; 11410 11411 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 11412 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 11413 EF = MethodDecl->param_end(); 11414 IM != EM && IF != EF; ++IM, ++IF) { 11415 const ParmVarDecl *DeclVar = (*IF); 11416 const ParmVarDecl *ImplVar = (*IM); 11417 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 11418 return false; 11419 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 11420 return false; 11421 } 11422 11423 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 11424 } 11425 11426 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 11427 LangAS AS; 11428 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 11429 AS = LangAS::Default; 11430 else 11431 AS = QT->getPointeeType().getAddressSpace(); 11432 11433 return getTargetInfo().getNullPointerValue(AS); 11434 } 11435 11436 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 11437 if (isTargetAddressSpace(AS)) 11438 return toTargetAddressSpace(AS); 11439 else 11440 return (*AddrSpaceMap)[(unsigned)AS]; 11441 } 11442 11443 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 11444 assert(Ty->isFixedPointType()); 11445 11446 if (Ty->isSaturatedFixedPointType()) return Ty; 11447 11448 switch (Ty->castAs<BuiltinType>()->getKind()) { 11449 default: 11450 llvm_unreachable("Not a fixed point type!"); 11451 case BuiltinType::ShortAccum: 11452 return SatShortAccumTy; 11453 case BuiltinType::Accum: 11454 return SatAccumTy; 11455 case BuiltinType::LongAccum: 11456 return SatLongAccumTy; 11457 case BuiltinType::UShortAccum: 11458 return SatUnsignedShortAccumTy; 11459 case BuiltinType::UAccum: 11460 return SatUnsignedAccumTy; 11461 case BuiltinType::ULongAccum: 11462 return SatUnsignedLongAccumTy; 11463 case BuiltinType::ShortFract: 11464 return SatShortFractTy; 11465 case BuiltinType::Fract: 11466 return SatFractTy; 11467 case BuiltinType::LongFract: 11468 return SatLongFractTy; 11469 case BuiltinType::UShortFract: 11470 return SatUnsignedShortFractTy; 11471 case BuiltinType::UFract: 11472 return SatUnsignedFractTy; 11473 case BuiltinType::ULongFract: 11474 return SatUnsignedLongFractTy; 11475 } 11476 } 11477 11478 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 11479 if (LangOpts.OpenCL) 11480 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 11481 11482 if (LangOpts.CUDA) 11483 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 11484 11485 return getLangASFromTargetAS(AS); 11486 } 11487 11488 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 11489 // doesn't include ASTContext.h 11490 template 11491 clang::LazyGenerationalUpdatePtr< 11492 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 11493 clang::LazyGenerationalUpdatePtr< 11494 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 11495 const clang::ASTContext &Ctx, Decl *Value); 11496 11497 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 11498 assert(Ty->isFixedPointType()); 11499 11500 const TargetInfo &Target = getTargetInfo(); 11501 switch (Ty->castAs<BuiltinType>()->getKind()) { 11502 default: 11503 llvm_unreachable("Not a fixed point type!"); 11504 case BuiltinType::ShortAccum: 11505 case BuiltinType::SatShortAccum: 11506 return Target.getShortAccumScale(); 11507 case BuiltinType::Accum: 11508 case BuiltinType::SatAccum: 11509 return Target.getAccumScale(); 11510 case BuiltinType::LongAccum: 11511 case BuiltinType::SatLongAccum: 11512 return Target.getLongAccumScale(); 11513 case BuiltinType::UShortAccum: 11514 case BuiltinType::SatUShortAccum: 11515 return Target.getUnsignedShortAccumScale(); 11516 case BuiltinType::UAccum: 11517 case BuiltinType::SatUAccum: 11518 return Target.getUnsignedAccumScale(); 11519 case BuiltinType::ULongAccum: 11520 case BuiltinType::SatULongAccum: 11521 return Target.getUnsignedLongAccumScale(); 11522 case BuiltinType::ShortFract: 11523 case BuiltinType::SatShortFract: 11524 return Target.getShortFractScale(); 11525 case BuiltinType::Fract: 11526 case BuiltinType::SatFract: 11527 return Target.getFractScale(); 11528 case BuiltinType::LongFract: 11529 case BuiltinType::SatLongFract: 11530 return Target.getLongFractScale(); 11531 case BuiltinType::UShortFract: 11532 case BuiltinType::SatUShortFract: 11533 return Target.getUnsignedShortFractScale(); 11534 case BuiltinType::UFract: 11535 case BuiltinType::SatUFract: 11536 return Target.getUnsignedFractScale(); 11537 case BuiltinType::ULongFract: 11538 case BuiltinType::SatULongFract: 11539 return Target.getUnsignedLongFractScale(); 11540 } 11541 } 11542 11543 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 11544 assert(Ty->isFixedPointType()); 11545 11546 const TargetInfo &Target = getTargetInfo(); 11547 switch (Ty->castAs<BuiltinType>()->getKind()) { 11548 default: 11549 llvm_unreachable("Not a fixed point type!"); 11550 case BuiltinType::ShortAccum: 11551 case BuiltinType::SatShortAccum: 11552 return Target.getShortAccumIBits(); 11553 case BuiltinType::Accum: 11554 case BuiltinType::SatAccum: 11555 return Target.getAccumIBits(); 11556 case BuiltinType::LongAccum: 11557 case BuiltinType::SatLongAccum: 11558 return Target.getLongAccumIBits(); 11559 case BuiltinType::UShortAccum: 11560 case BuiltinType::SatUShortAccum: 11561 return Target.getUnsignedShortAccumIBits(); 11562 case BuiltinType::UAccum: 11563 case BuiltinType::SatUAccum: 11564 return Target.getUnsignedAccumIBits(); 11565 case BuiltinType::ULongAccum: 11566 case BuiltinType::SatULongAccum: 11567 return Target.getUnsignedLongAccumIBits(); 11568 case BuiltinType::ShortFract: 11569 case BuiltinType::SatShortFract: 11570 case BuiltinType::Fract: 11571 case BuiltinType::SatFract: 11572 case BuiltinType::LongFract: 11573 case BuiltinType::SatLongFract: 11574 case BuiltinType::UShortFract: 11575 case BuiltinType::SatUShortFract: 11576 case BuiltinType::UFract: 11577 case BuiltinType::SatUFract: 11578 case BuiltinType::ULongFract: 11579 case BuiltinType::SatULongFract: 11580 return 0; 11581 } 11582 } 11583 11584 llvm::FixedPointSemantics 11585 ASTContext::getFixedPointSemantics(QualType Ty) const { 11586 assert((Ty->isFixedPointType() || Ty->isIntegerType()) && 11587 "Can only get the fixed point semantics for a " 11588 "fixed point or integer type."); 11589 if (Ty->isIntegerType()) 11590 return llvm::FixedPointSemantics::GetIntegerSemantics( 11591 getIntWidth(Ty), Ty->isSignedIntegerType()); 11592 11593 bool isSigned = Ty->isSignedFixedPointType(); 11594 return llvm::FixedPointSemantics( 11595 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 11596 Ty->isSaturatedFixedPointType(), 11597 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 11598 } 11599 11600 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 11601 assert(Ty->isFixedPointType()); 11602 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty)); 11603 } 11604 11605 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 11606 assert(Ty->isFixedPointType()); 11607 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty)); 11608 } 11609 11610 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { 11611 assert(Ty->isUnsignedFixedPointType() && 11612 "Expected unsigned fixed point type"); 11613 11614 switch (Ty->castAs<BuiltinType>()->getKind()) { 11615 case BuiltinType::UShortAccum: 11616 return ShortAccumTy; 11617 case BuiltinType::UAccum: 11618 return AccumTy; 11619 case BuiltinType::ULongAccum: 11620 return LongAccumTy; 11621 case BuiltinType::SatUShortAccum: 11622 return SatShortAccumTy; 11623 case BuiltinType::SatUAccum: 11624 return SatAccumTy; 11625 case BuiltinType::SatULongAccum: 11626 return SatLongAccumTy; 11627 case BuiltinType::UShortFract: 11628 return ShortFractTy; 11629 case BuiltinType::UFract: 11630 return FractTy; 11631 case BuiltinType::ULongFract: 11632 return LongFractTy; 11633 case BuiltinType::SatUShortFract: 11634 return SatShortFractTy; 11635 case BuiltinType::SatUFract: 11636 return SatFractTy; 11637 case BuiltinType::SatULongFract: 11638 return SatLongFractTy; 11639 default: 11640 llvm_unreachable("Unexpected unsigned fixed point type"); 11641 } 11642 } 11643 11644 ParsedTargetAttr 11645 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { 11646 assert(TD != nullptr); 11647 ParsedTargetAttr ParsedAttr = TD->parse(); 11648 11649 ParsedAttr.Features.erase( 11650 llvm::remove_if(ParsedAttr.Features, 11651 [&](const std::string &Feat) { 11652 return !Target->isValidFeatureName( 11653 StringRef{Feat}.substr(1)); 11654 }), 11655 ParsedAttr.Features.end()); 11656 return ParsedAttr; 11657 } 11658 11659 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11660 const FunctionDecl *FD) const { 11661 if (FD) 11662 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); 11663 else 11664 Target->initFeatureMap(FeatureMap, getDiagnostics(), 11665 Target->getTargetOpts().CPU, 11666 Target->getTargetOpts().Features); 11667 } 11668 11669 // Fills in the supplied string map with the set of target features for the 11670 // passed in function. 11671 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 11672 GlobalDecl GD) const { 11673 StringRef TargetCPU = Target->getTargetOpts().CPU; 11674 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 11675 if (const auto *TD = FD->getAttr<TargetAttr>()) { 11676 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 11677 11678 // Make a copy of the features as passed on the command line into the 11679 // beginning of the additional features from the function to override. 11680 ParsedAttr.Features.insert( 11681 ParsedAttr.Features.begin(), 11682 Target->getTargetOpts().FeaturesAsWritten.begin(), 11683 Target->getTargetOpts().FeaturesAsWritten.end()); 11684 11685 if (ParsedAttr.Architecture != "" && 11686 Target->isValidCPUName(ParsedAttr.Architecture)) 11687 TargetCPU = ParsedAttr.Architecture; 11688 11689 // Now populate the feature map, first with the TargetCPU which is either 11690 // the default or a new one from the target attribute string. Then we'll use 11691 // the passed in features (FeaturesAsWritten) along with the new ones from 11692 // the attribute. 11693 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 11694 ParsedAttr.Features); 11695 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 11696 llvm::SmallVector<StringRef, 32> FeaturesTmp; 11697 Target->getCPUSpecificCPUDispatchFeatures( 11698 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 11699 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 11700 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); 11701 } else { 11702 FeatureMap = Target->getTargetOpts().FeatureMap; 11703 } 11704 } 11705 11706 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() { 11707 OMPTraitInfoVector.emplace_back(new OMPTraitInfo()); 11708 return *OMPTraitInfoVector.back(); 11709 } 11710 11711 const StreamingDiagnostic &clang:: 11712 operator<<(const StreamingDiagnostic &DB, 11713 const ASTContext::SectionInfo &Section) { 11714 if (Section.Decl) 11715 return DB << Section.Decl; 11716 return DB << "a prior #pragma section"; 11717 } 11718 11719 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { 11720 bool IsStaticVar = 11721 isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static; 11722 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() && 11723 !D->getAttr<CUDADeviceAttr>()->isImplicit()) || 11724 (D->hasAttr<CUDAConstantAttr>() && 11725 !D->getAttr<CUDAConstantAttr>()->isImplicit()); 11726 // CUDA/HIP: static managed variables need to be externalized since it is 11727 // a declaration in IR, therefore cannot have internal linkage. 11728 return IsStaticVar && 11729 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar); 11730 } 11731 11732 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { 11733 return mayExternalizeStaticVar(D) && 11734 (D->hasAttr<HIPManagedAttr>() || 11735 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D))); 11736 } 11737 11738 StringRef ASTContext::getCUIDHash() const { 11739 if (!CUIDHash.empty()) 11740 return CUIDHash; 11741 if (LangOpts.CUID.empty()) 11742 return StringRef(); 11743 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true); 11744 return CUIDHash; 11745 } 11746 11747 // Get the closest named parent, so we can order the sycl naming decls somewhere 11748 // that mangling is meaningful. 11749 static const DeclContext *GetNamedParent(const CXXRecordDecl *RD) { 11750 const DeclContext *DC = RD->getDeclContext(); 11751 11752 while (!isa<NamedDecl, TranslationUnitDecl>(DC)) 11753 DC = DC->getParent(); 11754 return DC; 11755 } 11756 11757 void ASTContext::AddSYCLKernelNamingDecl(const CXXRecordDecl *RD) { 11758 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11759 RD = RD->getCanonicalDecl(); 11760 const DeclContext *DC = GetNamedParent(RD); 11761 11762 assert(RD->getLocation().isValid() && 11763 "Invalid location on kernel naming decl"); 11764 11765 (void)SYCLKernelNamingTypes[DC].insert(RD); 11766 } 11767 11768 bool ASTContext::IsSYCLKernelNamingDecl(const NamedDecl *ND) const { 11769 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11770 const auto *RD = dyn_cast<CXXRecordDecl>(ND); 11771 if (!RD) 11772 return false; 11773 RD = RD->getCanonicalDecl(); 11774 const DeclContext *DC = GetNamedParent(RD); 11775 11776 auto Itr = SYCLKernelNamingTypes.find(DC); 11777 11778 if (Itr == SYCLKernelNamingTypes.end()) 11779 return false; 11780 11781 return Itr->getSecond().count(RD); 11782 } 11783 11784 // Filters the Decls list to those that share the lambda mangling with the 11785 // passed RD. 11786 void ASTContext::FilterSYCLKernelNamingDecls( 11787 const CXXRecordDecl *RD, 11788 llvm::SmallVectorImpl<const CXXRecordDecl *> &Decls) { 11789 11790 if (!SYCLKernelFilterContext) 11791 SYCLKernelFilterContext.reset( 11792 ItaniumMangleContext::create(*this, getDiagnostics())); 11793 11794 llvm::SmallString<128> LambdaSig; 11795 llvm::raw_svector_ostream Out(LambdaSig); 11796 SYCLKernelFilterContext->mangleLambdaSig(RD, Out); 11797 11798 llvm::erase_if(Decls, [this, &LambdaSig](const CXXRecordDecl *LocalRD) { 11799 llvm::SmallString<128> LocalLambdaSig; 11800 llvm::raw_svector_ostream LocalOut(LocalLambdaSig); 11801 SYCLKernelFilterContext->mangleLambdaSig(LocalRD, LocalOut); 11802 return LambdaSig != LocalLambdaSig; 11803 }); 11804 } 11805 11806 unsigned ASTContext::GetSYCLKernelNamingIndex(const NamedDecl *ND) { 11807 assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); 11808 assert(IsSYCLKernelNamingDecl(ND) && 11809 "Lambda not involved in mangling asked for a naming index?"); 11810 11811 const CXXRecordDecl *RD = cast<CXXRecordDecl>(ND)->getCanonicalDecl(); 11812 const DeclContext *DC = GetNamedParent(RD); 11813 11814 auto Itr = SYCLKernelNamingTypes.find(DC); 11815 assert(Itr != SYCLKernelNamingTypes.end() && "Not a valid DeclContext?"); 11816 11817 const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &Set = Itr->getSecond(); 11818 11819 llvm::SmallVector<const CXXRecordDecl *> Decls{Set.begin(), Set.end()}; 11820 11821 FilterSYCLKernelNamingDecls(RD, Decls); 11822 11823 llvm::sort(Decls, [](const CXXRecordDecl *LHS, const CXXRecordDecl *RHS) { 11824 return LHS->getLambdaManglingNumber() < RHS->getLambdaManglingNumber(); 11825 }); 11826 11827 return llvm::find(Decls, RD) - Decls.begin(); 11828 } 11829