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