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