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