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