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