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