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