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