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