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