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