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