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