ASTContext.cpp revision 1eed60297ef4701b899c6a3b9680bf08f3403422
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/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExternalASTSource.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Basic/TargetInfo.h" 23#include "llvm/ADT/StringExtras.h" 24#include "llvm/Support/MathExtras.h" 25#include "llvm/Support/MemoryBuffer.h" 26using namespace clang; 27 28enum FloatingRank { 29 FloatRank, DoubleRank, LongDoubleRank 30}; 31 32ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 33 TargetInfo &t, 34 IdentifierTable &idents, SelectorTable &sels, 35 bool FreeMem, unsigned size_reserve, 36 bool InitializeBuiltins) : 37 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), 38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts), 39 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels), 40 ExternalSource(0) { 41 if (size_reserve > 0) Types.reserve(size_reserve); 42 InitBuiltinTypes(); 43 TUDecl = TranslationUnitDecl::Create(*this); 44 BuiltinInfo.InitializeTargetBuiltins(Target); 45 if (InitializeBuiltins) 46 this->InitializeBuiltins(idents); 47} 48 49ASTContext::~ASTContext() { 50 // Deallocate all the types. 51 while (!Types.empty()) { 52 Types.back()->Destroy(*this); 53 Types.pop_back(); 54 } 55 56 { 57 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 58 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); 59 while (I != E) { 60 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 61 delete R; 62 } 63 } 64 65 { 66 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator 67 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); 68 while (I != E) { 69 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 70 delete R; 71 } 72 } 73 74 // Destroy nested-name-specifiers. 75 for (llvm::FoldingSet<NestedNameSpecifier>::iterator 76 NNS = NestedNameSpecifiers.begin(), 77 NNSEnd = NestedNameSpecifiers.end(); 78 NNS != NNSEnd; 79 /* Increment in loop */) 80 (*NNS++).Destroy(*this); 81 82 if (GlobalNestedNameSpecifier) 83 GlobalNestedNameSpecifier->Destroy(*this); 84 85 TUDecl->Destroy(*this); 86} 87 88void ASTContext::InitializeBuiltins(IdentifierTable &idents) { 89 BuiltinInfo.InitializeBuiltins(idents, LangOpts.NoBuiltin); 90} 91 92void 93ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 94 ExternalSource.reset(Source.take()); 95} 96 97void ASTContext::PrintStats() const { 98 fprintf(stderr, "*** AST Context Stats:\n"); 99 fprintf(stderr, " %d types total.\n", (int)Types.size()); 100 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0; 101 unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0; 102 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0; 103 unsigned NumLValueReference = 0, NumRValueReference = 0, NumMemberPointer = 0; 104 105 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0; 106 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0; 107 unsigned NumObjCQualifiedIds = 0; 108 unsigned NumTypeOfTypes = 0, NumTypeOfExprTypes = 0; 109 unsigned NumExtQual = 0; 110 111 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 112 Type *T = Types[i]; 113 if (isa<BuiltinType>(T)) 114 ++NumBuiltin; 115 else if (isa<PointerType>(T)) 116 ++NumPointer; 117 else if (isa<BlockPointerType>(T)) 118 ++NumBlockPointer; 119 else if (isa<LValueReferenceType>(T)) 120 ++NumLValueReference; 121 else if (isa<RValueReferenceType>(T)) 122 ++NumRValueReference; 123 else if (isa<MemberPointerType>(T)) 124 ++NumMemberPointer; 125 else if (isa<ComplexType>(T)) 126 ++NumComplex; 127 else if (isa<ArrayType>(T)) 128 ++NumArray; 129 else if (isa<VectorType>(T)) 130 ++NumVector; 131 else if (isa<FunctionNoProtoType>(T)) 132 ++NumFunctionNP; 133 else if (isa<FunctionProtoType>(T)) 134 ++NumFunctionP; 135 else if (isa<TypedefType>(T)) 136 ++NumTypeName; 137 else if (TagType *TT = dyn_cast<TagType>(T)) { 138 ++NumTagged; 139 switch (TT->getDecl()->getTagKind()) { 140 default: assert(0 && "Unknown tagged type!"); 141 case TagDecl::TK_struct: ++NumTagStruct; break; 142 case TagDecl::TK_union: ++NumTagUnion; break; 143 case TagDecl::TK_class: ++NumTagClass; break; 144 case TagDecl::TK_enum: ++NumTagEnum; break; 145 } 146 } else if (isa<ObjCInterfaceType>(T)) 147 ++NumObjCInterfaces; 148 else if (isa<ObjCQualifiedInterfaceType>(T)) 149 ++NumObjCQualifiedInterfaces; 150 else if (isa<ObjCQualifiedIdType>(T)) 151 ++NumObjCQualifiedIds; 152 else if (isa<TypeOfType>(T)) 153 ++NumTypeOfTypes; 154 else if (isa<TypeOfExprType>(T)) 155 ++NumTypeOfExprTypes; 156 else if (isa<ExtQualType>(T)) 157 ++NumExtQual; 158 else { 159 QualType(T, 0).dump(); 160 assert(0 && "Unknown type!"); 161 } 162 } 163 164 fprintf(stderr, " %d builtin types\n", NumBuiltin); 165 fprintf(stderr, " %d pointer types\n", NumPointer); 166 fprintf(stderr, " %d block pointer types\n", NumBlockPointer); 167 fprintf(stderr, " %d lvalue reference types\n", NumLValueReference); 168 fprintf(stderr, " %d rvalue reference types\n", NumRValueReference); 169 fprintf(stderr, " %d member pointer types\n", NumMemberPointer); 170 fprintf(stderr, " %d complex types\n", NumComplex); 171 fprintf(stderr, " %d array types\n", NumArray); 172 fprintf(stderr, " %d vector types\n", NumVector); 173 fprintf(stderr, " %d function types with proto\n", NumFunctionP); 174 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP); 175 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName); 176 fprintf(stderr, " %d tagged types\n", NumTagged); 177 fprintf(stderr, " %d struct types\n", NumTagStruct); 178 fprintf(stderr, " %d union types\n", NumTagUnion); 179 fprintf(stderr, " %d class types\n", NumTagClass); 180 fprintf(stderr, " %d enum types\n", NumTagEnum); 181 fprintf(stderr, " %d interface types\n", NumObjCInterfaces); 182 fprintf(stderr, " %d protocol qualified interface types\n", 183 NumObjCQualifiedInterfaces); 184 fprintf(stderr, " %d protocol qualified id types\n", 185 NumObjCQualifiedIds); 186 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes); 187 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprTypes); 188 fprintf(stderr, " %d attribute-qualified types\n", NumExtQual); 189 190 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+ 191 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+ 192 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+ 193 NumLValueReference*sizeof(LValueReferenceType)+ 194 NumRValueReference*sizeof(RValueReferenceType)+ 195 NumMemberPointer*sizeof(MemberPointerType)+ 196 NumFunctionP*sizeof(FunctionProtoType)+ 197 NumFunctionNP*sizeof(FunctionNoProtoType)+ 198 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+ 199 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprTypes*sizeof(TypeOfExprType)+ 200 NumExtQual*sizeof(ExtQualType))); 201 202 if (ExternalSource.get()) { 203 fprintf(stderr, "\n"); 204 ExternalSource->PrintStats(); 205 } 206} 207 208 209void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { 210 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr()); 211} 212 213void ASTContext::InitBuiltinTypes() { 214 assert(VoidTy.isNull() && "Context reinitialized?"); 215 216 // C99 6.2.5p19. 217 InitBuiltinType(VoidTy, BuiltinType::Void); 218 219 // C99 6.2.5p2. 220 InitBuiltinType(BoolTy, BuiltinType::Bool); 221 // C99 6.2.5p3. 222 if (Target.isCharSigned()) 223 InitBuiltinType(CharTy, BuiltinType::Char_S); 224 else 225 InitBuiltinType(CharTy, BuiltinType::Char_U); 226 // C99 6.2.5p4. 227 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 228 InitBuiltinType(ShortTy, BuiltinType::Short); 229 InitBuiltinType(IntTy, BuiltinType::Int); 230 InitBuiltinType(LongTy, BuiltinType::Long); 231 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 232 233 // C99 6.2.5p6. 234 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 235 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 236 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 237 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 238 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 239 240 // C99 6.2.5p10. 241 InitBuiltinType(FloatTy, BuiltinType::Float); 242 InitBuiltinType(DoubleTy, BuiltinType::Double); 243 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 244 245 // GNU extension, 128-bit integers. 246 InitBuiltinType(Int128Ty, BuiltinType::Int128); 247 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 248 249 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 250 InitBuiltinType(WCharTy, BuiltinType::WChar); 251 else // C99 252 WCharTy = getFromTargetType(Target.getWCharType()); 253 254 // Placeholder type for functions. 255 InitBuiltinType(OverloadTy, BuiltinType::Overload); 256 257 // Placeholder type for type-dependent expressions whose type is 258 // completely unknown. No code should ever check a type against 259 // DependentTy and users should never see it; however, it is here to 260 // help diagnose failures to properly check for type-dependent 261 // expressions. 262 InitBuiltinType(DependentTy, BuiltinType::Dependent); 263 264 // C99 6.2.5p11. 265 FloatComplexTy = getComplexType(FloatTy); 266 DoubleComplexTy = getComplexType(DoubleTy); 267 LongDoubleComplexTy = getComplexType(LongDoubleTy); 268 269 BuiltinVaListType = QualType(); 270 ObjCIdType = QualType(); 271 IdStructType = 0; 272 ObjCClassType = QualType(); 273 ClassStructType = 0; 274 275 ObjCConstantStringType = QualType(); 276 277 // void * type 278 VoidPtrTy = getPointerType(VoidTy); 279 280 // nullptr type (C++0x 2.14.7) 281 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 282} 283 284//===----------------------------------------------------------------------===// 285// Type Sizing and Analysis 286//===----------------------------------------------------------------------===// 287 288/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 289/// scalar floating point type. 290const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 291 const BuiltinType *BT = T->getAsBuiltinType(); 292 assert(BT && "Not a floating point type!"); 293 switch (BT->getKind()) { 294 default: assert(0 && "Not a floating point type!"); 295 case BuiltinType::Float: return Target.getFloatFormat(); 296 case BuiltinType::Double: return Target.getDoubleFormat(); 297 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 298 } 299} 300 301/// getDeclAlign - Return a conservative estimate of the alignment of the 302/// specified decl. Note that bitfields do not have a valid alignment, so 303/// this method will assert on them. 304unsigned ASTContext::getDeclAlignInBytes(const Decl *D) { 305 unsigned Align = Target.getCharWidth(); 306 307 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) 308 Align = std::max(Align, AA->getAlignment()); 309 310 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 311 QualType T = VD->getType(); 312 if (const ReferenceType* RT = T->getAsReferenceType()) { 313 unsigned AS = RT->getPointeeType().getAddressSpace(); 314 Align = Target.getPointerAlign(AS); 315 } else if (!T->isIncompleteType() && !T->isFunctionType()) { 316 // Incomplete or function types default to 1. 317 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 318 T = cast<ArrayType>(T)->getElementType(); 319 320 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 321 } 322 } 323 324 return Align / Target.getCharWidth(); 325} 326 327/// getTypeSize - Return the size of the specified type, in bits. This method 328/// does not work on incomplete types. 329std::pair<uint64_t, unsigned> 330ASTContext::getTypeInfo(const Type *T) { 331 uint64_t Width=0; 332 unsigned Align=8; 333 switch (T->getTypeClass()) { 334#define TYPE(Class, Base) 335#define ABSTRACT_TYPE(Class, Base) 336#define NON_CANONICAL_TYPE(Class, Base) 337#define DEPENDENT_TYPE(Class, Base) case Type::Class: 338#include "clang/AST/TypeNodes.def" 339 assert(false && "Should not see dependent types"); 340 break; 341 342 case Type::FunctionNoProto: 343 case Type::FunctionProto: 344 // GCC extension: alignof(function) = 32 bits 345 Width = 0; 346 Align = 32; 347 break; 348 349 case Type::IncompleteArray: 350 case Type::VariableArray: 351 Width = 0; 352 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 353 break; 354 355 case Type::ConstantArray: { 356 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 357 358 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 359 Width = EltInfo.first*CAT->getSize().getZExtValue(); 360 Align = EltInfo.second; 361 break; 362 } 363 case Type::ExtVector: 364 case Type::Vector: { 365 std::pair<uint64_t, unsigned> EltInfo = 366 getTypeInfo(cast<VectorType>(T)->getElementType()); 367 Width = EltInfo.first*cast<VectorType>(T)->getNumElements(); 368 Align = Width; 369 // If the alignment is not a power of 2, round up to the next power of 2. 370 // This happens for non-power-of-2 length vectors. 371 // FIXME: this should probably be a target property. 372 Align = 1 << llvm::Log2_32_Ceil(Align); 373 break; 374 } 375 376 case Type::Builtin: 377 switch (cast<BuiltinType>(T)->getKind()) { 378 default: assert(0 && "Unknown builtin type!"); 379 case BuiltinType::Void: 380 // GCC extension: alignof(void) = 8 bits. 381 Width = 0; 382 Align = 8; 383 break; 384 385 case BuiltinType::Bool: 386 Width = Target.getBoolWidth(); 387 Align = Target.getBoolAlign(); 388 break; 389 case BuiltinType::Char_S: 390 case BuiltinType::Char_U: 391 case BuiltinType::UChar: 392 case BuiltinType::SChar: 393 Width = Target.getCharWidth(); 394 Align = Target.getCharAlign(); 395 break; 396 case BuiltinType::WChar: 397 Width = Target.getWCharWidth(); 398 Align = Target.getWCharAlign(); 399 break; 400 case BuiltinType::UShort: 401 case BuiltinType::Short: 402 Width = Target.getShortWidth(); 403 Align = Target.getShortAlign(); 404 break; 405 case BuiltinType::UInt: 406 case BuiltinType::Int: 407 Width = Target.getIntWidth(); 408 Align = Target.getIntAlign(); 409 break; 410 case BuiltinType::ULong: 411 case BuiltinType::Long: 412 Width = Target.getLongWidth(); 413 Align = Target.getLongAlign(); 414 break; 415 case BuiltinType::ULongLong: 416 case BuiltinType::LongLong: 417 Width = Target.getLongLongWidth(); 418 Align = Target.getLongLongAlign(); 419 break; 420 case BuiltinType::Int128: 421 case BuiltinType::UInt128: 422 Width = 128; 423 Align = 128; // int128_t is 128-bit aligned on all targets. 424 break; 425 case BuiltinType::Float: 426 Width = Target.getFloatWidth(); 427 Align = Target.getFloatAlign(); 428 break; 429 case BuiltinType::Double: 430 Width = Target.getDoubleWidth(); 431 Align = Target.getDoubleAlign(); 432 break; 433 case BuiltinType::LongDouble: 434 Width = Target.getLongDoubleWidth(); 435 Align = Target.getLongDoubleAlign(); 436 break; 437 case BuiltinType::NullPtr: 438 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 439 Align = Target.getPointerAlign(0); // == sizeof(void*) 440 } 441 break; 442 case Type::FixedWidthInt: 443 // FIXME: This isn't precisely correct; the width/alignment should depend 444 // on the available types for the target 445 Width = cast<FixedWidthIntType>(T)->getWidth(); 446 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8); 447 Align = Width; 448 break; 449 case Type::ExtQual: 450 // FIXME: Pointers into different addr spaces could have different sizes and 451 // alignment requirements: getPointerInfo should take an AddrSpace. 452 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0)); 453 case Type::ObjCQualifiedId: 454 case Type::ObjCQualifiedInterface: 455 Width = Target.getPointerWidth(0); 456 Align = Target.getPointerAlign(0); 457 break; 458 case Type::BlockPointer: { 459 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 460 Width = Target.getPointerWidth(AS); 461 Align = Target.getPointerAlign(AS); 462 break; 463 } 464 case Type::Pointer: { 465 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 466 Width = Target.getPointerWidth(AS); 467 Align = Target.getPointerAlign(AS); 468 break; 469 } 470 case Type::LValueReference: 471 case Type::RValueReference: 472 // "When applied to a reference or a reference type, the result is the size 473 // of the referenced type." C++98 5.3.3p2: expr.sizeof. 474 // FIXME: This is wrong for struct layout: a reference in a struct has 475 // pointer size. 476 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType()); 477 case Type::MemberPointer: { 478 // FIXME: This is ABI dependent. We use the Itanium C++ ABI. 479 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers 480 // If we ever want to support other ABIs this needs to be abstracted. 481 482 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 483 std::pair<uint64_t, unsigned> PtrDiffInfo = 484 getTypeInfo(getPointerDiffType()); 485 Width = PtrDiffInfo.first; 486 if (Pointee->isFunctionType()) 487 Width *= 2; 488 Align = PtrDiffInfo.second; 489 break; 490 } 491 case Type::Complex: { 492 // Complex types have the same alignment as their elements, but twice the 493 // size. 494 std::pair<uint64_t, unsigned> EltInfo = 495 getTypeInfo(cast<ComplexType>(T)->getElementType()); 496 Width = EltInfo.first*2; 497 Align = EltInfo.second; 498 break; 499 } 500 case Type::ObjCInterface: { 501 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 502 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 503 Width = Layout.getSize(); 504 Align = Layout.getAlignment(); 505 break; 506 } 507 case Type::Record: 508 case Type::Enum: { 509 const TagType *TT = cast<TagType>(T); 510 511 if (TT->getDecl()->isInvalidDecl()) { 512 Width = 1; 513 Align = 1; 514 break; 515 } 516 517 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 518 return getTypeInfo(ET->getDecl()->getIntegerType()); 519 520 const RecordType *RT = cast<RecordType>(TT); 521 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 522 Width = Layout.getSize(); 523 Align = Layout.getAlignment(); 524 break; 525 } 526 527 case Type::Typedef: { 528 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 529 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) { 530 Align = Aligned->getAlignment(); 531 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr()); 532 } else 533 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 534 break; 535 } 536 537 case Type::TypeOfExpr: 538 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 539 .getTypePtr()); 540 541 case Type::TypeOf: 542 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 543 544 case Type::QualifiedName: 545 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr()); 546 547 case Type::TemplateSpecialization: 548 assert(getCanonicalType(T) != T && 549 "Cannot request the size of a dependent type"); 550 // FIXME: this is likely to be wrong once we support template 551 // aliases, since a template alias could refer to a typedef that 552 // has an __aligned__ attribute on it. 553 return getTypeInfo(getCanonicalType(T)); 554 } 555 556 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 557 return std::make_pair(Width, Align); 558} 559 560/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 561/// type for the current target in bits. This can be different than the ABI 562/// alignment in cases where it is beneficial for performance to overalign 563/// a data type. 564unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 565 unsigned ABIAlign = getTypeAlign(T); 566 567 // Double and long long should be naturally aligned if possible. 568 if (const ComplexType* CT = T->getAsComplexType()) 569 T = CT->getElementType().getTypePtr(); 570 if (T->isSpecificBuiltinType(BuiltinType::Double) || 571 T->isSpecificBuiltinType(BuiltinType::LongLong)) 572 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 573 574 return ABIAlign; 575} 576 577 578/// LayoutField - Field layout. 579void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo, 580 bool IsUnion, unsigned StructPacking, 581 ASTContext &Context) { 582 unsigned FieldPacking = StructPacking; 583 uint64_t FieldOffset = IsUnion ? 0 : Size; 584 uint64_t FieldSize; 585 unsigned FieldAlign; 586 587 // FIXME: Should this override struct packing? Probably we want to 588 // take the minimum? 589 if (const PackedAttr *PA = FD->getAttr<PackedAttr>()) 590 FieldPacking = PA->getAlignment(); 591 592 if (const Expr *BitWidthExpr = FD->getBitWidth()) { 593 // TODO: Need to check this algorithm on other targets! 594 // (tested on Linux-X86) 595 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue(); 596 597 std::pair<uint64_t, unsigned> FieldInfo = 598 Context.getTypeInfo(FD->getType()); 599 uint64_t TypeSize = FieldInfo.first; 600 601 // Determine the alignment of this bitfield. The packing 602 // attributes define a maximum and the alignment attribute defines 603 // a minimum. 604 // FIXME: What is the right behavior when the specified alignment 605 // is smaller than the specified packing? 606 FieldAlign = FieldInfo.second; 607 if (FieldPacking) 608 FieldAlign = std::min(FieldAlign, FieldPacking); 609 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 610 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 611 612 // Check if we need to add padding to give the field the correct 613 // alignment. 614 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 615 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 616 617 // Padding members don't affect overall alignment 618 if (!FD->getIdentifier()) 619 FieldAlign = 1; 620 } else { 621 if (FD->getType()->isIncompleteArrayType()) { 622 // This is a flexible array member; we can't directly 623 // query getTypeInfo about these, so we figure it out here. 624 // Flexible array members don't have any size, but they 625 // have to be aligned appropriately for their element type. 626 FieldSize = 0; 627 const ArrayType* ATy = Context.getAsArrayType(FD->getType()); 628 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 629 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) { 630 unsigned AS = RT->getPointeeType().getAddressSpace(); 631 FieldSize = Context.Target.getPointerWidth(AS); 632 FieldAlign = Context.Target.getPointerAlign(AS); 633 } else { 634 std::pair<uint64_t, unsigned> FieldInfo = 635 Context.getTypeInfo(FD->getType()); 636 FieldSize = FieldInfo.first; 637 FieldAlign = FieldInfo.second; 638 } 639 640 // Determine the alignment of this bitfield. The packing 641 // attributes define a maximum and the alignment attribute defines 642 // a minimum. Additionally, the packing alignment must be at least 643 // a byte for non-bitfields. 644 // 645 // FIXME: What is the right behavior when the specified alignment 646 // is smaller than the specified packing? 647 if (FieldPacking) 648 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking)); 649 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 650 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 651 652 // Round up the current record size to the field's alignment boundary. 653 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 654 } 655 656 // Place this field at the current location. 657 FieldOffsets[FieldNo] = FieldOffset; 658 659 // Reserve space for this field. 660 if (IsUnion) { 661 Size = std::max(Size, FieldSize); 662 } else { 663 Size = FieldOffset + FieldSize; 664 } 665 666 // Remember the next available offset. 667 NextOffset = Size; 668 669 // Remember max struct/class alignment. 670 Alignment = std::max(Alignment, FieldAlign); 671} 672 673static void CollectLocalObjCIvars(ASTContext *Ctx, 674 const ObjCInterfaceDecl *OI, 675 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 676 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 677 E = OI->ivar_end(); I != E; ++I) { 678 ObjCIvarDecl *IVDecl = *I; 679 if (!IVDecl->isInvalidDecl()) 680 Fields.push_back(cast<FieldDecl>(IVDecl)); 681 } 682} 683 684void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI, 685 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 686 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 687 CollectObjCIvars(SuperClass, Fields); 688 CollectLocalObjCIvars(this, OI, Fields); 689} 690 691void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD, 692 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 693 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this), 694 E = PD->prop_end(*this); I != E; ++I) 695 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 696 Ivars.push_back(Ivar); 697 698 // Also look into nested protocols. 699 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), 700 E = PD->protocol_end(); P != E; ++P) 701 CollectProtocolSynthesizedIvars(*P, Ivars); 702} 703 704/// CollectSynthesizedIvars - 705/// This routine collect synthesized ivars for the designated class. 706/// 707void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI, 708 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 709 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this), 710 E = OI->prop_end(*this); I != E; ++I) { 711 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 712 Ivars.push_back(Ivar); 713 } 714 // Also look into interface's protocol list for properties declared 715 // in the protocol and whose ivars are synthesized. 716 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 717 PE = OI->protocol_end(); P != PE; ++P) { 718 ObjCProtocolDecl *PD = (*P); 719 CollectProtocolSynthesizedIvars(PD, Ivars); 720 } 721} 722 723/// getInterfaceLayoutImpl - Get or compute information about the 724/// layout of the given interface. 725/// 726/// \param Impl - If given, also include the layout of the interface's 727/// implementation. This may differ by including synthesized ivars. 728const ASTRecordLayout & 729ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 730 const ObjCImplementationDecl *Impl) { 731 assert(!D->isForwardDecl() && "Invalid interface decl!"); 732 733 // Look up this layout, if already laid out, return what we have. 734 ObjCContainerDecl *Key = 735 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 736 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 737 return *Entry; 738 739 unsigned FieldCount = D->ivar_size(); 740 // Add in synthesized ivar count if laying out an implementation. 741 if (Impl) { 742 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 743 CollectSynthesizedIvars(D, Ivars); 744 FieldCount += Ivars.size(); 745 // If there aren't any sythesized ivars then reuse the interface 746 // entry. Note we can't cache this because we simply free all 747 // entries later; however we shouldn't look up implementations 748 // frequently. 749 if (FieldCount == D->ivar_size()) 750 return getObjCLayout(D, 0); 751 } 752 753 ASTRecordLayout *NewEntry = NULL; 754 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 755 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD); 756 unsigned Alignment = SL.getAlignment(); 757 758 // We start laying out ivars not at the end of the superclass 759 // structure, but at the next byte following the last field. 760 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8); 761 762 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment); 763 NewEntry->InitializeLayout(FieldCount); 764 } else { 765 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(); 766 NewEntry->InitializeLayout(FieldCount); 767 } 768 769 unsigned StructPacking = 0; 770 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 771 StructPacking = PA->getAlignment(); 772 773 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 774 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 775 AA->getAlignment())); 776 777 // Layout each ivar sequentially. 778 unsigned i = 0; 779 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(), 780 IVE = D->ivar_end(); IVI != IVE; ++IVI) { 781 const ObjCIvarDecl* Ivar = (*IVI); 782 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this); 783 } 784 // And synthesized ivars, if this is an implementation. 785 if (Impl) { 786 // FIXME. Do we need to colltect twice? 787 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 788 CollectSynthesizedIvars(D, Ivars); 789 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) 790 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this); 791 } 792 793 // Finally, round the size of the total struct up to the alignment of the 794 // struct itself. 795 NewEntry->FinalizeLayout(); 796 return *NewEntry; 797} 798 799const ASTRecordLayout & 800ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 801 return getObjCLayout(D, 0); 802} 803 804const ASTRecordLayout & 805ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 806 return getObjCLayout(D->getClassInterface(), D); 807} 808 809/// getASTRecordLayout - Get or compute information about the layout of the 810/// specified record (struct/union/class), which indicates its size and field 811/// position information. 812const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 813 D = D->getDefinition(*this); 814 assert(D && "Cannot get layout of forward declarations!"); 815 816 // Look up this layout, if already laid out, return what we have. 817 const ASTRecordLayout *&Entry = ASTRecordLayouts[D]; 818 if (Entry) return *Entry; 819 820 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 821 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 822 ASTRecordLayout *NewEntry = new ASTRecordLayout(); 823 Entry = NewEntry; 824 825 // FIXME: Avoid linear walk through the fields, if possible. 826 NewEntry->InitializeLayout(std::distance(D->field_begin(*this), 827 D->field_end(*this))); 828 bool IsUnion = D->isUnion(); 829 830 unsigned StructPacking = 0; 831 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 832 StructPacking = PA->getAlignment(); 833 834 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 835 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 836 AA->getAlignment())); 837 838 // Layout each field, for now, just sequentially, respecting alignment. In 839 // the future, this will need to be tweakable by targets. 840 unsigned FieldIdx = 0; 841 for (RecordDecl::field_iterator Field = D->field_begin(*this), 842 FieldEnd = D->field_end(*this); 843 Field != FieldEnd; (void)++Field, ++FieldIdx) 844 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this); 845 846 // Finally, round the size of the total struct up to the alignment of the 847 // struct itself. 848 NewEntry->FinalizeLayout(); 849 return *NewEntry; 850} 851 852//===----------------------------------------------------------------------===// 853// Type creation/memoization methods 854//===----------------------------------------------------------------------===// 855 856QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 857 QualType CanT = getCanonicalType(T); 858 if (CanT.getAddressSpace() == AddressSpace) 859 return T; 860 861 // If we are composing extended qualifiers together, merge together into one 862 // ExtQualType node. 863 unsigned CVRQuals = T.getCVRQualifiers(); 864 QualType::GCAttrTypes GCAttr = QualType::GCNone; 865 Type *TypeNode = T.getTypePtr(); 866 867 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 868 // If this type already has an address space specified, it cannot get 869 // another one. 870 assert(EQT->getAddressSpace() == 0 && 871 "Type cannot be in multiple addr spaces!"); 872 GCAttr = EQT->getObjCGCAttr(); 873 TypeNode = EQT->getBaseType(); 874 } 875 876 // Check if we've already instantiated this type. 877 llvm::FoldingSetNodeID ID; 878 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 879 void *InsertPos = 0; 880 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 881 return QualType(EXTQy, CVRQuals); 882 883 // If the base type isn't canonical, this won't be a canonical type either, 884 // so fill in the canonical type field. 885 QualType Canonical; 886 if (!TypeNode->isCanonical()) { 887 Canonical = getAddrSpaceQualType(CanT, AddressSpace); 888 889 // Update InsertPos, the previous call could have invalidated it. 890 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 891 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 892 } 893 ExtQualType *New = 894 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 895 ExtQualTypes.InsertNode(New, InsertPos); 896 Types.push_back(New); 897 return QualType(New, CVRQuals); 898} 899 900QualType ASTContext::getObjCGCQualType(QualType T, 901 QualType::GCAttrTypes GCAttr) { 902 QualType CanT = getCanonicalType(T); 903 if (CanT.getObjCGCAttr() == GCAttr) 904 return T; 905 906 // If we are composing extended qualifiers together, merge together into one 907 // ExtQualType node. 908 unsigned CVRQuals = T.getCVRQualifiers(); 909 Type *TypeNode = T.getTypePtr(); 910 unsigned AddressSpace = 0; 911 912 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 913 // If this type already has an address space specified, it cannot get 914 // another one. 915 assert(EQT->getObjCGCAttr() == QualType::GCNone && 916 "Type cannot be in multiple addr spaces!"); 917 AddressSpace = EQT->getAddressSpace(); 918 TypeNode = EQT->getBaseType(); 919 } 920 921 // Check if we've already instantiated an gc qual'd type of this type. 922 llvm::FoldingSetNodeID ID; 923 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 924 void *InsertPos = 0; 925 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 926 return QualType(EXTQy, CVRQuals); 927 928 // If the base type isn't canonical, this won't be a canonical type either, 929 // so fill in the canonical type field. 930 // FIXME: Isn't this also not canonical if the base type is a array 931 // or pointer type? I can't find any documentation for objc_gc, though... 932 QualType Canonical; 933 if (!T->isCanonical()) { 934 Canonical = getObjCGCQualType(CanT, GCAttr); 935 936 // Update InsertPos, the previous call could have invalidated it. 937 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 938 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 939 } 940 ExtQualType *New = 941 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 942 ExtQualTypes.InsertNode(New, InsertPos); 943 Types.push_back(New); 944 return QualType(New, CVRQuals); 945} 946 947/// getComplexType - Return the uniqued reference to the type for a complex 948/// number with the specified element type. 949QualType ASTContext::getComplexType(QualType T) { 950 // Unique pointers, to guarantee there is only one pointer of a particular 951 // structure. 952 llvm::FoldingSetNodeID ID; 953 ComplexType::Profile(ID, T); 954 955 void *InsertPos = 0; 956 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 957 return QualType(CT, 0); 958 959 // If the pointee type isn't canonical, this won't be a canonical type either, 960 // so fill in the canonical type field. 961 QualType Canonical; 962 if (!T->isCanonical()) { 963 Canonical = getComplexType(getCanonicalType(T)); 964 965 // Get the new insert position for the node we care about. 966 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 967 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 968 } 969 ComplexType *New = new (*this,8) ComplexType(T, Canonical); 970 Types.push_back(New); 971 ComplexTypes.InsertNode(New, InsertPos); 972 return QualType(New, 0); 973} 974 975QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) { 976 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ? 977 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes; 978 FixedWidthIntType *&Entry = Map[Width]; 979 if (!Entry) 980 Entry = new FixedWidthIntType(Width, Signed); 981 return QualType(Entry, 0); 982} 983 984/// getPointerType - Return the uniqued reference to the type for a pointer to 985/// the specified type. 986QualType ASTContext::getPointerType(QualType T) { 987 // Unique pointers, to guarantee there is only one pointer of a particular 988 // structure. 989 llvm::FoldingSetNodeID ID; 990 PointerType::Profile(ID, T); 991 992 void *InsertPos = 0; 993 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 994 return QualType(PT, 0); 995 996 // If the pointee type isn't canonical, this won't be a canonical type either, 997 // so fill in the canonical type field. 998 QualType Canonical; 999 if (!T->isCanonical()) { 1000 Canonical = getPointerType(getCanonicalType(T)); 1001 1002 // Get the new insert position for the node we care about. 1003 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1004 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1005 } 1006 PointerType *New = new (*this,8) PointerType(T, Canonical); 1007 Types.push_back(New); 1008 PointerTypes.InsertNode(New, InsertPos); 1009 return QualType(New, 0); 1010} 1011 1012/// getBlockPointerType - Return the uniqued reference to the type for 1013/// a pointer to the specified block. 1014QualType ASTContext::getBlockPointerType(QualType T) { 1015 assert(T->isFunctionType() && "block of function types only"); 1016 // Unique pointers, to guarantee there is only one block of a particular 1017 // structure. 1018 llvm::FoldingSetNodeID ID; 1019 BlockPointerType::Profile(ID, T); 1020 1021 void *InsertPos = 0; 1022 if (BlockPointerType *PT = 1023 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1024 return QualType(PT, 0); 1025 1026 // If the block pointee type isn't canonical, this won't be a canonical 1027 // type either so fill in the canonical type field. 1028 QualType Canonical; 1029 if (!T->isCanonical()) { 1030 Canonical = getBlockPointerType(getCanonicalType(T)); 1031 1032 // Get the new insert position for the node we care about. 1033 BlockPointerType *NewIP = 1034 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1035 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1036 } 1037 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical); 1038 Types.push_back(New); 1039 BlockPointerTypes.InsertNode(New, InsertPos); 1040 return QualType(New, 0); 1041} 1042 1043/// getLValueReferenceType - Return the uniqued reference to the type for an 1044/// lvalue reference to the specified type. 1045QualType ASTContext::getLValueReferenceType(QualType T) { 1046 // Unique pointers, to guarantee there is only one pointer of a particular 1047 // structure. 1048 llvm::FoldingSetNodeID ID; 1049 ReferenceType::Profile(ID, T); 1050 1051 void *InsertPos = 0; 1052 if (LValueReferenceType *RT = 1053 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1054 return QualType(RT, 0); 1055 1056 // If the referencee type isn't canonical, this won't be a canonical type 1057 // either, so fill in the canonical type field. 1058 QualType Canonical; 1059 if (!T->isCanonical()) { 1060 Canonical = getLValueReferenceType(getCanonicalType(T)); 1061 1062 // Get the new insert position for the node we care about. 1063 LValueReferenceType *NewIP = 1064 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1065 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1066 } 1067 1068 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical); 1069 Types.push_back(New); 1070 LValueReferenceTypes.InsertNode(New, InsertPos); 1071 return QualType(New, 0); 1072} 1073 1074/// getRValueReferenceType - Return the uniqued reference to the type for an 1075/// rvalue reference to the specified type. 1076QualType ASTContext::getRValueReferenceType(QualType T) { 1077 // Unique pointers, to guarantee there is only one pointer of a particular 1078 // structure. 1079 llvm::FoldingSetNodeID ID; 1080 ReferenceType::Profile(ID, T); 1081 1082 void *InsertPos = 0; 1083 if (RValueReferenceType *RT = 1084 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1085 return QualType(RT, 0); 1086 1087 // If the referencee type isn't canonical, this won't be a canonical type 1088 // either, so fill in the canonical type field. 1089 QualType Canonical; 1090 if (!T->isCanonical()) { 1091 Canonical = getRValueReferenceType(getCanonicalType(T)); 1092 1093 // Get the new insert position for the node we care about. 1094 RValueReferenceType *NewIP = 1095 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1096 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1097 } 1098 1099 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical); 1100 Types.push_back(New); 1101 RValueReferenceTypes.InsertNode(New, InsertPos); 1102 return QualType(New, 0); 1103} 1104 1105/// getMemberPointerType - Return the uniqued reference to the type for a 1106/// member pointer to the specified type, in the specified class. 1107QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) 1108{ 1109 // Unique pointers, to guarantee there is only one pointer of a particular 1110 // structure. 1111 llvm::FoldingSetNodeID ID; 1112 MemberPointerType::Profile(ID, T, Cls); 1113 1114 void *InsertPos = 0; 1115 if (MemberPointerType *PT = 1116 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1117 return QualType(PT, 0); 1118 1119 // If the pointee or class type isn't canonical, this won't be a canonical 1120 // type either, so fill in the canonical type field. 1121 QualType Canonical; 1122 if (!T->isCanonical()) { 1123 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1124 1125 // Get the new insert position for the node we care about. 1126 MemberPointerType *NewIP = 1127 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1128 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1129 } 1130 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical); 1131 Types.push_back(New); 1132 MemberPointerTypes.InsertNode(New, InsertPos); 1133 return QualType(New, 0); 1134} 1135 1136/// getConstantArrayType - Return the unique reference to the type for an 1137/// array of the specified element type. 1138QualType ASTContext::getConstantArrayType(QualType EltTy, 1139 const llvm::APInt &ArySizeIn, 1140 ArrayType::ArraySizeModifier ASM, 1141 unsigned EltTypeQuals) { 1142 // Convert the array size into a canonical width matching the pointer size for 1143 // the target. 1144 llvm::APInt ArySize(ArySizeIn); 1145 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1146 1147 llvm::FoldingSetNodeID ID; 1148 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1149 1150 void *InsertPos = 0; 1151 if (ConstantArrayType *ATP = 1152 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1153 return QualType(ATP, 0); 1154 1155 // If the element type isn't canonical, this won't be a canonical type either, 1156 // so fill in the canonical type field. 1157 QualType Canonical; 1158 if (!EltTy->isCanonical()) { 1159 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1160 ASM, EltTypeQuals); 1161 // Get the new insert position for the node we care about. 1162 ConstantArrayType *NewIP = 1163 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1164 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1165 } 1166 1167 ConstantArrayType *New = 1168 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1169 ConstantArrayTypes.InsertNode(New, InsertPos); 1170 Types.push_back(New); 1171 return QualType(New, 0); 1172} 1173 1174/// getVariableArrayType - Returns a non-unique reference to the type for a 1175/// variable array of the specified element type. 1176QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 1177 ArrayType::ArraySizeModifier ASM, 1178 unsigned EltTypeQuals) { 1179 // Since we don't unique expressions, it isn't possible to unique VLA's 1180 // that have an expression provided for their size. 1181 1182 VariableArrayType *New = 1183 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals); 1184 1185 VariableArrayTypes.push_back(New); 1186 Types.push_back(New); 1187 return QualType(New, 0); 1188} 1189 1190/// getDependentSizedArrayType - Returns a non-unique reference to 1191/// the type for a dependently-sized array of the specified element 1192/// type. FIXME: We will need these to be uniqued, or at least 1193/// comparable, at some point. 1194QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 1195 ArrayType::ArraySizeModifier ASM, 1196 unsigned EltTypeQuals) { 1197 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && 1198 "Size must be type- or value-dependent!"); 1199 1200 // Since we don't unique expressions, it isn't possible to unique 1201 // dependently-sized array types. 1202 1203 DependentSizedArrayType *New = 1204 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts, 1205 ASM, EltTypeQuals); 1206 1207 DependentSizedArrayTypes.push_back(New); 1208 Types.push_back(New); 1209 return QualType(New, 0); 1210} 1211 1212QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1213 ArrayType::ArraySizeModifier ASM, 1214 unsigned EltTypeQuals) { 1215 llvm::FoldingSetNodeID ID; 1216 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1217 1218 void *InsertPos = 0; 1219 if (IncompleteArrayType *ATP = 1220 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1221 return QualType(ATP, 0); 1222 1223 // If the element type isn't canonical, this won't be a canonical type 1224 // either, so fill in the canonical type field. 1225 QualType Canonical; 1226 1227 if (!EltTy->isCanonical()) { 1228 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1229 ASM, EltTypeQuals); 1230 1231 // Get the new insert position for the node we care about. 1232 IncompleteArrayType *NewIP = 1233 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1234 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1235 } 1236 1237 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical, 1238 ASM, EltTypeQuals); 1239 1240 IncompleteArrayTypes.InsertNode(New, InsertPos); 1241 Types.push_back(New); 1242 return QualType(New, 0); 1243} 1244 1245/// getVectorType - Return the unique reference to a vector type of 1246/// the specified element type and size. VectorType must be a built-in type. 1247QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { 1248 BuiltinType *baseType; 1249 1250 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1251 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1252 1253 // Check if we've already instantiated a vector of this type. 1254 llvm::FoldingSetNodeID ID; 1255 VectorType::Profile(ID, vecType, NumElts, Type::Vector); 1256 void *InsertPos = 0; 1257 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1258 return QualType(VTP, 0); 1259 1260 // If the element type isn't canonical, this won't be a canonical type either, 1261 // so fill in the canonical type field. 1262 QualType Canonical; 1263 if (!vecType->isCanonical()) { 1264 Canonical = getVectorType(getCanonicalType(vecType), NumElts); 1265 1266 // Get the new insert position for the node we care about. 1267 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1269 } 1270 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical); 1271 VectorTypes.InsertNode(New, InsertPos); 1272 Types.push_back(New); 1273 return QualType(New, 0); 1274} 1275 1276/// getExtVectorType - Return the unique reference to an extended vector type of 1277/// the specified element type and size. VectorType must be a built-in type. 1278QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1279 BuiltinType *baseType; 1280 1281 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1282 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1283 1284 // Check if we've already instantiated a vector of this type. 1285 llvm::FoldingSetNodeID ID; 1286 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); 1287 void *InsertPos = 0; 1288 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1289 return QualType(VTP, 0); 1290 1291 // If the element type isn't canonical, this won't be a canonical type either, 1292 // so fill in the canonical type field. 1293 QualType Canonical; 1294 if (!vecType->isCanonical()) { 1295 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1296 1297 // Get the new insert position for the node we care about. 1298 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1299 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1300 } 1301 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical); 1302 VectorTypes.InsertNode(New, InsertPos); 1303 Types.push_back(New); 1304 return QualType(New, 0); 1305} 1306 1307/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1308/// 1309QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) { 1310 // Unique functions, to guarantee there is only one function of a particular 1311 // structure. 1312 llvm::FoldingSetNodeID ID; 1313 FunctionNoProtoType::Profile(ID, ResultTy); 1314 1315 void *InsertPos = 0; 1316 if (FunctionNoProtoType *FT = 1317 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1318 return QualType(FT, 0); 1319 1320 QualType Canonical; 1321 if (!ResultTy->isCanonical()) { 1322 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy)); 1323 1324 // Get the new insert position for the node we care about. 1325 FunctionNoProtoType *NewIP = 1326 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1327 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1328 } 1329 1330 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical); 1331 Types.push_back(New); 1332 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1333 return QualType(New, 0); 1334} 1335 1336/// getFunctionType - Return a normal function type with a typed argument 1337/// list. isVariadic indicates whether the argument list includes '...'. 1338QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1339 unsigned NumArgs, bool isVariadic, 1340 unsigned TypeQuals) { 1341 // Unique functions, to guarantee there is only one function of a particular 1342 // structure. 1343 llvm::FoldingSetNodeID ID; 1344 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1345 TypeQuals); 1346 1347 void *InsertPos = 0; 1348 if (FunctionProtoType *FTP = 1349 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1350 return QualType(FTP, 0); 1351 1352 // Determine whether the type being created is already canonical or not. 1353 bool isCanonical = ResultTy->isCanonical(); 1354 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1355 if (!ArgArray[i]->isCanonical()) 1356 isCanonical = false; 1357 1358 // If this type isn't canonical, get the canonical version of it. 1359 QualType Canonical; 1360 if (!isCanonical) { 1361 llvm::SmallVector<QualType, 16> CanonicalArgs; 1362 CanonicalArgs.reserve(NumArgs); 1363 for (unsigned i = 0; i != NumArgs; ++i) 1364 CanonicalArgs.push_back(getCanonicalType(ArgArray[i])); 1365 1366 Canonical = getFunctionType(getCanonicalType(ResultTy), 1367 CanonicalArgs.data(), NumArgs, 1368 isVariadic, TypeQuals); 1369 1370 // Get the new insert position for the node we care about. 1371 FunctionProtoType *NewIP = 1372 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1373 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1374 } 1375 1376 // FunctionProtoType objects are allocated with extra bytes after them 1377 // for a variable size array (for parameter types) at the end of them. 1378 FunctionProtoType *FTP = 1379 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1380 NumArgs*sizeof(QualType), 8); 1381 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1382 TypeQuals, Canonical); 1383 Types.push_back(FTP); 1384 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1385 return QualType(FTP, 0); 1386} 1387 1388/// getTypeDeclType - Return the unique reference to the type for the 1389/// specified type declaration. 1390QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { 1391 assert(Decl && "Passed null for Decl param"); 1392 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1393 1394 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1395 return getTypedefType(Typedef); 1396 else if (isa<TemplateTypeParmDecl>(Decl)) { 1397 assert(false && "Template type parameter types are always available."); 1398 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl)) 1399 return getObjCInterfaceType(ObjCInterface); 1400 1401 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1402 if (PrevDecl) 1403 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1404 else 1405 Decl->TypeForDecl = new (*this,8) RecordType(Record); 1406 } 1407 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1408 if (PrevDecl) 1409 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1410 else 1411 Decl->TypeForDecl = new (*this,8) EnumType(Enum); 1412 } 1413 else 1414 assert(false && "TypeDecl without a type?"); 1415 1416 if (!PrevDecl) Types.push_back(Decl->TypeForDecl); 1417 return QualType(Decl->TypeForDecl, 0); 1418} 1419 1420/// getTypedefType - Return the unique reference to the type for the 1421/// specified typename decl. 1422QualType ASTContext::getTypedefType(TypedefDecl *Decl) { 1423 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1424 1425 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 1426 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical); 1427 Types.push_back(Decl->TypeForDecl); 1428 return QualType(Decl->TypeForDecl, 0); 1429} 1430 1431/// getObjCInterfaceType - Return the unique reference to the type for the 1432/// specified ObjC interface decl. 1433QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 1434 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1435 1436 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl); 1437 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID); 1438 Types.push_back(Decl->TypeForDecl); 1439 return QualType(Decl->TypeForDecl, 0); 1440} 1441 1442/// \brief Retrieve the template type parameter type for a template 1443/// parameter with the given depth, index, and (optionally) name. 1444QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1445 IdentifierInfo *Name) { 1446 llvm::FoldingSetNodeID ID; 1447 TemplateTypeParmType::Profile(ID, Depth, Index, Name); 1448 void *InsertPos = 0; 1449 TemplateTypeParmType *TypeParm 1450 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1451 1452 if (TypeParm) 1453 return QualType(TypeParm, 0); 1454 1455 if (Name) 1456 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name, 1457 getTemplateTypeParmType(Depth, Index)); 1458 else 1459 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index); 1460 1461 Types.push_back(TypeParm); 1462 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1463 1464 return QualType(TypeParm, 0); 1465} 1466 1467QualType 1468ASTContext::getTemplateSpecializationType(TemplateName Template, 1469 const TemplateArgument *Args, 1470 unsigned NumArgs, 1471 QualType Canon) { 1472 if (!Canon.isNull()) 1473 Canon = getCanonicalType(Canon); 1474 1475 llvm::FoldingSetNodeID ID; 1476 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs); 1477 1478 void *InsertPos = 0; 1479 TemplateSpecializationType *Spec 1480 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 1481 1482 if (Spec) 1483 return QualType(Spec, 0); 1484 1485 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1486 sizeof(TemplateArgument) * NumArgs), 1487 8); 1488 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon); 1489 Types.push_back(Spec); 1490 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 1491 1492 return QualType(Spec, 0); 1493} 1494 1495QualType 1496ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS, 1497 QualType NamedType) { 1498 llvm::FoldingSetNodeID ID; 1499 QualifiedNameType::Profile(ID, NNS, NamedType); 1500 1501 void *InsertPos = 0; 1502 QualifiedNameType *T 1503 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); 1504 if (T) 1505 return QualType(T, 0); 1506 1507 T = new (*this) QualifiedNameType(NNS, NamedType, 1508 getCanonicalType(NamedType)); 1509 Types.push_back(T); 1510 QualifiedNameTypes.InsertNode(T, InsertPos); 1511 return QualType(T, 0); 1512} 1513 1514QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1515 const IdentifierInfo *Name, 1516 QualType Canon) { 1517 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1518 1519 if (Canon.isNull()) { 1520 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1521 if (CanonNNS != NNS) 1522 Canon = getTypenameType(CanonNNS, Name); 1523 } 1524 1525 llvm::FoldingSetNodeID ID; 1526 TypenameType::Profile(ID, NNS, Name); 1527 1528 void *InsertPos = 0; 1529 TypenameType *T 1530 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1531 if (T) 1532 return QualType(T, 0); 1533 1534 T = new (*this) TypenameType(NNS, Name, Canon); 1535 Types.push_back(T); 1536 TypenameTypes.InsertNode(T, InsertPos); 1537 return QualType(T, 0); 1538} 1539 1540QualType 1541ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1542 const TemplateSpecializationType *TemplateId, 1543 QualType Canon) { 1544 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1545 1546 if (Canon.isNull()) { 1547 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1548 QualType CanonType = getCanonicalType(QualType(TemplateId, 0)); 1549 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) { 1550 const TemplateSpecializationType *CanonTemplateId 1551 = CanonType->getAsTemplateSpecializationType(); 1552 assert(CanonTemplateId && 1553 "Canonical type must also be a template specialization type"); 1554 Canon = getTypenameType(CanonNNS, CanonTemplateId); 1555 } 1556 } 1557 1558 llvm::FoldingSetNodeID ID; 1559 TypenameType::Profile(ID, NNS, TemplateId); 1560 1561 void *InsertPos = 0; 1562 TypenameType *T 1563 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1564 if (T) 1565 return QualType(T, 0); 1566 1567 T = new (*this) TypenameType(NNS, TemplateId, Canon); 1568 Types.push_back(T); 1569 TypenameTypes.InsertNode(T, InsertPos); 1570 return QualType(T, 0); 1571} 1572 1573/// CmpProtocolNames - Comparison predicate for sorting protocols 1574/// alphabetically. 1575static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 1576 const ObjCProtocolDecl *RHS) { 1577 return LHS->getDeclName() < RHS->getDeclName(); 1578} 1579 1580static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, 1581 unsigned &NumProtocols) { 1582 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 1583 1584 // Sort protocols, keyed by name. 1585 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 1586 1587 // Remove duplicates. 1588 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 1589 NumProtocols = ProtocolsEnd-Protocols; 1590} 1591 1592 1593/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for 1594/// the given interface decl and the conforming protocol list. 1595QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl, 1596 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 1597 // Sort the protocol list alphabetically to canonicalize it. 1598 SortAndUniqueProtocols(Protocols, NumProtocols); 1599 1600 llvm::FoldingSetNodeID ID; 1601 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 1602 1603 void *InsertPos = 0; 1604 if (ObjCQualifiedInterfaceType *QT = 1605 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1606 return QualType(QT, 0); 1607 1608 // No Match; 1609 ObjCQualifiedInterfaceType *QType = 1610 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols); 1611 1612 Types.push_back(QType); 1613 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos); 1614 return QualType(QType, 0); 1615} 1616 1617/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl 1618/// and the conforming protocol list. 1619QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols, 1620 unsigned NumProtocols) { 1621 // Sort the protocol list alphabetically to canonicalize it. 1622 SortAndUniqueProtocols(Protocols, NumProtocols); 1623 1624 llvm::FoldingSetNodeID ID; 1625 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols); 1626 1627 void *InsertPos = 0; 1628 if (ObjCQualifiedIdType *QT = 1629 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos)) 1630 return QualType(QT, 0); 1631 1632 // No Match; 1633 ObjCQualifiedIdType *QType = 1634 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols); 1635 Types.push_back(QType); 1636 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos); 1637 return QualType(QType, 0); 1638} 1639 1640/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 1641/// TypeOfExprType AST's (since expression's are never shared). For example, 1642/// multiple declarations that refer to "typeof(x)" all contain different 1643/// DeclRefExpr's. This doesn't effect the type checker, since it operates 1644/// on canonical type's (which are always unique). 1645QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 1646 QualType Canonical = getCanonicalType(tofExpr->getType()); 1647 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical); 1648 Types.push_back(toe); 1649 return QualType(toe, 0); 1650} 1651 1652/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 1653/// TypeOfType AST's. The only motivation to unique these nodes would be 1654/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 1655/// an issue. This doesn't effect the type checker, since it operates 1656/// on canonical type's (which are always unique). 1657QualType ASTContext::getTypeOfType(QualType tofType) { 1658 QualType Canonical = getCanonicalType(tofType); 1659 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical); 1660 Types.push_back(tot); 1661 return QualType(tot, 0); 1662} 1663 1664/// getTagDeclType - Return the unique reference to the type for the 1665/// specified TagDecl (struct/union/class/enum) decl. 1666QualType ASTContext::getTagDeclType(TagDecl *Decl) { 1667 assert (Decl); 1668 return getTypeDeclType(Decl); 1669} 1670 1671/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 1672/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 1673/// needs to agree with the definition in <stddef.h>. 1674QualType ASTContext::getSizeType() const { 1675 return getFromTargetType(Target.getSizeType()); 1676} 1677 1678/// getSignedWCharType - Return the type of "signed wchar_t". 1679/// Used when in C++, as a GCC extension. 1680QualType ASTContext::getSignedWCharType() const { 1681 // FIXME: derive from "Target" ? 1682 return WCharTy; 1683} 1684 1685/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 1686/// Used when in C++, as a GCC extension. 1687QualType ASTContext::getUnsignedWCharType() const { 1688 // FIXME: derive from "Target" ? 1689 return UnsignedIntTy; 1690} 1691 1692/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 1693/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1694QualType ASTContext::getPointerDiffType() const { 1695 return getFromTargetType(Target.getPtrDiffType(0)); 1696} 1697 1698//===----------------------------------------------------------------------===// 1699// Type Operators 1700//===----------------------------------------------------------------------===// 1701 1702/// getCanonicalType - Return the canonical (structural) type corresponding to 1703/// the specified potentially non-canonical type. The non-canonical version 1704/// of a type may have many "decorated" versions of types. Decorators can 1705/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 1706/// to be free of any of these, allowing two canonical types to be compared 1707/// for exact equality with a simple pointer comparison. 1708QualType ASTContext::getCanonicalType(QualType T) { 1709 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); 1710 1711 // If the result has type qualifiers, make sure to canonicalize them as well. 1712 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); 1713 if (TypeQuals == 0) return CanType; 1714 1715 // If the type qualifiers are on an array type, get the canonical type of the 1716 // array with the qualifiers applied to the element type. 1717 ArrayType *AT = dyn_cast<ArrayType>(CanType); 1718 if (!AT) 1719 return CanType.getQualifiedType(TypeQuals); 1720 1721 // Get the canonical version of the element with the extra qualifiers on it. 1722 // This can recursively sink qualifiers through multiple levels of arrays. 1723 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); 1724 NewEltTy = getCanonicalType(NewEltTy); 1725 1726 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1727 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(), 1728 CAT->getIndexTypeQualifier()); 1729 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 1730 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 1731 IAT->getIndexTypeQualifier()); 1732 1733 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 1734 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(), 1735 DSAT->getSizeModifier(), 1736 DSAT->getIndexTypeQualifier()); 1737 1738 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1739 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1740 VAT->getSizeModifier(), 1741 VAT->getIndexTypeQualifier()); 1742} 1743 1744Decl *ASTContext::getCanonicalDecl(Decl *D) { 1745 if (!D) 1746 return 0; 1747 1748 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) { 1749 QualType T = getTagDeclType(Tag); 1750 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType) 1751 ->getDecl()); 1752 } 1753 1754 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) { 1755 while (Template->getPreviousDeclaration()) 1756 Template = Template->getPreviousDeclaration(); 1757 return Template; 1758 } 1759 1760 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 1761 while (Function->getPreviousDeclaration()) 1762 Function = Function->getPreviousDeclaration(); 1763 return const_cast<FunctionDecl *>(Function); 1764 } 1765 1766 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 1767 while (Var->getPreviousDeclaration()) 1768 Var = Var->getPreviousDeclaration(); 1769 return const_cast<VarDecl *>(Var); 1770 } 1771 1772 return D; 1773} 1774 1775TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 1776 // If this template name refers to a template, the canonical 1777 // template name merely stores the template itself. 1778 if (TemplateDecl *Template = Name.getAsTemplateDecl()) 1779 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template))); 1780 1781 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 1782 assert(DTN && "Non-dependent template names must refer to template decls."); 1783 return DTN->CanonicalTemplateName; 1784} 1785 1786NestedNameSpecifier * 1787ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 1788 if (!NNS) 1789 return 0; 1790 1791 switch (NNS->getKind()) { 1792 case NestedNameSpecifier::Identifier: 1793 // Canonicalize the prefix but keep the identifier the same. 1794 return NestedNameSpecifier::Create(*this, 1795 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 1796 NNS->getAsIdentifier()); 1797 1798 case NestedNameSpecifier::Namespace: 1799 // A namespace is canonical; build a nested-name-specifier with 1800 // this namespace and no prefix. 1801 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 1802 1803 case NestedNameSpecifier::TypeSpec: 1804 case NestedNameSpecifier::TypeSpecWithTemplate: { 1805 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 1806 NestedNameSpecifier *Prefix = 0; 1807 1808 // FIXME: This isn't the right check! 1809 if (T->isDependentType()) 1810 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix()); 1811 1812 return NestedNameSpecifier::Create(*this, Prefix, 1813 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 1814 T.getTypePtr()); 1815 } 1816 1817 case NestedNameSpecifier::Global: 1818 // The global specifier is canonical and unique. 1819 return NNS; 1820 } 1821 1822 // Required to silence a GCC warning 1823 return 0; 1824} 1825 1826 1827const ArrayType *ASTContext::getAsArrayType(QualType T) { 1828 // Handle the non-qualified case efficiently. 1829 if (T.getCVRQualifiers() == 0) { 1830 // Handle the common positive case fast. 1831 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 1832 return AT; 1833 } 1834 1835 // Handle the common negative case fast, ignoring CVR qualifiers. 1836 QualType CType = T->getCanonicalTypeInternal(); 1837 1838 // Make sure to look through type qualifiers (like ExtQuals) for the negative 1839 // test. 1840 if (!isa<ArrayType>(CType) && 1841 !isa<ArrayType>(CType.getUnqualifiedType())) 1842 return 0; 1843 1844 // Apply any CVR qualifiers from the array type to the element type. This 1845 // implements C99 6.7.3p8: "If the specification of an array type includes 1846 // any type qualifiers, the element type is so qualified, not the array type." 1847 1848 // If we get here, we either have type qualifiers on the type, or we have 1849 // sugar such as a typedef in the way. If we have type qualifiers on the type 1850 // we must propagate them down into the elemeng type. 1851 unsigned CVRQuals = T.getCVRQualifiers(); 1852 unsigned AddrSpace = 0; 1853 Type *Ty = T.getTypePtr(); 1854 1855 // Rip through ExtQualType's and typedefs to get to a concrete type. 1856 while (1) { 1857 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) { 1858 AddrSpace = EXTQT->getAddressSpace(); 1859 Ty = EXTQT->getBaseType(); 1860 } else { 1861 T = Ty->getDesugaredType(); 1862 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0) 1863 break; 1864 CVRQuals |= T.getCVRQualifiers(); 1865 Ty = T.getTypePtr(); 1866 } 1867 } 1868 1869 // If we have a simple case, just return now. 1870 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 1871 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) 1872 return ATy; 1873 1874 // Otherwise, we have an array and we have qualifiers on it. Push the 1875 // qualifiers into the array element type and return a new array type. 1876 // Get the canonical version of the element with the extra qualifiers on it. 1877 // This can recursively sink qualifiers through multiple levels of arrays. 1878 QualType NewEltTy = ATy->getElementType(); 1879 if (AddrSpace) 1880 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace); 1881 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); 1882 1883 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 1884 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 1885 CAT->getSizeModifier(), 1886 CAT->getIndexTypeQualifier())); 1887 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 1888 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 1889 IAT->getSizeModifier(), 1890 IAT->getIndexTypeQualifier())); 1891 1892 if (const DependentSizedArrayType *DSAT 1893 = dyn_cast<DependentSizedArrayType>(ATy)) 1894 return cast<ArrayType>( 1895 getDependentSizedArrayType(NewEltTy, 1896 DSAT->getSizeExpr(), 1897 DSAT->getSizeModifier(), 1898 DSAT->getIndexTypeQualifier())); 1899 1900 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 1901 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1902 VAT->getSizeModifier(), 1903 VAT->getIndexTypeQualifier())); 1904} 1905 1906 1907/// getArrayDecayedType - Return the properly qualified result of decaying the 1908/// specified array type to a pointer. This operation is non-trivial when 1909/// handling typedefs etc. The canonical type of "T" must be an array type, 1910/// this returns a pointer to a properly qualified element of the array. 1911/// 1912/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 1913QualType ASTContext::getArrayDecayedType(QualType Ty) { 1914 // Get the element type with 'getAsArrayType' so that we don't lose any 1915 // typedefs in the element type of the array. This also handles propagation 1916 // of type qualifiers from the array type into the element type if present 1917 // (C99 6.7.3p8). 1918 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 1919 assert(PrettyArrayType && "Not an array type!"); 1920 1921 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 1922 1923 // int x[restrict 4] -> int *restrict 1924 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier()); 1925} 1926 1927QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) { 1928 QualType ElemTy = VAT->getElementType(); 1929 1930 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy)) 1931 return getBaseElementType(VAT); 1932 1933 return ElemTy; 1934} 1935 1936/// getFloatingRank - Return a relative rank for floating point types. 1937/// This routine will assert if passed a built-in type that isn't a float. 1938static FloatingRank getFloatingRank(QualType T) { 1939 if (const ComplexType *CT = T->getAsComplexType()) 1940 return getFloatingRank(CT->getElementType()); 1941 1942 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type"); 1943 switch (T->getAsBuiltinType()->getKind()) { 1944 default: assert(0 && "getFloatingRank(): not a floating type"); 1945 case BuiltinType::Float: return FloatRank; 1946 case BuiltinType::Double: return DoubleRank; 1947 case BuiltinType::LongDouble: return LongDoubleRank; 1948 } 1949} 1950 1951/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 1952/// point or a complex type (based on typeDomain/typeSize). 1953/// 'typeDomain' is a real floating point or complex type. 1954/// 'typeSize' is a real floating point or complex type. 1955QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 1956 QualType Domain) const { 1957 FloatingRank EltRank = getFloatingRank(Size); 1958 if (Domain->isComplexType()) { 1959 switch (EltRank) { 1960 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1961 case FloatRank: return FloatComplexTy; 1962 case DoubleRank: return DoubleComplexTy; 1963 case LongDoubleRank: return LongDoubleComplexTy; 1964 } 1965 } 1966 1967 assert(Domain->isRealFloatingType() && "Unknown domain!"); 1968 switch (EltRank) { 1969 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1970 case FloatRank: return FloatTy; 1971 case DoubleRank: return DoubleTy; 1972 case LongDoubleRank: return LongDoubleTy; 1973 } 1974} 1975 1976/// getFloatingTypeOrder - Compare the rank of the two specified floating 1977/// point types, ignoring the domain of the type (i.e. 'double' == 1978/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 1979/// LHS < RHS, return -1. 1980int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 1981 FloatingRank LHSR = getFloatingRank(LHS); 1982 FloatingRank RHSR = getFloatingRank(RHS); 1983 1984 if (LHSR == RHSR) 1985 return 0; 1986 if (LHSR > RHSR) 1987 return 1; 1988 return -1; 1989} 1990 1991/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 1992/// routine will assert if passed a built-in type that isn't an integer or enum, 1993/// or if it is not canonicalized. 1994unsigned ASTContext::getIntegerRank(Type *T) { 1995 assert(T->isCanonical() && "T should be canonicalized"); 1996 if (EnumType* ET = dyn_cast<EnumType>(T)) 1997 T = ET->getDecl()->getIntegerType().getTypePtr(); 1998 1999 // There are two things which impact the integer rank: the width, and 2000 // the ordering of builtins. The builtin ordering is encoded in the 2001 // bottom three bits; the width is encoded in the bits above that. 2002 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 2003 return FWIT->getWidth() << 3; 2004 } 2005 2006 switch (cast<BuiltinType>(T)->getKind()) { 2007 default: assert(0 && "getIntegerRank(): not a built-in integer"); 2008 case BuiltinType::Bool: 2009 return 1 + (getIntWidth(BoolTy) << 3); 2010 case BuiltinType::Char_S: 2011 case BuiltinType::Char_U: 2012 case BuiltinType::SChar: 2013 case BuiltinType::UChar: 2014 return 2 + (getIntWidth(CharTy) << 3); 2015 case BuiltinType::Short: 2016 case BuiltinType::UShort: 2017 return 3 + (getIntWidth(ShortTy) << 3); 2018 case BuiltinType::Int: 2019 case BuiltinType::UInt: 2020 return 4 + (getIntWidth(IntTy) << 3); 2021 case BuiltinType::Long: 2022 case BuiltinType::ULong: 2023 return 5 + (getIntWidth(LongTy) << 3); 2024 case BuiltinType::LongLong: 2025 case BuiltinType::ULongLong: 2026 return 6 + (getIntWidth(LongLongTy) << 3); 2027 case BuiltinType::Int128: 2028 case BuiltinType::UInt128: 2029 return 7 + (getIntWidth(Int128Ty) << 3); 2030 } 2031} 2032 2033/// getIntegerTypeOrder - Returns the highest ranked integer type: 2034/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 2035/// LHS < RHS, return -1. 2036int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 2037 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 2038 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 2039 if (LHSC == RHSC) return 0; 2040 2041 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 2042 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 2043 2044 unsigned LHSRank = getIntegerRank(LHSC); 2045 unsigned RHSRank = getIntegerRank(RHSC); 2046 2047 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 2048 if (LHSRank == RHSRank) return 0; 2049 return LHSRank > RHSRank ? 1 : -1; 2050 } 2051 2052 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 2053 if (LHSUnsigned) { 2054 // If the unsigned [LHS] type is larger, return it. 2055 if (LHSRank >= RHSRank) 2056 return 1; 2057 2058 // If the signed type can represent all values of the unsigned type, it 2059 // wins. Because we are dealing with 2's complement and types that are 2060 // powers of two larger than each other, this is always safe. 2061 return -1; 2062 } 2063 2064 // If the unsigned [RHS] type is larger, return it. 2065 if (RHSRank >= LHSRank) 2066 return -1; 2067 2068 // If the signed type can represent all values of the unsigned type, it 2069 // wins. Because we are dealing with 2's complement and types that are 2070 // powers of two larger than each other, this is always safe. 2071 return 1; 2072} 2073 2074// getCFConstantStringType - Return the type used for constant CFStrings. 2075QualType ASTContext::getCFConstantStringType() { 2076 if (!CFConstantStringTypeDecl) { 2077 CFConstantStringTypeDecl = 2078 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2079 &Idents.get("NSConstantString")); 2080 QualType FieldTypes[4]; 2081 2082 // const int *isa; 2083 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); 2084 // int flags; 2085 FieldTypes[1] = IntTy; 2086 // const char *str; 2087 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); 2088 // long length; 2089 FieldTypes[3] = LongTy; 2090 2091 // Create fields 2092 for (unsigned i = 0; i < 4; ++i) { 2093 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 2094 SourceLocation(), 0, 2095 FieldTypes[i], /*BitWidth=*/0, 2096 /*Mutable=*/false); 2097 CFConstantStringTypeDecl->addDecl(*this, Field); 2098 } 2099 2100 CFConstantStringTypeDecl->completeDefinition(*this); 2101 } 2102 2103 return getTagDeclType(CFConstantStringTypeDecl); 2104} 2105 2106void ASTContext::setCFConstantStringType(QualType T) { 2107 const RecordType *Rec = T->getAsRecordType(); 2108 assert(Rec && "Invalid CFConstantStringType"); 2109 CFConstantStringTypeDecl = Rec->getDecl(); 2110} 2111 2112QualType ASTContext::getObjCFastEnumerationStateType() 2113{ 2114 if (!ObjCFastEnumerationStateTypeDecl) { 2115 ObjCFastEnumerationStateTypeDecl = 2116 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2117 &Idents.get("__objcFastEnumerationState")); 2118 2119 QualType FieldTypes[] = { 2120 UnsignedLongTy, 2121 getPointerType(ObjCIdType), 2122 getPointerType(UnsignedLongTy), 2123 getConstantArrayType(UnsignedLongTy, 2124 llvm::APInt(32, 5), ArrayType::Normal, 0) 2125 }; 2126 2127 for (size_t i = 0; i < 4; ++i) { 2128 FieldDecl *Field = FieldDecl::Create(*this, 2129 ObjCFastEnumerationStateTypeDecl, 2130 SourceLocation(), 0, 2131 FieldTypes[i], /*BitWidth=*/0, 2132 /*Mutable=*/false); 2133 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field); 2134 } 2135 2136 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this); 2137 } 2138 2139 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 2140} 2141 2142void ASTContext::setObjCFastEnumerationStateType(QualType T) { 2143 const RecordType *Rec = T->getAsRecordType(); 2144 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 2145 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 2146} 2147 2148// This returns true if a type has been typedefed to BOOL: 2149// typedef <type> BOOL; 2150static bool isTypeTypedefedAsBOOL(QualType T) { 2151 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 2152 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 2153 return II->isStr("BOOL"); 2154 2155 return false; 2156} 2157 2158/// getObjCEncodingTypeSize returns size of type for objective-c encoding 2159/// purpose. 2160int ASTContext::getObjCEncodingTypeSize(QualType type) { 2161 uint64_t sz = getTypeSize(type); 2162 2163 // Make all integer and enum types at least as large as an int 2164 if (sz > 0 && type->isIntegralType()) 2165 sz = std::max(sz, getTypeSize(IntTy)); 2166 // Treat arrays as pointers, since that's how they're passed in. 2167 else if (type->isArrayType()) 2168 sz = getTypeSize(VoidPtrTy); 2169 return sz / getTypeSize(CharTy); 2170} 2171 2172/// getObjCEncodingForMethodDecl - Return the encoded type for this method 2173/// declaration. 2174void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 2175 std::string& S) { 2176 // FIXME: This is not very efficient. 2177 // Encode type qualifer, 'in', 'inout', etc. for the return type. 2178 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 2179 // Encode result type. 2180 getObjCEncodingForType(Decl->getResultType(), S); 2181 // Compute size of all parameters. 2182 // Start with computing size of a pointer in number of bytes. 2183 // FIXME: There might(should) be a better way of doing this computation! 2184 SourceLocation Loc; 2185 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy); 2186 // The first two arguments (self and _cmd) are pointers; account for 2187 // their size. 2188 int ParmOffset = 2 * PtrSize; 2189 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2190 E = Decl->param_end(); PI != E; ++PI) { 2191 QualType PType = (*PI)->getType(); 2192 int sz = getObjCEncodingTypeSize(PType); 2193 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type"); 2194 ParmOffset += sz; 2195 } 2196 S += llvm::utostr(ParmOffset); 2197 S += "@0:"; 2198 S += llvm::utostr(PtrSize); 2199 2200 // Argument types. 2201 ParmOffset = 2 * PtrSize; 2202 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2203 E = Decl->param_end(); PI != E; ++PI) { 2204 ParmVarDecl *PVDecl = *PI; 2205 QualType PType = PVDecl->getOriginalType(); 2206 if (const ArrayType *AT = 2207 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 2208 // Use array's original type only if it has known number of 2209 // elements. 2210 if (!isa<ConstantArrayType>(AT)) 2211 PType = PVDecl->getType(); 2212 } else if (PType->isFunctionType()) 2213 PType = PVDecl->getType(); 2214 // Process argument qualifiers for user supplied arguments; such as, 2215 // 'in', 'inout', etc. 2216 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 2217 getObjCEncodingForType(PType, S); 2218 S += llvm::utostr(ParmOffset); 2219 ParmOffset += getObjCEncodingTypeSize(PType); 2220 } 2221} 2222 2223/// getObjCEncodingForPropertyDecl - Return the encoded type for this 2224/// property declaration. If non-NULL, Container must be either an 2225/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 2226/// NULL when getting encodings for protocol properties. 2227/// Property attributes are stored as a comma-delimited C string. The simple 2228/// attributes readonly and bycopy are encoded as single characters. The 2229/// parametrized attributes, getter=name, setter=name, and ivar=name, are 2230/// encoded as single characters, followed by an identifier. Property types 2231/// are also encoded as a parametrized attribute. The characters used to encode 2232/// these attributes are defined by the following enumeration: 2233/// @code 2234/// enum PropertyAttributes { 2235/// kPropertyReadOnly = 'R', // property is read-only. 2236/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 2237/// kPropertyByref = '&', // property is a reference to the value last assigned 2238/// kPropertyDynamic = 'D', // property is dynamic 2239/// kPropertyGetter = 'G', // followed by getter selector name 2240/// kPropertySetter = 'S', // followed by setter selector name 2241/// kPropertyInstanceVariable = 'V' // followed by instance variable name 2242/// kPropertyType = 't' // followed by old-style type encoding. 2243/// kPropertyWeak = 'W' // 'weak' property 2244/// kPropertyStrong = 'P' // property GC'able 2245/// kPropertyNonAtomic = 'N' // property non-atomic 2246/// }; 2247/// @endcode 2248void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 2249 const Decl *Container, 2250 std::string& S) { 2251 // Collect information from the property implementation decl(s). 2252 bool Dynamic = false; 2253 ObjCPropertyImplDecl *SynthesizePID = 0; 2254 2255 // FIXME: Duplicated code due to poor abstraction. 2256 if (Container) { 2257 if (const ObjCCategoryImplDecl *CID = 2258 dyn_cast<ObjCCategoryImplDecl>(Container)) { 2259 for (ObjCCategoryImplDecl::propimpl_iterator 2260 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this); 2261 i != e; ++i) { 2262 ObjCPropertyImplDecl *PID = *i; 2263 if (PID->getPropertyDecl() == PD) { 2264 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2265 Dynamic = true; 2266 } else { 2267 SynthesizePID = PID; 2268 } 2269 } 2270 } 2271 } else { 2272 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 2273 for (ObjCCategoryImplDecl::propimpl_iterator 2274 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this); 2275 i != e; ++i) { 2276 ObjCPropertyImplDecl *PID = *i; 2277 if (PID->getPropertyDecl() == PD) { 2278 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2279 Dynamic = true; 2280 } else { 2281 SynthesizePID = PID; 2282 } 2283 } 2284 } 2285 } 2286 } 2287 2288 // FIXME: This is not very efficient. 2289 S = "T"; 2290 2291 // Encode result type. 2292 // GCC has some special rules regarding encoding of properties which 2293 // closely resembles encoding of ivars. 2294 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 2295 true /* outermost type */, 2296 true /* encoding for property */); 2297 2298 if (PD->isReadOnly()) { 2299 S += ",R"; 2300 } else { 2301 switch (PD->getSetterKind()) { 2302 case ObjCPropertyDecl::Assign: break; 2303 case ObjCPropertyDecl::Copy: S += ",C"; break; 2304 case ObjCPropertyDecl::Retain: S += ",&"; break; 2305 } 2306 } 2307 2308 // It really isn't clear at all what this means, since properties 2309 // are "dynamic by default". 2310 if (Dynamic) 2311 S += ",D"; 2312 2313 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 2314 S += ",N"; 2315 2316 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 2317 S += ",G"; 2318 S += PD->getGetterName().getAsString(); 2319 } 2320 2321 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 2322 S += ",S"; 2323 S += PD->getSetterName().getAsString(); 2324 } 2325 2326 if (SynthesizePID) { 2327 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 2328 S += ",V"; 2329 S += OID->getNameAsString(); 2330 } 2331 2332 // FIXME: OBJCGC: weak & strong 2333} 2334 2335/// getLegacyIntegralTypeEncoding - 2336/// Another legacy compatibility encoding: 32-bit longs are encoded as 2337/// 'l' or 'L' , but not always. For typedefs, we need to use 2338/// 'i' or 'I' instead if encoding a struct field, or a pointer! 2339/// 2340void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 2341 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) { 2342 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) { 2343 if (BT->getKind() == BuiltinType::ULong && 2344 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2345 PointeeTy = UnsignedIntTy; 2346 else 2347 if (BT->getKind() == BuiltinType::Long && 2348 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2349 PointeeTy = IntTy; 2350 } 2351 } 2352} 2353 2354void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 2355 const FieldDecl *Field) { 2356 // We follow the behavior of gcc, expanding structures which are 2357 // directly pointed to, and expanding embedded structures. Note that 2358 // these rules are sufficient to prevent recursive encoding of the 2359 // same type. 2360 getObjCEncodingForTypeImpl(T, S, true, true, Field, 2361 true /* outermost type */); 2362} 2363 2364static void EncodeBitField(const ASTContext *Context, std::string& S, 2365 const FieldDecl *FD) { 2366 const Expr *E = FD->getBitWidth(); 2367 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 2368 ASTContext *Ctx = const_cast<ASTContext*>(Context); 2369 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 2370 S += 'b'; 2371 S += llvm::utostr(N); 2372} 2373 2374void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 2375 bool ExpandPointedToStructures, 2376 bool ExpandStructures, 2377 const FieldDecl *FD, 2378 bool OutermostType, 2379 bool EncodingProperty) { 2380 if (const BuiltinType *BT = T->getAsBuiltinType()) { 2381 if (FD && FD->isBitField()) { 2382 EncodeBitField(this, S, FD); 2383 } 2384 else { 2385 char encoding; 2386 switch (BT->getKind()) { 2387 default: assert(0 && "Unhandled builtin type kind"); 2388 case BuiltinType::Void: encoding = 'v'; break; 2389 case BuiltinType::Bool: encoding = 'B'; break; 2390 case BuiltinType::Char_U: 2391 case BuiltinType::UChar: encoding = 'C'; break; 2392 case BuiltinType::UShort: encoding = 'S'; break; 2393 case BuiltinType::UInt: encoding = 'I'; break; 2394 case BuiltinType::ULong: 2395 encoding = 2396 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; 2397 break; 2398 case BuiltinType::UInt128: encoding = 'T'; break; 2399 case BuiltinType::ULongLong: encoding = 'Q'; break; 2400 case BuiltinType::Char_S: 2401 case BuiltinType::SChar: encoding = 'c'; break; 2402 case BuiltinType::Short: encoding = 's'; break; 2403 case BuiltinType::Int: encoding = 'i'; break; 2404 case BuiltinType::Long: 2405 encoding = 2406 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q'; 2407 break; 2408 case BuiltinType::LongLong: encoding = 'q'; break; 2409 case BuiltinType::Int128: encoding = 't'; break; 2410 case BuiltinType::Float: encoding = 'f'; break; 2411 case BuiltinType::Double: encoding = 'd'; break; 2412 case BuiltinType::LongDouble: encoding = 'd'; break; 2413 } 2414 2415 S += encoding; 2416 } 2417 } else if (const ComplexType *CT = T->getAsComplexType()) { 2418 S += 'j'; 2419 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 2420 false); 2421 } else if (T->isObjCQualifiedIdType()) { 2422 getObjCEncodingForTypeImpl(getObjCIdType(), S, 2423 ExpandPointedToStructures, 2424 ExpandStructures, FD); 2425 if (FD || EncodingProperty) { 2426 // Note that we do extended encoding of protocol qualifer list 2427 // Only when doing ivar or property encoding. 2428 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType(); 2429 S += '"'; 2430 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) { 2431 ObjCProtocolDecl *Proto = QIDT->getProtocols(i); 2432 S += '<'; 2433 S += Proto->getNameAsString(); 2434 S += '>'; 2435 } 2436 S += '"'; 2437 } 2438 return; 2439 } 2440 else if (const PointerType *PT = T->getAsPointerType()) { 2441 QualType PointeeTy = PT->getPointeeType(); 2442 bool isReadOnly = false; 2443 // For historical/compatibility reasons, the read-only qualifier of the 2444 // pointee gets emitted _before_ the '^'. The read-only qualifier of 2445 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 2446 // Also, do not emit the 'r' for anything but the outermost type! 2447 if (dyn_cast<TypedefType>(T.getTypePtr())) { 2448 if (OutermostType && T.isConstQualified()) { 2449 isReadOnly = true; 2450 S += 'r'; 2451 } 2452 } 2453 else if (OutermostType) { 2454 QualType P = PointeeTy; 2455 while (P->getAsPointerType()) 2456 P = P->getAsPointerType()->getPointeeType(); 2457 if (P.isConstQualified()) { 2458 isReadOnly = true; 2459 S += 'r'; 2460 } 2461 } 2462 if (isReadOnly) { 2463 // Another legacy compatibility encoding. Some ObjC qualifier and type 2464 // combinations need to be rearranged. 2465 // Rewrite "in const" from "nr" to "rn" 2466 const char * s = S.c_str(); 2467 int len = S.length(); 2468 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') { 2469 std::string replace = "rn"; 2470 S.replace(S.end()-2, S.end(), replace); 2471 } 2472 } 2473 if (isObjCIdStructType(PointeeTy)) { 2474 S += '@'; 2475 return; 2476 } 2477 else if (PointeeTy->isObjCInterfaceType()) { 2478 if (!EncodingProperty && 2479 isa<TypedefType>(PointeeTy.getTypePtr())) { 2480 // Another historical/compatibility reason. 2481 // We encode the underlying type which comes out as 2482 // {...}; 2483 S += '^'; 2484 getObjCEncodingForTypeImpl(PointeeTy, S, 2485 false, ExpandPointedToStructures, 2486 NULL); 2487 return; 2488 } 2489 S += '@'; 2490 if (FD || EncodingProperty) { 2491 const ObjCInterfaceType *OIT = 2492 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType(); 2493 ObjCInterfaceDecl *OI = OIT->getDecl(); 2494 S += '"'; 2495 S += OI->getNameAsCString(); 2496 for (unsigned i =0; i < OIT->getNumProtocols(); i++) { 2497 ObjCProtocolDecl *Proto = OIT->getProtocol(i); 2498 S += '<'; 2499 S += Proto->getNameAsString(); 2500 S += '>'; 2501 } 2502 S += '"'; 2503 } 2504 return; 2505 } else if (isObjCClassStructType(PointeeTy)) { 2506 S += '#'; 2507 return; 2508 } else if (isObjCSelType(PointeeTy)) { 2509 S += ':'; 2510 return; 2511 } 2512 2513 if (PointeeTy->isCharType()) { 2514 // char pointer types should be encoded as '*' unless it is a 2515 // type that has been typedef'd to 'BOOL'. 2516 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 2517 S += '*'; 2518 return; 2519 } 2520 } 2521 2522 S += '^'; 2523 getLegacyIntegralTypeEncoding(PointeeTy); 2524 2525 getObjCEncodingForTypeImpl(PointeeTy, S, 2526 false, ExpandPointedToStructures, 2527 NULL); 2528 } else if (const ArrayType *AT = 2529 // Ignore type qualifiers etc. 2530 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 2531 if (isa<IncompleteArrayType>(AT)) { 2532 // Incomplete arrays are encoded as a pointer to the array element. 2533 S += '^'; 2534 2535 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2536 false, ExpandStructures, FD); 2537 } else { 2538 S += '['; 2539 2540 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2541 S += llvm::utostr(CAT->getSize().getZExtValue()); 2542 else { 2543 //Variable length arrays are encoded as a regular array with 0 elements. 2544 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 2545 S += '0'; 2546 } 2547 2548 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2549 false, ExpandStructures, FD); 2550 S += ']'; 2551 } 2552 } else if (T->getAsFunctionType()) { 2553 S += '?'; 2554 } else if (const RecordType *RTy = T->getAsRecordType()) { 2555 RecordDecl *RDecl = RTy->getDecl(); 2556 S += RDecl->isUnion() ? '(' : '{'; 2557 // Anonymous structures print as '?' 2558 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 2559 S += II->getName(); 2560 } else { 2561 S += '?'; 2562 } 2563 if (ExpandStructures) { 2564 S += '='; 2565 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this), 2566 FieldEnd = RDecl->field_end(*this); 2567 Field != FieldEnd; ++Field) { 2568 if (FD) { 2569 S += '"'; 2570 S += Field->getNameAsString(); 2571 S += '"'; 2572 } 2573 2574 // Special case bit-fields. 2575 if (Field->isBitField()) { 2576 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 2577 (*Field)); 2578 } else { 2579 QualType qt = Field->getType(); 2580 getLegacyIntegralTypeEncoding(qt); 2581 getObjCEncodingForTypeImpl(qt, S, false, true, 2582 FD); 2583 } 2584 } 2585 } 2586 S += RDecl->isUnion() ? ')' : '}'; 2587 } else if (T->isEnumeralType()) { 2588 if (FD && FD->isBitField()) 2589 EncodeBitField(this, S, FD); 2590 else 2591 S += 'i'; 2592 } else if (T->isBlockPointerType()) { 2593 S += "@?"; // Unlike a pointer-to-function, which is "^?". 2594 } else if (T->isObjCInterfaceType()) { 2595 // @encode(class_name) 2596 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl(); 2597 S += '{'; 2598 const IdentifierInfo *II = OI->getIdentifier(); 2599 S += II->getName(); 2600 S += '='; 2601 llvm::SmallVector<FieldDecl*, 32> RecFields; 2602 CollectObjCIvars(OI, RecFields); 2603 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2604 if (RecFields[i]->isBitField()) 2605 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2606 RecFields[i]); 2607 else 2608 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2609 FD); 2610 } 2611 S += '}'; 2612 } 2613 else 2614 assert(0 && "@encode for type not implemented!"); 2615} 2616 2617void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 2618 std::string& S) const { 2619 if (QT & Decl::OBJC_TQ_In) 2620 S += 'n'; 2621 if (QT & Decl::OBJC_TQ_Inout) 2622 S += 'N'; 2623 if (QT & Decl::OBJC_TQ_Out) 2624 S += 'o'; 2625 if (QT & Decl::OBJC_TQ_Bycopy) 2626 S += 'O'; 2627 if (QT & Decl::OBJC_TQ_Byref) 2628 S += 'R'; 2629 if (QT & Decl::OBJC_TQ_Oneway) 2630 S += 'V'; 2631} 2632 2633void ASTContext::setBuiltinVaListType(QualType T) 2634{ 2635 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 2636 2637 BuiltinVaListType = T; 2638} 2639 2640void ASTContext::setObjCIdType(QualType T) 2641{ 2642 ObjCIdType = T; 2643 2644 const TypedefType *TT = T->getAsTypedefType(); 2645 if (!TT) 2646 return; 2647 2648 TypedefDecl *TD = TT->getDecl(); 2649 2650 // typedef struct objc_object *id; 2651 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2652 // User error - caller will issue diagnostics. 2653 if (!ptr) 2654 return; 2655 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2656 // User error - caller will issue diagnostics. 2657 if (!rec) 2658 return; 2659 IdStructType = rec; 2660} 2661 2662void ASTContext::setObjCSelType(QualType T) 2663{ 2664 ObjCSelType = T; 2665 2666 const TypedefType *TT = T->getAsTypedefType(); 2667 if (!TT) 2668 return; 2669 TypedefDecl *TD = TT->getDecl(); 2670 2671 // typedef struct objc_selector *SEL; 2672 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2673 if (!ptr) 2674 return; 2675 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2676 if (!rec) 2677 return; 2678 SelStructType = rec; 2679} 2680 2681void ASTContext::setObjCProtoType(QualType QT) 2682{ 2683 ObjCProtoType = QT; 2684} 2685 2686void ASTContext::setObjCClassType(QualType T) 2687{ 2688 ObjCClassType = T; 2689 2690 const TypedefType *TT = T->getAsTypedefType(); 2691 if (!TT) 2692 return; 2693 TypedefDecl *TD = TT->getDecl(); 2694 2695 // typedef struct objc_class *Class; 2696 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2697 assert(ptr && "'Class' incorrectly typed"); 2698 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2699 assert(rec && "'Class' incorrectly typed"); 2700 ClassStructType = rec; 2701} 2702 2703void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 2704 assert(ObjCConstantStringType.isNull() && 2705 "'NSConstantString' type already set!"); 2706 2707 ObjCConstantStringType = getObjCInterfaceType(Decl); 2708} 2709 2710/// \brief Retrieve the template name that represents a qualified 2711/// template name such as \c std::vector. 2712TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 2713 bool TemplateKeyword, 2714 TemplateDecl *Template) { 2715 llvm::FoldingSetNodeID ID; 2716 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 2717 2718 void *InsertPos = 0; 2719 QualifiedTemplateName *QTN = 2720 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2721 if (!QTN) { 2722 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 2723 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 2724 } 2725 2726 return TemplateName(QTN); 2727} 2728 2729/// \brief Retrieve the template name that represents a dependent 2730/// template name such as \c MetaFun::template apply. 2731TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 2732 const IdentifierInfo *Name) { 2733 assert(NNS->isDependent() && "Nested name specifier must be dependent"); 2734 2735 llvm::FoldingSetNodeID ID; 2736 DependentTemplateName::Profile(ID, NNS, Name); 2737 2738 void *InsertPos = 0; 2739 DependentTemplateName *QTN = 2740 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2741 2742 if (QTN) 2743 return TemplateName(QTN); 2744 2745 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2746 if (CanonNNS == NNS) { 2747 QTN = new (*this,4) DependentTemplateName(NNS, Name); 2748 } else { 2749 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 2750 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 2751 } 2752 2753 DependentTemplateNames.InsertNode(QTN, InsertPos); 2754 return TemplateName(QTN); 2755} 2756 2757/// getFromTargetType - Given one of the integer types provided by 2758/// TargetInfo, produce the corresponding type. The unsigned @p Type 2759/// is actually a value of type @c TargetInfo::IntType. 2760QualType ASTContext::getFromTargetType(unsigned Type) const { 2761 switch (Type) { 2762 case TargetInfo::NoInt: return QualType(); 2763 case TargetInfo::SignedShort: return ShortTy; 2764 case TargetInfo::UnsignedShort: return UnsignedShortTy; 2765 case TargetInfo::SignedInt: return IntTy; 2766 case TargetInfo::UnsignedInt: return UnsignedIntTy; 2767 case TargetInfo::SignedLong: return LongTy; 2768 case TargetInfo::UnsignedLong: return UnsignedLongTy; 2769 case TargetInfo::SignedLongLong: return LongLongTy; 2770 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 2771 } 2772 2773 assert(false && "Unhandled TargetInfo::IntType value"); 2774 return QualType(); 2775} 2776 2777//===----------------------------------------------------------------------===// 2778// Type Predicates. 2779//===----------------------------------------------------------------------===// 2780 2781/// isObjCNSObjectType - Return true if this is an NSObject object using 2782/// NSObject attribute on a c-style pointer type. 2783/// FIXME - Make it work directly on types. 2784/// 2785bool ASTContext::isObjCNSObjectType(QualType Ty) const { 2786 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 2787 if (TypedefDecl *TD = TDT->getDecl()) 2788 if (TD->getAttr<ObjCNSObjectAttr>()) 2789 return true; 2790 } 2791 return false; 2792} 2793 2794/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 2795/// to an object type. This includes "id" and "Class" (two 'special' pointers 2796/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 2797/// ID type). 2798bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 2799 if (Ty->isObjCQualifiedIdType()) 2800 return true; 2801 2802 // Blocks are objects. 2803 if (Ty->isBlockPointerType()) 2804 return true; 2805 2806 // All other object types are pointers. 2807 const PointerType *PT = Ty->getAsPointerType(); 2808 if (PT == 0) 2809 return false; 2810 2811 // If this a pointer to an interface (e.g. NSString*), it is ok. 2812 if (PT->getPointeeType()->isObjCInterfaceType() || 2813 // If is has NSObject attribute, OK as well. 2814 isObjCNSObjectType(Ty)) 2815 return true; 2816 2817 // Check to see if this is 'id' or 'Class', both of which are typedefs for 2818 // pointer types. This looks for the typedef specifically, not for the 2819 // underlying type. Iteratively strip off typedefs so that we can handle 2820 // typedefs of typedefs. 2821 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 2822 if (Ty.getUnqualifiedType() == getObjCIdType() || 2823 Ty.getUnqualifiedType() == getObjCClassType()) 2824 return true; 2825 2826 Ty = TDT->getDecl()->getUnderlyingType(); 2827 } 2828 2829 return false; 2830} 2831 2832/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 2833/// garbage collection attribute. 2834/// 2835QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 2836 QualType::GCAttrTypes GCAttrs = QualType::GCNone; 2837 if (getLangOptions().ObjC1 && 2838 getLangOptions().getGCMode() != LangOptions::NonGC) { 2839 GCAttrs = Ty.getObjCGCAttr(); 2840 // Default behavious under objective-c's gc is for objective-c pointers 2841 // (or pointers to them) be treated as though they were declared 2842 // as __strong. 2843 if (GCAttrs == QualType::GCNone) { 2844 if (isObjCObjectPointerType(Ty)) 2845 GCAttrs = QualType::Strong; 2846 else if (Ty->isPointerType()) 2847 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType()); 2848 } 2849 // Non-pointers have none gc'able attribute regardless of the attribute 2850 // set on them. 2851 else if (!isObjCObjectPointerType(Ty) && !Ty->isPointerType()) 2852 return QualType::GCNone; 2853 } 2854 return GCAttrs; 2855} 2856 2857//===----------------------------------------------------------------------===// 2858// Type Compatibility Testing 2859//===----------------------------------------------------------------------===// 2860 2861/// typesAreBlockCompatible - This routine is called when comparing two 2862/// block types. Types must be strictly compatible here. For example, 2863/// C unfortunately doesn't produce an error for the following: 2864/// 2865/// int (*emptyArgFunc)(); 2866/// int (*intArgList)(int) = emptyArgFunc; 2867/// 2868/// For blocks, we will produce an error for the following (similar to C++): 2869/// 2870/// int (^emptyArgBlock)(); 2871/// int (^intArgBlock)(int) = emptyArgBlock; 2872/// 2873/// FIXME: When the dust settles on this integration, fold this into mergeTypes. 2874/// 2875bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) { 2876 const FunctionType *lbase = lhs->getAsFunctionType(); 2877 const FunctionType *rbase = rhs->getAsFunctionType(); 2878 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 2879 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 2880 if (lproto && rproto == 0) 2881 return false; 2882 return !mergeTypes(lhs, rhs).isNull(); 2883} 2884 2885/// areCompatVectorTypes - Return true if the two specified vector types are 2886/// compatible. 2887static bool areCompatVectorTypes(const VectorType *LHS, 2888 const VectorType *RHS) { 2889 assert(LHS->isCanonical() && RHS->isCanonical()); 2890 return LHS->getElementType() == RHS->getElementType() && 2891 LHS->getNumElements() == RHS->getNumElements(); 2892} 2893 2894/// canAssignObjCInterfaces - Return true if the two interface types are 2895/// compatible for assignment from RHS to LHS. This handles validation of any 2896/// protocol qualifiers on the LHS or RHS. 2897/// 2898bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 2899 const ObjCInterfaceType *RHS) { 2900 // Verify that the base decls are compatible: the RHS must be a subclass of 2901 // the LHS. 2902 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 2903 return false; 2904 2905 // RHS must have a superset of the protocols in the LHS. If the LHS is not 2906 // protocol qualified at all, then we are good. 2907 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 2908 return true; 2909 2910 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 2911 // isn't a superset. 2912 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 2913 return true; // FIXME: should return false! 2914 2915 // Finally, we must have two protocol-qualified interfaces. 2916 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 2917 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 2918 2919 // All LHS protocols must have a presence on the RHS. 2920 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?"); 2921 2922 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(), 2923 LHSPE = LHSP->qual_end(); 2924 LHSPI != LHSPE; LHSPI++) { 2925 bool RHSImplementsProtocol = false; 2926 2927 // If the RHS doesn't implement the protocol on the left, the types 2928 // are incompatible. 2929 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(), 2930 RHSPE = RHSP->qual_end(); 2931 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) { 2932 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) 2933 RHSImplementsProtocol = true; 2934 } 2935 // FIXME: For better diagnostics, consider passing back the protocol name. 2936 if (!RHSImplementsProtocol) 2937 return false; 2938 } 2939 // The RHS implements all protocols listed on the LHS. 2940 return true; 2941} 2942 2943bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 2944 // get the "pointed to" types 2945 const PointerType *LHSPT = LHS->getAsPointerType(); 2946 const PointerType *RHSPT = RHS->getAsPointerType(); 2947 2948 if (!LHSPT || !RHSPT) 2949 return false; 2950 2951 QualType lhptee = LHSPT->getPointeeType(); 2952 QualType rhptee = RHSPT->getPointeeType(); 2953 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2954 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2955 // ID acts sort of like void* for ObjC interfaces 2956 if (LHSIface && isObjCIdStructType(rhptee)) 2957 return true; 2958 if (RHSIface && isObjCIdStructType(lhptee)) 2959 return true; 2960 if (!LHSIface || !RHSIface) 2961 return false; 2962 return canAssignObjCInterfaces(LHSIface, RHSIface) || 2963 canAssignObjCInterfaces(RHSIface, LHSIface); 2964} 2965 2966/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 2967/// both shall have the identically qualified version of a compatible type. 2968/// C99 6.2.7p1: Two types have compatible types if their types are the 2969/// same. See 6.7.[2,3,5] for additional rules. 2970bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 2971 return !mergeTypes(LHS, RHS).isNull(); 2972} 2973 2974QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { 2975 const FunctionType *lbase = lhs->getAsFunctionType(); 2976 const FunctionType *rbase = rhs->getAsFunctionType(); 2977 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 2978 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 2979 bool allLTypes = true; 2980 bool allRTypes = true; 2981 2982 // Check return type 2983 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 2984 if (retType.isNull()) return QualType(); 2985 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 2986 allLTypes = false; 2987 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 2988 allRTypes = false; 2989 2990 if (lproto && rproto) { // two C99 style function prototypes 2991 unsigned lproto_nargs = lproto->getNumArgs(); 2992 unsigned rproto_nargs = rproto->getNumArgs(); 2993 2994 // Compatible functions must have the same number of arguments 2995 if (lproto_nargs != rproto_nargs) 2996 return QualType(); 2997 2998 // Variadic and non-variadic functions aren't compatible 2999 if (lproto->isVariadic() != rproto->isVariadic()) 3000 return QualType(); 3001 3002 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 3003 return QualType(); 3004 3005 // Check argument compatibility 3006 llvm::SmallVector<QualType, 10> types; 3007 for (unsigned i = 0; i < lproto_nargs; i++) { 3008 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 3009 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 3010 QualType argtype = mergeTypes(largtype, rargtype); 3011 if (argtype.isNull()) return QualType(); 3012 types.push_back(argtype); 3013 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 3014 allLTypes = false; 3015 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 3016 allRTypes = false; 3017 } 3018 if (allLTypes) return lhs; 3019 if (allRTypes) return rhs; 3020 return getFunctionType(retType, types.begin(), types.size(), 3021 lproto->isVariadic(), lproto->getTypeQuals()); 3022 } 3023 3024 if (lproto) allRTypes = false; 3025 if (rproto) allLTypes = false; 3026 3027 const FunctionProtoType *proto = lproto ? lproto : rproto; 3028 if (proto) { 3029 if (proto->isVariadic()) return QualType(); 3030 // Check that the types are compatible with the types that 3031 // would result from default argument promotions (C99 6.7.5.3p15). 3032 // The only types actually affected are promotable integer 3033 // types and floats, which would be passed as a different 3034 // type depending on whether the prototype is visible. 3035 unsigned proto_nargs = proto->getNumArgs(); 3036 for (unsigned i = 0; i < proto_nargs; ++i) { 3037 QualType argTy = proto->getArgType(i); 3038 if (argTy->isPromotableIntegerType() || 3039 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 3040 return QualType(); 3041 } 3042 3043 if (allLTypes) return lhs; 3044 if (allRTypes) return rhs; 3045 return getFunctionType(retType, proto->arg_type_begin(), 3046 proto->getNumArgs(), lproto->isVariadic(), 3047 lproto->getTypeQuals()); 3048 } 3049 3050 if (allLTypes) return lhs; 3051 if (allRTypes) return rhs; 3052 return getFunctionNoProtoType(retType); 3053} 3054 3055QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { 3056 // C++ [expr]: If an expression initially has the type "reference to T", the 3057 // type is adjusted to "T" prior to any further analysis, the expression 3058 // designates the object or function denoted by the reference, and the 3059 // expression is an lvalue unless the reference is an rvalue reference and 3060 // the expression is a function call (possibly inside parentheses). 3061 // FIXME: C++ shouldn't be going through here! The rules are different 3062 // enough that they should be handled separately. 3063 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really* 3064 // shouldn't be going through here! 3065 if (const ReferenceType *RT = LHS->getAsReferenceType()) 3066 LHS = RT->getPointeeType(); 3067 if (const ReferenceType *RT = RHS->getAsReferenceType()) 3068 RHS = RT->getPointeeType(); 3069 3070 QualType LHSCan = getCanonicalType(LHS), 3071 RHSCan = getCanonicalType(RHS); 3072 3073 // If two types are identical, they are compatible. 3074 if (LHSCan == RHSCan) 3075 return LHS; 3076 3077 // If the qualifiers are different, the types aren't compatible 3078 // Note that we handle extended qualifiers later, in the 3079 // case for ExtQualType. 3080 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers()) 3081 return QualType(); 3082 3083 Type::TypeClass LHSClass = LHSCan.getUnqualifiedType()->getTypeClass(); 3084 Type::TypeClass RHSClass = RHSCan.getUnqualifiedType()->getTypeClass(); 3085 3086 // We want to consider the two function types to be the same for these 3087 // comparisons, just force one to the other. 3088 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 3089 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 3090 3091 // Same as above for arrays 3092 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 3093 LHSClass = Type::ConstantArray; 3094 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 3095 RHSClass = Type::ConstantArray; 3096 3097 // Canonicalize ExtVector -> Vector. 3098 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 3099 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 3100 3101 // Consider qualified interfaces and interfaces the same. 3102 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 3103 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 3104 3105 // If the canonical type classes don't match. 3106 if (LHSClass != RHSClass) { 3107 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3108 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3109 3110 // 'id' and 'Class' act sort of like void* for ObjC interfaces 3111 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS))) 3112 return LHS; 3113 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS))) 3114 return RHS; 3115 3116 // ID is compatible with all qualified id types. 3117 if (LHS->isObjCQualifiedIdType()) { 3118 if (const PointerType *PT = RHS->getAsPointerType()) { 3119 QualType pType = PT->getPointeeType(); 3120 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3121 return LHS; 3122 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3123 // Unfortunately, this API is part of Sema (which we don't have access 3124 // to. Need to refactor. The following check is insufficient, since we 3125 // need to make sure the class implements the protocol. 3126 if (pType->isObjCInterfaceType()) 3127 return LHS; 3128 } 3129 } 3130 if (RHS->isObjCQualifiedIdType()) { 3131 if (const PointerType *PT = LHS->getAsPointerType()) { 3132 QualType pType = PT->getPointeeType(); 3133 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3134 return RHS; 3135 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3136 // Unfortunately, this API is part of Sema (which we don't have access 3137 // to. Need to refactor. The following check is insufficient, since we 3138 // need to make sure the class implements the protocol. 3139 if (pType->isObjCInterfaceType()) 3140 return RHS; 3141 } 3142 } 3143 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 3144 // a signed integer type, or an unsigned integer type. 3145 if (const EnumType* ETy = LHS->getAsEnumType()) { 3146 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 3147 return RHS; 3148 } 3149 if (const EnumType* ETy = RHS->getAsEnumType()) { 3150 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 3151 return LHS; 3152 } 3153 3154 return QualType(); 3155 } 3156 3157 // The canonical type classes match. 3158 switch (LHSClass) { 3159#define TYPE(Class, Base) 3160#define ABSTRACT_TYPE(Class, Base) 3161#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3162#define DEPENDENT_TYPE(Class, Base) case Type::Class: 3163#include "clang/AST/TypeNodes.def" 3164 assert(false && "Non-canonical and dependent types shouldn't get here"); 3165 return QualType(); 3166 3167 case Type::LValueReference: 3168 case Type::RValueReference: 3169 case Type::MemberPointer: 3170 assert(false && "C++ should never be in mergeTypes"); 3171 return QualType(); 3172 3173 case Type::IncompleteArray: 3174 case Type::VariableArray: 3175 case Type::FunctionProto: 3176 case Type::ExtVector: 3177 case Type::ObjCQualifiedInterface: 3178 assert(false && "Types are eliminated above"); 3179 return QualType(); 3180 3181 case Type::Pointer: 3182 { 3183 // Merge two pointer types, while trying to preserve typedef info 3184 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType(); 3185 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType(); 3186 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3187 if (ResultType.isNull()) return QualType(); 3188 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3189 return LHS; 3190 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3191 return RHS; 3192 return getPointerType(ResultType); 3193 } 3194 case Type::BlockPointer: 3195 { 3196 // Merge two block pointer types, while trying to preserve typedef info 3197 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType(); 3198 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType(); 3199 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3200 if (ResultType.isNull()) return QualType(); 3201 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3202 return LHS; 3203 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3204 return RHS; 3205 return getBlockPointerType(ResultType); 3206 } 3207 case Type::ConstantArray: 3208 { 3209 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 3210 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 3211 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 3212 return QualType(); 3213 3214 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 3215 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 3216 QualType ResultType = mergeTypes(LHSElem, RHSElem); 3217 if (ResultType.isNull()) return QualType(); 3218 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3219 return LHS; 3220 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3221 return RHS; 3222 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 3223 ArrayType::ArraySizeModifier(), 0); 3224 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 3225 ArrayType::ArraySizeModifier(), 0); 3226 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 3227 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 3228 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3229 return LHS; 3230 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3231 return RHS; 3232 if (LVAT) { 3233 // FIXME: This isn't correct! But tricky to implement because 3234 // the array's size has to be the size of LHS, but the type 3235 // has to be different. 3236 return LHS; 3237 } 3238 if (RVAT) { 3239 // FIXME: This isn't correct! But tricky to implement because 3240 // the array's size has to be the size of RHS, but the type 3241 // has to be different. 3242 return RHS; 3243 } 3244 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 3245 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 3246 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0); 3247 } 3248 case Type::FunctionNoProto: 3249 return mergeFunctionTypes(LHS, RHS); 3250 case Type::Record: 3251 case Type::Enum: 3252 // FIXME: Why are these compatible? 3253 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS; 3254 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS; 3255 return QualType(); 3256 case Type::Builtin: 3257 // Only exactly equal builtin types are compatible, which is tested above. 3258 return QualType(); 3259 case Type::Complex: 3260 // Distinct complex types are incompatible. 3261 return QualType(); 3262 case Type::Vector: 3263 // FIXME: The merged type should be an ExtVector! 3264 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType())) 3265 return LHS; 3266 return QualType(); 3267 case Type::ObjCInterface: { 3268 // Check if the interfaces are assignment compatible. 3269 // FIXME: This should be type compatibility, e.g. whether 3270 // "LHS x; RHS x;" at global scope is legal. 3271 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3272 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3273 if (LHSIface && RHSIface && 3274 canAssignObjCInterfaces(LHSIface, RHSIface)) 3275 return LHS; 3276 3277 return QualType(); 3278 } 3279 case Type::ObjCQualifiedId: 3280 // Distinct qualified id's are not compatible. 3281 return QualType(); 3282 case Type::FixedWidthInt: 3283 // Distinct fixed-width integers are not compatible. 3284 return QualType(); 3285 case Type::ExtQual: 3286 // FIXME: ExtQual types can be compatible even if they're not 3287 // identical! 3288 return QualType(); 3289 // First attempt at an implementation, but I'm not really sure it's 3290 // right... 3291#if 0 3292 ExtQualType* LQual = cast<ExtQualType>(LHSCan); 3293 ExtQualType* RQual = cast<ExtQualType>(RHSCan); 3294 if (LQual->getAddressSpace() != RQual->getAddressSpace() || 3295 LQual->getObjCGCAttr() != RQual->getObjCGCAttr()) 3296 return QualType(); 3297 QualType LHSBase, RHSBase, ResultType, ResCanUnqual; 3298 LHSBase = QualType(LQual->getBaseType(), 0); 3299 RHSBase = QualType(RQual->getBaseType(), 0); 3300 ResultType = mergeTypes(LHSBase, RHSBase); 3301 if (ResultType.isNull()) return QualType(); 3302 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType(); 3303 if (LHSCan.getUnqualifiedType() == ResCanUnqual) 3304 return LHS; 3305 if (RHSCan.getUnqualifiedType() == ResCanUnqual) 3306 return RHS; 3307 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace()); 3308 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr()); 3309 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers()); 3310 return ResultType; 3311#endif 3312 3313 case Type::TemplateSpecialization: 3314 assert(false && "Dependent types have no size"); 3315 break; 3316 } 3317 3318 return QualType(); 3319} 3320 3321//===----------------------------------------------------------------------===// 3322// Integer Predicates 3323//===----------------------------------------------------------------------===// 3324 3325unsigned ASTContext::getIntWidth(QualType T) { 3326 if (T == BoolTy) 3327 return 1; 3328 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 3329 return FWIT->getWidth(); 3330 } 3331 // For builtin types, just use the standard type sizing method 3332 return (unsigned)getTypeSize(T); 3333} 3334 3335QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 3336 assert(T->isSignedIntegerType() && "Unexpected type"); 3337 if (const EnumType* ETy = T->getAsEnumType()) 3338 T = ETy->getDecl()->getIntegerType(); 3339 const BuiltinType* BTy = T->getAsBuiltinType(); 3340 assert (BTy && "Unexpected signed integer type"); 3341 switch (BTy->getKind()) { 3342 case BuiltinType::Char_S: 3343 case BuiltinType::SChar: 3344 return UnsignedCharTy; 3345 case BuiltinType::Short: 3346 return UnsignedShortTy; 3347 case BuiltinType::Int: 3348 return UnsignedIntTy; 3349 case BuiltinType::Long: 3350 return UnsignedLongTy; 3351 case BuiltinType::LongLong: 3352 return UnsignedLongLongTy; 3353 case BuiltinType::Int128: 3354 return UnsignedInt128Ty; 3355 default: 3356 assert(0 && "Unexpected signed integer type"); 3357 return QualType(); 3358 } 3359} 3360 3361ExternalASTSource::~ExternalASTSource() { } 3362 3363void ExternalASTSource::PrintStats() { } 3364