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