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