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