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