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