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