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