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