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