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