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