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