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