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