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