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