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