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