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