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