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