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