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