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