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