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