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