ASTContext.cpp revision 8d2dbbf9ddfd9d762a341d83f83d840ff68ce03d
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); 1199 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1200 PE = Proto->protocol_end(); P != PE; ++P) { 1201 Protocols.insert(*P); 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); 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); 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->getPreviousDeclaration()) { 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->getPreviousDeclaration() && 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->getPreviousDeclaration() && 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->getPreviousDeclaration()) 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->getPreviousDeclaration()) 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 for (unsigned i = 1; i != NumProtocols; ++i) 2714 if (!CmpProtocolNames(Protocols[i-1], Protocols[i])) 2715 return false; 2716 return true; 2717} 2718 2719static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2720 unsigned &NumProtocols) { 2721 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2722 2723 // Sort protocols, keyed by name. 2724 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2725 2726 // Remove duplicates. 2727 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2728 NumProtocols = ProtocolsEnd-Protocols; 2729} 2730 2731QualType ASTContext::getObjCObjectType(QualType BaseType, 2732 ObjCProtocolDecl * const *Protocols, 2733 unsigned NumProtocols) const { 2734 // If the base type is an interface and there aren't any protocols 2735 // to add, then the interface type will do just fine. 2736 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2737 return BaseType; 2738 2739 // Look in the folding set for an existing type. 2740 llvm::FoldingSetNodeID ID; 2741 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2742 void *InsertPos = 0; 2743 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2744 return QualType(QT, 0); 2745 2746 // Build the canonical type, which has the canonical base type and 2747 // a sorted-and-uniqued list of protocols. 2748 QualType Canonical; 2749 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2750 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2751 if (!ProtocolsSorted) { 2752 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2753 Protocols + NumProtocols); 2754 unsigned UniqueCount = NumProtocols; 2755 2756 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2757 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2758 &Sorted[0], UniqueCount); 2759 } else { 2760 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2761 Protocols, NumProtocols); 2762 } 2763 2764 // Regenerate InsertPos. 2765 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2766 } 2767 2768 unsigned Size = sizeof(ObjCObjectTypeImpl); 2769 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2770 void *Mem = Allocate(Size, TypeAlignment); 2771 ObjCObjectTypeImpl *T = 2772 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2773 2774 Types.push_back(T); 2775 ObjCObjectTypes.InsertNode(T, InsertPos); 2776 return QualType(T, 0); 2777} 2778 2779/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2780/// the given object type. 2781QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 2782 llvm::FoldingSetNodeID ID; 2783 ObjCObjectPointerType::Profile(ID, ObjectT); 2784 2785 void *InsertPos = 0; 2786 if (ObjCObjectPointerType *QT = 2787 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2788 return QualType(QT, 0); 2789 2790 // Find the canonical object type. 2791 QualType Canonical; 2792 if (!ObjectT.isCanonical()) { 2793 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2794 2795 // Regenerate InsertPos. 2796 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2797 } 2798 2799 // No match. 2800 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2801 ObjCObjectPointerType *QType = 2802 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2803 2804 Types.push_back(QType); 2805 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2806 return QualType(QType, 0); 2807} 2808 2809/// getObjCInterfaceType - Return the unique reference to the type for the 2810/// specified ObjC interface decl. The list of protocols is optional. 2811QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 2812 ObjCInterfaceDecl *PrevDecl) const { 2813 if (Decl->TypeForDecl) 2814 return QualType(Decl->TypeForDecl, 0); 2815 2816 if (PrevDecl) { 2817 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 2818 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2819 return QualType(PrevDecl->TypeForDecl, 0); 2820 } 2821 2822 // Prefer the definition, if there is one. 2823 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 2824 Decl = Def; 2825 2826 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2827 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2828 Decl->TypeForDecl = T; 2829 Types.push_back(T); 2830 return QualType(T, 0); 2831} 2832 2833/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2834/// TypeOfExprType AST's (since expression's are never shared). For example, 2835/// multiple declarations that refer to "typeof(x)" all contain different 2836/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2837/// on canonical type's (which are always unique). 2838QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 2839 TypeOfExprType *toe; 2840 if (tofExpr->isTypeDependent()) { 2841 llvm::FoldingSetNodeID ID; 2842 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2843 2844 void *InsertPos = 0; 2845 DependentTypeOfExprType *Canon 2846 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2847 if (Canon) { 2848 // We already have a "canonical" version of an identical, dependent 2849 // typeof(expr) type. Use that as our canonical type. 2850 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 2851 QualType((TypeOfExprType*)Canon, 0)); 2852 } else { 2853 // Build a new, canonical typeof(expr) type. 2854 Canon 2855 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 2856 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 2857 toe = Canon; 2858 } 2859 } else { 2860 QualType Canonical = getCanonicalType(tofExpr->getType()); 2861 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 2862 } 2863 Types.push_back(toe); 2864 return QualType(toe, 0); 2865} 2866 2867/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 2868/// TypeOfType AST's. The only motivation to unique these nodes would be 2869/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 2870/// an issue. This doesn't effect the type checker, since it operates 2871/// on canonical type's (which are always unique). 2872QualType ASTContext::getTypeOfType(QualType tofType) const { 2873 QualType Canonical = getCanonicalType(tofType); 2874 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 2875 Types.push_back(tot); 2876 return QualType(tot, 0); 2877} 2878 2879/// getDecltypeForExpr - Given an expr, will return the decltype for that 2880/// expression, according to the rules in C++0x [dcl.type.simple]p4 2881static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) { 2882 if (e->isTypeDependent()) 2883 return Context.DependentTy; 2884 2885 // If e is an id expression or a class member access, decltype(e) is defined 2886 // as the type of the entity named by e. 2887 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 2888 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 2889 return VD->getType(); 2890 } 2891 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 2892 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2893 return FD->getType(); 2894 } 2895 // If e is a function call or an invocation of an overloaded operator, 2896 // (parentheses around e are ignored), decltype(e) is defined as the 2897 // return type of that function. 2898 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 2899 return CE->getCallReturnType(); 2900 2901 QualType T = e->getType(); 2902 2903 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 2904 // defined as T&, otherwise decltype(e) is defined as T. 2905 if (e->isLValue()) 2906 T = Context.getLValueReferenceType(T); 2907 2908 return T; 2909} 2910 2911/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 2912/// DecltypeType AST's. The only motivation to unique these nodes would be 2913/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 2914/// an issue. This doesn't effect the type checker, since it operates 2915/// on canonical types (which are always unique). 2916QualType ASTContext::getDecltypeType(Expr *e) const { 2917 DecltypeType *dt; 2918 2919 // C++0x [temp.type]p2: 2920 // If an expression e involves a template parameter, decltype(e) denotes a 2921 // unique dependent type. Two such decltype-specifiers refer to the same 2922 // type only if their expressions are equivalent (14.5.6.1). 2923 if (e->isInstantiationDependent()) { 2924 llvm::FoldingSetNodeID ID; 2925 DependentDecltypeType::Profile(ID, *this, e); 2926 2927 void *InsertPos = 0; 2928 DependentDecltypeType *Canon 2929 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 2930 if (Canon) { 2931 // We already have a "canonical" version of an equivalent, dependent 2932 // decltype type. Use that as our canonical type. 2933 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 2934 QualType((DecltypeType*)Canon, 0)); 2935 } else { 2936 // Build a new, canonical typeof(expr) type. 2937 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 2938 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 2939 dt = Canon; 2940 } 2941 } else { 2942 QualType T = getDecltypeForExpr(e, *this); 2943 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T)); 2944 } 2945 Types.push_back(dt); 2946 return QualType(dt, 0); 2947} 2948 2949/// getUnaryTransformationType - We don't unique these, since the memory 2950/// savings are minimal and these are rare. 2951QualType ASTContext::getUnaryTransformType(QualType BaseType, 2952 QualType UnderlyingType, 2953 UnaryTransformType::UTTKind Kind) 2954 const { 2955 UnaryTransformType *Ty = 2956 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 2957 Kind, 2958 UnderlyingType->isDependentType() ? 2959 QualType() : UnderlyingType); 2960 Types.push_back(Ty); 2961 return QualType(Ty, 0); 2962} 2963 2964/// getAutoType - We only unique auto types after they've been deduced. 2965QualType ASTContext::getAutoType(QualType DeducedType) const { 2966 void *InsertPos = 0; 2967 if (!DeducedType.isNull()) { 2968 // Look in the folding set for an existing type. 2969 llvm::FoldingSetNodeID ID; 2970 AutoType::Profile(ID, DeducedType); 2971 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2972 return QualType(AT, 0); 2973 } 2974 2975 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType); 2976 Types.push_back(AT); 2977 if (InsertPos) 2978 AutoTypes.InsertNode(AT, InsertPos); 2979 return QualType(AT, 0); 2980} 2981 2982/// getAtomicType - Return the uniqued reference to the atomic type for 2983/// the given value type. 2984QualType ASTContext::getAtomicType(QualType T) const { 2985 // Unique pointers, to guarantee there is only one pointer of a particular 2986 // structure. 2987 llvm::FoldingSetNodeID ID; 2988 AtomicType::Profile(ID, T); 2989 2990 void *InsertPos = 0; 2991 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 2992 return QualType(AT, 0); 2993 2994 // If the atomic value type isn't canonical, this won't be a canonical type 2995 // either, so fill in the canonical type field. 2996 QualType Canonical; 2997 if (!T.isCanonical()) { 2998 Canonical = getAtomicType(getCanonicalType(T)); 2999 3000 // Get the new insert position for the node we care about. 3001 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3002 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3003 } 3004 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3005 Types.push_back(New); 3006 AtomicTypes.InsertNode(New, InsertPos); 3007 return QualType(New, 0); 3008} 3009 3010/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3011QualType ASTContext::getAutoDeductType() const { 3012 if (AutoDeductTy.isNull()) 3013 AutoDeductTy = getAutoType(QualType()); 3014 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern"); 3015 return AutoDeductTy; 3016} 3017 3018/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3019QualType ASTContext::getAutoRRefDeductType() const { 3020 if (AutoRRefDeductTy.isNull()) 3021 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3022 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3023 return AutoRRefDeductTy; 3024} 3025 3026/// getTagDeclType - Return the unique reference to the type for the 3027/// specified TagDecl (struct/union/class/enum) decl. 3028QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3029 assert (Decl); 3030 // FIXME: What is the design on getTagDeclType when it requires casting 3031 // away const? mutable? 3032 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3033} 3034 3035/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3036/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3037/// needs to agree with the definition in <stddef.h>. 3038CanQualType ASTContext::getSizeType() const { 3039 return getFromTargetType(Target->getSizeType()); 3040} 3041 3042/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3043CanQualType ASTContext::getIntMaxType() const { 3044 return getFromTargetType(Target->getIntMaxType()); 3045} 3046 3047/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3048CanQualType ASTContext::getUIntMaxType() const { 3049 return getFromTargetType(Target->getUIntMaxType()); 3050} 3051 3052/// getSignedWCharType - Return the type of "signed wchar_t". 3053/// Used when in C++, as a GCC extension. 3054QualType ASTContext::getSignedWCharType() const { 3055 // FIXME: derive from "Target" ? 3056 return WCharTy; 3057} 3058 3059/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3060/// Used when in C++, as a GCC extension. 3061QualType ASTContext::getUnsignedWCharType() const { 3062 // FIXME: derive from "Target" ? 3063 return UnsignedIntTy; 3064} 3065 3066/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3067/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3068QualType ASTContext::getPointerDiffType() const { 3069 return getFromTargetType(Target->getPtrDiffType(0)); 3070} 3071 3072//===----------------------------------------------------------------------===// 3073// Type Operators 3074//===----------------------------------------------------------------------===// 3075 3076CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3077 // Push qualifiers into arrays, and then discard any remaining 3078 // qualifiers. 3079 T = getCanonicalType(T); 3080 T = getVariableArrayDecayedType(T); 3081 const Type *Ty = T.getTypePtr(); 3082 QualType Result; 3083 if (isa<ArrayType>(Ty)) { 3084 Result = getArrayDecayedType(QualType(Ty,0)); 3085 } else if (isa<FunctionType>(Ty)) { 3086 Result = getPointerType(QualType(Ty, 0)); 3087 } else { 3088 Result = QualType(Ty, 0); 3089 } 3090 3091 return CanQualType::CreateUnsafe(Result); 3092} 3093 3094QualType ASTContext::getUnqualifiedArrayType(QualType type, 3095 Qualifiers &quals) { 3096 SplitQualType splitType = type.getSplitUnqualifiedType(); 3097 3098 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3099 // the unqualified desugared type and then drops it on the floor. 3100 // We then have to strip that sugar back off with 3101 // getUnqualifiedDesugaredType(), which is silly. 3102 const ArrayType *AT = 3103 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType()); 3104 3105 // If we don't have an array, just use the results in splitType. 3106 if (!AT) { 3107 quals = splitType.second; 3108 return QualType(splitType.first, 0); 3109 } 3110 3111 // Otherwise, recurse on the array's element type. 3112 QualType elementType = AT->getElementType(); 3113 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3114 3115 // If that didn't change the element type, AT has no qualifiers, so we 3116 // can just use the results in splitType. 3117 if (elementType == unqualElementType) { 3118 assert(quals.empty()); // from the recursive call 3119 quals = splitType.second; 3120 return QualType(splitType.first, 0); 3121 } 3122 3123 // Otherwise, add in the qualifiers from the outermost type, then 3124 // build the type back up. 3125 quals.addConsistentQualifiers(splitType.second); 3126 3127 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3128 return getConstantArrayType(unqualElementType, CAT->getSize(), 3129 CAT->getSizeModifier(), 0); 3130 } 3131 3132 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3133 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3134 } 3135 3136 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3137 return getVariableArrayType(unqualElementType, 3138 VAT->getSizeExpr(), 3139 VAT->getSizeModifier(), 3140 VAT->getIndexTypeCVRQualifiers(), 3141 VAT->getBracketsRange()); 3142 } 3143 3144 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3145 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3146 DSAT->getSizeModifier(), 0, 3147 SourceRange()); 3148} 3149 3150/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3151/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3152/// they point to and return true. If T1 and T2 aren't pointer types 3153/// or pointer-to-member types, or if they are not similar at this 3154/// level, returns false and leaves T1 and T2 unchanged. Top-level 3155/// qualifiers on T1 and T2 are ignored. This function will typically 3156/// be called in a loop that successively "unwraps" pointer and 3157/// pointer-to-member types to compare them at each level. 3158bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3159 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3160 *T2PtrType = T2->getAs<PointerType>(); 3161 if (T1PtrType && T2PtrType) { 3162 T1 = T1PtrType->getPointeeType(); 3163 T2 = T2PtrType->getPointeeType(); 3164 return true; 3165 } 3166 3167 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3168 *T2MPType = T2->getAs<MemberPointerType>(); 3169 if (T1MPType && T2MPType && 3170 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3171 QualType(T2MPType->getClass(), 0))) { 3172 T1 = T1MPType->getPointeeType(); 3173 T2 = T2MPType->getPointeeType(); 3174 return true; 3175 } 3176 3177 if (getLangOptions().ObjC1) { 3178 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3179 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3180 if (T1OPType && T2OPType) { 3181 T1 = T1OPType->getPointeeType(); 3182 T2 = T2OPType->getPointeeType(); 3183 return true; 3184 } 3185 } 3186 3187 // FIXME: Block pointers, too? 3188 3189 return false; 3190} 3191 3192DeclarationNameInfo 3193ASTContext::getNameForTemplate(TemplateName Name, 3194 SourceLocation NameLoc) const { 3195 switch (Name.getKind()) { 3196 case TemplateName::QualifiedTemplate: 3197 case TemplateName::Template: 3198 // DNInfo work in progress: CHECKME: what about DNLoc? 3199 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3200 NameLoc); 3201 3202 case TemplateName::OverloadedTemplate: { 3203 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3204 // DNInfo work in progress: CHECKME: what about DNLoc? 3205 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3206 } 3207 3208 case TemplateName::DependentTemplate: { 3209 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3210 DeclarationName DName; 3211 if (DTN->isIdentifier()) { 3212 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3213 return DeclarationNameInfo(DName, NameLoc); 3214 } else { 3215 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3216 // DNInfo work in progress: FIXME: source locations? 3217 DeclarationNameLoc DNLoc; 3218 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3219 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3220 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3221 } 3222 } 3223 3224 case TemplateName::SubstTemplateTemplateParm: { 3225 SubstTemplateTemplateParmStorage *subst 3226 = Name.getAsSubstTemplateTemplateParm(); 3227 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3228 NameLoc); 3229 } 3230 3231 case TemplateName::SubstTemplateTemplateParmPack: { 3232 SubstTemplateTemplateParmPackStorage *subst 3233 = Name.getAsSubstTemplateTemplateParmPack(); 3234 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3235 NameLoc); 3236 } 3237 } 3238 3239 llvm_unreachable("bad template name kind!"); 3240} 3241 3242TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3243 switch (Name.getKind()) { 3244 case TemplateName::QualifiedTemplate: 3245 case TemplateName::Template: { 3246 TemplateDecl *Template = Name.getAsTemplateDecl(); 3247 if (TemplateTemplateParmDecl *TTP 3248 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3249 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3250 3251 // The canonical template name is the canonical template declaration. 3252 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3253 } 3254 3255 case TemplateName::OverloadedTemplate: 3256 llvm_unreachable("cannot canonicalize overloaded template"); 3257 3258 case TemplateName::DependentTemplate: { 3259 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3260 assert(DTN && "Non-dependent template names must refer to template decls."); 3261 return DTN->CanonicalTemplateName; 3262 } 3263 3264 case TemplateName::SubstTemplateTemplateParm: { 3265 SubstTemplateTemplateParmStorage *subst 3266 = Name.getAsSubstTemplateTemplateParm(); 3267 return getCanonicalTemplateName(subst->getReplacement()); 3268 } 3269 3270 case TemplateName::SubstTemplateTemplateParmPack: { 3271 SubstTemplateTemplateParmPackStorage *subst 3272 = Name.getAsSubstTemplateTemplateParmPack(); 3273 TemplateTemplateParmDecl *canonParameter 3274 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3275 TemplateArgument canonArgPack 3276 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3277 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3278 } 3279 } 3280 3281 llvm_unreachable("bad template name!"); 3282} 3283 3284bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 3285 X = getCanonicalTemplateName(X); 3286 Y = getCanonicalTemplateName(Y); 3287 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 3288} 3289 3290TemplateArgument 3291ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 3292 switch (Arg.getKind()) { 3293 case TemplateArgument::Null: 3294 return Arg; 3295 3296 case TemplateArgument::Expression: 3297 return Arg; 3298 3299 case TemplateArgument::Declaration: 3300 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl()); 3301 3302 case TemplateArgument::Template: 3303 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 3304 3305 case TemplateArgument::TemplateExpansion: 3306 return TemplateArgument(getCanonicalTemplateName( 3307 Arg.getAsTemplateOrTemplatePattern()), 3308 Arg.getNumTemplateExpansions()); 3309 3310 case TemplateArgument::Integral: 3311 return TemplateArgument(*Arg.getAsIntegral(), 3312 getCanonicalType(Arg.getIntegralType())); 3313 3314 case TemplateArgument::Type: 3315 return TemplateArgument(getCanonicalType(Arg.getAsType())); 3316 3317 case TemplateArgument::Pack: { 3318 if (Arg.pack_size() == 0) 3319 return Arg; 3320 3321 TemplateArgument *CanonArgs 3322 = new (*this) TemplateArgument[Arg.pack_size()]; 3323 unsigned Idx = 0; 3324 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 3325 AEnd = Arg.pack_end(); 3326 A != AEnd; (void)++A, ++Idx) 3327 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 3328 3329 return TemplateArgument(CanonArgs, Arg.pack_size()); 3330 } 3331 } 3332 3333 // Silence GCC warning 3334 llvm_unreachable("Unhandled template argument kind"); 3335} 3336 3337NestedNameSpecifier * 3338ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 3339 if (!NNS) 3340 return 0; 3341 3342 switch (NNS->getKind()) { 3343 case NestedNameSpecifier::Identifier: 3344 // Canonicalize the prefix but keep the identifier the same. 3345 return NestedNameSpecifier::Create(*this, 3346 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 3347 NNS->getAsIdentifier()); 3348 3349 case NestedNameSpecifier::Namespace: 3350 // A namespace is canonical; build a nested-name-specifier with 3351 // this namespace and no prefix. 3352 return NestedNameSpecifier::Create(*this, 0, 3353 NNS->getAsNamespace()->getOriginalNamespace()); 3354 3355 case NestedNameSpecifier::NamespaceAlias: 3356 // A namespace is canonical; build a nested-name-specifier with 3357 // this namespace and no prefix. 3358 return NestedNameSpecifier::Create(*this, 0, 3359 NNS->getAsNamespaceAlias()->getNamespace() 3360 ->getOriginalNamespace()); 3361 3362 case NestedNameSpecifier::TypeSpec: 3363 case NestedNameSpecifier::TypeSpecWithTemplate: { 3364 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 3365 3366 // If we have some kind of dependent-named type (e.g., "typename T::type"), 3367 // break it apart into its prefix and identifier, then reconsititute those 3368 // as the canonical nested-name-specifier. This is required to canonicalize 3369 // a dependent nested-name-specifier involving typedefs of dependent-name 3370 // types, e.g., 3371 // typedef typename T::type T1; 3372 // typedef typename T1::type T2; 3373 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) { 3374 NestedNameSpecifier *Prefix 3375 = getCanonicalNestedNameSpecifier(DNT->getQualifier()); 3376 return NestedNameSpecifier::Create(*this, Prefix, 3377 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 3378 } 3379 3380 // Do the same thing as above, but with dependent-named specializations. 3381 if (const DependentTemplateSpecializationType *DTST 3382 = T->getAs<DependentTemplateSpecializationType>()) { 3383 NestedNameSpecifier *Prefix 3384 = getCanonicalNestedNameSpecifier(DTST->getQualifier()); 3385 3386 T = getDependentTemplateSpecializationType(DTST->getKeyword(), 3387 Prefix, DTST->getIdentifier(), 3388 DTST->getNumArgs(), 3389 DTST->getArgs()); 3390 T = getCanonicalType(T); 3391 } 3392 3393 return NestedNameSpecifier::Create(*this, 0, false, 3394 const_cast<Type*>(T.getTypePtr())); 3395 } 3396 3397 case NestedNameSpecifier::Global: 3398 // The global specifier is canonical and unique. 3399 return NNS; 3400 } 3401 3402 // Required to silence a GCC warning 3403 return 0; 3404} 3405 3406 3407const ArrayType *ASTContext::getAsArrayType(QualType T) const { 3408 // Handle the non-qualified case efficiently. 3409 if (!T.hasLocalQualifiers()) { 3410 // Handle the common positive case fast. 3411 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 3412 return AT; 3413 } 3414 3415 // Handle the common negative case fast. 3416 if (!isa<ArrayType>(T.getCanonicalType())) 3417 return 0; 3418 3419 // Apply any qualifiers from the array type to the element type. This 3420 // implements C99 6.7.3p8: "If the specification of an array type includes 3421 // any type qualifiers, the element type is so qualified, not the array type." 3422 3423 // If we get here, we either have type qualifiers on the type, or we have 3424 // sugar such as a typedef in the way. If we have type qualifiers on the type 3425 // we must propagate them down into the element type. 3426 3427 SplitQualType split = T.getSplitDesugaredType(); 3428 Qualifiers qs = split.second; 3429 3430 // If we have a simple case, just return now. 3431 const ArrayType *ATy = dyn_cast<ArrayType>(split.first); 3432 if (ATy == 0 || qs.empty()) 3433 return ATy; 3434 3435 // Otherwise, we have an array and we have qualifiers on it. Push the 3436 // qualifiers into the array element type and return a new array type. 3437 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 3438 3439 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 3440 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 3441 CAT->getSizeModifier(), 3442 CAT->getIndexTypeCVRQualifiers())); 3443 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 3444 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 3445 IAT->getSizeModifier(), 3446 IAT->getIndexTypeCVRQualifiers())); 3447 3448 if (const DependentSizedArrayType *DSAT 3449 = dyn_cast<DependentSizedArrayType>(ATy)) 3450 return cast<ArrayType>( 3451 getDependentSizedArrayType(NewEltTy, 3452 DSAT->getSizeExpr(), 3453 DSAT->getSizeModifier(), 3454 DSAT->getIndexTypeCVRQualifiers(), 3455 DSAT->getBracketsRange())); 3456 3457 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 3458 return cast<ArrayType>(getVariableArrayType(NewEltTy, 3459 VAT->getSizeExpr(), 3460 VAT->getSizeModifier(), 3461 VAT->getIndexTypeCVRQualifiers(), 3462 VAT->getBracketsRange())); 3463} 3464 3465QualType ASTContext::getAdjustedParameterType(QualType T) { 3466 // C99 6.7.5.3p7: 3467 // A declaration of a parameter as "array of type" shall be 3468 // adjusted to "qualified pointer to type", where the type 3469 // qualifiers (if any) are those specified within the [ and ] of 3470 // the array type derivation. 3471 if (T->isArrayType()) 3472 return getArrayDecayedType(T); 3473 3474 // C99 6.7.5.3p8: 3475 // A declaration of a parameter as "function returning type" 3476 // shall be adjusted to "pointer to function returning type", as 3477 // in 6.3.2.1. 3478 if (T->isFunctionType()) 3479 return getPointerType(T); 3480 3481 return T; 3482} 3483 3484QualType ASTContext::getSignatureParameterType(QualType T) { 3485 T = getVariableArrayDecayedType(T); 3486 T = getAdjustedParameterType(T); 3487 return T.getUnqualifiedType(); 3488} 3489 3490/// getArrayDecayedType - Return the properly qualified result of decaying the 3491/// specified array type to a pointer. This operation is non-trivial when 3492/// handling typedefs etc. The canonical type of "T" must be an array type, 3493/// this returns a pointer to a properly qualified element of the array. 3494/// 3495/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 3496QualType ASTContext::getArrayDecayedType(QualType Ty) const { 3497 // Get the element type with 'getAsArrayType' so that we don't lose any 3498 // typedefs in the element type of the array. This also handles propagation 3499 // of type qualifiers from the array type into the element type if present 3500 // (C99 6.7.3p8). 3501 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 3502 assert(PrettyArrayType && "Not an array type!"); 3503 3504 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 3505 3506 // int x[restrict 4] -> int *restrict 3507 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 3508} 3509 3510QualType ASTContext::getBaseElementType(const ArrayType *array) const { 3511 return getBaseElementType(array->getElementType()); 3512} 3513 3514QualType ASTContext::getBaseElementType(QualType type) const { 3515 Qualifiers qs; 3516 while (true) { 3517 SplitQualType split = type.getSplitDesugaredType(); 3518 const ArrayType *array = split.first->getAsArrayTypeUnsafe(); 3519 if (!array) break; 3520 3521 type = array->getElementType(); 3522 qs.addConsistentQualifiers(split.second); 3523 } 3524 3525 return getQualifiedType(type, qs); 3526} 3527 3528/// getConstantArrayElementCount - Returns number of constant array elements. 3529uint64_t 3530ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 3531 uint64_t ElementCount = 1; 3532 do { 3533 ElementCount *= CA->getSize().getZExtValue(); 3534 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 3535 } while (CA); 3536 return ElementCount; 3537} 3538 3539/// getFloatingRank - Return a relative rank for floating point types. 3540/// This routine will assert if passed a built-in type that isn't a float. 3541static FloatingRank getFloatingRank(QualType T) { 3542 if (const ComplexType *CT = T->getAs<ComplexType>()) 3543 return getFloatingRank(CT->getElementType()); 3544 3545 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 3546 switch (T->getAs<BuiltinType>()->getKind()) { 3547 default: llvm_unreachable("getFloatingRank(): not a floating type"); 3548 case BuiltinType::Half: return HalfRank; 3549 case BuiltinType::Float: return FloatRank; 3550 case BuiltinType::Double: return DoubleRank; 3551 case BuiltinType::LongDouble: return LongDoubleRank; 3552 } 3553} 3554 3555/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 3556/// point or a complex type (based on typeDomain/typeSize). 3557/// 'typeDomain' is a real floating point or complex type. 3558/// 'typeSize' is a real floating point or complex type. 3559QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 3560 QualType Domain) const { 3561 FloatingRank EltRank = getFloatingRank(Size); 3562 if (Domain->isComplexType()) { 3563 switch (EltRank) { 3564 default: llvm_unreachable("getFloatingRank(): illegal value for rank"); 3565 case FloatRank: return FloatComplexTy; 3566 case DoubleRank: return DoubleComplexTy; 3567 case LongDoubleRank: return LongDoubleComplexTy; 3568 } 3569 } 3570 3571 assert(Domain->isRealFloatingType() && "Unknown domain!"); 3572 switch (EltRank) { 3573 default: llvm_unreachable("getFloatingRank(): illegal value for rank"); 3574 case FloatRank: return FloatTy; 3575 case DoubleRank: return DoubleTy; 3576 case LongDoubleRank: return LongDoubleTy; 3577 } 3578} 3579 3580/// getFloatingTypeOrder - Compare the rank of the two specified floating 3581/// point types, ignoring the domain of the type (i.e. 'double' == 3582/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 3583/// LHS < RHS, return -1. 3584int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 3585 FloatingRank LHSR = getFloatingRank(LHS); 3586 FloatingRank RHSR = getFloatingRank(RHS); 3587 3588 if (LHSR == RHSR) 3589 return 0; 3590 if (LHSR > RHSR) 3591 return 1; 3592 return -1; 3593} 3594 3595/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 3596/// routine will assert if passed a built-in type that isn't an integer or enum, 3597/// or if it is not canonicalized. 3598unsigned ASTContext::getIntegerRank(const Type *T) const { 3599 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 3600 3601 switch (cast<BuiltinType>(T)->getKind()) { 3602 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 3603 case BuiltinType::Bool: 3604 return 1 + (getIntWidth(BoolTy) << 3); 3605 case BuiltinType::Char_S: 3606 case BuiltinType::Char_U: 3607 case BuiltinType::SChar: 3608 case BuiltinType::UChar: 3609 return 2 + (getIntWidth(CharTy) << 3); 3610 case BuiltinType::Short: 3611 case BuiltinType::UShort: 3612 return 3 + (getIntWidth(ShortTy) << 3); 3613 case BuiltinType::Int: 3614 case BuiltinType::UInt: 3615 return 4 + (getIntWidth(IntTy) << 3); 3616 case BuiltinType::Long: 3617 case BuiltinType::ULong: 3618 return 5 + (getIntWidth(LongTy) << 3); 3619 case BuiltinType::LongLong: 3620 case BuiltinType::ULongLong: 3621 return 6 + (getIntWidth(LongLongTy) << 3); 3622 case BuiltinType::Int128: 3623 case BuiltinType::UInt128: 3624 return 7 + (getIntWidth(Int128Ty) << 3); 3625 } 3626} 3627 3628/// \brief Whether this is a promotable bitfield reference according 3629/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3630/// 3631/// \returns the type this bit-field will promote to, or NULL if no 3632/// promotion occurs. 3633QualType ASTContext::isPromotableBitField(Expr *E) const { 3634 if (E->isTypeDependent() || E->isValueDependent()) 3635 return QualType(); 3636 3637 FieldDecl *Field = E->getBitField(); 3638 if (!Field) 3639 return QualType(); 3640 3641 QualType FT = Field->getType(); 3642 3643 uint64_t BitWidth = Field->getBitWidthValue(*this); 3644 uint64_t IntSize = getTypeSize(IntTy); 3645 // GCC extension compatibility: if the bit-field size is less than or equal 3646 // to the size of int, it gets promoted no matter what its type is. 3647 // For instance, unsigned long bf : 4 gets promoted to signed int. 3648 if (BitWidth < IntSize) 3649 return IntTy; 3650 3651 if (BitWidth == IntSize) 3652 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3653 3654 // Types bigger than int are not subject to promotions, and therefore act 3655 // like the base type. 3656 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3657 // is ridiculous. 3658 return QualType(); 3659} 3660 3661/// getPromotedIntegerType - Returns the type that Promotable will 3662/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3663/// integer type. 3664QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 3665 assert(!Promotable.isNull()); 3666 assert(Promotable->isPromotableIntegerType()); 3667 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3668 return ET->getDecl()->getPromotionType(); 3669 3670 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 3671 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 3672 // (3.9.1) can be converted to a prvalue of the first of the following 3673 // types that can represent all the values of its underlying type: 3674 // int, unsigned int, long int, unsigned long int, long long int, or 3675 // unsigned long long int [...] 3676 // FIXME: Is there some better way to compute this? 3677 if (BT->getKind() == BuiltinType::WChar_S || 3678 BT->getKind() == BuiltinType::WChar_U || 3679 BT->getKind() == BuiltinType::Char16 || 3680 BT->getKind() == BuiltinType::Char32) { 3681 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 3682 uint64_t FromSize = getTypeSize(BT); 3683 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 3684 LongLongTy, UnsignedLongLongTy }; 3685 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 3686 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 3687 if (FromSize < ToSize || 3688 (FromSize == ToSize && 3689 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 3690 return PromoteTypes[Idx]; 3691 } 3692 llvm_unreachable("char type should fit into long long"); 3693 } 3694 } 3695 3696 // At this point, we should have a signed or unsigned integer type. 3697 if (Promotable->isSignedIntegerType()) 3698 return IntTy; 3699 uint64_t PromotableSize = getTypeSize(Promotable); 3700 uint64_t IntSize = getTypeSize(IntTy); 3701 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 3702 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 3703} 3704 3705/// \brief Recurses in pointer/array types until it finds an objc retainable 3706/// type and returns its ownership. 3707Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 3708 while (!T.isNull()) { 3709 if (T.getObjCLifetime() != Qualifiers::OCL_None) 3710 return T.getObjCLifetime(); 3711 if (T->isArrayType()) 3712 T = getBaseElementType(T); 3713 else if (const PointerType *PT = T->getAs<PointerType>()) 3714 T = PT->getPointeeType(); 3715 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3716 T = RT->getPointeeType(); 3717 else 3718 break; 3719 } 3720 3721 return Qualifiers::OCL_None; 3722} 3723 3724/// getIntegerTypeOrder - Returns the highest ranked integer type: 3725/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 3726/// LHS < RHS, return -1. 3727int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 3728 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 3729 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 3730 if (LHSC == RHSC) return 0; 3731 3732 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 3733 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 3734 3735 unsigned LHSRank = getIntegerRank(LHSC); 3736 unsigned RHSRank = getIntegerRank(RHSC); 3737 3738 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 3739 if (LHSRank == RHSRank) return 0; 3740 return LHSRank > RHSRank ? 1 : -1; 3741 } 3742 3743 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3744 if (LHSUnsigned) { 3745 // If the unsigned [LHS] type is larger, return it. 3746 if (LHSRank >= RHSRank) 3747 return 1; 3748 3749 // If the signed type can represent all values of the unsigned type, it 3750 // wins. Because we are dealing with 2's complement and types that are 3751 // powers of two larger than each other, this is always safe. 3752 return -1; 3753 } 3754 3755 // If the unsigned [RHS] type is larger, return it. 3756 if (RHSRank >= LHSRank) 3757 return -1; 3758 3759 // If the signed type can represent all values of the unsigned type, it 3760 // wins. Because we are dealing with 2's complement and types that are 3761 // powers of two larger than each other, this is always safe. 3762 return 1; 3763} 3764 3765static RecordDecl * 3766CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 3767 DeclContext *DC, IdentifierInfo *Id) { 3768 SourceLocation Loc; 3769 if (Ctx.getLangOptions().CPlusPlus) 3770 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3771 else 3772 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3773} 3774 3775// getCFConstantStringType - Return the type used for constant CFStrings. 3776QualType ASTContext::getCFConstantStringType() const { 3777 if (!CFConstantStringTypeDecl) { 3778 CFConstantStringTypeDecl = 3779 CreateRecordDecl(*this, TTK_Struct, TUDecl, 3780 &Idents.get("NSConstantString")); 3781 CFConstantStringTypeDecl->startDefinition(); 3782 3783 QualType FieldTypes[4]; 3784 3785 // const int *isa; 3786 FieldTypes[0] = getPointerType(IntTy.withConst()); 3787 // int flags; 3788 FieldTypes[1] = IntTy; 3789 // const char *str; 3790 FieldTypes[2] = getPointerType(CharTy.withConst()); 3791 // long length; 3792 FieldTypes[3] = LongTy; 3793 3794 // Create fields 3795 for (unsigned i = 0; i < 4; ++i) { 3796 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 3797 SourceLocation(), 3798 SourceLocation(), 0, 3799 FieldTypes[i], /*TInfo=*/0, 3800 /*BitWidth=*/0, 3801 /*Mutable=*/false, 3802 /*HasInit=*/false); 3803 Field->setAccess(AS_public); 3804 CFConstantStringTypeDecl->addDecl(Field); 3805 } 3806 3807 CFConstantStringTypeDecl->completeDefinition(); 3808 } 3809 3810 return getTagDeclType(CFConstantStringTypeDecl); 3811} 3812 3813void ASTContext::setCFConstantStringType(QualType T) { 3814 const RecordType *Rec = T->getAs<RecordType>(); 3815 assert(Rec && "Invalid CFConstantStringType"); 3816 CFConstantStringTypeDecl = Rec->getDecl(); 3817} 3818 3819QualType ASTContext::getBlockDescriptorType() const { 3820 if (BlockDescriptorType) 3821 return getTagDeclType(BlockDescriptorType); 3822 3823 RecordDecl *T; 3824 // FIXME: Needs the FlagAppleBlock bit. 3825 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3826 &Idents.get("__block_descriptor")); 3827 T->startDefinition(); 3828 3829 QualType FieldTypes[] = { 3830 UnsignedLongTy, 3831 UnsignedLongTy, 3832 }; 3833 3834 const char *FieldNames[] = { 3835 "reserved", 3836 "Size" 3837 }; 3838 3839 for (size_t i = 0; i < 2; ++i) { 3840 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3841 SourceLocation(), 3842 &Idents.get(FieldNames[i]), 3843 FieldTypes[i], /*TInfo=*/0, 3844 /*BitWidth=*/0, 3845 /*Mutable=*/false, 3846 /*HasInit=*/false); 3847 Field->setAccess(AS_public); 3848 T->addDecl(Field); 3849 } 3850 3851 T->completeDefinition(); 3852 3853 BlockDescriptorType = T; 3854 3855 return getTagDeclType(BlockDescriptorType); 3856} 3857 3858QualType ASTContext::getBlockDescriptorExtendedType() const { 3859 if (BlockDescriptorExtendedType) 3860 return getTagDeclType(BlockDescriptorExtendedType); 3861 3862 RecordDecl *T; 3863 // FIXME: Needs the FlagAppleBlock bit. 3864 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3865 &Idents.get("__block_descriptor_withcopydispose")); 3866 T->startDefinition(); 3867 3868 QualType FieldTypes[] = { 3869 UnsignedLongTy, 3870 UnsignedLongTy, 3871 getPointerType(VoidPtrTy), 3872 getPointerType(VoidPtrTy) 3873 }; 3874 3875 const char *FieldNames[] = { 3876 "reserved", 3877 "Size", 3878 "CopyFuncPtr", 3879 "DestroyFuncPtr" 3880 }; 3881 3882 for (size_t i = 0; i < 4; ++i) { 3883 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3884 SourceLocation(), 3885 &Idents.get(FieldNames[i]), 3886 FieldTypes[i], /*TInfo=*/0, 3887 /*BitWidth=*/0, 3888 /*Mutable=*/false, 3889 /*HasInit=*/false); 3890 Field->setAccess(AS_public); 3891 T->addDecl(Field); 3892 } 3893 3894 T->completeDefinition(); 3895 3896 BlockDescriptorExtendedType = T; 3897 3898 return getTagDeclType(BlockDescriptorExtendedType); 3899} 3900 3901bool ASTContext::BlockRequiresCopying(QualType Ty) const { 3902 if (Ty->isObjCRetainableType()) 3903 return true; 3904 if (getLangOptions().CPlusPlus) { 3905 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3906 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3907 return RD->hasConstCopyConstructor(); 3908 3909 } 3910 } 3911 return false; 3912} 3913 3914QualType 3915ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const { 3916 // type = struct __Block_byref_1_X { 3917 // void *__isa; 3918 // struct __Block_byref_1_X *__forwarding; 3919 // unsigned int __flags; 3920 // unsigned int __size; 3921 // void *__copy_helper; // as needed 3922 // void *__destroy_help // as needed 3923 // int X; 3924 // } * 3925 3926 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 3927 3928 // FIXME: Move up 3929 llvm::SmallString<36> Name; 3930 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 3931 ++UniqueBlockByRefTypeID << '_' << DeclName; 3932 RecordDecl *T; 3933 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str())); 3934 T->startDefinition(); 3935 QualType Int32Ty = IntTy; 3936 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 3937 QualType FieldTypes[] = { 3938 getPointerType(VoidPtrTy), 3939 getPointerType(getTagDeclType(T)), 3940 Int32Ty, 3941 Int32Ty, 3942 getPointerType(VoidPtrTy), 3943 getPointerType(VoidPtrTy), 3944 Ty 3945 }; 3946 3947 StringRef FieldNames[] = { 3948 "__isa", 3949 "__forwarding", 3950 "__flags", 3951 "__size", 3952 "__copy_helper", 3953 "__destroy_helper", 3954 DeclName, 3955 }; 3956 3957 for (size_t i = 0; i < 7; ++i) { 3958 if (!HasCopyAndDispose && i >=4 && i <= 5) 3959 continue; 3960 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3961 SourceLocation(), 3962 &Idents.get(FieldNames[i]), 3963 FieldTypes[i], /*TInfo=*/0, 3964 /*BitWidth=*/0, /*Mutable=*/false, 3965 /*HasInit=*/false); 3966 Field->setAccess(AS_public); 3967 T->addDecl(Field); 3968 } 3969 3970 T->completeDefinition(); 3971 3972 return getPointerType(getTagDeclType(T)); 3973} 3974 3975TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 3976 if (!ObjCInstanceTypeDecl) 3977 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 3978 getTranslationUnitDecl(), 3979 SourceLocation(), 3980 SourceLocation(), 3981 &Idents.get("instancetype"), 3982 getTrivialTypeSourceInfo(getObjCIdType())); 3983 return ObjCInstanceTypeDecl; 3984} 3985 3986// This returns true if a type has been typedefed to BOOL: 3987// typedef <type> BOOL; 3988static bool isTypeTypedefedAsBOOL(QualType T) { 3989 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 3990 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 3991 return II->isStr("BOOL"); 3992 3993 return false; 3994} 3995 3996/// getObjCEncodingTypeSize returns size of type for objective-c encoding 3997/// purpose. 3998CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 3999 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4000 return CharUnits::Zero(); 4001 4002 CharUnits sz = getTypeSizeInChars(type); 4003 4004 // Make all integer and enum types at least as large as an int 4005 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4006 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4007 // Treat arrays as pointers, since that's how they're passed in. 4008 else if (type->isArrayType()) 4009 sz = getTypeSizeInChars(VoidPtrTy); 4010 return sz; 4011} 4012 4013static inline 4014std::string charUnitsToString(const CharUnits &CU) { 4015 return llvm::itostr(CU.getQuantity()); 4016} 4017 4018/// getObjCEncodingForBlock - Return the encoded type for this block 4019/// declaration. 4020std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4021 std::string S; 4022 4023 const BlockDecl *Decl = Expr->getBlockDecl(); 4024 QualType BlockTy = 4025 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4026 // Encode result type. 4027 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 4028 // Compute size of all parameters. 4029 // Start with computing size of a pointer in number of bytes. 4030 // FIXME: There might(should) be a better way of doing this computation! 4031 SourceLocation Loc; 4032 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4033 CharUnits ParmOffset = PtrSize; 4034 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4035 E = Decl->param_end(); PI != E; ++PI) { 4036 QualType PType = (*PI)->getType(); 4037 CharUnits sz = getObjCEncodingTypeSize(PType); 4038 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4039 ParmOffset += sz; 4040 } 4041 // Size of the argument frame 4042 S += charUnitsToString(ParmOffset); 4043 // Block pointer and offset. 4044 S += "@?0"; 4045 4046 // Argument types. 4047 ParmOffset = PtrSize; 4048 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4049 Decl->param_end(); PI != E; ++PI) { 4050 ParmVarDecl *PVDecl = *PI; 4051 QualType PType = PVDecl->getOriginalType(); 4052 if (const ArrayType *AT = 4053 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4054 // Use array's original type only if it has known number of 4055 // elements. 4056 if (!isa<ConstantArrayType>(AT)) 4057 PType = PVDecl->getType(); 4058 } else if (PType->isFunctionType()) 4059 PType = PVDecl->getType(); 4060 getObjCEncodingForType(PType, S); 4061 S += charUnitsToString(ParmOffset); 4062 ParmOffset += getObjCEncodingTypeSize(PType); 4063 } 4064 4065 return S; 4066} 4067 4068bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4069 std::string& S) { 4070 // Encode result type. 4071 getObjCEncodingForType(Decl->getResultType(), S); 4072 CharUnits ParmOffset; 4073 // Compute size of all parameters. 4074 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4075 E = Decl->param_end(); PI != E; ++PI) { 4076 QualType PType = (*PI)->getType(); 4077 CharUnits sz = getObjCEncodingTypeSize(PType); 4078 if (sz.isZero()) 4079 return true; 4080 4081 assert (sz.isPositive() && 4082 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4083 ParmOffset += sz; 4084 } 4085 S += charUnitsToString(ParmOffset); 4086 ParmOffset = CharUnits::Zero(); 4087 4088 // Argument types. 4089 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4090 E = Decl->param_end(); PI != E; ++PI) { 4091 ParmVarDecl *PVDecl = *PI; 4092 QualType PType = PVDecl->getOriginalType(); 4093 if (const ArrayType *AT = 4094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4095 // Use array's original type only if it has known number of 4096 // elements. 4097 if (!isa<ConstantArrayType>(AT)) 4098 PType = PVDecl->getType(); 4099 } else if (PType->isFunctionType()) 4100 PType = PVDecl->getType(); 4101 getObjCEncodingForType(PType, S); 4102 S += charUnitsToString(ParmOffset); 4103 ParmOffset += getObjCEncodingTypeSize(PType); 4104 } 4105 4106 return false; 4107} 4108 4109/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4110/// method parameter or return type. If Extended, include class names and 4111/// block object types. 4112void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4113 QualType T, std::string& S, 4114 bool Extended) const { 4115 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4116 getObjCEncodingForTypeQualifier(QT, S); 4117 // Encode parameter type. 4118 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4119 true /*OutermostType*/, 4120 false /*EncodingProperty*/, 4121 false /*StructField*/, 4122 Extended /*EncodeBlockParameters*/, 4123 Extended /*EncodeClassNames*/); 4124} 4125 4126/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4127/// declaration. 4128bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4129 std::string& S, 4130 bool Extended) const { 4131 // FIXME: This is not very efficient. 4132 // Encode return type. 4133 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4134 Decl->getResultType(), S, Extended); 4135 // Compute size of all parameters. 4136 // Start with computing size of a pointer in number of bytes. 4137 // FIXME: There might(should) be a better way of doing this computation! 4138 SourceLocation Loc; 4139 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4140 // The first two arguments (self and _cmd) are pointers; account for 4141 // their size. 4142 CharUnits ParmOffset = 2 * PtrSize; 4143 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4144 E = Decl->sel_param_end(); PI != E; ++PI) { 4145 QualType PType = (*PI)->getType(); 4146 CharUnits sz = getObjCEncodingTypeSize(PType); 4147 if (sz.isZero()) 4148 return true; 4149 4150 assert (sz.isPositive() && 4151 "getObjCEncodingForMethodDecl - Incomplete param type"); 4152 ParmOffset += sz; 4153 } 4154 S += charUnitsToString(ParmOffset); 4155 S += "@0:"; 4156 S += charUnitsToString(PtrSize); 4157 4158 // Argument types. 4159 ParmOffset = 2 * PtrSize; 4160 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4161 E = Decl->sel_param_end(); PI != E; ++PI) { 4162 const ParmVarDecl *PVDecl = *PI; 4163 QualType PType = PVDecl->getOriginalType(); 4164 if (const ArrayType *AT = 4165 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4166 // Use array's original type only if it has known number of 4167 // elements. 4168 if (!isa<ConstantArrayType>(AT)) 4169 PType = PVDecl->getType(); 4170 } else if (PType->isFunctionType()) 4171 PType = PVDecl->getType(); 4172 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4173 PType, S, Extended); 4174 S += charUnitsToString(ParmOffset); 4175 ParmOffset += getObjCEncodingTypeSize(PType); 4176 } 4177 4178 return false; 4179} 4180 4181/// getObjCEncodingForPropertyDecl - Return the encoded type for this 4182/// property declaration. If non-NULL, Container must be either an 4183/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4184/// NULL when getting encodings for protocol properties. 4185/// Property attributes are stored as a comma-delimited C string. The simple 4186/// attributes readonly and bycopy are encoded as single characters. The 4187/// parametrized attributes, getter=name, setter=name, and ivar=name, are 4188/// encoded as single characters, followed by an identifier. Property types 4189/// are also encoded as a parametrized attribute. The characters used to encode 4190/// these attributes are defined by the following enumeration: 4191/// @code 4192/// enum PropertyAttributes { 4193/// kPropertyReadOnly = 'R', // property is read-only. 4194/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4195/// kPropertyByref = '&', // property is a reference to the value last assigned 4196/// kPropertyDynamic = 'D', // property is dynamic 4197/// kPropertyGetter = 'G', // followed by getter selector name 4198/// kPropertySetter = 'S', // followed by setter selector name 4199/// kPropertyInstanceVariable = 'V' // followed by instance variable name 4200/// kPropertyType = 't' // followed by old-style type encoding. 4201/// kPropertyWeak = 'W' // 'weak' property 4202/// kPropertyStrong = 'P' // property GC'able 4203/// kPropertyNonAtomic = 'N' // property non-atomic 4204/// }; 4205/// @endcode 4206void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4207 const Decl *Container, 4208 std::string& S) const { 4209 // Collect information from the property implementation decl(s). 4210 bool Dynamic = false; 4211 ObjCPropertyImplDecl *SynthesizePID = 0; 4212 4213 // FIXME: Duplicated code due to poor abstraction. 4214 if (Container) { 4215 if (const ObjCCategoryImplDecl *CID = 4216 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4217 for (ObjCCategoryImplDecl::propimpl_iterator 4218 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4219 i != e; ++i) { 4220 ObjCPropertyImplDecl *PID = *i; 4221 if (PID->getPropertyDecl() == PD) { 4222 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4223 Dynamic = true; 4224 } else { 4225 SynthesizePID = PID; 4226 } 4227 } 4228 } 4229 } else { 4230 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4231 for (ObjCCategoryImplDecl::propimpl_iterator 4232 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4233 i != e; ++i) { 4234 ObjCPropertyImplDecl *PID = *i; 4235 if (PID->getPropertyDecl() == PD) { 4236 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4237 Dynamic = true; 4238 } else { 4239 SynthesizePID = PID; 4240 } 4241 } 4242 } 4243 } 4244 } 4245 4246 // FIXME: This is not very efficient. 4247 S = "T"; 4248 4249 // Encode result type. 4250 // GCC has some special rules regarding encoding of properties which 4251 // closely resembles encoding of ivars. 4252 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4253 true /* outermost type */, 4254 true /* encoding for property */); 4255 4256 if (PD->isReadOnly()) { 4257 S += ",R"; 4258 } else { 4259 switch (PD->getSetterKind()) { 4260 case ObjCPropertyDecl::Assign: break; 4261 case ObjCPropertyDecl::Copy: S += ",C"; break; 4262 case ObjCPropertyDecl::Retain: S += ",&"; break; 4263 case ObjCPropertyDecl::Weak: S += ",W"; break; 4264 } 4265 } 4266 4267 // It really isn't clear at all what this means, since properties 4268 // are "dynamic by default". 4269 if (Dynamic) 4270 S += ",D"; 4271 4272 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4273 S += ",N"; 4274 4275 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4276 S += ",G"; 4277 S += PD->getGetterName().getAsString(); 4278 } 4279 4280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4281 S += ",S"; 4282 S += PD->getSetterName().getAsString(); 4283 } 4284 4285 if (SynthesizePID) { 4286 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4287 S += ",V"; 4288 S += OID->getNameAsString(); 4289 } 4290 4291 // FIXME: OBJCGC: weak & strong 4292} 4293 4294/// getLegacyIntegralTypeEncoding - 4295/// Another legacy compatibility encoding: 32-bit longs are encoded as 4296/// 'l' or 'L' , but not always. For typedefs, we need to use 4297/// 'i' or 'I' instead if encoding a struct field, or a pointer! 4298/// 4299void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 4300 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 4301 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 4302 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 4303 PointeeTy = UnsignedIntTy; 4304 else 4305 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 4306 PointeeTy = IntTy; 4307 } 4308 } 4309} 4310 4311void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 4312 const FieldDecl *Field) const { 4313 // We follow the behavior of gcc, expanding structures which are 4314 // directly pointed to, and expanding embedded structures. Note that 4315 // these rules are sufficient to prevent recursive encoding of the 4316 // same type. 4317 getObjCEncodingForTypeImpl(T, S, true, true, Field, 4318 true /* outermost type */); 4319} 4320 4321static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 4322 switch (T->getAs<BuiltinType>()->getKind()) { 4323 default: llvm_unreachable("Unhandled builtin type kind"); 4324 case BuiltinType::Void: return 'v'; 4325 case BuiltinType::Bool: return 'B'; 4326 case BuiltinType::Char_U: 4327 case BuiltinType::UChar: return 'C'; 4328 case BuiltinType::UShort: return 'S'; 4329 case BuiltinType::UInt: return 'I'; 4330 case BuiltinType::ULong: 4331 return C->getIntWidth(T) == 32 ? 'L' : 'Q'; 4332 case BuiltinType::UInt128: return 'T'; 4333 case BuiltinType::ULongLong: return 'Q'; 4334 case BuiltinType::Char_S: 4335 case BuiltinType::SChar: return 'c'; 4336 case BuiltinType::Short: return 's'; 4337 case BuiltinType::WChar_S: 4338 case BuiltinType::WChar_U: 4339 case BuiltinType::Int: return 'i'; 4340 case BuiltinType::Long: 4341 return C->getIntWidth(T) == 32 ? 'l' : 'q'; 4342 case BuiltinType::LongLong: return 'q'; 4343 case BuiltinType::Int128: return 't'; 4344 case BuiltinType::Float: return 'f'; 4345 case BuiltinType::Double: return 'd'; 4346 case BuiltinType::LongDouble: return 'D'; 4347 } 4348} 4349 4350static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 4351 EnumDecl *Enum = ET->getDecl(); 4352 4353 // The encoding of an non-fixed enum type is always 'i', regardless of size. 4354 if (!Enum->isFixed()) 4355 return 'i'; 4356 4357 // The encoding of a fixed enum type matches its fixed underlying type. 4358 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType()); 4359} 4360 4361static void EncodeBitField(const ASTContext *Ctx, std::string& S, 4362 QualType T, const FieldDecl *FD) { 4363 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 4364 S += 'b'; 4365 // The NeXT runtime encodes bit fields as b followed by the number of bits. 4366 // The GNU runtime requires more information; bitfields are encoded as b, 4367 // then the offset (in bits) of the first element, then the type of the 4368 // bitfield, then the size in bits. For example, in this structure: 4369 // 4370 // struct 4371 // { 4372 // int integer; 4373 // int flags:2; 4374 // }; 4375 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 4376 // runtime, but b32i2 for the GNU runtime. The reason for this extra 4377 // information is not especially sensible, but we're stuck with it for 4378 // compatibility with GCC, although providing it breaks anything that 4379 // actually uses runtime introspection and wants to work on both runtimes... 4380 if (!Ctx->getLangOptions().NeXTRuntime) { 4381 const RecordDecl *RD = FD->getParent(); 4382 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 4383 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 4384 if (const EnumType *ET = T->getAs<EnumType>()) 4385 S += ObjCEncodingForEnumType(Ctx, ET); 4386 else 4387 S += ObjCEncodingForPrimitiveKind(Ctx, T); 4388 } 4389 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 4390} 4391 4392// FIXME: Use SmallString for accumulating string. 4393void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 4394 bool ExpandPointedToStructures, 4395 bool ExpandStructures, 4396 const FieldDecl *FD, 4397 bool OutermostType, 4398 bool EncodingProperty, 4399 bool StructField, 4400 bool EncodeBlockParameters, 4401 bool EncodeClassNames) const { 4402 if (T->getAs<BuiltinType>()) { 4403 if (FD && FD->isBitField()) 4404 return EncodeBitField(this, S, T, FD); 4405 S += ObjCEncodingForPrimitiveKind(this, T); 4406 return; 4407 } 4408 4409 if (const ComplexType *CT = T->getAs<ComplexType>()) { 4410 S += 'j'; 4411 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 4412 false); 4413 return; 4414 } 4415 4416 // encoding for pointer or r3eference types. 4417 QualType PointeeTy; 4418 if (const PointerType *PT = T->getAs<PointerType>()) { 4419 if (PT->isObjCSelType()) { 4420 S += ':'; 4421 return; 4422 } 4423 PointeeTy = PT->getPointeeType(); 4424 } 4425 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4426 PointeeTy = RT->getPointeeType(); 4427 if (!PointeeTy.isNull()) { 4428 bool isReadOnly = false; 4429 // For historical/compatibility reasons, the read-only qualifier of the 4430 // pointee gets emitted _before_ the '^'. The read-only qualifier of 4431 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 4432 // Also, do not emit the 'r' for anything but the outermost type! 4433 if (isa<TypedefType>(T.getTypePtr())) { 4434 if (OutermostType && T.isConstQualified()) { 4435 isReadOnly = true; 4436 S += 'r'; 4437 } 4438 } else if (OutermostType) { 4439 QualType P = PointeeTy; 4440 while (P->getAs<PointerType>()) 4441 P = P->getAs<PointerType>()->getPointeeType(); 4442 if (P.isConstQualified()) { 4443 isReadOnly = true; 4444 S += 'r'; 4445 } 4446 } 4447 if (isReadOnly) { 4448 // Another legacy compatibility encoding. Some ObjC qualifier and type 4449 // combinations need to be rearranged. 4450 // Rewrite "in const" from "nr" to "rn" 4451 if (StringRef(S).endswith("nr")) 4452 S.replace(S.end()-2, S.end(), "rn"); 4453 } 4454 4455 if (PointeeTy->isCharType()) { 4456 // char pointer types should be encoded as '*' unless it is a 4457 // type that has been typedef'd to 'BOOL'. 4458 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 4459 S += '*'; 4460 return; 4461 } 4462 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 4463 // GCC binary compat: Need to convert "struct objc_class *" to "#". 4464 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 4465 S += '#'; 4466 return; 4467 } 4468 // GCC binary compat: Need to convert "struct objc_object *" to "@". 4469 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 4470 S += '@'; 4471 return; 4472 } 4473 // fall through... 4474 } 4475 S += '^'; 4476 getLegacyIntegralTypeEncoding(PointeeTy); 4477 4478 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 4479 NULL); 4480 return; 4481 } 4482 4483 if (const ArrayType *AT = 4484 // Ignore type qualifiers etc. 4485 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 4486 if (isa<IncompleteArrayType>(AT) && !StructField) { 4487 // Incomplete arrays are encoded as a pointer to the array element. 4488 S += '^'; 4489 4490 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4491 false, ExpandStructures, FD); 4492 } else { 4493 S += '['; 4494 4495 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4496 if (getTypeSize(CAT->getElementType()) == 0) 4497 S += '0'; 4498 else 4499 S += llvm::utostr(CAT->getSize().getZExtValue()); 4500 } else { 4501 //Variable length arrays are encoded as a regular array with 0 elements. 4502 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 4503 "Unknown array type!"); 4504 S += '0'; 4505 } 4506 4507 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4508 false, ExpandStructures, FD); 4509 S += ']'; 4510 } 4511 return; 4512 } 4513 4514 if (T->getAs<FunctionType>()) { 4515 S += '?'; 4516 return; 4517 } 4518 4519 if (const RecordType *RTy = T->getAs<RecordType>()) { 4520 RecordDecl *RDecl = RTy->getDecl(); 4521 S += RDecl->isUnion() ? '(' : '{'; 4522 // Anonymous structures print as '?' 4523 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 4524 S += II->getName(); 4525 if (ClassTemplateSpecializationDecl *Spec 4526 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 4527 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 4528 std::string TemplateArgsStr 4529 = TemplateSpecializationType::PrintTemplateArgumentList( 4530 TemplateArgs.data(), 4531 TemplateArgs.size(), 4532 (*this).getPrintingPolicy()); 4533 4534 S += TemplateArgsStr; 4535 } 4536 } else { 4537 S += '?'; 4538 } 4539 if (ExpandStructures) { 4540 S += '='; 4541 if (!RDecl->isUnion()) { 4542 getObjCEncodingForStructureImpl(RDecl, S, FD); 4543 } else { 4544 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4545 FieldEnd = RDecl->field_end(); 4546 Field != FieldEnd; ++Field) { 4547 if (FD) { 4548 S += '"'; 4549 S += Field->getNameAsString(); 4550 S += '"'; 4551 } 4552 4553 // Special case bit-fields. 4554 if (Field->isBitField()) { 4555 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 4556 (*Field)); 4557 } else { 4558 QualType qt = Field->getType(); 4559 getLegacyIntegralTypeEncoding(qt); 4560 getObjCEncodingForTypeImpl(qt, S, false, true, 4561 FD, /*OutermostType*/false, 4562 /*EncodingProperty*/false, 4563 /*StructField*/true); 4564 } 4565 } 4566 } 4567 } 4568 S += RDecl->isUnion() ? ')' : '}'; 4569 return; 4570 } 4571 4572 if (const EnumType *ET = T->getAs<EnumType>()) { 4573 if (FD && FD->isBitField()) 4574 EncodeBitField(this, S, T, FD); 4575 else 4576 S += ObjCEncodingForEnumType(this, ET); 4577 return; 4578 } 4579 4580 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 4581 S += "@?"; // Unlike a pointer-to-function, which is "^?". 4582 if (EncodeBlockParameters) { 4583 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>(); 4584 4585 S += '<'; 4586 // Block return type 4587 getObjCEncodingForTypeImpl(FT->getResultType(), S, 4588 ExpandPointedToStructures, ExpandStructures, 4589 FD, 4590 false /* OutermostType */, 4591 EncodingProperty, 4592 false /* StructField */, 4593 EncodeBlockParameters, 4594 EncodeClassNames); 4595 // Block self 4596 S += "@?"; 4597 // Block parameters 4598 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 4599 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 4600 E = FPT->arg_type_end(); I && (I != E); ++I) { 4601 getObjCEncodingForTypeImpl(*I, S, 4602 ExpandPointedToStructures, 4603 ExpandStructures, 4604 FD, 4605 false /* OutermostType */, 4606 EncodingProperty, 4607 false /* StructField */, 4608 EncodeBlockParameters, 4609 EncodeClassNames); 4610 } 4611 } 4612 S += '>'; 4613 } 4614 return; 4615 } 4616 4617 // Ignore protocol qualifiers when mangling at this level. 4618 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 4619 T = OT->getBaseType(); 4620 4621 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4622 // @encode(class_name) 4623 ObjCInterfaceDecl *OI = OIT->getDecl(); 4624 S += '{'; 4625 const IdentifierInfo *II = OI->getIdentifier(); 4626 S += II->getName(); 4627 S += '='; 4628 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4629 DeepCollectObjCIvars(OI, true, Ivars); 4630 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4631 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4632 if (Field->isBitField()) 4633 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4634 else 4635 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4636 } 4637 S += '}'; 4638 return; 4639 } 4640 4641 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4642 if (OPT->isObjCIdType()) { 4643 S += '@'; 4644 return; 4645 } 4646 4647 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4648 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4649 // Since this is a binary compatibility issue, need to consult with runtime 4650 // folks. Fortunately, this is a *very* obsure construct. 4651 S += '#'; 4652 return; 4653 } 4654 4655 if (OPT->isObjCQualifiedIdType()) { 4656 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4657 ExpandPointedToStructures, 4658 ExpandStructures, FD); 4659 if (FD || EncodingProperty || EncodeClassNames) { 4660 // Note that we do extended encoding of protocol qualifer list 4661 // Only when doing ivar or property encoding. 4662 S += '"'; 4663 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4664 E = OPT->qual_end(); I != E; ++I) { 4665 S += '<'; 4666 S += (*I)->getNameAsString(); 4667 S += '>'; 4668 } 4669 S += '"'; 4670 } 4671 return; 4672 } 4673 4674 QualType PointeeTy = OPT->getPointeeType(); 4675 if (!EncodingProperty && 4676 isa<TypedefType>(PointeeTy.getTypePtr())) { 4677 // Another historical/compatibility reason. 4678 // We encode the underlying type which comes out as 4679 // {...}; 4680 S += '^'; 4681 getObjCEncodingForTypeImpl(PointeeTy, S, 4682 false, ExpandPointedToStructures, 4683 NULL); 4684 return; 4685 } 4686 4687 S += '@'; 4688 if (OPT->getInterfaceDecl() && 4689 (FD || EncodingProperty || EncodeClassNames)) { 4690 S += '"'; 4691 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 4692 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4693 E = OPT->qual_end(); I != E; ++I) { 4694 S += '<'; 4695 S += (*I)->getNameAsString(); 4696 S += '>'; 4697 } 4698 S += '"'; 4699 } 4700 return; 4701 } 4702 4703 // gcc just blithely ignores member pointers. 4704 // TODO: maybe there should be a mangling for these 4705 if (T->getAs<MemberPointerType>()) 4706 return; 4707 4708 if (T->isVectorType()) { 4709 // This matches gcc's encoding, even though technically it is 4710 // insufficient. 4711 // FIXME. We should do a better job than gcc. 4712 return; 4713 } 4714 4715 llvm_unreachable("@encode for type not implemented!"); 4716} 4717 4718void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 4719 std::string &S, 4720 const FieldDecl *FD, 4721 bool includeVBases) const { 4722 assert(RDecl && "Expected non-null RecordDecl"); 4723 assert(!RDecl->isUnion() && "Should not be called for unions"); 4724 if (!RDecl->getDefinition()) 4725 return; 4726 4727 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 4728 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 4729 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 4730 4731 if (CXXRec) { 4732 for (CXXRecordDecl::base_class_iterator 4733 BI = CXXRec->bases_begin(), 4734 BE = CXXRec->bases_end(); BI != BE; ++BI) { 4735 if (!BI->isVirtual()) { 4736 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4737 if (base->isEmpty()) 4738 continue; 4739 uint64_t offs = layout.getBaseClassOffsetInBits(base); 4740 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4741 std::make_pair(offs, base)); 4742 } 4743 } 4744 } 4745 4746 unsigned i = 0; 4747 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4748 FieldEnd = RDecl->field_end(); 4749 Field != FieldEnd; ++Field, ++i) { 4750 uint64_t offs = layout.getFieldOffset(i); 4751 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4752 std::make_pair(offs, *Field)); 4753 } 4754 4755 if (CXXRec && includeVBases) { 4756 for (CXXRecordDecl::base_class_iterator 4757 BI = CXXRec->vbases_begin(), 4758 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 4759 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4760 if (base->isEmpty()) 4761 continue; 4762 uint64_t offs = layout.getVBaseClassOffsetInBits(base); 4763 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 4764 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 4765 std::make_pair(offs, base)); 4766 } 4767 } 4768 4769 CharUnits size; 4770 if (CXXRec) { 4771 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 4772 } else { 4773 size = layout.getSize(); 4774 } 4775 4776 uint64_t CurOffs = 0; 4777 std::multimap<uint64_t, NamedDecl *>::iterator 4778 CurLayObj = FieldOrBaseOffsets.begin(); 4779 4780 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) || 4781 (CurLayObj == FieldOrBaseOffsets.end() && 4782 CXXRec && CXXRec->isDynamicClass())) { 4783 assert(CXXRec && CXXRec->isDynamicClass() && 4784 "Offset 0 was empty but no VTable ?"); 4785 if (FD) { 4786 S += "\"_vptr$"; 4787 std::string recname = CXXRec->getNameAsString(); 4788 if (recname.empty()) recname = "?"; 4789 S += recname; 4790 S += '"'; 4791 } 4792 S += "^^?"; 4793 CurOffs += getTypeSize(VoidPtrTy); 4794 } 4795 4796 if (!RDecl->hasFlexibleArrayMember()) { 4797 // Mark the end of the structure. 4798 uint64_t offs = toBits(size); 4799 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4800 std::make_pair(offs, (NamedDecl*)0)); 4801 } 4802 4803 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 4804 assert(CurOffs <= CurLayObj->first); 4805 4806 if (CurOffs < CurLayObj->first) { 4807 uint64_t padding = CurLayObj->first - CurOffs; 4808 // FIXME: There doesn't seem to be a way to indicate in the encoding that 4809 // packing/alignment of members is different that normal, in which case 4810 // the encoding will be out-of-sync with the real layout. 4811 // If the runtime switches to just consider the size of types without 4812 // taking into account alignment, we could make padding explicit in the 4813 // encoding (e.g. using arrays of chars). The encoding strings would be 4814 // longer then though. 4815 CurOffs += padding; 4816 } 4817 4818 NamedDecl *dcl = CurLayObj->second; 4819 if (dcl == 0) 4820 break; // reached end of structure. 4821 4822 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 4823 // We expand the bases without their virtual bases since those are going 4824 // in the initial structure. Note that this differs from gcc which 4825 // expands virtual bases each time one is encountered in the hierarchy, 4826 // making the encoding type bigger than it really is. 4827 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false); 4828 assert(!base->isEmpty()); 4829 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 4830 } else { 4831 FieldDecl *field = cast<FieldDecl>(dcl); 4832 if (FD) { 4833 S += '"'; 4834 S += field->getNameAsString(); 4835 S += '"'; 4836 } 4837 4838 if (field->isBitField()) { 4839 EncodeBitField(this, S, field->getType(), field); 4840 CurOffs += field->getBitWidthValue(*this); 4841 } else { 4842 QualType qt = field->getType(); 4843 getLegacyIntegralTypeEncoding(qt); 4844 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 4845 /*OutermostType*/false, 4846 /*EncodingProperty*/false, 4847 /*StructField*/true); 4848 CurOffs += getTypeSize(field->getType()); 4849 } 4850 } 4851 } 4852} 4853 4854void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 4855 std::string& S) const { 4856 if (QT & Decl::OBJC_TQ_In) 4857 S += 'n'; 4858 if (QT & Decl::OBJC_TQ_Inout) 4859 S += 'N'; 4860 if (QT & Decl::OBJC_TQ_Out) 4861 S += 'o'; 4862 if (QT & Decl::OBJC_TQ_Bycopy) 4863 S += 'O'; 4864 if (QT & Decl::OBJC_TQ_Byref) 4865 S += 'R'; 4866 if (QT & Decl::OBJC_TQ_Oneway) 4867 S += 'V'; 4868} 4869 4870void ASTContext::setBuiltinVaListType(QualType T) { 4871 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 4872 4873 BuiltinVaListType = T; 4874} 4875 4876TypedefDecl *ASTContext::getObjCIdDecl() const { 4877 if (!ObjCIdDecl) { 4878 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0); 4879 T = getObjCObjectPointerType(T); 4880 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T); 4881 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4882 getTranslationUnitDecl(), 4883 SourceLocation(), SourceLocation(), 4884 &Idents.get("id"), IdInfo); 4885 } 4886 4887 return ObjCIdDecl; 4888} 4889 4890TypedefDecl *ASTContext::getObjCSelDecl() const { 4891 if (!ObjCSelDecl) { 4892 QualType SelT = getPointerType(ObjCBuiltinSelTy); 4893 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT); 4894 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4895 getTranslationUnitDecl(), 4896 SourceLocation(), SourceLocation(), 4897 &Idents.get("SEL"), SelInfo); 4898 } 4899 return ObjCSelDecl; 4900} 4901 4902void ASTContext::setObjCProtoType(QualType QT) { 4903 ObjCProtoType = QT; 4904} 4905 4906TypedefDecl *ASTContext::getObjCClassDecl() const { 4907 if (!ObjCClassDecl) { 4908 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0); 4909 T = getObjCObjectPointerType(T); 4910 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T); 4911 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4912 getTranslationUnitDecl(), 4913 SourceLocation(), SourceLocation(), 4914 &Idents.get("Class"), ClassInfo); 4915 } 4916 4917 return ObjCClassDecl; 4918} 4919 4920void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 4921 assert(ObjCConstantStringType.isNull() && 4922 "'NSConstantString' type already set!"); 4923 4924 ObjCConstantStringType = getObjCInterfaceType(Decl); 4925} 4926 4927/// \brief Retrieve the template name that corresponds to a non-empty 4928/// lookup. 4929TemplateName 4930ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 4931 UnresolvedSetIterator End) const { 4932 unsigned size = End - Begin; 4933 assert(size > 1 && "set is not overloaded!"); 4934 4935 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 4936 size * sizeof(FunctionTemplateDecl*)); 4937 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 4938 4939 NamedDecl **Storage = OT->getStorage(); 4940 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 4941 NamedDecl *D = *I; 4942 assert(isa<FunctionTemplateDecl>(D) || 4943 (isa<UsingShadowDecl>(D) && 4944 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 4945 *Storage++ = D; 4946 } 4947 4948 return TemplateName(OT); 4949} 4950 4951/// \brief Retrieve the template name that represents a qualified 4952/// template name such as \c std::vector. 4953TemplateName 4954ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 4955 bool TemplateKeyword, 4956 TemplateDecl *Template) const { 4957 assert(NNS && "Missing nested-name-specifier in qualified template name"); 4958 4959 // FIXME: Canonicalization? 4960 llvm::FoldingSetNodeID ID; 4961 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 4962 4963 void *InsertPos = 0; 4964 QualifiedTemplateName *QTN = 4965 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4966 if (!QTN) { 4967 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 4968 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 4969 } 4970 4971 return TemplateName(QTN); 4972} 4973 4974/// \brief Retrieve the template name that represents a dependent 4975/// template name such as \c MetaFun::template apply. 4976TemplateName 4977ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4978 const IdentifierInfo *Name) const { 4979 assert((!NNS || NNS->isDependent()) && 4980 "Nested name specifier must be dependent"); 4981 4982 llvm::FoldingSetNodeID ID; 4983 DependentTemplateName::Profile(ID, NNS, Name); 4984 4985 void *InsertPos = 0; 4986 DependentTemplateName *QTN = 4987 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4988 4989 if (QTN) 4990 return TemplateName(QTN); 4991 4992 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4993 if (CanonNNS == NNS) { 4994 QTN = new (*this,4) DependentTemplateName(NNS, Name); 4995 } else { 4996 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 4997 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 4998 DependentTemplateName *CheckQTN = 4999 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5000 assert(!CheckQTN && "Dependent type name canonicalization broken"); 5001 (void)CheckQTN; 5002 } 5003 5004 DependentTemplateNames.InsertNode(QTN, InsertPos); 5005 return TemplateName(QTN); 5006} 5007 5008/// \brief Retrieve the template name that represents a dependent 5009/// template name such as \c MetaFun::template operator+. 5010TemplateName 5011ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5012 OverloadedOperatorKind Operator) const { 5013 assert((!NNS || NNS->isDependent()) && 5014 "Nested name specifier must be dependent"); 5015 5016 llvm::FoldingSetNodeID ID; 5017 DependentTemplateName::Profile(ID, NNS, Operator); 5018 5019 void *InsertPos = 0; 5020 DependentTemplateName *QTN 5021 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5022 5023 if (QTN) 5024 return TemplateName(QTN); 5025 5026 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5027 if (CanonNNS == NNS) { 5028 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 5029 } else { 5030 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 5031 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 5032 5033 DependentTemplateName *CheckQTN 5034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5035 assert(!CheckQTN && "Dependent template name canonicalization broken"); 5036 (void)CheckQTN; 5037 } 5038 5039 DependentTemplateNames.InsertNode(QTN, InsertPos); 5040 return TemplateName(QTN); 5041} 5042 5043TemplateName 5044ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 5045 TemplateName replacement) const { 5046 llvm::FoldingSetNodeID ID; 5047 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 5048 5049 void *insertPos = 0; 5050 SubstTemplateTemplateParmStorage *subst 5051 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 5052 5053 if (!subst) { 5054 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 5055 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 5056 } 5057 5058 return TemplateName(subst); 5059} 5060 5061TemplateName 5062ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 5063 const TemplateArgument &ArgPack) const { 5064 ASTContext &Self = const_cast<ASTContext &>(*this); 5065 llvm::FoldingSetNodeID ID; 5066 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 5067 5068 void *InsertPos = 0; 5069 SubstTemplateTemplateParmPackStorage *Subst 5070 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 5071 5072 if (!Subst) { 5073 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 5074 ArgPack.pack_size(), 5075 ArgPack.pack_begin()); 5076 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 5077 } 5078 5079 return TemplateName(Subst); 5080} 5081 5082/// getFromTargetType - Given one of the integer types provided by 5083/// TargetInfo, produce the corresponding type. The unsigned @p Type 5084/// is actually a value of type @c TargetInfo::IntType. 5085CanQualType ASTContext::getFromTargetType(unsigned Type) const { 5086 switch (Type) { 5087 case TargetInfo::NoInt: return CanQualType(); 5088 case TargetInfo::SignedShort: return ShortTy; 5089 case TargetInfo::UnsignedShort: return UnsignedShortTy; 5090 case TargetInfo::SignedInt: return IntTy; 5091 case TargetInfo::UnsignedInt: return UnsignedIntTy; 5092 case TargetInfo::SignedLong: return LongTy; 5093 case TargetInfo::UnsignedLong: return UnsignedLongTy; 5094 case TargetInfo::SignedLongLong: return LongLongTy; 5095 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 5096 } 5097 5098 llvm_unreachable("Unhandled TargetInfo::IntType value"); 5099} 5100 5101//===----------------------------------------------------------------------===// 5102// Type Predicates. 5103//===----------------------------------------------------------------------===// 5104 5105/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 5106/// garbage collection attribute. 5107/// 5108Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 5109 if (getLangOptions().getGC() == LangOptions::NonGC) 5110 return Qualifiers::GCNone; 5111 5112 assert(getLangOptions().ObjC1); 5113 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 5114 5115 // Default behaviour under objective-C's gc is for ObjC pointers 5116 // (or pointers to them) be treated as though they were declared 5117 // as __strong. 5118 if (GCAttrs == Qualifiers::GCNone) { 5119 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 5120 return Qualifiers::Strong; 5121 else if (Ty->isPointerType()) 5122 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 5123 } else { 5124 // It's not valid to set GC attributes on anything that isn't a 5125 // pointer. 5126#ifndef NDEBUG 5127 QualType CT = Ty->getCanonicalTypeInternal(); 5128 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 5129 CT = AT->getElementType(); 5130 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 5131#endif 5132 } 5133 return GCAttrs; 5134} 5135 5136//===----------------------------------------------------------------------===// 5137// Type Compatibility Testing 5138//===----------------------------------------------------------------------===// 5139 5140/// areCompatVectorTypes - Return true if the two specified vector types are 5141/// compatible. 5142static bool areCompatVectorTypes(const VectorType *LHS, 5143 const VectorType *RHS) { 5144 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 5145 return LHS->getElementType() == RHS->getElementType() && 5146 LHS->getNumElements() == RHS->getNumElements(); 5147} 5148 5149bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 5150 QualType SecondVec) { 5151 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 5152 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 5153 5154 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 5155 return true; 5156 5157 // Treat Neon vector types and most AltiVec vector types as if they are the 5158 // equivalent GCC vector types. 5159 const VectorType *First = FirstVec->getAs<VectorType>(); 5160 const VectorType *Second = SecondVec->getAs<VectorType>(); 5161 if (First->getNumElements() == Second->getNumElements() && 5162 hasSameType(First->getElementType(), Second->getElementType()) && 5163 First->getVectorKind() != VectorType::AltiVecPixel && 5164 First->getVectorKind() != VectorType::AltiVecBool && 5165 Second->getVectorKind() != VectorType::AltiVecPixel && 5166 Second->getVectorKind() != VectorType::AltiVecBool) 5167 return true; 5168 5169 return false; 5170} 5171 5172//===----------------------------------------------------------------------===// 5173// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 5174//===----------------------------------------------------------------------===// 5175 5176/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 5177/// inheritance hierarchy of 'rProto'. 5178bool 5179ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 5180 ObjCProtocolDecl *rProto) const { 5181 if (lProto == rProto) 5182 return true; 5183 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 5184 E = rProto->protocol_end(); PI != E; ++PI) 5185 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 5186 return true; 5187 return false; 5188} 5189 5190/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 5191/// return true if lhs's protocols conform to rhs's protocol; false 5192/// otherwise. 5193bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 5194 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 5195 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 5196 return false; 5197} 5198 5199/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 5200/// Class<p1, ...>. 5201bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 5202 QualType rhs) { 5203 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 5204 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5205 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 5206 5207 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5208 E = lhsQID->qual_end(); I != E; ++I) { 5209 bool match = false; 5210 ObjCProtocolDecl *lhsProto = *I; 5211 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5212 E = rhsOPT->qual_end(); J != E; ++J) { 5213 ObjCProtocolDecl *rhsProto = *J; 5214 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 5215 match = true; 5216 break; 5217 } 5218 } 5219 if (!match) 5220 return false; 5221 } 5222 return true; 5223} 5224 5225/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 5226/// ObjCQualifiedIDType. 5227bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 5228 bool compare) { 5229 // Allow id<P..> and an 'id' or void* type in all cases. 5230 if (lhs->isVoidPointerType() || 5231 lhs->isObjCIdType() || lhs->isObjCClassType()) 5232 return true; 5233 else if (rhs->isVoidPointerType() || 5234 rhs->isObjCIdType() || rhs->isObjCClassType()) 5235 return true; 5236 5237 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 5238 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5239 5240 if (!rhsOPT) return false; 5241 5242 if (rhsOPT->qual_empty()) { 5243 // If the RHS is a unqualified interface pointer "NSString*", 5244 // make sure we check the class hierarchy. 5245 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5246 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5247 E = lhsQID->qual_end(); I != E; ++I) { 5248 // when comparing an id<P> on lhs with a static type on rhs, 5249 // see if static class implements all of id's protocols, directly or 5250 // through its super class and categories. 5251 if (!rhsID->ClassImplementsProtocol(*I, true)) 5252 return false; 5253 } 5254 } 5255 // If there are no qualifiers and no interface, we have an 'id'. 5256 return true; 5257 } 5258 // Both the right and left sides have qualifiers. 5259 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5260 E = lhsQID->qual_end(); I != E; ++I) { 5261 ObjCProtocolDecl *lhsProto = *I; 5262 bool match = false; 5263 5264 // when comparing an id<P> on lhs with a static type on rhs, 5265 // see if static class implements all of id's protocols, directly or 5266 // through its super class and categories. 5267 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5268 E = rhsOPT->qual_end(); J != E; ++J) { 5269 ObjCProtocolDecl *rhsProto = *J; 5270 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5271 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5272 match = true; 5273 break; 5274 } 5275 } 5276 // If the RHS is a qualified interface pointer "NSString<P>*", 5277 // make sure we check the class hierarchy. 5278 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5279 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5280 E = lhsQID->qual_end(); I != E; ++I) { 5281 // when comparing an id<P> on lhs with a static type on rhs, 5282 // see if static class implements all of id's protocols, directly or 5283 // through its super class and categories. 5284 if (rhsID->ClassImplementsProtocol(*I, true)) { 5285 match = true; 5286 break; 5287 } 5288 } 5289 } 5290 if (!match) 5291 return false; 5292 } 5293 5294 return true; 5295 } 5296 5297 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 5298 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 5299 5300 if (const ObjCObjectPointerType *lhsOPT = 5301 lhs->getAsObjCInterfacePointerType()) { 5302 // If both the right and left sides have qualifiers. 5303 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 5304 E = lhsOPT->qual_end(); I != E; ++I) { 5305 ObjCProtocolDecl *lhsProto = *I; 5306 bool match = false; 5307 5308 // when comparing an id<P> on rhs with a static type on lhs, 5309 // see if static class implements all of id's protocols, directly or 5310 // through its super class and categories. 5311 // First, lhs protocols in the qualifier list must be found, direct 5312 // or indirect in rhs's qualifier list or it is a mismatch. 5313 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5314 E = rhsQID->qual_end(); J != E; ++J) { 5315 ObjCProtocolDecl *rhsProto = *J; 5316 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5317 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5318 match = true; 5319 break; 5320 } 5321 } 5322 if (!match) 5323 return false; 5324 } 5325 5326 // Static class's protocols, or its super class or category protocols 5327 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 5328 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 5329 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5330 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 5331 // This is rather dubious but matches gcc's behavior. If lhs has 5332 // no type qualifier and its class has no static protocol(s) 5333 // assume that it is mismatch. 5334 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 5335 return false; 5336 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5337 LHSInheritedProtocols.begin(), 5338 E = LHSInheritedProtocols.end(); I != E; ++I) { 5339 bool match = false; 5340 ObjCProtocolDecl *lhsProto = (*I); 5341 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5342 E = rhsQID->qual_end(); J != E; ++J) { 5343 ObjCProtocolDecl *rhsProto = *J; 5344 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5345 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5346 match = true; 5347 break; 5348 } 5349 } 5350 if (!match) 5351 return false; 5352 } 5353 } 5354 return true; 5355 } 5356 return false; 5357} 5358 5359/// canAssignObjCInterfaces - Return true if the two interface types are 5360/// compatible for assignment from RHS to LHS. This handles validation of any 5361/// protocol qualifiers on the LHS or RHS. 5362/// 5363bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 5364 const ObjCObjectPointerType *RHSOPT) { 5365 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5366 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5367 5368 // If either type represents the built-in 'id' or 'Class' types, return true. 5369 if (LHS->isObjCUnqualifiedIdOrClass() || 5370 RHS->isObjCUnqualifiedIdOrClass()) 5371 return true; 5372 5373 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 5374 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5375 QualType(RHSOPT,0), 5376 false); 5377 5378 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 5379 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 5380 QualType(RHSOPT,0)); 5381 5382 // If we have 2 user-defined types, fall into that path. 5383 if (LHS->getInterface() && RHS->getInterface()) 5384 return canAssignObjCInterfaces(LHS, RHS); 5385 5386 return false; 5387} 5388 5389/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 5390/// for providing type-safety for objective-c pointers used to pass/return 5391/// arguments in block literals. When passed as arguments, passing 'A*' where 5392/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 5393/// not OK. For the return type, the opposite is not OK. 5394bool ASTContext::canAssignObjCInterfacesInBlockPointer( 5395 const ObjCObjectPointerType *LHSOPT, 5396 const ObjCObjectPointerType *RHSOPT, 5397 bool BlockReturnType) { 5398 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 5399 return true; 5400 5401 if (LHSOPT->isObjCBuiltinType()) { 5402 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 5403 } 5404 5405 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 5406 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5407 QualType(RHSOPT,0), 5408 false); 5409 5410 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 5411 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 5412 if (LHS && RHS) { // We have 2 user-defined types. 5413 if (LHS != RHS) { 5414 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 5415 return BlockReturnType; 5416 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 5417 return !BlockReturnType; 5418 } 5419 else 5420 return true; 5421 } 5422 return false; 5423} 5424 5425/// getIntersectionOfProtocols - This routine finds the intersection of set 5426/// of protocols inherited from two distinct objective-c pointer objects. 5427/// It is used to build composite qualifier list of the composite type of 5428/// the conditional expression involving two objective-c pointer objects. 5429static 5430void getIntersectionOfProtocols(ASTContext &Context, 5431 const ObjCObjectPointerType *LHSOPT, 5432 const ObjCObjectPointerType *RHSOPT, 5433 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 5434 5435 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5436 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5437 assert(LHS->getInterface() && "LHS must have an interface base"); 5438 assert(RHS->getInterface() && "RHS must have an interface base"); 5439 5440 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 5441 unsigned LHSNumProtocols = LHS->getNumProtocols(); 5442 if (LHSNumProtocols > 0) 5443 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 5444 else { 5445 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5446 Context.CollectInheritedProtocols(LHS->getInterface(), 5447 LHSInheritedProtocols); 5448 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 5449 LHSInheritedProtocols.end()); 5450 } 5451 5452 unsigned RHSNumProtocols = RHS->getNumProtocols(); 5453 if (RHSNumProtocols > 0) { 5454 ObjCProtocolDecl **RHSProtocols = 5455 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 5456 for (unsigned i = 0; i < RHSNumProtocols; ++i) 5457 if (InheritedProtocolSet.count(RHSProtocols[i])) 5458 IntersectionOfProtocols.push_back(RHSProtocols[i]); 5459 } else { 5460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 5461 Context.CollectInheritedProtocols(RHS->getInterface(), 5462 RHSInheritedProtocols); 5463 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5464 RHSInheritedProtocols.begin(), 5465 E = RHSInheritedProtocols.end(); I != E; ++I) 5466 if (InheritedProtocolSet.count((*I))) 5467 IntersectionOfProtocols.push_back((*I)); 5468 } 5469} 5470 5471/// areCommonBaseCompatible - Returns common base class of the two classes if 5472/// one found. Note that this is O'2 algorithm. But it will be called as the 5473/// last type comparison in a ?-exp of ObjC pointer types before a 5474/// warning is issued. So, its invokation is extremely rare. 5475QualType ASTContext::areCommonBaseCompatible( 5476 const ObjCObjectPointerType *Lptr, 5477 const ObjCObjectPointerType *Rptr) { 5478 const ObjCObjectType *LHS = Lptr->getObjectType(); 5479 const ObjCObjectType *RHS = Rptr->getObjectType(); 5480 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 5481 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 5482 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 5483 return QualType(); 5484 5485 do { 5486 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 5487 if (canAssignObjCInterfaces(LHS, RHS)) { 5488 SmallVector<ObjCProtocolDecl *, 8> Protocols; 5489 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 5490 5491 QualType Result = QualType(LHS, 0); 5492 if (!Protocols.empty()) 5493 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 5494 Result = getObjCObjectPointerType(Result); 5495 return Result; 5496 } 5497 } while ((LDecl = LDecl->getSuperClass())); 5498 5499 return QualType(); 5500} 5501 5502bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 5503 const ObjCObjectType *RHS) { 5504 assert(LHS->getInterface() && "LHS is not an interface type"); 5505 assert(RHS->getInterface() && "RHS is not an interface type"); 5506 5507 // Verify that the base decls are compatible: the RHS must be a subclass of 5508 // the LHS. 5509 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 5510 return false; 5511 5512 // RHS must have a superset of the protocols in the LHS. If the LHS is not 5513 // protocol qualified at all, then we are good. 5514 if (LHS->getNumProtocols() == 0) 5515 return true; 5516 5517 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 5518 // more detailed analysis is required. 5519 if (RHS->getNumProtocols() == 0) { 5520 // OK, if LHS is a superclass of RHS *and* 5521 // this superclass is assignment compatible with LHS. 5522 // false otherwise. 5523 bool IsSuperClass = 5524 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 5525 if (IsSuperClass) { 5526 // OK if conversion of LHS to SuperClass results in narrowing of types 5527 // ; i.e., SuperClass may implement at least one of the protocols 5528 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 5529 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 5530 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 5531 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 5532 // If super class has no protocols, it is not a match. 5533 if (SuperClassInheritedProtocols.empty()) 5534 return false; 5535 5536 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5537 LHSPE = LHS->qual_end(); 5538 LHSPI != LHSPE; LHSPI++) { 5539 bool SuperImplementsProtocol = false; 5540 ObjCProtocolDecl *LHSProto = (*LHSPI); 5541 5542 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5543 SuperClassInheritedProtocols.begin(), 5544 E = SuperClassInheritedProtocols.end(); I != E; ++I) { 5545 ObjCProtocolDecl *SuperClassProto = (*I); 5546 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 5547 SuperImplementsProtocol = true; 5548 break; 5549 } 5550 } 5551 if (!SuperImplementsProtocol) 5552 return false; 5553 } 5554 return true; 5555 } 5556 return false; 5557 } 5558 5559 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5560 LHSPE = LHS->qual_end(); 5561 LHSPI != LHSPE; LHSPI++) { 5562 bool RHSImplementsProtocol = false; 5563 5564 // If the RHS doesn't implement the protocol on the left, the types 5565 // are incompatible. 5566 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 5567 RHSPE = RHS->qual_end(); 5568 RHSPI != RHSPE; RHSPI++) { 5569 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 5570 RHSImplementsProtocol = true; 5571 break; 5572 } 5573 } 5574 // FIXME: For better diagnostics, consider passing back the protocol name. 5575 if (!RHSImplementsProtocol) 5576 return false; 5577 } 5578 // The RHS implements all protocols listed on the LHS. 5579 return true; 5580} 5581 5582bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 5583 // get the "pointed to" types 5584 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 5585 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 5586 5587 if (!LHSOPT || !RHSOPT) 5588 return false; 5589 5590 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 5591 canAssignObjCInterfaces(RHSOPT, LHSOPT); 5592} 5593 5594bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 5595 return canAssignObjCInterfaces( 5596 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 5597 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 5598} 5599 5600/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 5601/// both shall have the identically qualified version of a compatible type. 5602/// C99 6.2.7p1: Two types have compatible types if their types are the 5603/// same. See 6.7.[2,3,5] for additional rules. 5604bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 5605 bool CompareUnqualified) { 5606 if (getLangOptions().CPlusPlus) 5607 return hasSameType(LHS, RHS); 5608 5609 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 5610} 5611 5612bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 5613 return typesAreCompatible(LHS, RHS); 5614} 5615 5616bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 5617 return !mergeTypes(LHS, RHS, true).isNull(); 5618} 5619 5620/// mergeTransparentUnionType - if T is a transparent union type and a member 5621/// of T is compatible with SubType, return the merged type, else return 5622/// QualType() 5623QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 5624 bool OfBlockPointer, 5625 bool Unqualified) { 5626 if (const RecordType *UT = T->getAsUnionType()) { 5627 RecordDecl *UD = UT->getDecl(); 5628 if (UD->hasAttr<TransparentUnionAttr>()) { 5629 for (RecordDecl::field_iterator it = UD->field_begin(), 5630 itend = UD->field_end(); it != itend; ++it) { 5631 QualType ET = it->getType().getUnqualifiedType(); 5632 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 5633 if (!MT.isNull()) 5634 return MT; 5635 } 5636 } 5637 } 5638 5639 return QualType(); 5640} 5641 5642/// mergeFunctionArgumentTypes - merge two types which appear as function 5643/// argument types 5644QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 5645 bool OfBlockPointer, 5646 bool Unqualified) { 5647 // GNU extension: two types are compatible if they appear as a function 5648 // argument, one of the types is a transparent union type and the other 5649 // type is compatible with a union member 5650 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 5651 Unqualified); 5652 if (!lmerge.isNull()) 5653 return lmerge; 5654 5655 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 5656 Unqualified); 5657 if (!rmerge.isNull()) 5658 return rmerge; 5659 5660 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 5661} 5662 5663QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 5664 bool OfBlockPointer, 5665 bool Unqualified) { 5666 const FunctionType *lbase = lhs->getAs<FunctionType>(); 5667 const FunctionType *rbase = rhs->getAs<FunctionType>(); 5668 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 5669 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 5670 bool allLTypes = true; 5671 bool allRTypes = true; 5672 5673 // Check return type 5674 QualType retType; 5675 if (OfBlockPointer) { 5676 QualType RHS = rbase->getResultType(); 5677 QualType LHS = lbase->getResultType(); 5678 bool UnqualifiedResult = Unqualified; 5679 if (!UnqualifiedResult) 5680 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 5681 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 5682 } 5683 else 5684 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false, 5685 Unqualified); 5686 if (retType.isNull()) return QualType(); 5687 5688 if (Unqualified) 5689 retType = retType.getUnqualifiedType(); 5690 5691 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 5692 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 5693 if (Unqualified) { 5694 LRetType = LRetType.getUnqualifiedType(); 5695 RRetType = RRetType.getUnqualifiedType(); 5696 } 5697 5698 if (getCanonicalType(retType) != LRetType) 5699 allLTypes = false; 5700 if (getCanonicalType(retType) != RRetType) 5701 allRTypes = false; 5702 5703 // FIXME: double check this 5704 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 5705 // rbase->getRegParmAttr() != 0 && 5706 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 5707 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 5708 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 5709 5710 // Compatible functions must have compatible calling conventions 5711 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC())) 5712 return QualType(); 5713 5714 // Regparm is part of the calling convention. 5715 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 5716 return QualType(); 5717 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 5718 return QualType(); 5719 5720 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 5721 return QualType(); 5722 5723 // functypes which return are preferred over those that do not. 5724 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn()) 5725 allLTypes = false; 5726 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()) 5727 allRTypes = false; 5728 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 5729 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 5730 5731 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 5732 5733 if (lproto && rproto) { // two C99 style function prototypes 5734 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 5735 "C++ shouldn't be here"); 5736 unsigned lproto_nargs = lproto->getNumArgs(); 5737 unsigned rproto_nargs = rproto->getNumArgs(); 5738 5739 // Compatible functions must have the same number of arguments 5740 if (lproto_nargs != rproto_nargs) 5741 return QualType(); 5742 5743 // Variadic and non-variadic functions aren't compatible 5744 if (lproto->isVariadic() != rproto->isVariadic()) 5745 return QualType(); 5746 5747 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 5748 return QualType(); 5749 5750 if (LangOpts.ObjCAutoRefCount && 5751 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 5752 return QualType(); 5753 5754 // Check argument compatibility 5755 SmallVector<QualType, 10> types; 5756 for (unsigned i = 0; i < lproto_nargs; i++) { 5757 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 5758 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 5759 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 5760 OfBlockPointer, 5761 Unqualified); 5762 if (argtype.isNull()) return QualType(); 5763 5764 if (Unqualified) 5765 argtype = argtype.getUnqualifiedType(); 5766 5767 types.push_back(argtype); 5768 if (Unqualified) { 5769 largtype = largtype.getUnqualifiedType(); 5770 rargtype = rargtype.getUnqualifiedType(); 5771 } 5772 5773 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 5774 allLTypes = false; 5775 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 5776 allRTypes = false; 5777 } 5778 5779 if (allLTypes) return lhs; 5780 if (allRTypes) return rhs; 5781 5782 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 5783 EPI.ExtInfo = einfo; 5784 return getFunctionType(retType, types.begin(), types.size(), EPI); 5785 } 5786 5787 if (lproto) allRTypes = false; 5788 if (rproto) allLTypes = false; 5789 5790 const FunctionProtoType *proto = lproto ? lproto : rproto; 5791 if (proto) { 5792 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 5793 if (proto->isVariadic()) return QualType(); 5794 // Check that the types are compatible with the types that 5795 // would result from default argument promotions (C99 6.7.5.3p15). 5796 // The only types actually affected are promotable integer 5797 // types and floats, which would be passed as a different 5798 // type depending on whether the prototype is visible. 5799 unsigned proto_nargs = proto->getNumArgs(); 5800 for (unsigned i = 0; i < proto_nargs; ++i) { 5801 QualType argTy = proto->getArgType(i); 5802 5803 // Look at the promotion type of enum types, since that is the type used 5804 // to pass enum values. 5805 if (const EnumType *Enum = argTy->getAs<EnumType>()) 5806 argTy = Enum->getDecl()->getPromotionType(); 5807 5808 if (argTy->isPromotableIntegerType() || 5809 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 5810 return QualType(); 5811 } 5812 5813 if (allLTypes) return lhs; 5814 if (allRTypes) return rhs; 5815 5816 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 5817 EPI.ExtInfo = einfo; 5818 return getFunctionType(retType, proto->arg_type_begin(), 5819 proto->getNumArgs(), EPI); 5820 } 5821 5822 if (allLTypes) return lhs; 5823 if (allRTypes) return rhs; 5824 return getFunctionNoProtoType(retType, einfo); 5825} 5826 5827QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 5828 bool OfBlockPointer, 5829 bool Unqualified, bool BlockReturnType) { 5830 // C++ [expr]: If an expression initially has the type "reference to T", the 5831 // type is adjusted to "T" prior to any further analysis, the expression 5832 // designates the object or function denoted by the reference, and the 5833 // expression is an lvalue unless the reference is an rvalue reference and 5834 // the expression is a function call (possibly inside parentheses). 5835 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 5836 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 5837 5838 if (Unqualified) { 5839 LHS = LHS.getUnqualifiedType(); 5840 RHS = RHS.getUnqualifiedType(); 5841 } 5842 5843 QualType LHSCan = getCanonicalType(LHS), 5844 RHSCan = getCanonicalType(RHS); 5845 5846 // If two types are identical, they are compatible. 5847 if (LHSCan == RHSCan) 5848 return LHS; 5849 5850 // If the qualifiers are different, the types aren't compatible... mostly. 5851 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 5852 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 5853 if (LQuals != RQuals) { 5854 // If any of these qualifiers are different, we have a type 5855 // mismatch. 5856 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 5857 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 5858 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 5859 return QualType(); 5860 5861 // Exactly one GC qualifier difference is allowed: __strong is 5862 // okay if the other type has no GC qualifier but is an Objective 5863 // C object pointer (i.e. implicitly strong by default). We fix 5864 // this by pretending that the unqualified type was actually 5865 // qualified __strong. 5866 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 5867 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 5868 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 5869 5870 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 5871 return QualType(); 5872 5873 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 5874 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 5875 } 5876 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 5877 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 5878 } 5879 return QualType(); 5880 } 5881 5882 // Okay, qualifiers are equal. 5883 5884 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 5885 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 5886 5887 // We want to consider the two function types to be the same for these 5888 // comparisons, just force one to the other. 5889 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 5890 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 5891 5892 // Same as above for arrays 5893 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 5894 LHSClass = Type::ConstantArray; 5895 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 5896 RHSClass = Type::ConstantArray; 5897 5898 // ObjCInterfaces are just specialized ObjCObjects. 5899 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 5900 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 5901 5902 // Canonicalize ExtVector -> Vector. 5903 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 5904 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 5905 5906 // If the canonical type classes don't match. 5907 if (LHSClass != RHSClass) { 5908 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 5909 // a signed integer type, or an unsigned integer type. 5910 // Compatibility is based on the underlying type, not the promotion 5911 // type. 5912 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 5913 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 5914 return RHS; 5915 } 5916 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 5917 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 5918 return LHS; 5919 } 5920 5921 return QualType(); 5922 } 5923 5924 // The canonical type classes match. 5925 switch (LHSClass) { 5926#define TYPE(Class, Base) 5927#define ABSTRACT_TYPE(Class, Base) 5928#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 5929#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 5930#define DEPENDENT_TYPE(Class, Base) case Type::Class: 5931#include "clang/AST/TypeNodes.def" 5932 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 5933 5934 case Type::LValueReference: 5935 case Type::RValueReference: 5936 case Type::MemberPointer: 5937 llvm_unreachable("C++ should never be in mergeTypes"); 5938 5939 case Type::ObjCInterface: 5940 case Type::IncompleteArray: 5941 case Type::VariableArray: 5942 case Type::FunctionProto: 5943 case Type::ExtVector: 5944 llvm_unreachable("Types are eliminated above"); 5945 5946 case Type::Pointer: 5947 { 5948 // Merge two pointer types, while trying to preserve typedef info 5949 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 5950 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 5951 if (Unqualified) { 5952 LHSPointee = LHSPointee.getUnqualifiedType(); 5953 RHSPointee = RHSPointee.getUnqualifiedType(); 5954 } 5955 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 5956 Unqualified); 5957 if (ResultType.isNull()) return QualType(); 5958 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 5959 return LHS; 5960 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 5961 return RHS; 5962 return getPointerType(ResultType); 5963 } 5964 case Type::BlockPointer: 5965 { 5966 // Merge two block pointer types, while trying to preserve typedef info 5967 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 5968 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 5969 if (Unqualified) { 5970 LHSPointee = LHSPointee.getUnqualifiedType(); 5971 RHSPointee = RHSPointee.getUnqualifiedType(); 5972 } 5973 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 5974 Unqualified); 5975 if (ResultType.isNull()) return QualType(); 5976 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 5977 return LHS; 5978 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 5979 return RHS; 5980 return getBlockPointerType(ResultType); 5981 } 5982 case Type::Atomic: 5983 { 5984 // Merge two pointer types, while trying to preserve typedef info 5985 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 5986 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 5987 if (Unqualified) { 5988 LHSValue = LHSValue.getUnqualifiedType(); 5989 RHSValue = RHSValue.getUnqualifiedType(); 5990 } 5991 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 5992 Unqualified); 5993 if (ResultType.isNull()) return QualType(); 5994 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 5995 return LHS; 5996 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 5997 return RHS; 5998 return getAtomicType(ResultType); 5999 } 6000 case Type::ConstantArray: 6001 { 6002 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 6003 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 6004 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 6005 return QualType(); 6006 6007 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 6008 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 6009 if (Unqualified) { 6010 LHSElem = LHSElem.getUnqualifiedType(); 6011 RHSElem = RHSElem.getUnqualifiedType(); 6012 } 6013 6014 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 6015 if (ResultType.isNull()) return QualType(); 6016 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6017 return LHS; 6018 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6019 return RHS; 6020 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 6021 ArrayType::ArraySizeModifier(), 0); 6022 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 6023 ArrayType::ArraySizeModifier(), 0); 6024 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 6025 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 6026 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6027 return LHS; 6028 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6029 return RHS; 6030 if (LVAT) { 6031 // FIXME: This isn't correct! But tricky to implement because 6032 // the array's size has to be the size of LHS, but the type 6033 // has to be different. 6034 return LHS; 6035 } 6036 if (RVAT) { 6037 // FIXME: This isn't correct! But tricky to implement because 6038 // the array's size has to be the size of RHS, but the type 6039 // has to be different. 6040 return RHS; 6041 } 6042 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 6043 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 6044 return getIncompleteArrayType(ResultType, 6045 ArrayType::ArraySizeModifier(), 0); 6046 } 6047 case Type::FunctionNoProto: 6048 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 6049 case Type::Record: 6050 case Type::Enum: 6051 return QualType(); 6052 case Type::Builtin: 6053 // Only exactly equal builtin types are compatible, which is tested above. 6054 return QualType(); 6055 case Type::Complex: 6056 // Distinct complex types are incompatible. 6057 return QualType(); 6058 case Type::Vector: 6059 // FIXME: The merged type should be an ExtVector! 6060 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 6061 RHSCan->getAs<VectorType>())) 6062 return LHS; 6063 return QualType(); 6064 case Type::ObjCObject: { 6065 // Check if the types are assignment compatible. 6066 // FIXME: This should be type compatibility, e.g. whether 6067 // "LHS x; RHS x;" at global scope is legal. 6068 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 6069 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 6070 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 6071 return LHS; 6072 6073 return QualType(); 6074 } 6075 case Type::ObjCObjectPointer: { 6076 if (OfBlockPointer) { 6077 if (canAssignObjCInterfacesInBlockPointer( 6078 LHS->getAs<ObjCObjectPointerType>(), 6079 RHS->getAs<ObjCObjectPointerType>(), 6080 BlockReturnType)) 6081 return LHS; 6082 return QualType(); 6083 } 6084 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 6085 RHS->getAs<ObjCObjectPointerType>())) 6086 return LHS; 6087 6088 return QualType(); 6089 } 6090 } 6091 6092 return QualType(); 6093} 6094 6095bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 6096 const FunctionProtoType *FromFunctionType, 6097 const FunctionProtoType *ToFunctionType) { 6098 if (FromFunctionType->hasAnyConsumedArgs() != 6099 ToFunctionType->hasAnyConsumedArgs()) 6100 return false; 6101 FunctionProtoType::ExtProtoInfo FromEPI = 6102 FromFunctionType->getExtProtoInfo(); 6103 FunctionProtoType::ExtProtoInfo ToEPI = 6104 ToFunctionType->getExtProtoInfo(); 6105 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments) 6106 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 6107 ArgIdx != NumArgs; ++ArgIdx) { 6108 if (FromEPI.ConsumedArguments[ArgIdx] != 6109 ToEPI.ConsumedArguments[ArgIdx]) 6110 return false; 6111 } 6112 return true; 6113} 6114 6115/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 6116/// 'RHS' attributes and returns the merged version; including for function 6117/// return types. 6118QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 6119 QualType LHSCan = getCanonicalType(LHS), 6120 RHSCan = getCanonicalType(RHS); 6121 // If two types are identical, they are compatible. 6122 if (LHSCan == RHSCan) 6123 return LHS; 6124 if (RHSCan->isFunctionType()) { 6125 if (!LHSCan->isFunctionType()) 6126 return QualType(); 6127 QualType OldReturnType = 6128 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 6129 QualType NewReturnType = 6130 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 6131 QualType ResReturnType = 6132 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 6133 if (ResReturnType.isNull()) 6134 return QualType(); 6135 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 6136 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 6137 // In either case, use OldReturnType to build the new function type. 6138 const FunctionType *F = LHS->getAs<FunctionType>(); 6139 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 6140 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6141 EPI.ExtInfo = getFunctionExtInfo(LHS); 6142 QualType ResultType 6143 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 6144 FPT->getNumArgs(), EPI); 6145 return ResultType; 6146 } 6147 } 6148 return QualType(); 6149 } 6150 6151 // If the qualifiers are different, the types can still be merged. 6152 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6153 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6154 if (LQuals != RQuals) { 6155 // If any of these qualifiers are different, we have a type mismatch. 6156 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6157 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 6158 return QualType(); 6159 6160 // Exactly one GC qualifier difference is allowed: __strong is 6161 // okay if the other type has no GC qualifier but is an Objective 6162 // C object pointer (i.e. implicitly strong by default). We fix 6163 // this by pretending that the unqualified type was actually 6164 // qualified __strong. 6165 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6166 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6167 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6168 6169 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6170 return QualType(); 6171 6172 if (GC_L == Qualifiers::Strong) 6173 return LHS; 6174 if (GC_R == Qualifiers::Strong) 6175 return RHS; 6176 return QualType(); 6177 } 6178 6179 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 6180 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6181 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6182 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 6183 if (ResQT == LHSBaseQT) 6184 return LHS; 6185 if (ResQT == RHSBaseQT) 6186 return RHS; 6187 } 6188 return QualType(); 6189} 6190 6191//===----------------------------------------------------------------------===// 6192// Integer Predicates 6193//===----------------------------------------------------------------------===// 6194 6195unsigned ASTContext::getIntWidth(QualType T) const { 6196 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6197 T = ET->getDecl()->getIntegerType(); 6198 if (T->isBooleanType()) 6199 return 1; 6200 // For builtin types, just use the standard type sizing method 6201 return (unsigned)getTypeSize(T); 6202} 6203 6204QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 6205 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 6206 6207 // Turn <4 x signed int> -> <4 x unsigned int> 6208 if (const VectorType *VTy = T->getAs<VectorType>()) 6209 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 6210 VTy->getNumElements(), VTy->getVectorKind()); 6211 6212 // For enums, we return the unsigned version of the base type. 6213 if (const EnumType *ETy = T->getAs<EnumType>()) 6214 T = ETy->getDecl()->getIntegerType(); 6215 6216 const BuiltinType *BTy = T->getAs<BuiltinType>(); 6217 assert(BTy && "Unexpected signed integer type"); 6218 switch (BTy->getKind()) { 6219 case BuiltinType::Char_S: 6220 case BuiltinType::SChar: 6221 return UnsignedCharTy; 6222 case BuiltinType::Short: 6223 return UnsignedShortTy; 6224 case BuiltinType::Int: 6225 return UnsignedIntTy; 6226 case BuiltinType::Long: 6227 return UnsignedLongTy; 6228 case BuiltinType::LongLong: 6229 return UnsignedLongLongTy; 6230 case BuiltinType::Int128: 6231 return UnsignedInt128Ty; 6232 default: 6233 llvm_unreachable("Unexpected signed integer type"); 6234 } 6235} 6236 6237ASTMutationListener::~ASTMutationListener() { } 6238 6239 6240//===----------------------------------------------------------------------===// 6241// Builtin Type Computation 6242//===----------------------------------------------------------------------===// 6243 6244/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 6245/// pointer over the consumed characters. This returns the resultant type. If 6246/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 6247/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 6248/// a vector of "i*". 6249/// 6250/// RequiresICE is filled in on return to indicate whether the value is required 6251/// to be an Integer Constant Expression. 6252static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 6253 ASTContext::GetBuiltinTypeError &Error, 6254 bool &RequiresICE, 6255 bool AllowTypeModifiers) { 6256 // Modifiers. 6257 int HowLong = 0; 6258 bool Signed = false, Unsigned = false; 6259 RequiresICE = false; 6260 6261 // Read the prefixed modifiers first. 6262 bool Done = false; 6263 while (!Done) { 6264 switch (*Str++) { 6265 default: Done = true; --Str; break; 6266 case 'I': 6267 RequiresICE = true; 6268 break; 6269 case 'S': 6270 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 6271 assert(!Signed && "Can't use 'S' modifier multiple times!"); 6272 Signed = true; 6273 break; 6274 case 'U': 6275 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 6276 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 6277 Unsigned = true; 6278 break; 6279 case 'L': 6280 assert(HowLong <= 2 && "Can't have LLLL modifier"); 6281 ++HowLong; 6282 break; 6283 } 6284 } 6285 6286 QualType Type; 6287 6288 // Read the base type. 6289 switch (*Str++) { 6290 default: llvm_unreachable("Unknown builtin type letter!"); 6291 case 'v': 6292 assert(HowLong == 0 && !Signed && !Unsigned && 6293 "Bad modifiers used with 'v'!"); 6294 Type = Context.VoidTy; 6295 break; 6296 case 'f': 6297 assert(HowLong == 0 && !Signed && !Unsigned && 6298 "Bad modifiers used with 'f'!"); 6299 Type = Context.FloatTy; 6300 break; 6301 case 'd': 6302 assert(HowLong < 2 && !Signed && !Unsigned && 6303 "Bad modifiers used with 'd'!"); 6304 if (HowLong) 6305 Type = Context.LongDoubleTy; 6306 else 6307 Type = Context.DoubleTy; 6308 break; 6309 case 's': 6310 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 6311 if (Unsigned) 6312 Type = Context.UnsignedShortTy; 6313 else 6314 Type = Context.ShortTy; 6315 break; 6316 case 'i': 6317 if (HowLong == 3) 6318 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 6319 else if (HowLong == 2) 6320 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 6321 else if (HowLong == 1) 6322 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 6323 else 6324 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 6325 break; 6326 case 'c': 6327 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 6328 if (Signed) 6329 Type = Context.SignedCharTy; 6330 else if (Unsigned) 6331 Type = Context.UnsignedCharTy; 6332 else 6333 Type = Context.CharTy; 6334 break; 6335 case 'b': // boolean 6336 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 6337 Type = Context.BoolTy; 6338 break; 6339 case 'z': // size_t. 6340 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 6341 Type = Context.getSizeType(); 6342 break; 6343 case 'F': 6344 Type = Context.getCFConstantStringType(); 6345 break; 6346 case 'G': 6347 Type = Context.getObjCIdType(); 6348 break; 6349 case 'H': 6350 Type = Context.getObjCSelType(); 6351 break; 6352 case 'a': 6353 Type = Context.getBuiltinVaListType(); 6354 assert(!Type.isNull() && "builtin va list type not initialized!"); 6355 break; 6356 case 'A': 6357 // This is a "reference" to a va_list; however, what exactly 6358 // this means depends on how va_list is defined. There are two 6359 // different kinds of va_list: ones passed by value, and ones 6360 // passed by reference. An example of a by-value va_list is 6361 // x86, where va_list is a char*. An example of by-ref va_list 6362 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 6363 // we want this argument to be a char*&; for x86-64, we want 6364 // it to be a __va_list_tag*. 6365 Type = Context.getBuiltinVaListType(); 6366 assert(!Type.isNull() && "builtin va list type not initialized!"); 6367 if (Type->isArrayType()) 6368 Type = Context.getArrayDecayedType(Type); 6369 else 6370 Type = Context.getLValueReferenceType(Type); 6371 break; 6372 case 'V': { 6373 char *End; 6374 unsigned NumElements = strtoul(Str, &End, 10); 6375 assert(End != Str && "Missing vector size"); 6376 Str = End; 6377 6378 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 6379 RequiresICE, false); 6380 assert(!RequiresICE && "Can't require vector ICE"); 6381 6382 // TODO: No way to make AltiVec vectors in builtins yet. 6383 Type = Context.getVectorType(ElementType, NumElements, 6384 VectorType::GenericVector); 6385 break; 6386 } 6387 case 'X': { 6388 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6389 false); 6390 assert(!RequiresICE && "Can't require complex ICE"); 6391 Type = Context.getComplexType(ElementType); 6392 break; 6393 } 6394 case 'Y' : { 6395 Type = Context.getPointerDiffType(); 6396 break; 6397 } 6398 case 'P': 6399 Type = Context.getFILEType(); 6400 if (Type.isNull()) { 6401 Error = ASTContext::GE_Missing_stdio; 6402 return QualType(); 6403 } 6404 break; 6405 case 'J': 6406 if (Signed) 6407 Type = Context.getsigjmp_bufType(); 6408 else 6409 Type = Context.getjmp_bufType(); 6410 6411 if (Type.isNull()) { 6412 Error = ASTContext::GE_Missing_setjmp; 6413 return QualType(); 6414 } 6415 break; 6416 case 'K': 6417 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 6418 Type = Context.getucontext_tType(); 6419 6420 if (Type.isNull()) { 6421 Error = ASTContext::GE_Missing_ucontext; 6422 return QualType(); 6423 } 6424 break; 6425 } 6426 6427 // If there are modifiers and if we're allowed to parse them, go for it. 6428 Done = !AllowTypeModifiers; 6429 while (!Done) { 6430 switch (char c = *Str++) { 6431 default: Done = true; --Str; break; 6432 case '*': 6433 case '&': { 6434 // Both pointers and references can have their pointee types 6435 // qualified with an address space. 6436 char *End; 6437 unsigned AddrSpace = strtoul(Str, &End, 10); 6438 if (End != Str && AddrSpace != 0) { 6439 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 6440 Str = End; 6441 } 6442 if (c == '*') 6443 Type = Context.getPointerType(Type); 6444 else 6445 Type = Context.getLValueReferenceType(Type); 6446 break; 6447 } 6448 // FIXME: There's no way to have a built-in with an rvalue ref arg. 6449 case 'C': 6450 Type = Type.withConst(); 6451 break; 6452 case 'D': 6453 Type = Context.getVolatileType(Type); 6454 break; 6455 } 6456 } 6457 6458 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 6459 "Integer constant 'I' type must be an integer"); 6460 6461 return Type; 6462} 6463 6464/// GetBuiltinType - Return the type for the specified builtin. 6465QualType ASTContext::GetBuiltinType(unsigned Id, 6466 GetBuiltinTypeError &Error, 6467 unsigned *IntegerConstantArgs) const { 6468 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 6469 6470 SmallVector<QualType, 8> ArgTypes; 6471 6472 bool RequiresICE = false; 6473 Error = GE_None; 6474 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 6475 RequiresICE, true); 6476 if (Error != GE_None) 6477 return QualType(); 6478 6479 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 6480 6481 while (TypeStr[0] && TypeStr[0] != '.') { 6482 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 6483 if (Error != GE_None) 6484 return QualType(); 6485 6486 // If this argument is required to be an IntegerConstantExpression and the 6487 // caller cares, fill in the bitmask we return. 6488 if (RequiresICE && IntegerConstantArgs) 6489 *IntegerConstantArgs |= 1 << ArgTypes.size(); 6490 6491 // Do array -> pointer decay. The builtin should use the decayed type. 6492 if (Ty->isArrayType()) 6493 Ty = getArrayDecayedType(Ty); 6494 6495 ArgTypes.push_back(Ty); 6496 } 6497 6498 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 6499 "'.' should only occur at end of builtin type list!"); 6500 6501 FunctionType::ExtInfo EI; 6502 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 6503 6504 bool Variadic = (TypeStr[0] == '.'); 6505 6506 // We really shouldn't be making a no-proto type here, especially in C++. 6507 if (ArgTypes.empty() && Variadic) 6508 return getFunctionNoProtoType(ResType, EI); 6509 6510 FunctionProtoType::ExtProtoInfo EPI; 6511 EPI.ExtInfo = EI; 6512 EPI.Variadic = Variadic; 6513 6514 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI); 6515} 6516 6517GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 6518 GVALinkage External = GVA_StrongExternal; 6519 6520 Linkage L = FD->getLinkage(); 6521 switch (L) { 6522 case NoLinkage: 6523 case InternalLinkage: 6524 case UniqueExternalLinkage: 6525 return GVA_Internal; 6526 6527 case ExternalLinkage: 6528 switch (FD->getTemplateSpecializationKind()) { 6529 case TSK_Undeclared: 6530 case TSK_ExplicitSpecialization: 6531 External = GVA_StrongExternal; 6532 break; 6533 6534 case TSK_ExplicitInstantiationDefinition: 6535 return GVA_ExplicitTemplateInstantiation; 6536 6537 case TSK_ExplicitInstantiationDeclaration: 6538 case TSK_ImplicitInstantiation: 6539 External = GVA_TemplateInstantiation; 6540 break; 6541 } 6542 } 6543 6544 if (!FD->isInlined()) 6545 return External; 6546 6547 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 6548 // GNU or C99 inline semantics. Determine whether this symbol should be 6549 // externally visible. 6550 if (FD->isInlineDefinitionExternallyVisible()) 6551 return External; 6552 6553 // C99 inline semantics, where the symbol is not externally visible. 6554 return GVA_C99Inline; 6555 } 6556 6557 // C++0x [temp.explicit]p9: 6558 // [ Note: The intent is that an inline function that is the subject of 6559 // an explicit instantiation declaration will still be implicitly 6560 // instantiated when used so that the body can be considered for 6561 // inlining, but that no out-of-line copy of the inline function would be 6562 // generated in the translation unit. -- end note ] 6563 if (FD->getTemplateSpecializationKind() 6564 == TSK_ExplicitInstantiationDeclaration) 6565 return GVA_C99Inline; 6566 6567 return GVA_CXXInline; 6568} 6569 6570GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 6571 // If this is a static data member, compute the kind of template 6572 // specialization. Otherwise, this variable is not part of a 6573 // template. 6574 TemplateSpecializationKind TSK = TSK_Undeclared; 6575 if (VD->isStaticDataMember()) 6576 TSK = VD->getTemplateSpecializationKind(); 6577 6578 Linkage L = VD->getLinkage(); 6579 if (L == ExternalLinkage && getLangOptions().CPlusPlus && 6580 VD->getType()->getLinkage() == UniqueExternalLinkage) 6581 L = UniqueExternalLinkage; 6582 6583 switch (L) { 6584 case NoLinkage: 6585 case InternalLinkage: 6586 case UniqueExternalLinkage: 6587 return GVA_Internal; 6588 6589 case ExternalLinkage: 6590 switch (TSK) { 6591 case TSK_Undeclared: 6592 case TSK_ExplicitSpecialization: 6593 return GVA_StrongExternal; 6594 6595 case TSK_ExplicitInstantiationDeclaration: 6596 llvm_unreachable("Variable should not be instantiated"); 6597 // Fall through to treat this like any other instantiation. 6598 6599 case TSK_ExplicitInstantiationDefinition: 6600 return GVA_ExplicitTemplateInstantiation; 6601 6602 case TSK_ImplicitInstantiation: 6603 return GVA_TemplateInstantiation; 6604 } 6605 } 6606 6607 return GVA_StrongExternal; 6608} 6609 6610bool ASTContext::DeclMustBeEmitted(const Decl *D) { 6611 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6612 if (!VD->isFileVarDecl()) 6613 return false; 6614 } else if (!isa<FunctionDecl>(D)) 6615 return false; 6616 6617 // Weak references don't produce any output by themselves. 6618 if (D->hasAttr<WeakRefAttr>()) 6619 return false; 6620 6621 // Aliases and used decls are required. 6622 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 6623 return true; 6624 6625 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6626 // Forward declarations aren't required. 6627 if (!FD->doesThisDeclarationHaveABody()) 6628 return FD->doesDeclarationForceExternallyVisibleDefinition(); 6629 6630 // Constructors and destructors are required. 6631 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 6632 return true; 6633 6634 // The key function for a class is required. 6635 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6636 const CXXRecordDecl *RD = MD->getParent(); 6637 if (MD->isOutOfLine() && RD->isDynamicClass()) { 6638 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 6639 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 6640 return true; 6641 } 6642 } 6643 6644 GVALinkage Linkage = GetGVALinkageForFunction(FD); 6645 6646 // static, static inline, always_inline, and extern inline functions can 6647 // always be deferred. Normal inline functions can be deferred in C99/C++. 6648 // Implicit template instantiations can also be deferred in C++. 6649 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 6650 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 6651 return false; 6652 return true; 6653 } 6654 6655 const VarDecl *VD = cast<VarDecl>(D); 6656 assert(VD->isFileVarDecl() && "Expected file scoped var"); 6657 6658 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 6659 return false; 6660 6661 // Structs that have non-trivial constructors or destructors are required. 6662 6663 // FIXME: Handle references. 6664 // FIXME: Be more selective about which constructors we care about. 6665 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 6666 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 6667 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() && 6668 RD->hasTrivialCopyConstructor() && 6669 RD->hasTrivialMoveConstructor() && 6670 RD->hasTrivialDestructor())) 6671 return true; 6672 } 6673 } 6674 6675 GVALinkage L = GetGVALinkageForVariable(VD); 6676 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 6677 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 6678 return false; 6679 } 6680 6681 return true; 6682} 6683 6684CallingConv ASTContext::getDefaultMethodCallConv() { 6685 // Pass through to the C++ ABI object 6686 return ABI->getDefaultMethodCallConv(); 6687} 6688 6689bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 6690 // Pass through to the C++ ABI object 6691 return ABI->isNearlyEmpty(RD); 6692} 6693 6694MangleContext *ASTContext::createMangleContext() { 6695 switch (Target->getCXXABI()) { 6696 case CXXABI_ARM: 6697 case CXXABI_Itanium: 6698 return createItaniumMangleContext(*this, getDiagnostics()); 6699 case CXXABI_Microsoft: 6700 return createMicrosoftMangleContext(*this, getDiagnostics()); 6701 } 6702 llvm_unreachable("Unsupported ABI"); 6703} 6704 6705CXXABI::~CXXABI() {} 6706 6707size_t ASTContext::getSideTableAllocatedMemory() const { 6708 return ASTRecordLayouts.getMemorySize() 6709 + llvm::capacity_in_bytes(ObjCLayouts) 6710 + llvm::capacity_in_bytes(KeyFunctions) 6711 + llvm::capacity_in_bytes(ObjCImpls) 6712 + llvm::capacity_in_bytes(BlockVarCopyInits) 6713 + llvm::capacity_in_bytes(DeclAttrs) 6714 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember) 6715 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) 6716 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) 6717 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) 6718 + llvm::capacity_in_bytes(OverriddenMethods) 6719 + llvm::capacity_in_bytes(Types) 6720 + llvm::capacity_in_bytes(VariableArrayTypes) 6721 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 6722} 6723 6724void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 6725 ParamIndices[D] = index; 6726} 6727 6728unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 6729 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 6730 assert(I != ParamIndices.end() && 6731 "ParmIndices lacks entry set by ParmVarDecl"); 6732 return I->second; 6733} 6734