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