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