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