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