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