ASTContext.cpp revision 8bdb58a7835a9a90dd9b9791fccf269cbc1dcef3
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/ExprCXX.h" 22#include "clang/AST/ExternalASTSource.h" 23#include "clang/AST/ASTMutationListener.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/Mangle.h" 26#include "clang/Basic/Builtins.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/SmallString.h" 30#include "llvm/ADT/StringExtras.h" 31#include "llvm/Support/MathExtras.h" 32#include "llvm/Support/raw_ostream.h" 33#include "llvm/Support/Capacity.h" 34#include "CXXABI.h" 35#include <map> 36 37using namespace clang; 38 39unsigned ASTContext::NumImplicitDefaultConstructors; 40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 41unsigned ASTContext::NumImplicitCopyConstructors; 42unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 43unsigned ASTContext::NumImplicitMoveConstructors; 44unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 45unsigned ASTContext::NumImplicitCopyAssignmentOperators; 46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 47unsigned ASTContext::NumImplicitMoveAssignmentOperators; 48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 49unsigned ASTContext::NumImplicitDestructors; 50unsigned ASTContext::NumImplicitDestructorsDeclared; 51 52enum FloatingRank { 53 HalfRank, FloatRank, DoubleRank, LongDoubleRank 54}; 55 56const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 57 if (!CommentsLoaded && ExternalSource) { 58 ExternalSource->ReadComments(); 59 CommentsLoaded = true; 60 } 61 62 assert(D); 63 64 // TODO: handle comments for function parameters properly. 65 if (isa<ParmVarDecl>(D)) 66 return NULL; 67 68 ArrayRef<RawComment> RawComments = Comments.getComments(); 69 70 // If there are no comments anywhere, we won't find anything. 71 if (RawComments.empty()) 72 return NULL; 73 74 // If the declaration doesn't map directly to a location in a file, we 75 // can't find the comment. 76 SourceLocation DeclLoc = D->getLocation(); 77 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 78 return NULL; 79 80 // Find the comment that occurs just after this declaration. 81 ArrayRef<RawComment>::iterator Comment 82 = std::lower_bound(RawComments.begin(), 83 RawComments.end(), 84 RawComment(SourceMgr, SourceRange(DeclLoc)), 85 BeforeThanCompare<RawComment>(SourceMgr)); 86 87 // Decompose the location for the declaration and find the beginning of the 88 // file buffer. 89 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 90 91 // First check whether we have a trailing comment. 92 if (Comment != RawComments.end() && 93 Comment->isDocumentation() && Comment->isTrailingComment() && 94 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) { 95 std::pair<FileID, unsigned> CommentBeginDecomp 96 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin()); 97 // Check that Doxygen trailing comment comes after the declaration, starts 98 // on the same line and in the same file as the declaration. 99 if (DeclLocDecomp.first == CommentBeginDecomp.first && 100 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 101 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 102 CommentBeginDecomp.second)) { 103 return &*Comment; 104 } 105 } 106 107 // The comment just after the declaration was not a trailing comment. 108 // Let's look at the previous comment. 109 if (Comment == RawComments.begin()) 110 return NULL; 111 --Comment; 112 113 // Check that we actually have a non-member Doxygen comment. 114 if (!Comment->isDocumentation() || Comment->isTrailingComment()) 115 return NULL; 116 117 // Decompose the end of the comment. 118 std::pair<FileID, unsigned> CommentEndDecomp 119 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd()); 120 121 // If the comment and the declaration aren't in the same file, then they 122 // aren't related. 123 if (DeclLocDecomp.first != CommentEndDecomp.first) 124 return NULL; 125 126 // Get the corresponding buffer. 127 bool Invalid = false; 128 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 129 &Invalid).data(); 130 if (Invalid) 131 return NULL; 132 133 // Extract text between the comment and declaration. 134 StringRef Text(Buffer + CommentEndDecomp.second, 135 DeclLocDecomp.second - CommentEndDecomp.second); 136 137 // There should be no other declarations or preprocessor directives between 138 // comment and declaration. 139 if (Text.find_first_of(",;{}#") != StringRef::npos) 140 return NULL; 141 142 return &*Comment; 143} 144 145const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const { 146 // Check whether we have cached a comment string for this declaration 147 // already. 148 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos 149 = DeclComments.find(D); 150 if (Pos != DeclComments.end()) 151 return Pos->second; 152 153 const RawComment *RC = getRawCommentForDeclNoCache(D); 154 DeclComments[D] = RC; 155 return RC; 156} 157 158void 159ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 160 TemplateTemplateParmDecl *Parm) { 161 ID.AddInteger(Parm->getDepth()); 162 ID.AddInteger(Parm->getPosition()); 163 ID.AddBoolean(Parm->isParameterPack()); 164 165 TemplateParameterList *Params = Parm->getTemplateParameters(); 166 ID.AddInteger(Params->size()); 167 for (TemplateParameterList::const_iterator P = Params->begin(), 168 PEnd = Params->end(); 169 P != PEnd; ++P) { 170 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 171 ID.AddInteger(0); 172 ID.AddBoolean(TTP->isParameterPack()); 173 continue; 174 } 175 176 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 177 ID.AddInteger(1); 178 ID.AddBoolean(NTTP->isParameterPack()); 179 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 180 if (NTTP->isExpandedParameterPack()) { 181 ID.AddBoolean(true); 182 ID.AddInteger(NTTP->getNumExpansionTypes()); 183 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 184 QualType T = NTTP->getExpansionType(I); 185 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 186 } 187 } else 188 ID.AddBoolean(false); 189 continue; 190 } 191 192 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 193 ID.AddInteger(2); 194 Profile(ID, TTP); 195 } 196} 197 198TemplateTemplateParmDecl * 199ASTContext::getCanonicalTemplateTemplateParmDecl( 200 TemplateTemplateParmDecl *TTP) const { 201 // Check if we already have a canonical template template parameter. 202 llvm::FoldingSetNodeID ID; 203 CanonicalTemplateTemplateParm::Profile(ID, TTP); 204 void *InsertPos = 0; 205 CanonicalTemplateTemplateParm *Canonical 206 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 207 if (Canonical) 208 return Canonical->getParam(); 209 210 // Build a canonical template parameter list. 211 TemplateParameterList *Params = TTP->getTemplateParameters(); 212 SmallVector<NamedDecl *, 4> CanonParams; 213 CanonParams.reserve(Params->size()); 214 for (TemplateParameterList::const_iterator P = Params->begin(), 215 PEnd = Params->end(); 216 P != PEnd; ++P) { 217 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 218 CanonParams.push_back( 219 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 220 SourceLocation(), 221 SourceLocation(), 222 TTP->getDepth(), 223 TTP->getIndex(), 0, false, 224 TTP->isParameterPack())); 225 else if (NonTypeTemplateParmDecl *NTTP 226 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 227 QualType T = getCanonicalType(NTTP->getType()); 228 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 229 NonTypeTemplateParmDecl *Param; 230 if (NTTP->isExpandedParameterPack()) { 231 SmallVector<QualType, 2> ExpandedTypes; 232 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 233 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 234 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 235 ExpandedTInfos.push_back( 236 getTrivialTypeSourceInfo(ExpandedTypes.back())); 237 } 238 239 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 240 SourceLocation(), 241 SourceLocation(), 242 NTTP->getDepth(), 243 NTTP->getPosition(), 0, 244 T, 245 TInfo, 246 ExpandedTypes.data(), 247 ExpandedTypes.size(), 248 ExpandedTInfos.data()); 249 } else { 250 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 251 SourceLocation(), 252 SourceLocation(), 253 NTTP->getDepth(), 254 NTTP->getPosition(), 0, 255 T, 256 NTTP->isParameterPack(), 257 TInfo); 258 } 259 CanonParams.push_back(Param); 260 261 } else 262 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 263 cast<TemplateTemplateParmDecl>(*P))); 264 } 265 266 TemplateTemplateParmDecl *CanonTTP 267 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 268 SourceLocation(), TTP->getDepth(), 269 TTP->getPosition(), 270 TTP->isParameterPack(), 271 0, 272 TemplateParameterList::Create(*this, SourceLocation(), 273 SourceLocation(), 274 CanonParams.data(), 275 CanonParams.size(), 276 SourceLocation())); 277 278 // Get the new insert position for the node we care about. 279 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 280 assert(Canonical == 0 && "Shouldn't be in the map!"); 281 (void)Canonical; 282 283 // Create the canonical template template parameter entry. 284 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 285 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 286 return CanonTTP; 287} 288 289CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 290 if (!LangOpts.CPlusPlus) return 0; 291 292 switch (T.getCXXABI()) { 293 case CXXABI_ARM: 294 return CreateARMCXXABI(*this); 295 case CXXABI_Itanium: 296 return CreateItaniumCXXABI(*this); 297 case CXXABI_Microsoft: 298 return CreateMicrosoftCXXABI(*this); 299 } 300 llvm_unreachable("Invalid CXXABI type!"); 301} 302 303static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 304 const LangOptions &LOpts) { 305 if (LOpts.FakeAddressSpaceMap) { 306 // The fake address space map must have a distinct entry for each 307 // language-specific address space. 308 static const unsigned FakeAddrSpaceMap[] = { 309 1, // opencl_global 310 2, // opencl_local 311 3, // opencl_constant 312 4, // cuda_device 313 5, // cuda_constant 314 6 // cuda_shared 315 }; 316 return &FakeAddrSpaceMap; 317 } else { 318 return &T.getAddressSpaceMap(); 319 } 320} 321 322ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 323 const TargetInfo *t, 324 IdentifierTable &idents, SelectorTable &sels, 325 Builtin::Context &builtins, 326 unsigned size_reserve, 327 bool DelayInitialization) 328 : FunctionProtoTypes(this_()), 329 TemplateSpecializationTypes(this_()), 330 DependentTemplateSpecializationTypes(this_()), 331 SubstTemplateTemplateParmPacks(this_()), 332 GlobalNestedNameSpecifier(0), 333 Int128Decl(0), UInt128Decl(0), 334 BuiltinVaListDecl(0), 335 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0), 336 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0), 337 FILEDecl(0), 338 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0), 339 BlockDescriptorType(0), BlockDescriptorExtendedType(0), 340 cudaConfigureCallDecl(0), 341 NullTypeSourceInfo(QualType()), 342 FirstLocalImport(), LastLocalImport(), 343 SourceMgr(SM), LangOpts(LOpts), 344 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts), 345 Idents(idents), Selectors(sels), 346 BuiltinInfo(builtins), 347 DeclarationNames(*this), 348 ExternalSource(0), Listener(0), 349 Comments(SM), CommentsLoaded(false), 350 LastSDM(0, 0), 351 UniqueBlockByRefTypeID(0) 352{ 353 if (size_reserve > 0) Types.reserve(size_reserve); 354 TUDecl = TranslationUnitDecl::Create(*this); 355 356 if (!DelayInitialization) { 357 assert(t && "No target supplied for ASTContext initialization"); 358 InitBuiltinTypes(*t); 359 } 360} 361 362ASTContext::~ASTContext() { 363 // Release the DenseMaps associated with DeclContext objects. 364 // FIXME: Is this the ideal solution? 365 ReleaseDeclContextMaps(); 366 367 // Call all of the deallocation functions. 368 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 369 Deallocations[I].first(Deallocations[I].second); 370 371 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 372 // because they can contain DenseMaps. 373 for (llvm::DenseMap<const ObjCContainerDecl*, 374 const ASTRecordLayout*>::iterator 375 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 376 // Increment in loop to prevent using deallocated memory. 377 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 378 R->Destroy(*this); 379 380 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 381 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 382 // Increment in loop to prevent using deallocated memory. 383 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 384 R->Destroy(*this); 385 } 386 387 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 388 AEnd = DeclAttrs.end(); 389 A != AEnd; ++A) 390 A->second->~AttrVec(); 391} 392 393void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 394 Deallocations.push_back(std::make_pair(Callback, Data)); 395} 396 397void 398ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) { 399 ExternalSource.reset(Source.take()); 400} 401 402void ASTContext::PrintStats() const { 403 llvm::errs() << "\n*** AST Context Stats:\n"; 404 llvm::errs() << " " << Types.size() << " types total.\n"; 405 406 unsigned counts[] = { 407#define TYPE(Name, Parent) 0, 408#define ABSTRACT_TYPE(Name, Parent) 409#include "clang/AST/TypeNodes.def" 410 0 // Extra 411 }; 412 413 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 414 Type *T = Types[i]; 415 counts[(unsigned)T->getTypeClass()]++; 416 } 417 418 unsigned Idx = 0; 419 unsigned TotalBytes = 0; 420#define TYPE(Name, Parent) \ 421 if (counts[Idx]) \ 422 llvm::errs() << " " << counts[Idx] << " " << #Name \ 423 << " types\n"; \ 424 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 425 ++Idx; 426#define ABSTRACT_TYPE(Name, Parent) 427#include "clang/AST/TypeNodes.def" 428 429 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 430 431 // Implicit special member functions. 432 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 433 << NumImplicitDefaultConstructors 434 << " implicit default constructors created\n"; 435 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 436 << NumImplicitCopyConstructors 437 << " implicit copy constructors created\n"; 438 if (getLangOpts().CPlusPlus) 439 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 440 << NumImplicitMoveConstructors 441 << " implicit move constructors created\n"; 442 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 443 << NumImplicitCopyAssignmentOperators 444 << " implicit copy assignment operators created\n"; 445 if (getLangOpts().CPlusPlus) 446 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 447 << NumImplicitMoveAssignmentOperators 448 << " implicit move assignment operators created\n"; 449 llvm::errs() << NumImplicitDestructorsDeclared << "/" 450 << NumImplicitDestructors 451 << " implicit destructors created\n"; 452 453 if (ExternalSource.get()) { 454 llvm::errs() << "\n"; 455 ExternalSource->PrintStats(); 456 } 457 458 BumpAlloc.PrintStats(); 459} 460 461TypedefDecl *ASTContext::getInt128Decl() const { 462 if (!Int128Decl) { 463 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty); 464 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 465 getTranslationUnitDecl(), 466 SourceLocation(), 467 SourceLocation(), 468 &Idents.get("__int128_t"), 469 TInfo); 470 } 471 472 return Int128Decl; 473} 474 475TypedefDecl *ASTContext::getUInt128Decl() const { 476 if (!UInt128Decl) { 477 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty); 478 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 479 getTranslationUnitDecl(), 480 SourceLocation(), 481 SourceLocation(), 482 &Idents.get("__uint128_t"), 483 TInfo); 484 } 485 486 return UInt128Decl; 487} 488 489void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 490 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 491 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 492 Types.push_back(Ty); 493} 494 495void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 496 assert((!this->Target || this->Target == &Target) && 497 "Incorrect target reinitialization"); 498 assert(VoidTy.isNull() && "Context reinitialized?"); 499 500 this->Target = &Target; 501 502 ABI.reset(createCXXABI(Target)); 503 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 504 505 // C99 6.2.5p19. 506 InitBuiltinType(VoidTy, BuiltinType::Void); 507 508 // C99 6.2.5p2. 509 InitBuiltinType(BoolTy, BuiltinType::Bool); 510 // C99 6.2.5p3. 511 if (LangOpts.CharIsSigned) 512 InitBuiltinType(CharTy, BuiltinType::Char_S); 513 else 514 InitBuiltinType(CharTy, BuiltinType::Char_U); 515 // C99 6.2.5p4. 516 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 517 InitBuiltinType(ShortTy, BuiltinType::Short); 518 InitBuiltinType(IntTy, BuiltinType::Int); 519 InitBuiltinType(LongTy, BuiltinType::Long); 520 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 521 522 // C99 6.2.5p6. 523 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 524 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 525 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 526 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 527 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 528 529 // C99 6.2.5p10. 530 InitBuiltinType(FloatTy, BuiltinType::Float); 531 InitBuiltinType(DoubleTy, BuiltinType::Double); 532 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 533 534 // GNU extension, 128-bit integers. 535 InitBuiltinType(Int128Ty, BuiltinType::Int128); 536 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 537 538 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5 539 if (TargetInfo::isTypeSigned(Target.getWCharType())) 540 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 541 else // -fshort-wchar makes wchar_t be unsigned. 542 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 543 } else // C99 544 WCharTy = getFromTargetType(Target.getWCharType()); 545 546 WIntTy = getFromTargetType(Target.getWIntType()); 547 548 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 549 InitBuiltinType(Char16Ty, BuiltinType::Char16); 550 else // C99 551 Char16Ty = getFromTargetType(Target.getChar16Type()); 552 553 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 554 InitBuiltinType(Char32Ty, BuiltinType::Char32); 555 else // C99 556 Char32Ty = getFromTargetType(Target.getChar32Type()); 557 558 // Placeholder type for type-dependent expressions whose type is 559 // completely unknown. No code should ever check a type against 560 // DependentTy and users should never see it; however, it is here to 561 // help diagnose failures to properly check for type-dependent 562 // expressions. 563 InitBuiltinType(DependentTy, BuiltinType::Dependent); 564 565 // Placeholder type for functions. 566 InitBuiltinType(OverloadTy, BuiltinType::Overload); 567 568 // Placeholder type for bound members. 569 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 570 571 // Placeholder type for pseudo-objects. 572 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 573 574 // "any" type; useful for debugger-like clients. 575 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 576 577 // Placeholder type for unbridged ARC casts. 578 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 579 580 // C99 6.2.5p11. 581 FloatComplexTy = getComplexType(FloatTy); 582 DoubleComplexTy = getComplexType(DoubleTy); 583 LongDoubleComplexTy = getComplexType(LongDoubleTy); 584 585 // Builtin types for 'id', 'Class', and 'SEL'. 586 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 587 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 588 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 589 590 // Builtin type for __objc_yes and __objc_no 591 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 592 SignedCharTy : BoolTy); 593 594 ObjCConstantStringType = QualType(); 595 596 // void * type 597 VoidPtrTy = getPointerType(VoidTy); 598 599 // nullptr type (C++0x 2.14.7) 600 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 601 602 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 603 InitBuiltinType(HalfTy, BuiltinType::Half); 604} 605 606DiagnosticsEngine &ASTContext::getDiagnostics() const { 607 return SourceMgr.getDiagnostics(); 608} 609 610AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 611 AttrVec *&Result = DeclAttrs[D]; 612 if (!Result) { 613 void *Mem = Allocate(sizeof(AttrVec)); 614 Result = new (Mem) AttrVec; 615 } 616 617 return *Result; 618} 619 620/// \brief Erase the attributes corresponding to the given declaration. 621void ASTContext::eraseDeclAttrs(const Decl *D) { 622 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 623 if (Pos != DeclAttrs.end()) { 624 Pos->second->~AttrVec(); 625 DeclAttrs.erase(Pos); 626 } 627} 628 629MemberSpecializationInfo * 630ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 631 assert(Var->isStaticDataMember() && "Not a static data member"); 632 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 633 = InstantiatedFromStaticDataMember.find(Var); 634 if (Pos == InstantiatedFromStaticDataMember.end()) 635 return 0; 636 637 return Pos->second; 638} 639 640void 641ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 642 TemplateSpecializationKind TSK, 643 SourceLocation PointOfInstantiation) { 644 assert(Inst->isStaticDataMember() && "Not a static data member"); 645 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 646 assert(!InstantiatedFromStaticDataMember[Inst] && 647 "Already noted what static data member was instantiated from"); 648 InstantiatedFromStaticDataMember[Inst] 649 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 650} 651 652FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 653 const FunctionDecl *FD){ 654 assert(FD && "Specialization is 0"); 655 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 656 = ClassScopeSpecializationPattern.find(FD); 657 if (Pos == ClassScopeSpecializationPattern.end()) 658 return 0; 659 660 return Pos->second; 661} 662 663void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 664 FunctionDecl *Pattern) { 665 assert(FD && "Specialization is 0"); 666 assert(Pattern && "Class scope specialization pattern is 0"); 667 ClassScopeSpecializationPattern[FD] = Pattern; 668} 669 670NamedDecl * 671ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 672 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 673 = InstantiatedFromUsingDecl.find(UUD); 674 if (Pos == InstantiatedFromUsingDecl.end()) 675 return 0; 676 677 return Pos->second; 678} 679 680void 681ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 682 assert((isa<UsingDecl>(Pattern) || 683 isa<UnresolvedUsingValueDecl>(Pattern) || 684 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 685 "pattern decl is not a using decl"); 686 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 687 InstantiatedFromUsingDecl[Inst] = Pattern; 688} 689 690UsingShadowDecl * 691ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 692 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 693 = InstantiatedFromUsingShadowDecl.find(Inst); 694 if (Pos == InstantiatedFromUsingShadowDecl.end()) 695 return 0; 696 697 return Pos->second; 698} 699 700void 701ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 702 UsingShadowDecl *Pattern) { 703 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 704 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 705} 706 707FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 708 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 709 = InstantiatedFromUnnamedFieldDecl.find(Field); 710 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 711 return 0; 712 713 return Pos->second; 714} 715 716void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 717 FieldDecl *Tmpl) { 718 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 719 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 720 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 721 "Already noted what unnamed field was instantiated from"); 722 723 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 724} 725 726bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 727 const FieldDecl *LastFD) const { 728 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 729 FD->getBitWidthValue(*this) == 0); 730} 731 732bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD, 733 const FieldDecl *LastFD) const { 734 return (FD->isBitField() && LastFD && LastFD->isBitField() && 735 FD->getBitWidthValue(*this) == 0 && 736 LastFD->getBitWidthValue(*this) != 0); 737} 738 739bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD, 740 const FieldDecl *LastFD) const { 741 return (FD->isBitField() && LastFD && LastFD->isBitField() && 742 FD->getBitWidthValue(*this) && 743 LastFD->getBitWidthValue(*this)); 744} 745 746bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD, 747 const FieldDecl *LastFD) const { 748 return (!FD->isBitField() && LastFD && LastFD->isBitField() && 749 LastFD->getBitWidthValue(*this)); 750} 751 752bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD, 753 const FieldDecl *LastFD) const { 754 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 755 FD->getBitWidthValue(*this)); 756} 757 758ASTContext::overridden_cxx_method_iterator 759ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 760 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 761 = OverriddenMethods.find(Method); 762 if (Pos == OverriddenMethods.end()) 763 return 0; 764 765 return Pos->second.begin(); 766} 767 768ASTContext::overridden_cxx_method_iterator 769ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 770 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 771 = OverriddenMethods.find(Method); 772 if (Pos == OverriddenMethods.end()) 773 return 0; 774 775 return Pos->second.end(); 776} 777 778unsigned 779ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 780 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 781 = OverriddenMethods.find(Method); 782 if (Pos == OverriddenMethods.end()) 783 return 0; 784 785 return Pos->second.size(); 786} 787 788void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 789 const CXXMethodDecl *Overridden) { 790 OverriddenMethods[Method].push_back(Overridden); 791} 792 793void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 794 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 795 assert(!Import->isFromASTFile() && "Non-local import declaration"); 796 if (!FirstLocalImport) { 797 FirstLocalImport = Import; 798 LastLocalImport = Import; 799 return; 800 } 801 802 LastLocalImport->NextLocalImport = Import; 803 LastLocalImport = Import; 804} 805 806//===----------------------------------------------------------------------===// 807// Type Sizing and Analysis 808//===----------------------------------------------------------------------===// 809 810/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 811/// scalar floating point type. 812const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 813 const BuiltinType *BT = T->getAs<BuiltinType>(); 814 assert(BT && "Not a floating point type!"); 815 switch (BT->getKind()) { 816 default: llvm_unreachable("Not a floating point type!"); 817 case BuiltinType::Half: return Target->getHalfFormat(); 818 case BuiltinType::Float: return Target->getFloatFormat(); 819 case BuiltinType::Double: return Target->getDoubleFormat(); 820 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 821 } 822} 823 824/// getDeclAlign - Return a conservative estimate of the alignment of the 825/// specified decl. Note that bitfields do not have a valid alignment, so 826/// this method will assert on them. 827/// If @p RefAsPointee, references are treated like their underlying type 828/// (for alignof), else they're treated like pointers (for CodeGen). 829CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const { 830 unsigned Align = Target->getCharWidth(); 831 832 bool UseAlignAttrOnly = false; 833 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 834 Align = AlignFromAttr; 835 836 // __attribute__((aligned)) can increase or decrease alignment 837 // *except* on a struct or struct member, where it only increases 838 // alignment unless 'packed' is also specified. 839 // 840 // It is an error for alignas to decrease alignment, so we can 841 // ignore that possibility; Sema should diagnose it. 842 if (isa<FieldDecl>(D)) { 843 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 844 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 845 } else { 846 UseAlignAttrOnly = true; 847 } 848 } 849 else if (isa<FieldDecl>(D)) 850 UseAlignAttrOnly = 851 D->hasAttr<PackedAttr>() || 852 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 853 854 // If we're using the align attribute only, just ignore everything 855 // else about the declaration and its type. 856 if (UseAlignAttrOnly) { 857 // do nothing 858 859 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 860 QualType T = VD->getType(); 861 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 862 if (RefAsPointee) 863 T = RT->getPointeeType(); 864 else 865 T = getPointerType(RT->getPointeeType()); 866 } 867 if (!T->isIncompleteType() && !T->isFunctionType()) { 868 // Adjust alignments of declarations with array type by the 869 // large-array alignment on the target. 870 unsigned MinWidth = Target->getLargeArrayMinWidth(); 871 const ArrayType *arrayType; 872 if (MinWidth && (arrayType = getAsArrayType(T))) { 873 if (isa<VariableArrayType>(arrayType)) 874 Align = std::max(Align, Target->getLargeArrayAlign()); 875 else if (isa<ConstantArrayType>(arrayType) && 876 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 877 Align = std::max(Align, Target->getLargeArrayAlign()); 878 879 // Walk through any array types while we're at it. 880 T = getBaseElementType(arrayType); 881 } 882 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 883 } 884 885 // Fields can be subject to extra alignment constraints, like if 886 // the field is packed, the struct is packed, or the struct has a 887 // a max-field-alignment constraint (#pragma pack). So calculate 888 // the actual alignment of the field within the struct, and then 889 // (as we're expected to) constrain that by the alignment of the type. 890 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) { 891 // So calculate the alignment of the field. 892 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent()); 893 894 // Start with the record's overall alignment. 895 unsigned fieldAlign = toBits(layout.getAlignment()); 896 897 // Use the GCD of that and the offset within the record. 898 uint64_t offset = layout.getFieldOffset(field->getFieldIndex()); 899 if (offset > 0) { 900 // Alignment is always a power of 2, so the GCD will be a power of 2, 901 // which means we get to do this crazy thing instead of Euclid's. 902 uint64_t lowBitOfOffset = offset & (~offset + 1); 903 if (lowBitOfOffset < fieldAlign) 904 fieldAlign = static_cast<unsigned>(lowBitOfOffset); 905 } 906 907 Align = std::min(Align, fieldAlign); 908 } 909 } 910 911 return toCharUnitsFromBits(Align); 912} 913 914std::pair<CharUnits, CharUnits> 915ASTContext::getTypeInfoInChars(const Type *T) const { 916 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 917 return std::make_pair(toCharUnitsFromBits(Info.first), 918 toCharUnitsFromBits(Info.second)); 919} 920 921std::pair<CharUnits, CharUnits> 922ASTContext::getTypeInfoInChars(QualType T) const { 923 return getTypeInfoInChars(T.getTypePtr()); 924} 925 926std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const { 927 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T); 928 if (it != MemoizedTypeInfo.end()) 929 return it->second; 930 931 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T); 932 MemoizedTypeInfo.insert(std::make_pair(T, Info)); 933 return Info; 934} 935 936/// getTypeInfoImpl - Return the size of the specified type, in bits. This 937/// method does not work on incomplete types. 938/// 939/// FIXME: Pointers into different addr spaces could have different sizes and 940/// alignment requirements: getPointerInfo should take an AddrSpace, this 941/// should take a QualType, &c. 942std::pair<uint64_t, unsigned> 943ASTContext::getTypeInfoImpl(const Type *T) const { 944 uint64_t Width=0; 945 unsigned Align=8; 946 switch (T->getTypeClass()) { 947#define TYPE(Class, Base) 948#define ABSTRACT_TYPE(Class, Base) 949#define NON_CANONICAL_TYPE(Class, Base) 950#define DEPENDENT_TYPE(Class, Base) case Type::Class: 951#include "clang/AST/TypeNodes.def" 952 llvm_unreachable("Should not see dependent types"); 953 954 case Type::FunctionNoProto: 955 case Type::FunctionProto: 956 // GCC extension: alignof(function) = 32 bits 957 Width = 0; 958 Align = 32; 959 break; 960 961 case Type::IncompleteArray: 962 case Type::VariableArray: 963 Width = 0; 964 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 965 break; 966 967 case Type::ConstantArray: { 968 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 969 970 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 971 uint64_t Size = CAT->getSize().getZExtValue(); 972 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 973 "Overflow in array type bit size evaluation"); 974 Width = EltInfo.first*Size; 975 Align = EltInfo.second; 976 Width = llvm::RoundUpToAlignment(Width, Align); 977 break; 978 } 979 case Type::ExtVector: 980 case Type::Vector: { 981 const VectorType *VT = cast<VectorType>(T); 982 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 983 Width = EltInfo.first*VT->getNumElements(); 984 Align = Width; 985 // If the alignment is not a power of 2, round up to the next power of 2. 986 // This happens for non-power-of-2 length vectors. 987 if (Align & (Align-1)) { 988 Align = llvm::NextPowerOf2(Align); 989 Width = llvm::RoundUpToAlignment(Width, Align); 990 } 991 break; 992 } 993 994 case Type::Builtin: 995 switch (cast<BuiltinType>(T)->getKind()) { 996 default: llvm_unreachable("Unknown builtin type!"); 997 case BuiltinType::Void: 998 // GCC extension: alignof(void) = 8 bits. 999 Width = 0; 1000 Align = 8; 1001 break; 1002 1003 case BuiltinType::Bool: 1004 Width = Target->getBoolWidth(); 1005 Align = Target->getBoolAlign(); 1006 break; 1007 case BuiltinType::Char_S: 1008 case BuiltinType::Char_U: 1009 case BuiltinType::UChar: 1010 case BuiltinType::SChar: 1011 Width = Target->getCharWidth(); 1012 Align = Target->getCharAlign(); 1013 break; 1014 case BuiltinType::WChar_S: 1015 case BuiltinType::WChar_U: 1016 Width = Target->getWCharWidth(); 1017 Align = Target->getWCharAlign(); 1018 break; 1019 case BuiltinType::Char16: 1020 Width = Target->getChar16Width(); 1021 Align = Target->getChar16Align(); 1022 break; 1023 case BuiltinType::Char32: 1024 Width = Target->getChar32Width(); 1025 Align = Target->getChar32Align(); 1026 break; 1027 case BuiltinType::UShort: 1028 case BuiltinType::Short: 1029 Width = Target->getShortWidth(); 1030 Align = Target->getShortAlign(); 1031 break; 1032 case BuiltinType::UInt: 1033 case BuiltinType::Int: 1034 Width = Target->getIntWidth(); 1035 Align = Target->getIntAlign(); 1036 break; 1037 case BuiltinType::ULong: 1038 case BuiltinType::Long: 1039 Width = Target->getLongWidth(); 1040 Align = Target->getLongAlign(); 1041 break; 1042 case BuiltinType::ULongLong: 1043 case BuiltinType::LongLong: 1044 Width = Target->getLongLongWidth(); 1045 Align = Target->getLongLongAlign(); 1046 break; 1047 case BuiltinType::Int128: 1048 case BuiltinType::UInt128: 1049 Width = 128; 1050 Align = 128; // int128_t is 128-bit aligned on all targets. 1051 break; 1052 case BuiltinType::Half: 1053 Width = Target->getHalfWidth(); 1054 Align = Target->getHalfAlign(); 1055 break; 1056 case BuiltinType::Float: 1057 Width = Target->getFloatWidth(); 1058 Align = Target->getFloatAlign(); 1059 break; 1060 case BuiltinType::Double: 1061 Width = Target->getDoubleWidth(); 1062 Align = Target->getDoubleAlign(); 1063 break; 1064 case BuiltinType::LongDouble: 1065 Width = Target->getLongDoubleWidth(); 1066 Align = Target->getLongDoubleAlign(); 1067 break; 1068 case BuiltinType::NullPtr: 1069 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1070 Align = Target->getPointerAlign(0); // == sizeof(void*) 1071 break; 1072 case BuiltinType::ObjCId: 1073 case BuiltinType::ObjCClass: 1074 case BuiltinType::ObjCSel: 1075 Width = Target->getPointerWidth(0); 1076 Align = Target->getPointerAlign(0); 1077 break; 1078 } 1079 break; 1080 case Type::ObjCObjectPointer: 1081 Width = Target->getPointerWidth(0); 1082 Align = Target->getPointerAlign(0); 1083 break; 1084 case Type::BlockPointer: { 1085 unsigned AS = getTargetAddressSpace( 1086 cast<BlockPointerType>(T)->getPointeeType()); 1087 Width = Target->getPointerWidth(AS); 1088 Align = Target->getPointerAlign(AS); 1089 break; 1090 } 1091 case Type::LValueReference: 1092 case Type::RValueReference: { 1093 // alignof and sizeof should never enter this code path here, so we go 1094 // the pointer route. 1095 unsigned AS = getTargetAddressSpace( 1096 cast<ReferenceType>(T)->getPointeeType()); 1097 Width = Target->getPointerWidth(AS); 1098 Align = Target->getPointerAlign(AS); 1099 break; 1100 } 1101 case Type::Pointer: { 1102 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1103 Width = Target->getPointerWidth(AS); 1104 Align = Target->getPointerAlign(AS); 1105 break; 1106 } 1107 case Type::MemberPointer: { 1108 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1109 std::pair<uint64_t, unsigned> PtrDiffInfo = 1110 getTypeInfo(getPointerDiffType()); 1111 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 1112 Align = PtrDiffInfo.second; 1113 break; 1114 } 1115 case Type::Complex: { 1116 // Complex types have the same alignment as their elements, but twice the 1117 // size. 1118 std::pair<uint64_t, unsigned> EltInfo = 1119 getTypeInfo(cast<ComplexType>(T)->getElementType()); 1120 Width = EltInfo.first*2; 1121 Align = EltInfo.second; 1122 break; 1123 } 1124 case Type::ObjCObject: 1125 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1126 case Type::ObjCInterface: { 1127 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1128 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1129 Width = toBits(Layout.getSize()); 1130 Align = toBits(Layout.getAlignment()); 1131 break; 1132 } 1133 case Type::Record: 1134 case Type::Enum: { 1135 const TagType *TT = cast<TagType>(T); 1136 1137 if (TT->getDecl()->isInvalidDecl()) { 1138 Width = 8; 1139 Align = 8; 1140 break; 1141 } 1142 1143 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1144 return getTypeInfo(ET->getDecl()->getIntegerType()); 1145 1146 const RecordType *RT = cast<RecordType>(TT); 1147 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1148 Width = toBits(Layout.getSize()); 1149 Align = toBits(Layout.getAlignment()); 1150 break; 1151 } 1152 1153 case Type::SubstTemplateTypeParm: 1154 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1155 getReplacementType().getTypePtr()); 1156 1157 case Type::Auto: { 1158 const AutoType *A = cast<AutoType>(T); 1159 assert(A->isDeduced() && "Cannot request the size of a dependent type"); 1160 return getTypeInfo(A->getDeducedType().getTypePtr()); 1161 } 1162 1163 case Type::Paren: 1164 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1165 1166 case Type::Typedef: { 1167 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1168 std::pair<uint64_t, unsigned> Info 1169 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1170 // If the typedef has an aligned attribute on it, it overrides any computed 1171 // alignment we have. This violates the GCC documentation (which says that 1172 // attribute(aligned) can only round up) but matches its implementation. 1173 if (unsigned AttrAlign = Typedef->getMaxAlignment()) 1174 Align = AttrAlign; 1175 else 1176 Align = Info.second; 1177 Width = Info.first; 1178 break; 1179 } 1180 1181 case Type::TypeOfExpr: 1182 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 1183 .getTypePtr()); 1184 1185 case Type::TypeOf: 1186 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 1187 1188 case Type::Decltype: 1189 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 1190 .getTypePtr()); 1191 1192 case Type::UnaryTransform: 1193 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType()); 1194 1195 case Type::Elaborated: 1196 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1197 1198 case Type::Attributed: 1199 return getTypeInfo( 1200 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1201 1202 case Type::TemplateSpecialization: { 1203 assert(getCanonicalType(T) != T && 1204 "Cannot request the size of a dependent type"); 1205 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T); 1206 // A type alias template specialization may refer to a typedef with the 1207 // aligned attribute on it. 1208 if (TST->isTypeAlias()) 1209 return getTypeInfo(TST->getAliasedType().getTypePtr()); 1210 else 1211 return getTypeInfo(getCanonicalType(T)); 1212 } 1213 1214 case Type::Atomic: { 1215 std::pair<uint64_t, unsigned> Info 1216 = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1217 Width = Info.first; 1218 Align = Info.second; 1219 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() && 1220 llvm::isPowerOf2_64(Width)) { 1221 // We can potentially perform lock-free atomic operations for this 1222 // type; promote the alignment appropriately. 1223 // FIXME: We could potentially promote the width here as well... 1224 // is that worthwhile? (Non-struct atomic types generally have 1225 // power-of-two size anyway, but structs might not. Requires a bit 1226 // of implementation work to make sure we zero out the extra bits.) 1227 Align = static_cast<unsigned>(Width); 1228 } 1229 } 1230 1231 } 1232 1233 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1234 return std::make_pair(Width, Align); 1235} 1236 1237/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1238CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1239 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1240} 1241 1242/// toBits - Convert a size in characters to a size in characters. 1243int64_t ASTContext::toBits(CharUnits CharSize) const { 1244 return CharSize.getQuantity() * getCharWidth(); 1245} 1246 1247/// getTypeSizeInChars - Return the size of the specified type, in characters. 1248/// This method does not work on incomplete types. 1249CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1250 return toCharUnitsFromBits(getTypeSize(T)); 1251} 1252CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1253 return toCharUnitsFromBits(getTypeSize(T)); 1254} 1255 1256/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1257/// characters. This method does not work on incomplete types. 1258CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1259 return toCharUnitsFromBits(getTypeAlign(T)); 1260} 1261CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1262 return toCharUnitsFromBits(getTypeAlign(T)); 1263} 1264 1265/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1266/// type for the current target in bits. This can be different than the ABI 1267/// alignment in cases where it is beneficial for performance to overalign 1268/// a data type. 1269unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1270 unsigned ABIAlign = getTypeAlign(T); 1271 1272 // Double and long long should be naturally aligned if possible. 1273 if (const ComplexType* CT = T->getAs<ComplexType>()) 1274 T = CT->getElementType().getTypePtr(); 1275 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1276 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1277 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1278 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1279 1280 return ABIAlign; 1281} 1282 1283/// DeepCollectObjCIvars - 1284/// This routine first collects all declared, but not synthesized, ivars in 1285/// super class and then collects all ivars, including those synthesized for 1286/// current class. This routine is used for implementation of current class 1287/// when all ivars, declared and synthesized are known. 1288/// 1289void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1290 bool leafClass, 1291 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1292 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1293 DeepCollectObjCIvars(SuperClass, false, Ivars); 1294 if (!leafClass) { 1295 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1296 E = OI->ivar_end(); I != E; ++I) 1297 Ivars.push_back(*I); 1298 } else { 1299 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1300 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1301 Iv= Iv->getNextIvar()) 1302 Ivars.push_back(Iv); 1303 } 1304} 1305 1306/// CollectInheritedProtocols - Collect all protocols in current class and 1307/// those inherited by it. 1308void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1309 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1310 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1311 // We can use protocol_iterator here instead of 1312 // all_referenced_protocol_iterator since we are walking all categories. 1313 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 1314 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 1315 ObjCProtocolDecl *Proto = (*P); 1316 Protocols.insert(Proto->getCanonicalDecl()); 1317 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1318 PE = Proto->protocol_end(); P != PE; ++P) { 1319 Protocols.insert((*P)->getCanonicalDecl()); 1320 CollectInheritedProtocols(*P, Protocols); 1321 } 1322 } 1323 1324 // Categories of this Interface. 1325 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 1326 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 1327 CollectInheritedProtocols(CDeclChain, Protocols); 1328 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1329 while (SD) { 1330 CollectInheritedProtocols(SD, Protocols); 1331 SD = SD->getSuperClass(); 1332 } 1333 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1334 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 1335 PE = OC->protocol_end(); P != PE; ++P) { 1336 ObjCProtocolDecl *Proto = (*P); 1337 Protocols.insert(Proto->getCanonicalDecl()); 1338 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1339 PE = Proto->protocol_end(); P != PE; ++P) 1340 CollectInheritedProtocols(*P, Protocols); 1341 } 1342 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1343 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 1344 PE = OP->protocol_end(); P != PE; ++P) { 1345 ObjCProtocolDecl *Proto = (*P); 1346 Protocols.insert(Proto->getCanonicalDecl()); 1347 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1348 PE = Proto->protocol_end(); P != PE; ++P) 1349 CollectInheritedProtocols(*P, Protocols); 1350 } 1351 } 1352} 1353 1354unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1355 unsigned count = 0; 1356 // Count ivars declared in class extension. 1357 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 1358 CDecl = CDecl->getNextClassExtension()) 1359 count += CDecl->ivar_size(); 1360 1361 // Count ivar defined in this class's implementation. This 1362 // includes synthesized ivars. 1363 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1364 count += ImplDecl->ivar_size(); 1365 1366 return count; 1367} 1368 1369bool ASTContext::isSentinelNullExpr(const Expr *E) { 1370 if (!E) 1371 return false; 1372 1373 // nullptr_t is always treated as null. 1374 if (E->getType()->isNullPtrType()) return true; 1375 1376 if (E->getType()->isAnyPointerType() && 1377 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1378 Expr::NPC_ValueDependentIsNull)) 1379 return true; 1380 1381 // Unfortunately, __null has type 'int'. 1382 if (isa<GNUNullExpr>(E)) return true; 1383 1384 return false; 1385} 1386 1387/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1388ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1389 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1390 I = ObjCImpls.find(D); 1391 if (I != ObjCImpls.end()) 1392 return cast<ObjCImplementationDecl>(I->second); 1393 return 0; 1394} 1395/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1396ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1397 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1398 I = ObjCImpls.find(D); 1399 if (I != ObjCImpls.end()) 1400 return cast<ObjCCategoryImplDecl>(I->second); 1401 return 0; 1402} 1403 1404/// \brief Set the implementation of ObjCInterfaceDecl. 1405void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1406 ObjCImplementationDecl *ImplD) { 1407 assert(IFaceD && ImplD && "Passed null params"); 1408 ObjCImpls[IFaceD] = ImplD; 1409} 1410/// \brief Set the implementation of ObjCCategoryDecl. 1411void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1412 ObjCCategoryImplDecl *ImplD) { 1413 assert(CatD && ImplD && "Passed null params"); 1414 ObjCImpls[CatD] = ImplD; 1415} 1416 1417ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const { 1418 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1419 return ID; 1420 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1421 return CD->getClassInterface(); 1422 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1423 return IMD->getClassInterface(); 1424 1425 return 0; 1426} 1427 1428/// \brief Get the copy initialization expression of VarDecl,or NULL if 1429/// none exists. 1430Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1431 assert(VD && "Passed null params"); 1432 assert(VD->hasAttr<BlocksAttr>() && 1433 "getBlockVarCopyInits - not __block var"); 1434 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1435 I = BlockVarCopyInits.find(VD); 1436 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1437} 1438 1439/// \brief Set the copy inialization expression of a block var decl. 1440void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1441 assert(VD && Init && "Passed null params"); 1442 assert(VD->hasAttr<BlocksAttr>() && 1443 "setBlockVarCopyInits - not __block var"); 1444 BlockVarCopyInits[VD] = Init; 1445} 1446 1447TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1448 unsigned DataSize) const { 1449 if (!DataSize) 1450 DataSize = TypeLoc::getFullDataSizeForType(T); 1451 else 1452 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1453 "incorrect data size provided to CreateTypeSourceInfo!"); 1454 1455 TypeSourceInfo *TInfo = 1456 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1457 new (TInfo) TypeSourceInfo(T); 1458 return TInfo; 1459} 1460 1461TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1462 SourceLocation L) const { 1463 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1464 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1465 return DI; 1466} 1467 1468const ASTRecordLayout & 1469ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1470 return getObjCLayout(D, 0); 1471} 1472 1473const ASTRecordLayout & 1474ASTContext::getASTObjCImplementationLayout( 1475 const ObjCImplementationDecl *D) const { 1476 return getObjCLayout(D->getClassInterface(), D); 1477} 1478 1479//===----------------------------------------------------------------------===// 1480// Type creation/memoization methods 1481//===----------------------------------------------------------------------===// 1482 1483QualType 1484ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 1485 unsigned fastQuals = quals.getFastQualifiers(); 1486 quals.removeFastQualifiers(); 1487 1488 // Check if we've already instantiated this type. 1489 llvm::FoldingSetNodeID ID; 1490 ExtQuals::Profile(ID, baseType, quals); 1491 void *insertPos = 0; 1492 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 1493 assert(eq->getQualifiers() == quals); 1494 return QualType(eq, fastQuals); 1495 } 1496 1497 // If the base type is not canonical, make the appropriate canonical type. 1498 QualType canon; 1499 if (!baseType->isCanonicalUnqualified()) { 1500 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 1501 canonSplit.Quals.addConsistentQualifiers(quals); 1502 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 1503 1504 // Re-find the insert position. 1505 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 1506 } 1507 1508 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 1509 ExtQualNodes.InsertNode(eq, insertPos); 1510 return QualType(eq, fastQuals); 1511} 1512 1513QualType 1514ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 1515 QualType CanT = getCanonicalType(T); 1516 if (CanT.getAddressSpace() == AddressSpace) 1517 return T; 1518 1519 // If we are composing extended qualifiers together, merge together 1520 // into one ExtQuals node. 1521 QualifierCollector Quals; 1522 const Type *TypeNode = Quals.strip(T); 1523 1524 // If this type already has an address space specified, it cannot get 1525 // another one. 1526 assert(!Quals.hasAddressSpace() && 1527 "Type cannot be in multiple addr spaces!"); 1528 Quals.addAddressSpace(AddressSpace); 1529 1530 return getExtQualType(TypeNode, Quals); 1531} 1532 1533QualType ASTContext::getObjCGCQualType(QualType T, 1534 Qualifiers::GC GCAttr) const { 1535 QualType CanT = getCanonicalType(T); 1536 if (CanT.getObjCGCAttr() == GCAttr) 1537 return T; 1538 1539 if (const PointerType *ptr = T->getAs<PointerType>()) { 1540 QualType Pointee = ptr->getPointeeType(); 1541 if (Pointee->isAnyPointerType()) { 1542 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1543 return getPointerType(ResultType); 1544 } 1545 } 1546 1547 // If we are composing extended qualifiers together, merge together 1548 // into one ExtQuals node. 1549 QualifierCollector Quals; 1550 const Type *TypeNode = Quals.strip(T); 1551 1552 // If this type already has an ObjCGC specified, it cannot get 1553 // another one. 1554 assert(!Quals.hasObjCGCAttr() && 1555 "Type cannot have multiple ObjCGCs!"); 1556 Quals.addObjCGCAttr(GCAttr); 1557 1558 return getExtQualType(TypeNode, Quals); 1559} 1560 1561const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 1562 FunctionType::ExtInfo Info) { 1563 if (T->getExtInfo() == Info) 1564 return T; 1565 1566 QualType Result; 1567 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 1568 Result = getFunctionNoProtoType(FNPT->getResultType(), Info); 1569 } else { 1570 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1571 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 1572 EPI.ExtInfo = Info; 1573 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1574 FPT->getNumArgs(), EPI); 1575 } 1576 1577 return cast<FunctionType>(Result.getTypePtr()); 1578} 1579 1580/// getComplexType - Return the uniqued reference to the type for a complex 1581/// number with the specified element type. 1582QualType ASTContext::getComplexType(QualType T) const { 1583 // Unique pointers, to guarantee there is only one pointer of a particular 1584 // structure. 1585 llvm::FoldingSetNodeID ID; 1586 ComplexType::Profile(ID, T); 1587 1588 void *InsertPos = 0; 1589 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1590 return QualType(CT, 0); 1591 1592 // If the pointee type isn't canonical, this won't be a canonical type either, 1593 // so fill in the canonical type field. 1594 QualType Canonical; 1595 if (!T.isCanonical()) { 1596 Canonical = getComplexType(getCanonicalType(T)); 1597 1598 // Get the new insert position for the node we care about. 1599 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1600 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1601 } 1602 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1603 Types.push_back(New); 1604 ComplexTypes.InsertNode(New, InsertPos); 1605 return QualType(New, 0); 1606} 1607 1608/// getPointerType - Return the uniqued reference to the type for a pointer to 1609/// the specified type. 1610QualType ASTContext::getPointerType(QualType T) const { 1611 // Unique pointers, to guarantee there is only one pointer of a particular 1612 // structure. 1613 llvm::FoldingSetNodeID ID; 1614 PointerType::Profile(ID, T); 1615 1616 void *InsertPos = 0; 1617 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1618 return QualType(PT, 0); 1619 1620 // If the pointee type isn't canonical, this won't be a canonical type either, 1621 // so fill in the canonical type field. 1622 QualType Canonical; 1623 if (!T.isCanonical()) { 1624 Canonical = getPointerType(getCanonicalType(T)); 1625 1626 // Get the new insert position for the node we care about. 1627 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1628 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1629 } 1630 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1631 Types.push_back(New); 1632 PointerTypes.InsertNode(New, InsertPos); 1633 return QualType(New, 0); 1634} 1635 1636/// getBlockPointerType - Return the uniqued reference to the type for 1637/// a pointer to the specified block. 1638QualType ASTContext::getBlockPointerType(QualType T) const { 1639 assert(T->isFunctionType() && "block of function types only"); 1640 // Unique pointers, to guarantee there is only one block of a particular 1641 // structure. 1642 llvm::FoldingSetNodeID ID; 1643 BlockPointerType::Profile(ID, T); 1644 1645 void *InsertPos = 0; 1646 if (BlockPointerType *PT = 1647 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1648 return QualType(PT, 0); 1649 1650 // If the block pointee type isn't canonical, this won't be a canonical 1651 // type either so fill in the canonical type field. 1652 QualType Canonical; 1653 if (!T.isCanonical()) { 1654 Canonical = getBlockPointerType(getCanonicalType(T)); 1655 1656 // Get the new insert position for the node we care about. 1657 BlockPointerType *NewIP = 1658 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1659 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1660 } 1661 BlockPointerType *New 1662 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1663 Types.push_back(New); 1664 BlockPointerTypes.InsertNode(New, InsertPos); 1665 return QualType(New, 0); 1666} 1667 1668/// getLValueReferenceType - Return the uniqued reference to the type for an 1669/// lvalue reference to the specified type. 1670QualType 1671ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 1672 assert(getCanonicalType(T) != OverloadTy && 1673 "Unresolved overloaded function type"); 1674 1675 // Unique pointers, to guarantee there is only one pointer of a particular 1676 // structure. 1677 llvm::FoldingSetNodeID ID; 1678 ReferenceType::Profile(ID, T, SpelledAsLValue); 1679 1680 void *InsertPos = 0; 1681 if (LValueReferenceType *RT = 1682 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1683 return QualType(RT, 0); 1684 1685 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1686 1687 // If the referencee type isn't canonical, this won't be a canonical type 1688 // either, so fill in the canonical type field. 1689 QualType Canonical; 1690 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1691 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1692 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1693 1694 // Get the new insert position for the node we care about. 1695 LValueReferenceType *NewIP = 1696 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1697 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1698 } 1699 1700 LValueReferenceType *New 1701 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1702 SpelledAsLValue); 1703 Types.push_back(New); 1704 LValueReferenceTypes.InsertNode(New, InsertPos); 1705 1706 return QualType(New, 0); 1707} 1708 1709/// getRValueReferenceType - Return the uniqued reference to the type for an 1710/// rvalue reference to the specified type. 1711QualType ASTContext::getRValueReferenceType(QualType T) const { 1712 // Unique pointers, to guarantee there is only one pointer of a particular 1713 // structure. 1714 llvm::FoldingSetNodeID ID; 1715 ReferenceType::Profile(ID, T, false); 1716 1717 void *InsertPos = 0; 1718 if (RValueReferenceType *RT = 1719 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1720 return QualType(RT, 0); 1721 1722 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1723 1724 // If the referencee type isn't canonical, this won't be a canonical type 1725 // either, so fill in the canonical type field. 1726 QualType Canonical; 1727 if (InnerRef || !T.isCanonical()) { 1728 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1729 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1730 1731 // Get the new insert position for the node we care about. 1732 RValueReferenceType *NewIP = 1733 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1734 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1735 } 1736 1737 RValueReferenceType *New 1738 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1739 Types.push_back(New); 1740 RValueReferenceTypes.InsertNode(New, InsertPos); 1741 return QualType(New, 0); 1742} 1743 1744/// getMemberPointerType - Return the uniqued reference to the type for a 1745/// member pointer to the specified type, in the specified class. 1746QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 1747 // Unique pointers, to guarantee there is only one pointer of a particular 1748 // structure. 1749 llvm::FoldingSetNodeID ID; 1750 MemberPointerType::Profile(ID, T, Cls); 1751 1752 void *InsertPos = 0; 1753 if (MemberPointerType *PT = 1754 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1755 return QualType(PT, 0); 1756 1757 // If the pointee or class type isn't canonical, this won't be a canonical 1758 // type either, so fill in the canonical type field. 1759 QualType Canonical; 1760 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1761 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1762 1763 // Get the new insert position for the node we care about. 1764 MemberPointerType *NewIP = 1765 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1766 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1767 } 1768 MemberPointerType *New 1769 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1770 Types.push_back(New); 1771 MemberPointerTypes.InsertNode(New, InsertPos); 1772 return QualType(New, 0); 1773} 1774 1775/// getConstantArrayType - Return the unique reference to the type for an 1776/// array of the specified element type. 1777QualType ASTContext::getConstantArrayType(QualType EltTy, 1778 const llvm::APInt &ArySizeIn, 1779 ArrayType::ArraySizeModifier ASM, 1780 unsigned IndexTypeQuals) const { 1781 assert((EltTy->isDependentType() || 1782 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1783 "Constant array of VLAs is illegal!"); 1784 1785 // Convert the array size into a canonical width matching the pointer size for 1786 // the target. 1787 llvm::APInt ArySize(ArySizeIn); 1788 ArySize = 1789 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 1790 1791 llvm::FoldingSetNodeID ID; 1792 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 1793 1794 void *InsertPos = 0; 1795 if (ConstantArrayType *ATP = 1796 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1797 return QualType(ATP, 0); 1798 1799 // If the element type isn't canonical or has qualifiers, this won't 1800 // be a canonical type either, so fill in the canonical type field. 1801 QualType Canon; 1802 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1803 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1804 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 1805 ASM, IndexTypeQuals); 1806 Canon = getQualifiedType(Canon, canonSplit.Quals); 1807 1808 // Get the new insert position for the node we care about. 1809 ConstantArrayType *NewIP = 1810 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1811 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1812 } 1813 1814 ConstantArrayType *New = new(*this,TypeAlignment) 1815 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 1816 ConstantArrayTypes.InsertNode(New, InsertPos); 1817 Types.push_back(New); 1818 return QualType(New, 0); 1819} 1820 1821/// getVariableArrayDecayedType - Turns the given type, which may be 1822/// variably-modified, into the corresponding type with all the known 1823/// sizes replaced with [*]. 1824QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 1825 // Vastly most common case. 1826 if (!type->isVariablyModifiedType()) return type; 1827 1828 QualType result; 1829 1830 SplitQualType split = type.getSplitDesugaredType(); 1831 const Type *ty = split.Ty; 1832 switch (ty->getTypeClass()) { 1833#define TYPE(Class, Base) 1834#define ABSTRACT_TYPE(Class, Base) 1835#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 1836#include "clang/AST/TypeNodes.def" 1837 llvm_unreachable("didn't desugar past all non-canonical types?"); 1838 1839 // These types should never be variably-modified. 1840 case Type::Builtin: 1841 case Type::Complex: 1842 case Type::Vector: 1843 case Type::ExtVector: 1844 case Type::DependentSizedExtVector: 1845 case Type::ObjCObject: 1846 case Type::ObjCInterface: 1847 case Type::ObjCObjectPointer: 1848 case Type::Record: 1849 case Type::Enum: 1850 case Type::UnresolvedUsing: 1851 case Type::TypeOfExpr: 1852 case Type::TypeOf: 1853 case Type::Decltype: 1854 case Type::UnaryTransform: 1855 case Type::DependentName: 1856 case Type::InjectedClassName: 1857 case Type::TemplateSpecialization: 1858 case Type::DependentTemplateSpecialization: 1859 case Type::TemplateTypeParm: 1860 case Type::SubstTemplateTypeParmPack: 1861 case Type::Auto: 1862 case Type::PackExpansion: 1863 llvm_unreachable("type should never be variably-modified"); 1864 1865 // These types can be variably-modified but should never need to 1866 // further decay. 1867 case Type::FunctionNoProto: 1868 case Type::FunctionProto: 1869 case Type::BlockPointer: 1870 case Type::MemberPointer: 1871 return type; 1872 1873 // These types can be variably-modified. All these modifications 1874 // preserve structure except as noted by comments. 1875 // TODO: if we ever care about optimizing VLAs, there are no-op 1876 // optimizations available here. 1877 case Type::Pointer: 1878 result = getPointerType(getVariableArrayDecayedType( 1879 cast<PointerType>(ty)->getPointeeType())); 1880 break; 1881 1882 case Type::LValueReference: { 1883 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 1884 result = getLValueReferenceType( 1885 getVariableArrayDecayedType(lv->getPointeeType()), 1886 lv->isSpelledAsLValue()); 1887 break; 1888 } 1889 1890 case Type::RValueReference: { 1891 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 1892 result = getRValueReferenceType( 1893 getVariableArrayDecayedType(lv->getPointeeType())); 1894 break; 1895 } 1896 1897 case Type::Atomic: { 1898 const AtomicType *at = cast<AtomicType>(ty); 1899 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 1900 break; 1901 } 1902 1903 case Type::ConstantArray: { 1904 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 1905 result = getConstantArrayType( 1906 getVariableArrayDecayedType(cat->getElementType()), 1907 cat->getSize(), 1908 cat->getSizeModifier(), 1909 cat->getIndexTypeCVRQualifiers()); 1910 break; 1911 } 1912 1913 case Type::DependentSizedArray: { 1914 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 1915 result = getDependentSizedArrayType( 1916 getVariableArrayDecayedType(dat->getElementType()), 1917 dat->getSizeExpr(), 1918 dat->getSizeModifier(), 1919 dat->getIndexTypeCVRQualifiers(), 1920 dat->getBracketsRange()); 1921 break; 1922 } 1923 1924 // Turn incomplete types into [*] types. 1925 case Type::IncompleteArray: { 1926 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 1927 result = getVariableArrayType( 1928 getVariableArrayDecayedType(iat->getElementType()), 1929 /*size*/ 0, 1930 ArrayType::Normal, 1931 iat->getIndexTypeCVRQualifiers(), 1932 SourceRange()); 1933 break; 1934 } 1935 1936 // Turn VLA types into [*] types. 1937 case Type::VariableArray: { 1938 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1939 result = getVariableArrayType( 1940 getVariableArrayDecayedType(vat->getElementType()), 1941 /*size*/ 0, 1942 ArrayType::Star, 1943 vat->getIndexTypeCVRQualifiers(), 1944 vat->getBracketsRange()); 1945 break; 1946 } 1947 } 1948 1949 // Apply the top-level qualifiers from the original. 1950 return getQualifiedType(result, split.Quals); 1951} 1952 1953/// getVariableArrayType - Returns a non-unique reference to the type for a 1954/// variable array of the specified element type. 1955QualType ASTContext::getVariableArrayType(QualType EltTy, 1956 Expr *NumElts, 1957 ArrayType::ArraySizeModifier ASM, 1958 unsigned IndexTypeQuals, 1959 SourceRange Brackets) const { 1960 // Since we don't unique expressions, it isn't possible to unique VLA's 1961 // that have an expression provided for their size. 1962 QualType Canon; 1963 1964 // Be sure to pull qualifiers off the element type. 1965 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1966 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1967 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 1968 IndexTypeQuals, Brackets); 1969 Canon = getQualifiedType(Canon, canonSplit.Quals); 1970 } 1971 1972 VariableArrayType *New = new(*this, TypeAlignment) 1973 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 1974 1975 VariableArrayTypes.push_back(New); 1976 Types.push_back(New); 1977 return QualType(New, 0); 1978} 1979 1980/// getDependentSizedArrayType - Returns a non-unique reference to 1981/// the type for a dependently-sized array of the specified element 1982/// type. 1983QualType ASTContext::getDependentSizedArrayType(QualType elementType, 1984 Expr *numElements, 1985 ArrayType::ArraySizeModifier ASM, 1986 unsigned elementTypeQuals, 1987 SourceRange brackets) const { 1988 assert((!numElements || numElements->isTypeDependent() || 1989 numElements->isValueDependent()) && 1990 "Size must be type- or value-dependent!"); 1991 1992 // Dependently-sized array types that do not have a specified number 1993 // of elements will have their sizes deduced from a dependent 1994 // initializer. We do no canonicalization here at all, which is okay 1995 // because they can't be used in most locations. 1996 if (!numElements) { 1997 DependentSizedArrayType *newType 1998 = new (*this, TypeAlignment) 1999 DependentSizedArrayType(*this, elementType, QualType(), 2000 numElements, ASM, elementTypeQuals, 2001 brackets); 2002 Types.push_back(newType); 2003 return QualType(newType, 0); 2004 } 2005 2006 // Otherwise, we actually build a new type every time, but we 2007 // also build a canonical type. 2008 2009 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2010 2011 void *insertPos = 0; 2012 llvm::FoldingSetNodeID ID; 2013 DependentSizedArrayType::Profile(ID, *this, 2014 QualType(canonElementType.Ty, 0), 2015 ASM, elementTypeQuals, numElements); 2016 2017 // Look for an existing type with these properties. 2018 DependentSizedArrayType *canonTy = 2019 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2020 2021 // If we don't have one, build one. 2022 if (!canonTy) { 2023 canonTy = new (*this, TypeAlignment) 2024 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2025 QualType(), numElements, ASM, elementTypeQuals, 2026 brackets); 2027 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2028 Types.push_back(canonTy); 2029 } 2030 2031 // Apply qualifiers from the element type to the array. 2032 QualType canon = getQualifiedType(QualType(canonTy,0), 2033 canonElementType.Quals); 2034 2035 // If we didn't need extra canonicalization for the element type, 2036 // then just use that as our result. 2037 if (QualType(canonElementType.Ty, 0) == elementType) 2038 return canon; 2039 2040 // Otherwise, we need to build a type which follows the spelling 2041 // of the element type. 2042 DependentSizedArrayType *sugaredType 2043 = new (*this, TypeAlignment) 2044 DependentSizedArrayType(*this, elementType, canon, numElements, 2045 ASM, elementTypeQuals, brackets); 2046 Types.push_back(sugaredType); 2047 return QualType(sugaredType, 0); 2048} 2049 2050QualType ASTContext::getIncompleteArrayType(QualType elementType, 2051 ArrayType::ArraySizeModifier ASM, 2052 unsigned elementTypeQuals) const { 2053 llvm::FoldingSetNodeID ID; 2054 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2055 2056 void *insertPos = 0; 2057 if (IncompleteArrayType *iat = 2058 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2059 return QualType(iat, 0); 2060 2061 // If the element type isn't canonical, this won't be a canonical type 2062 // either, so fill in the canonical type field. We also have to pull 2063 // qualifiers off the element type. 2064 QualType canon; 2065 2066 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2067 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2068 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2069 ASM, elementTypeQuals); 2070 canon = getQualifiedType(canon, canonSplit.Quals); 2071 2072 // Get the new insert position for the node we care about. 2073 IncompleteArrayType *existing = 2074 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2075 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2076 } 2077 2078 IncompleteArrayType *newType = new (*this, TypeAlignment) 2079 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2080 2081 IncompleteArrayTypes.InsertNode(newType, insertPos); 2082 Types.push_back(newType); 2083 return QualType(newType, 0); 2084} 2085 2086/// getVectorType - Return the unique reference to a vector type of 2087/// the specified element type and size. VectorType must be a built-in type. 2088QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2089 VectorType::VectorKind VecKind) const { 2090 assert(vecType->isBuiltinType()); 2091 2092 // Check if we've already instantiated a vector of this type. 2093 llvm::FoldingSetNodeID ID; 2094 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2095 2096 void *InsertPos = 0; 2097 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2098 return QualType(VTP, 0); 2099 2100 // If the element type isn't canonical, this won't be a canonical type either, 2101 // so fill in the canonical type field. 2102 QualType Canonical; 2103 if (!vecType.isCanonical()) { 2104 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2105 2106 // Get the new insert position for the node we care about. 2107 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2108 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2109 } 2110 VectorType *New = new (*this, TypeAlignment) 2111 VectorType(vecType, NumElts, Canonical, VecKind); 2112 VectorTypes.InsertNode(New, InsertPos); 2113 Types.push_back(New); 2114 return QualType(New, 0); 2115} 2116 2117/// getExtVectorType - Return the unique reference to an extended vector type of 2118/// the specified element type and size. VectorType must be a built-in type. 2119QualType 2120ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2121 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2122 2123 // Check if we've already instantiated a vector of this type. 2124 llvm::FoldingSetNodeID ID; 2125 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2126 VectorType::GenericVector); 2127 void *InsertPos = 0; 2128 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2129 return QualType(VTP, 0); 2130 2131 // If the element type isn't canonical, this won't be a canonical type either, 2132 // so fill in the canonical type field. 2133 QualType Canonical; 2134 if (!vecType.isCanonical()) { 2135 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2136 2137 // Get the new insert position for the node we care about. 2138 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2139 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2140 } 2141 ExtVectorType *New = new (*this, TypeAlignment) 2142 ExtVectorType(vecType, NumElts, Canonical); 2143 VectorTypes.InsertNode(New, InsertPos); 2144 Types.push_back(New); 2145 return QualType(New, 0); 2146} 2147 2148QualType 2149ASTContext::getDependentSizedExtVectorType(QualType vecType, 2150 Expr *SizeExpr, 2151 SourceLocation AttrLoc) const { 2152 llvm::FoldingSetNodeID ID; 2153 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2154 SizeExpr); 2155 2156 void *InsertPos = 0; 2157 DependentSizedExtVectorType *Canon 2158 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2159 DependentSizedExtVectorType *New; 2160 if (Canon) { 2161 // We already have a canonical version of this array type; use it as 2162 // the canonical type for a newly-built type. 2163 New = new (*this, TypeAlignment) 2164 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2165 SizeExpr, AttrLoc); 2166 } else { 2167 QualType CanonVecTy = getCanonicalType(vecType); 2168 if (CanonVecTy == vecType) { 2169 New = new (*this, TypeAlignment) 2170 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2171 AttrLoc); 2172 2173 DependentSizedExtVectorType *CanonCheck 2174 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2175 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2176 (void)CanonCheck; 2177 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2178 } else { 2179 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2180 SourceLocation()); 2181 New = new (*this, TypeAlignment) 2182 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2183 } 2184 } 2185 2186 Types.push_back(New); 2187 return QualType(New, 0); 2188} 2189 2190/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2191/// 2192QualType 2193ASTContext::getFunctionNoProtoType(QualType ResultTy, 2194 const FunctionType::ExtInfo &Info) const { 2195 const CallingConv DefaultCC = Info.getCC(); 2196 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2197 CC_X86StdCall : DefaultCC; 2198 // Unique functions, to guarantee there is only one function of a particular 2199 // structure. 2200 llvm::FoldingSetNodeID ID; 2201 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2202 2203 void *InsertPos = 0; 2204 if (FunctionNoProtoType *FT = 2205 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2206 return QualType(FT, 0); 2207 2208 QualType Canonical; 2209 if (!ResultTy.isCanonical() || 2210 getCanonicalCallConv(CallConv) != CallConv) { 2211 Canonical = 2212 getFunctionNoProtoType(getCanonicalType(ResultTy), 2213 Info.withCallingConv(getCanonicalCallConv(CallConv))); 2214 2215 // Get the new insert position for the node we care about. 2216 FunctionNoProtoType *NewIP = 2217 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2218 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2219 } 2220 2221 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2222 FunctionNoProtoType *New = new (*this, TypeAlignment) 2223 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2224 Types.push_back(New); 2225 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2226 return QualType(New, 0); 2227} 2228 2229/// getFunctionType - Return a normal function type with a typed argument 2230/// list. isVariadic indicates whether the argument list includes '...'. 2231QualType 2232ASTContext::getFunctionType(QualType ResultTy, 2233 const QualType *ArgArray, unsigned NumArgs, 2234 const FunctionProtoType::ExtProtoInfo &EPI) const { 2235 // Unique functions, to guarantee there is only one function of a particular 2236 // structure. 2237 llvm::FoldingSetNodeID ID; 2238 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this); 2239 2240 void *InsertPos = 0; 2241 if (FunctionProtoType *FTP = 2242 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2243 return QualType(FTP, 0); 2244 2245 // Determine whether the type being created is already canonical or not. 2246 bool isCanonical = 2247 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() && 2248 !EPI.HasTrailingReturn; 2249 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2250 if (!ArgArray[i].isCanonicalAsParam()) 2251 isCanonical = false; 2252 2253 const CallingConv DefaultCC = EPI.ExtInfo.getCC(); 2254 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2255 CC_X86StdCall : DefaultCC; 2256 2257 // If this type isn't canonical, get the canonical version of it. 2258 // The exception spec is not part of the canonical type. 2259 QualType Canonical; 2260 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 2261 SmallVector<QualType, 16> CanonicalArgs; 2262 CanonicalArgs.reserve(NumArgs); 2263 for (unsigned i = 0; i != NumArgs; ++i) 2264 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2265 2266 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2267 CanonicalEPI.HasTrailingReturn = false; 2268 CanonicalEPI.ExceptionSpecType = EST_None; 2269 CanonicalEPI.NumExceptions = 0; 2270 CanonicalEPI.ExtInfo 2271 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv)); 2272 2273 Canonical = getFunctionType(getCanonicalType(ResultTy), 2274 CanonicalArgs.data(), NumArgs, 2275 CanonicalEPI); 2276 2277 // Get the new insert position for the node we care about. 2278 FunctionProtoType *NewIP = 2279 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2280 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2281 } 2282 2283 // FunctionProtoType objects are allocated with extra bytes after 2284 // them for three variable size arrays at the end: 2285 // - parameter types 2286 // - exception types 2287 // - consumed-arguments flags 2288 // Instead of the exception types, there could be a noexcept 2289 // expression. 2290 size_t Size = sizeof(FunctionProtoType) + 2291 NumArgs * sizeof(QualType); 2292 if (EPI.ExceptionSpecType == EST_Dynamic) 2293 Size += EPI.NumExceptions * sizeof(QualType); 2294 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) { 2295 Size += sizeof(Expr*); 2296 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) { 2297 Size += 2 * sizeof(FunctionDecl*); 2298 } 2299 if (EPI.ConsumedArguments) 2300 Size += NumArgs * sizeof(bool); 2301 2302 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2303 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2304 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv); 2305 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI); 2306 Types.push_back(FTP); 2307 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2308 return QualType(FTP, 0); 2309} 2310 2311#ifndef NDEBUG 2312static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2313 if (!isa<CXXRecordDecl>(D)) return false; 2314 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2315 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2316 return true; 2317 if (RD->getDescribedClassTemplate() && 2318 !isa<ClassTemplateSpecializationDecl>(RD)) 2319 return true; 2320 return false; 2321} 2322#endif 2323 2324/// getInjectedClassNameType - Return the unique reference to the 2325/// injected class name type for the specified templated declaration. 2326QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2327 QualType TST) const { 2328 assert(NeedsInjectedClassNameType(Decl)); 2329 if (Decl->TypeForDecl) { 2330 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2331 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2332 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2333 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2334 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2335 } else { 2336 Type *newType = 2337 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2338 Decl->TypeForDecl = newType; 2339 Types.push_back(newType); 2340 } 2341 return QualType(Decl->TypeForDecl, 0); 2342} 2343 2344/// getTypeDeclType - Return the unique reference to the type for the 2345/// specified type declaration. 2346QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2347 assert(Decl && "Passed null for Decl param"); 2348 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2349 2350 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2351 return getTypedefType(Typedef); 2352 2353 assert(!isa<TemplateTypeParmDecl>(Decl) && 2354 "Template type parameter types are always available."); 2355 2356 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2357 assert(!Record->getPreviousDecl() && 2358 "struct/union has previous declaration"); 2359 assert(!NeedsInjectedClassNameType(Record)); 2360 return getRecordType(Record); 2361 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2362 assert(!Enum->getPreviousDecl() && 2363 "enum has previous declaration"); 2364 return getEnumType(Enum); 2365 } else if (const UnresolvedUsingTypenameDecl *Using = 2366 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2367 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2368 Decl->TypeForDecl = newType; 2369 Types.push_back(newType); 2370 } else 2371 llvm_unreachable("TypeDecl without a type?"); 2372 2373 return QualType(Decl->TypeForDecl, 0); 2374} 2375 2376/// getTypedefType - Return the unique reference to the type for the 2377/// specified typedef name decl. 2378QualType 2379ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2380 QualType Canonical) const { 2381 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2382 2383 if (Canonical.isNull()) 2384 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2385 TypedefType *newType = new(*this, TypeAlignment) 2386 TypedefType(Type::Typedef, Decl, Canonical); 2387 Decl->TypeForDecl = newType; 2388 Types.push_back(newType); 2389 return QualType(newType, 0); 2390} 2391 2392QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2393 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2394 2395 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2396 if (PrevDecl->TypeForDecl) 2397 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2398 2399 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 2400 Decl->TypeForDecl = newType; 2401 Types.push_back(newType); 2402 return QualType(newType, 0); 2403} 2404 2405QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 2406 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2407 2408 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 2409 if (PrevDecl->TypeForDecl) 2410 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2411 2412 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 2413 Decl->TypeForDecl = newType; 2414 Types.push_back(newType); 2415 return QualType(newType, 0); 2416} 2417 2418QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 2419 QualType modifiedType, 2420 QualType equivalentType) { 2421 llvm::FoldingSetNodeID id; 2422 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 2423 2424 void *insertPos = 0; 2425 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 2426 if (type) return QualType(type, 0); 2427 2428 QualType canon = getCanonicalType(equivalentType); 2429 type = new (*this, TypeAlignment) 2430 AttributedType(canon, attrKind, modifiedType, equivalentType); 2431 2432 Types.push_back(type); 2433 AttributedTypes.InsertNode(type, insertPos); 2434 2435 return QualType(type, 0); 2436} 2437 2438 2439/// \brief Retrieve a substitution-result type. 2440QualType 2441ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 2442 QualType Replacement) const { 2443 assert(Replacement.isCanonical() 2444 && "replacement types must always be canonical"); 2445 2446 llvm::FoldingSetNodeID ID; 2447 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 2448 void *InsertPos = 0; 2449 SubstTemplateTypeParmType *SubstParm 2450 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2451 2452 if (!SubstParm) { 2453 SubstParm = new (*this, TypeAlignment) 2454 SubstTemplateTypeParmType(Parm, Replacement); 2455 Types.push_back(SubstParm); 2456 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2457 } 2458 2459 return QualType(SubstParm, 0); 2460} 2461 2462/// \brief Retrieve a 2463QualType ASTContext::getSubstTemplateTypeParmPackType( 2464 const TemplateTypeParmType *Parm, 2465 const TemplateArgument &ArgPack) { 2466#ifndef NDEBUG 2467 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 2468 PEnd = ArgPack.pack_end(); 2469 P != PEnd; ++P) { 2470 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 2471 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type"); 2472 } 2473#endif 2474 2475 llvm::FoldingSetNodeID ID; 2476 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 2477 void *InsertPos = 0; 2478 if (SubstTemplateTypeParmPackType *SubstParm 2479 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 2480 return QualType(SubstParm, 0); 2481 2482 QualType Canon; 2483 if (!Parm->isCanonicalUnqualified()) { 2484 Canon = getCanonicalType(QualType(Parm, 0)); 2485 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 2486 ArgPack); 2487 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 2488 } 2489 2490 SubstTemplateTypeParmPackType *SubstParm 2491 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 2492 ArgPack); 2493 Types.push_back(SubstParm); 2494 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2495 return QualType(SubstParm, 0); 2496} 2497 2498/// \brief Retrieve the template type parameter type for a template 2499/// parameter or parameter pack with the given depth, index, and (optionally) 2500/// name. 2501QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 2502 bool ParameterPack, 2503 TemplateTypeParmDecl *TTPDecl) const { 2504 llvm::FoldingSetNodeID ID; 2505 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 2506 void *InsertPos = 0; 2507 TemplateTypeParmType *TypeParm 2508 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2509 2510 if (TypeParm) 2511 return QualType(TypeParm, 0); 2512 2513 if (TTPDecl) { 2514 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 2515 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 2516 2517 TemplateTypeParmType *TypeCheck 2518 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2519 assert(!TypeCheck && "Template type parameter canonical type broken"); 2520 (void)TypeCheck; 2521 } else 2522 TypeParm = new (*this, TypeAlignment) 2523 TemplateTypeParmType(Depth, Index, ParameterPack); 2524 2525 Types.push_back(TypeParm); 2526 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 2527 2528 return QualType(TypeParm, 0); 2529} 2530 2531TypeSourceInfo * 2532ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 2533 SourceLocation NameLoc, 2534 const TemplateArgumentListInfo &Args, 2535 QualType Underlying) const { 2536 assert(!Name.getAsDependentTemplateName() && 2537 "No dependent template names here!"); 2538 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 2539 2540 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 2541 TemplateSpecializationTypeLoc TL 2542 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 2543 TL.setTemplateKeywordLoc(SourceLocation()); 2544 TL.setTemplateNameLoc(NameLoc); 2545 TL.setLAngleLoc(Args.getLAngleLoc()); 2546 TL.setRAngleLoc(Args.getRAngleLoc()); 2547 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 2548 TL.setArgLocInfo(i, Args[i].getLocInfo()); 2549 return DI; 2550} 2551 2552QualType 2553ASTContext::getTemplateSpecializationType(TemplateName Template, 2554 const TemplateArgumentListInfo &Args, 2555 QualType Underlying) const { 2556 assert(!Template.getAsDependentTemplateName() && 2557 "No dependent template names here!"); 2558 2559 unsigned NumArgs = Args.size(); 2560 2561 SmallVector<TemplateArgument, 4> ArgVec; 2562 ArgVec.reserve(NumArgs); 2563 for (unsigned i = 0; i != NumArgs; ++i) 2564 ArgVec.push_back(Args[i].getArgument()); 2565 2566 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 2567 Underlying); 2568} 2569 2570#ifndef NDEBUG 2571static bool hasAnyPackExpansions(const TemplateArgument *Args, 2572 unsigned NumArgs) { 2573 for (unsigned I = 0; I != NumArgs; ++I) 2574 if (Args[I].isPackExpansion()) 2575 return true; 2576 2577 return true; 2578} 2579#endif 2580 2581QualType 2582ASTContext::getTemplateSpecializationType(TemplateName Template, 2583 const TemplateArgument *Args, 2584 unsigned NumArgs, 2585 QualType Underlying) const { 2586 assert(!Template.getAsDependentTemplateName() && 2587 "No dependent template names here!"); 2588 // Look through qualified template names. 2589 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2590 Template = TemplateName(QTN->getTemplateDecl()); 2591 2592 bool IsTypeAlias = 2593 Template.getAsTemplateDecl() && 2594 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 2595 QualType CanonType; 2596 if (!Underlying.isNull()) 2597 CanonType = getCanonicalType(Underlying); 2598 else { 2599 // We can get here with an alias template when the specialization contains 2600 // a pack expansion that does not match up with a parameter pack. 2601 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 2602 "Caller must compute aliased type"); 2603 IsTypeAlias = false; 2604 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 2605 NumArgs); 2606 } 2607 2608 // Allocate the (non-canonical) template specialization type, but don't 2609 // try to unique it: these types typically have location information that 2610 // we don't unique and don't want to lose. 2611 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 2612 sizeof(TemplateArgument) * NumArgs + 2613 (IsTypeAlias? sizeof(QualType) : 0), 2614 TypeAlignment); 2615 TemplateSpecializationType *Spec 2616 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 2617 IsTypeAlias ? Underlying : QualType()); 2618 2619 Types.push_back(Spec); 2620 return QualType(Spec, 0); 2621} 2622 2623QualType 2624ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2625 const TemplateArgument *Args, 2626 unsigned NumArgs) const { 2627 assert(!Template.getAsDependentTemplateName() && 2628 "No dependent template names here!"); 2629 2630 // Look through qualified template names. 2631 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2632 Template = TemplateName(QTN->getTemplateDecl()); 2633 2634 // Build the canonical template specialization type. 2635 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2636 SmallVector<TemplateArgument, 4> CanonArgs; 2637 CanonArgs.reserve(NumArgs); 2638 for (unsigned I = 0; I != NumArgs; ++I) 2639 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2640 2641 // Determine whether this canonical template specialization type already 2642 // exists. 2643 llvm::FoldingSetNodeID ID; 2644 TemplateSpecializationType::Profile(ID, CanonTemplate, 2645 CanonArgs.data(), NumArgs, *this); 2646 2647 void *InsertPos = 0; 2648 TemplateSpecializationType *Spec 2649 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2650 2651 if (!Spec) { 2652 // Allocate a new canonical template specialization type. 2653 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2654 sizeof(TemplateArgument) * NumArgs), 2655 TypeAlignment); 2656 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2657 CanonArgs.data(), NumArgs, 2658 QualType(), QualType()); 2659 Types.push_back(Spec); 2660 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2661 } 2662 2663 assert(Spec->isDependentType() && 2664 "Non-dependent template-id type must have a canonical type"); 2665 return QualType(Spec, 0); 2666} 2667 2668QualType 2669ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2670 NestedNameSpecifier *NNS, 2671 QualType NamedType) const { 2672 llvm::FoldingSetNodeID ID; 2673 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2674 2675 void *InsertPos = 0; 2676 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2677 if (T) 2678 return QualType(T, 0); 2679 2680 QualType Canon = NamedType; 2681 if (!Canon.isCanonical()) { 2682 Canon = getCanonicalType(NamedType); 2683 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2684 assert(!CheckT && "Elaborated canonical type broken"); 2685 (void)CheckT; 2686 } 2687 2688 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2689 Types.push_back(T); 2690 ElaboratedTypes.InsertNode(T, InsertPos); 2691 return QualType(T, 0); 2692} 2693 2694QualType 2695ASTContext::getParenType(QualType InnerType) const { 2696 llvm::FoldingSetNodeID ID; 2697 ParenType::Profile(ID, InnerType); 2698 2699 void *InsertPos = 0; 2700 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2701 if (T) 2702 return QualType(T, 0); 2703 2704 QualType Canon = InnerType; 2705 if (!Canon.isCanonical()) { 2706 Canon = getCanonicalType(InnerType); 2707 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2708 assert(!CheckT && "Paren canonical type broken"); 2709 (void)CheckT; 2710 } 2711 2712 T = new (*this) ParenType(InnerType, Canon); 2713 Types.push_back(T); 2714 ParenTypes.InsertNode(T, InsertPos); 2715 return QualType(T, 0); 2716} 2717 2718QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2719 NestedNameSpecifier *NNS, 2720 const IdentifierInfo *Name, 2721 QualType Canon) const { 2722 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2723 2724 if (Canon.isNull()) { 2725 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2726 ElaboratedTypeKeyword CanonKeyword = Keyword; 2727 if (Keyword == ETK_None) 2728 CanonKeyword = ETK_Typename; 2729 2730 if (CanonNNS != NNS || CanonKeyword != Keyword) 2731 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2732 } 2733 2734 llvm::FoldingSetNodeID ID; 2735 DependentNameType::Profile(ID, Keyword, NNS, Name); 2736 2737 void *InsertPos = 0; 2738 DependentNameType *T 2739 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2740 if (T) 2741 return QualType(T, 0); 2742 2743 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2744 Types.push_back(T); 2745 DependentNameTypes.InsertNode(T, InsertPos); 2746 return QualType(T, 0); 2747} 2748 2749QualType 2750ASTContext::getDependentTemplateSpecializationType( 2751 ElaboratedTypeKeyword Keyword, 2752 NestedNameSpecifier *NNS, 2753 const IdentifierInfo *Name, 2754 const TemplateArgumentListInfo &Args) const { 2755 // TODO: avoid this copy 2756 SmallVector<TemplateArgument, 16> ArgCopy; 2757 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2758 ArgCopy.push_back(Args[I].getArgument()); 2759 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2760 ArgCopy.size(), 2761 ArgCopy.data()); 2762} 2763 2764QualType 2765ASTContext::getDependentTemplateSpecializationType( 2766 ElaboratedTypeKeyword Keyword, 2767 NestedNameSpecifier *NNS, 2768 const IdentifierInfo *Name, 2769 unsigned NumArgs, 2770 const TemplateArgument *Args) const { 2771 assert((!NNS || NNS->isDependent()) && 2772 "nested-name-specifier must be dependent"); 2773 2774 llvm::FoldingSetNodeID ID; 2775 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2776 Name, NumArgs, Args); 2777 2778 void *InsertPos = 0; 2779 DependentTemplateSpecializationType *T 2780 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2781 if (T) 2782 return QualType(T, 0); 2783 2784 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2785 2786 ElaboratedTypeKeyword CanonKeyword = Keyword; 2787 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2788 2789 bool AnyNonCanonArgs = false; 2790 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2791 for (unsigned I = 0; I != NumArgs; ++I) { 2792 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2793 if (!CanonArgs[I].structurallyEquals(Args[I])) 2794 AnyNonCanonArgs = true; 2795 } 2796 2797 QualType Canon; 2798 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2799 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2800 Name, NumArgs, 2801 CanonArgs.data()); 2802 2803 // Find the insert position again. 2804 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2805 } 2806 2807 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2808 sizeof(TemplateArgument) * NumArgs), 2809 TypeAlignment); 2810 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2811 Name, NumArgs, Args, Canon); 2812 Types.push_back(T); 2813 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2814 return QualType(T, 0); 2815} 2816 2817QualType ASTContext::getPackExpansionType(QualType Pattern, 2818 llvm::Optional<unsigned> NumExpansions) { 2819 llvm::FoldingSetNodeID ID; 2820 PackExpansionType::Profile(ID, Pattern, NumExpansions); 2821 2822 assert(Pattern->containsUnexpandedParameterPack() && 2823 "Pack expansions must expand one or more parameter packs"); 2824 void *InsertPos = 0; 2825 PackExpansionType *T 2826 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2827 if (T) 2828 return QualType(T, 0); 2829 2830 QualType Canon; 2831 if (!Pattern.isCanonical()) { 2832 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions); 2833 2834 // Find the insert position again. 2835 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2836 } 2837 2838 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 2839 Types.push_back(T); 2840 PackExpansionTypes.InsertNode(T, InsertPos); 2841 return QualType(T, 0); 2842} 2843 2844/// CmpProtocolNames - Comparison predicate for sorting protocols 2845/// alphabetically. 2846static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2847 const ObjCProtocolDecl *RHS) { 2848 return LHS->getDeclName() < RHS->getDeclName(); 2849} 2850 2851static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2852 unsigned NumProtocols) { 2853 if (NumProtocols == 0) return true; 2854 2855 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 2856 return false; 2857 2858 for (unsigned i = 1; i != NumProtocols; ++i) 2859 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 2860 Protocols[i]->getCanonicalDecl() != Protocols[i]) 2861 return false; 2862 return true; 2863} 2864 2865static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2866 unsigned &NumProtocols) { 2867 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2868 2869 // Sort protocols, keyed by name. 2870 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2871 2872 // Canonicalize. 2873 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 2874 Protocols[I] = Protocols[I]->getCanonicalDecl(); 2875 2876 // Remove duplicates. 2877 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2878 NumProtocols = ProtocolsEnd-Protocols; 2879} 2880 2881QualType ASTContext::getObjCObjectType(QualType BaseType, 2882 ObjCProtocolDecl * const *Protocols, 2883 unsigned NumProtocols) const { 2884 // If the base type is an interface and there aren't any protocols 2885 // to add, then the interface type will do just fine. 2886 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2887 return BaseType; 2888 2889 // Look in the folding set for an existing type. 2890 llvm::FoldingSetNodeID ID; 2891 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2892 void *InsertPos = 0; 2893 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2894 return QualType(QT, 0); 2895 2896 // Build the canonical type, which has the canonical base type and 2897 // a sorted-and-uniqued list of protocols. 2898 QualType Canonical; 2899 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2900 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2901 if (!ProtocolsSorted) { 2902 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2903 Protocols + NumProtocols); 2904 unsigned UniqueCount = NumProtocols; 2905 2906 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2907 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2908 &Sorted[0], UniqueCount); 2909 } else { 2910 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2911 Protocols, NumProtocols); 2912 } 2913 2914 // Regenerate InsertPos. 2915 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2916 } 2917 2918 unsigned Size = sizeof(ObjCObjectTypeImpl); 2919 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2920 void *Mem = Allocate(Size, TypeAlignment); 2921 ObjCObjectTypeImpl *T = 2922 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2923 2924 Types.push_back(T); 2925 ObjCObjectTypes.InsertNode(T, InsertPos); 2926 return QualType(T, 0); 2927} 2928 2929/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2930/// the given object type. 2931QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 2932 llvm::FoldingSetNodeID ID; 2933 ObjCObjectPointerType::Profile(ID, ObjectT); 2934 2935 void *InsertPos = 0; 2936 if (ObjCObjectPointerType *QT = 2937 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2938 return QualType(QT, 0); 2939 2940 // Find the canonical object type. 2941 QualType Canonical; 2942 if (!ObjectT.isCanonical()) { 2943 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2944 2945 // Regenerate InsertPos. 2946 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2947 } 2948 2949 // No match. 2950 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2951 ObjCObjectPointerType *QType = 2952 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2953 2954 Types.push_back(QType); 2955 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2956 return QualType(QType, 0); 2957} 2958 2959/// getObjCInterfaceType - Return the unique reference to the type for the 2960/// specified ObjC interface decl. The list of protocols is optional. 2961QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 2962 ObjCInterfaceDecl *PrevDecl) const { 2963 if (Decl->TypeForDecl) 2964 return QualType(Decl->TypeForDecl, 0); 2965 2966 if (PrevDecl) { 2967 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 2968 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2969 return QualType(PrevDecl->TypeForDecl, 0); 2970 } 2971 2972 // Prefer the definition, if there is one. 2973 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 2974 Decl = Def; 2975 2976 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2977 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2978 Decl->TypeForDecl = T; 2979 Types.push_back(T); 2980 return QualType(T, 0); 2981} 2982 2983/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2984/// TypeOfExprType AST's (since expression's are never shared). For example, 2985/// multiple declarations that refer to "typeof(x)" all contain different 2986/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2987/// on canonical type's (which are always unique). 2988QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 2989 TypeOfExprType *toe; 2990 if (tofExpr->isTypeDependent()) { 2991 llvm::FoldingSetNodeID ID; 2992 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2993 2994 void *InsertPos = 0; 2995 DependentTypeOfExprType *Canon 2996 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2997 if (Canon) { 2998 // We already have a "canonical" version of an identical, dependent 2999 // typeof(expr) type. Use that as our canonical type. 3000 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3001 QualType((TypeOfExprType*)Canon, 0)); 3002 } else { 3003 // Build a new, canonical typeof(expr) type. 3004 Canon 3005 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3006 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3007 toe = Canon; 3008 } 3009 } else { 3010 QualType Canonical = getCanonicalType(tofExpr->getType()); 3011 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3012 } 3013 Types.push_back(toe); 3014 return QualType(toe, 0); 3015} 3016 3017/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3018/// TypeOfType AST's. The only motivation to unique these nodes would be 3019/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3020/// an issue. This doesn't effect the type checker, since it operates 3021/// on canonical type's (which are always unique). 3022QualType ASTContext::getTypeOfType(QualType tofType) const { 3023 QualType Canonical = getCanonicalType(tofType); 3024 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3025 Types.push_back(tot); 3026 return QualType(tot, 0); 3027} 3028 3029 3030/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 3031/// DecltypeType AST's. The only motivation to unique these nodes would be 3032/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 3033/// an issue. This doesn't effect the type checker, since it operates 3034/// on canonical types (which are always unique). 3035QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3036 DecltypeType *dt; 3037 3038 // C++0x [temp.type]p2: 3039 // If an expression e involves a template parameter, decltype(e) denotes a 3040 // unique dependent type. Two such decltype-specifiers refer to the same 3041 // type only if their expressions are equivalent (14.5.6.1). 3042 if (e->isInstantiationDependent()) { 3043 llvm::FoldingSetNodeID ID; 3044 DependentDecltypeType::Profile(ID, *this, e); 3045 3046 void *InsertPos = 0; 3047 DependentDecltypeType *Canon 3048 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3049 if (Canon) { 3050 // We already have a "canonical" version of an equivalent, dependent 3051 // decltype type. Use that as our canonical type. 3052 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 3053 QualType((DecltypeType*)Canon, 0)); 3054 } else { 3055 // Build a new, canonical typeof(expr) type. 3056 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3057 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3058 dt = Canon; 3059 } 3060 } else { 3061 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3062 getCanonicalType(UnderlyingType)); 3063 } 3064 Types.push_back(dt); 3065 return QualType(dt, 0); 3066} 3067 3068/// getUnaryTransformationType - We don't unique these, since the memory 3069/// savings are minimal and these are rare. 3070QualType ASTContext::getUnaryTransformType(QualType BaseType, 3071 QualType UnderlyingType, 3072 UnaryTransformType::UTTKind Kind) 3073 const { 3074 UnaryTransformType *Ty = 3075 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3076 Kind, 3077 UnderlyingType->isDependentType() ? 3078 QualType() : getCanonicalType(UnderlyingType)); 3079 Types.push_back(Ty); 3080 return QualType(Ty, 0); 3081} 3082 3083/// getAutoType - We only unique auto types after they've been deduced. 3084QualType ASTContext::getAutoType(QualType DeducedType) const { 3085 void *InsertPos = 0; 3086 if (!DeducedType.isNull()) { 3087 // Look in the folding set for an existing type. 3088 llvm::FoldingSetNodeID ID; 3089 AutoType::Profile(ID, DeducedType); 3090 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3091 return QualType(AT, 0); 3092 } 3093 3094 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType); 3095 Types.push_back(AT); 3096 if (InsertPos) 3097 AutoTypes.InsertNode(AT, InsertPos); 3098 return QualType(AT, 0); 3099} 3100 3101/// getAtomicType - Return the uniqued reference to the atomic type for 3102/// the given value type. 3103QualType ASTContext::getAtomicType(QualType T) const { 3104 // Unique pointers, to guarantee there is only one pointer of a particular 3105 // structure. 3106 llvm::FoldingSetNodeID ID; 3107 AtomicType::Profile(ID, T); 3108 3109 void *InsertPos = 0; 3110 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3111 return QualType(AT, 0); 3112 3113 // If the atomic value type isn't canonical, this won't be a canonical type 3114 // either, so fill in the canonical type field. 3115 QualType Canonical; 3116 if (!T.isCanonical()) { 3117 Canonical = getAtomicType(getCanonicalType(T)); 3118 3119 // Get the new insert position for the node we care about. 3120 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3122 } 3123 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3124 Types.push_back(New); 3125 AtomicTypes.InsertNode(New, InsertPos); 3126 return QualType(New, 0); 3127} 3128 3129/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3130QualType ASTContext::getAutoDeductType() const { 3131 if (AutoDeductTy.isNull()) 3132 AutoDeductTy = getAutoType(QualType()); 3133 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern"); 3134 return AutoDeductTy; 3135} 3136 3137/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3138QualType ASTContext::getAutoRRefDeductType() const { 3139 if (AutoRRefDeductTy.isNull()) 3140 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3141 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3142 return AutoRRefDeductTy; 3143} 3144 3145/// getTagDeclType - Return the unique reference to the type for the 3146/// specified TagDecl (struct/union/class/enum) decl. 3147QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3148 assert (Decl); 3149 // FIXME: What is the design on getTagDeclType when it requires casting 3150 // away const? mutable? 3151 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3152} 3153 3154/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3155/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3156/// needs to agree with the definition in <stddef.h>. 3157CanQualType ASTContext::getSizeType() const { 3158 return getFromTargetType(Target->getSizeType()); 3159} 3160 3161/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3162CanQualType ASTContext::getIntMaxType() const { 3163 return getFromTargetType(Target->getIntMaxType()); 3164} 3165 3166/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3167CanQualType ASTContext::getUIntMaxType() const { 3168 return getFromTargetType(Target->getUIntMaxType()); 3169} 3170 3171/// getSignedWCharType - Return the type of "signed wchar_t". 3172/// Used when in C++, as a GCC extension. 3173QualType ASTContext::getSignedWCharType() const { 3174 // FIXME: derive from "Target" ? 3175 return WCharTy; 3176} 3177 3178/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3179/// Used when in C++, as a GCC extension. 3180QualType ASTContext::getUnsignedWCharType() const { 3181 // FIXME: derive from "Target" ? 3182 return UnsignedIntTy; 3183} 3184 3185/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3186/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3187QualType ASTContext::getPointerDiffType() const { 3188 return getFromTargetType(Target->getPtrDiffType(0)); 3189} 3190 3191//===----------------------------------------------------------------------===// 3192// Type Operators 3193//===----------------------------------------------------------------------===// 3194 3195CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3196 // Push qualifiers into arrays, and then discard any remaining 3197 // qualifiers. 3198 T = getCanonicalType(T); 3199 T = getVariableArrayDecayedType(T); 3200 const Type *Ty = T.getTypePtr(); 3201 QualType Result; 3202 if (isa<ArrayType>(Ty)) { 3203 Result = getArrayDecayedType(QualType(Ty,0)); 3204 } else if (isa<FunctionType>(Ty)) { 3205 Result = getPointerType(QualType(Ty, 0)); 3206 } else { 3207 Result = QualType(Ty, 0); 3208 } 3209 3210 return CanQualType::CreateUnsafe(Result); 3211} 3212 3213QualType ASTContext::getUnqualifiedArrayType(QualType type, 3214 Qualifiers &quals) { 3215 SplitQualType splitType = type.getSplitUnqualifiedType(); 3216 3217 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3218 // the unqualified desugared type and then drops it on the floor. 3219 // We then have to strip that sugar back off with 3220 // getUnqualifiedDesugaredType(), which is silly. 3221 const ArrayType *AT = 3222 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3223 3224 // If we don't have an array, just use the results in splitType. 3225 if (!AT) { 3226 quals = splitType.Quals; 3227 return QualType(splitType.Ty, 0); 3228 } 3229 3230 // Otherwise, recurse on the array's element type. 3231 QualType elementType = AT->getElementType(); 3232 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3233 3234 // If that didn't change the element type, AT has no qualifiers, so we 3235 // can just use the results in splitType. 3236 if (elementType == unqualElementType) { 3237 assert(quals.empty()); // from the recursive call 3238 quals = splitType.Quals; 3239 return QualType(splitType.Ty, 0); 3240 } 3241 3242 // Otherwise, add in the qualifiers from the outermost type, then 3243 // build the type back up. 3244 quals.addConsistentQualifiers(splitType.Quals); 3245 3246 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3247 return getConstantArrayType(unqualElementType, CAT->getSize(), 3248 CAT->getSizeModifier(), 0); 3249 } 3250 3251 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3252 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3253 } 3254 3255 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3256 return getVariableArrayType(unqualElementType, 3257 VAT->getSizeExpr(), 3258 VAT->getSizeModifier(), 3259 VAT->getIndexTypeCVRQualifiers(), 3260 VAT->getBracketsRange()); 3261 } 3262 3263 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3264 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3265 DSAT->getSizeModifier(), 0, 3266 SourceRange()); 3267} 3268 3269/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3270/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3271/// they point to and return true. If T1 and T2 aren't pointer types 3272/// or pointer-to-member types, or if they are not similar at this 3273/// level, returns false and leaves T1 and T2 unchanged. Top-level 3274/// qualifiers on T1 and T2 are ignored. This function will typically 3275/// be called in a loop that successively "unwraps" pointer and 3276/// pointer-to-member types to compare them at each level. 3277bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3278 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3279 *T2PtrType = T2->getAs<PointerType>(); 3280 if (T1PtrType && T2PtrType) { 3281 T1 = T1PtrType->getPointeeType(); 3282 T2 = T2PtrType->getPointeeType(); 3283 return true; 3284 } 3285 3286 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3287 *T2MPType = T2->getAs<MemberPointerType>(); 3288 if (T1MPType && T2MPType && 3289 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3290 QualType(T2MPType->getClass(), 0))) { 3291 T1 = T1MPType->getPointeeType(); 3292 T2 = T2MPType->getPointeeType(); 3293 return true; 3294 } 3295 3296 if (getLangOpts().ObjC1) { 3297 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3298 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3299 if (T1OPType && T2OPType) { 3300 T1 = T1OPType->getPointeeType(); 3301 T2 = T2OPType->getPointeeType(); 3302 return true; 3303 } 3304 } 3305 3306 // FIXME: Block pointers, too? 3307 3308 return false; 3309} 3310 3311DeclarationNameInfo 3312ASTContext::getNameForTemplate(TemplateName Name, 3313 SourceLocation NameLoc) const { 3314 switch (Name.getKind()) { 3315 case TemplateName::QualifiedTemplate: 3316 case TemplateName::Template: 3317 // DNInfo work in progress: CHECKME: what about DNLoc? 3318 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3319 NameLoc); 3320 3321 case TemplateName::OverloadedTemplate: { 3322 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3323 // DNInfo work in progress: CHECKME: what about DNLoc? 3324 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3325 } 3326 3327 case TemplateName::DependentTemplate: { 3328 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3329 DeclarationName DName; 3330 if (DTN->isIdentifier()) { 3331 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3332 return DeclarationNameInfo(DName, NameLoc); 3333 } else { 3334 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3335 // DNInfo work in progress: FIXME: source locations? 3336 DeclarationNameLoc DNLoc; 3337 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3338 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3339 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3340 } 3341 } 3342 3343 case TemplateName::SubstTemplateTemplateParm: { 3344 SubstTemplateTemplateParmStorage *subst 3345 = Name.getAsSubstTemplateTemplateParm(); 3346 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3347 NameLoc); 3348 } 3349 3350 case TemplateName::SubstTemplateTemplateParmPack: { 3351 SubstTemplateTemplateParmPackStorage *subst 3352 = Name.getAsSubstTemplateTemplateParmPack(); 3353 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3354 NameLoc); 3355 } 3356 } 3357 3358 llvm_unreachable("bad template name kind!"); 3359} 3360 3361TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3362 switch (Name.getKind()) { 3363 case TemplateName::QualifiedTemplate: 3364 case TemplateName::Template: { 3365 TemplateDecl *Template = Name.getAsTemplateDecl(); 3366 if (TemplateTemplateParmDecl *TTP 3367 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3368 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3369 3370 // The canonical template name is the canonical template declaration. 3371 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3372 } 3373 3374 case TemplateName::OverloadedTemplate: 3375 llvm_unreachable("cannot canonicalize overloaded template"); 3376 3377 case TemplateName::DependentTemplate: { 3378 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3379 assert(DTN && "Non-dependent template names must refer to template decls."); 3380 return DTN->CanonicalTemplateName; 3381 } 3382 3383 case TemplateName::SubstTemplateTemplateParm: { 3384 SubstTemplateTemplateParmStorage *subst 3385 = Name.getAsSubstTemplateTemplateParm(); 3386 return getCanonicalTemplateName(subst->getReplacement()); 3387 } 3388 3389 case TemplateName::SubstTemplateTemplateParmPack: { 3390 SubstTemplateTemplateParmPackStorage *subst 3391 = Name.getAsSubstTemplateTemplateParmPack(); 3392 TemplateTemplateParmDecl *canonParameter 3393 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3394 TemplateArgument canonArgPack 3395 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3396 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3397 } 3398 } 3399 3400 llvm_unreachable("bad template name!"); 3401} 3402 3403bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 3404 X = getCanonicalTemplateName(X); 3405 Y = getCanonicalTemplateName(Y); 3406 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 3407} 3408 3409TemplateArgument 3410ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 3411 switch (Arg.getKind()) { 3412 case TemplateArgument::Null: 3413 return Arg; 3414 3415 case TemplateArgument::Expression: 3416 return Arg; 3417 3418 case TemplateArgument::Declaration: { 3419 if (Decl *D = Arg.getAsDecl()) 3420 return TemplateArgument(D->getCanonicalDecl()); 3421 return TemplateArgument((Decl*)0); 3422 } 3423 3424 case TemplateArgument::Template: 3425 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 3426 3427 case TemplateArgument::TemplateExpansion: 3428 return TemplateArgument(getCanonicalTemplateName( 3429 Arg.getAsTemplateOrTemplatePattern()), 3430 Arg.getNumTemplateExpansions()); 3431 3432 case TemplateArgument::Integral: 3433 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 3434 3435 case TemplateArgument::Type: 3436 return TemplateArgument(getCanonicalType(Arg.getAsType())); 3437 3438 case TemplateArgument::Pack: { 3439 if (Arg.pack_size() == 0) 3440 return Arg; 3441 3442 TemplateArgument *CanonArgs 3443 = new (*this) TemplateArgument[Arg.pack_size()]; 3444 unsigned Idx = 0; 3445 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 3446 AEnd = Arg.pack_end(); 3447 A != AEnd; (void)++A, ++Idx) 3448 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 3449 3450 return TemplateArgument(CanonArgs, Arg.pack_size()); 3451 } 3452 } 3453 3454 // Silence GCC warning 3455 llvm_unreachable("Unhandled template argument kind"); 3456} 3457 3458NestedNameSpecifier * 3459ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 3460 if (!NNS) 3461 return 0; 3462 3463 switch (NNS->getKind()) { 3464 case NestedNameSpecifier::Identifier: 3465 // Canonicalize the prefix but keep the identifier the same. 3466 return NestedNameSpecifier::Create(*this, 3467 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 3468 NNS->getAsIdentifier()); 3469 3470 case NestedNameSpecifier::Namespace: 3471 // A namespace is canonical; build a nested-name-specifier with 3472 // this namespace and no prefix. 3473 return NestedNameSpecifier::Create(*this, 0, 3474 NNS->getAsNamespace()->getOriginalNamespace()); 3475 3476 case NestedNameSpecifier::NamespaceAlias: 3477 // A namespace is canonical; build a nested-name-specifier with 3478 // this namespace and no prefix. 3479 return NestedNameSpecifier::Create(*this, 0, 3480 NNS->getAsNamespaceAlias()->getNamespace() 3481 ->getOriginalNamespace()); 3482 3483 case NestedNameSpecifier::TypeSpec: 3484 case NestedNameSpecifier::TypeSpecWithTemplate: { 3485 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 3486 3487 // If we have some kind of dependent-named type (e.g., "typename T::type"), 3488 // break it apart into its prefix and identifier, then reconsititute those 3489 // as the canonical nested-name-specifier. This is required to canonicalize 3490 // a dependent nested-name-specifier involving typedefs of dependent-name 3491 // types, e.g., 3492 // typedef typename T::type T1; 3493 // typedef typename T1::type T2; 3494 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 3495 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 3496 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 3497 3498 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 3499 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 3500 // first place? 3501 return NestedNameSpecifier::Create(*this, 0, false, 3502 const_cast<Type*>(T.getTypePtr())); 3503 } 3504 3505 case NestedNameSpecifier::Global: 3506 // The global specifier is canonical and unique. 3507 return NNS; 3508 } 3509 3510 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 3511} 3512 3513 3514const ArrayType *ASTContext::getAsArrayType(QualType T) const { 3515 // Handle the non-qualified case efficiently. 3516 if (!T.hasLocalQualifiers()) { 3517 // Handle the common positive case fast. 3518 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 3519 return AT; 3520 } 3521 3522 // Handle the common negative case fast. 3523 if (!isa<ArrayType>(T.getCanonicalType())) 3524 return 0; 3525 3526 // Apply any qualifiers from the array type to the element type. This 3527 // implements C99 6.7.3p8: "If the specification of an array type includes 3528 // any type qualifiers, the element type is so qualified, not the array type." 3529 3530 // If we get here, we either have type qualifiers on the type, or we have 3531 // sugar such as a typedef in the way. If we have type qualifiers on the type 3532 // we must propagate them down into the element type. 3533 3534 SplitQualType split = T.getSplitDesugaredType(); 3535 Qualifiers qs = split.Quals; 3536 3537 // If we have a simple case, just return now. 3538 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 3539 if (ATy == 0 || qs.empty()) 3540 return ATy; 3541 3542 // Otherwise, we have an array and we have qualifiers on it. Push the 3543 // qualifiers into the array element type and return a new array type. 3544 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 3545 3546 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 3547 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 3548 CAT->getSizeModifier(), 3549 CAT->getIndexTypeCVRQualifiers())); 3550 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 3551 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 3552 IAT->getSizeModifier(), 3553 IAT->getIndexTypeCVRQualifiers())); 3554 3555 if (const DependentSizedArrayType *DSAT 3556 = dyn_cast<DependentSizedArrayType>(ATy)) 3557 return cast<ArrayType>( 3558 getDependentSizedArrayType(NewEltTy, 3559 DSAT->getSizeExpr(), 3560 DSAT->getSizeModifier(), 3561 DSAT->getIndexTypeCVRQualifiers(), 3562 DSAT->getBracketsRange())); 3563 3564 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 3565 return cast<ArrayType>(getVariableArrayType(NewEltTy, 3566 VAT->getSizeExpr(), 3567 VAT->getSizeModifier(), 3568 VAT->getIndexTypeCVRQualifiers(), 3569 VAT->getBracketsRange())); 3570} 3571 3572QualType ASTContext::getAdjustedParameterType(QualType T) const { 3573 // C99 6.7.5.3p7: 3574 // A declaration of a parameter as "array of type" shall be 3575 // adjusted to "qualified pointer to type", where the type 3576 // qualifiers (if any) are those specified within the [ and ] of 3577 // the array type derivation. 3578 if (T->isArrayType()) 3579 return getArrayDecayedType(T); 3580 3581 // C99 6.7.5.3p8: 3582 // A declaration of a parameter as "function returning type" 3583 // shall be adjusted to "pointer to function returning type", as 3584 // in 6.3.2.1. 3585 if (T->isFunctionType()) 3586 return getPointerType(T); 3587 3588 return T; 3589} 3590 3591QualType ASTContext::getSignatureParameterType(QualType T) const { 3592 T = getVariableArrayDecayedType(T); 3593 T = getAdjustedParameterType(T); 3594 return T.getUnqualifiedType(); 3595} 3596 3597/// getArrayDecayedType - Return the properly qualified result of decaying the 3598/// specified array type to a pointer. This operation is non-trivial when 3599/// handling typedefs etc. The canonical type of "T" must be an array type, 3600/// this returns a pointer to a properly qualified element of the array. 3601/// 3602/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 3603QualType ASTContext::getArrayDecayedType(QualType Ty) const { 3604 // Get the element type with 'getAsArrayType' so that we don't lose any 3605 // typedefs in the element type of the array. This also handles propagation 3606 // of type qualifiers from the array type into the element type if present 3607 // (C99 6.7.3p8). 3608 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 3609 assert(PrettyArrayType && "Not an array type!"); 3610 3611 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 3612 3613 // int x[restrict 4] -> int *restrict 3614 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 3615} 3616 3617QualType ASTContext::getBaseElementType(const ArrayType *array) const { 3618 return getBaseElementType(array->getElementType()); 3619} 3620 3621QualType ASTContext::getBaseElementType(QualType type) const { 3622 Qualifiers qs; 3623 while (true) { 3624 SplitQualType split = type.getSplitDesugaredType(); 3625 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 3626 if (!array) break; 3627 3628 type = array->getElementType(); 3629 qs.addConsistentQualifiers(split.Quals); 3630 } 3631 3632 return getQualifiedType(type, qs); 3633} 3634 3635/// getConstantArrayElementCount - Returns number of constant array elements. 3636uint64_t 3637ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 3638 uint64_t ElementCount = 1; 3639 do { 3640 ElementCount *= CA->getSize().getZExtValue(); 3641 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 3642 } while (CA); 3643 return ElementCount; 3644} 3645 3646/// getFloatingRank - Return a relative rank for floating point types. 3647/// This routine will assert if passed a built-in type that isn't a float. 3648static FloatingRank getFloatingRank(QualType T) { 3649 if (const ComplexType *CT = T->getAs<ComplexType>()) 3650 return getFloatingRank(CT->getElementType()); 3651 3652 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 3653 switch (T->getAs<BuiltinType>()->getKind()) { 3654 default: llvm_unreachable("getFloatingRank(): not a floating type"); 3655 case BuiltinType::Half: return HalfRank; 3656 case BuiltinType::Float: return FloatRank; 3657 case BuiltinType::Double: return DoubleRank; 3658 case BuiltinType::LongDouble: return LongDoubleRank; 3659 } 3660} 3661 3662/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 3663/// point or a complex type (based on typeDomain/typeSize). 3664/// 'typeDomain' is a real floating point or complex type. 3665/// 'typeSize' is a real floating point or complex type. 3666QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 3667 QualType Domain) const { 3668 FloatingRank EltRank = getFloatingRank(Size); 3669 if (Domain->isComplexType()) { 3670 switch (EltRank) { 3671 case HalfRank: llvm_unreachable("Complex half is not supported"); 3672 case FloatRank: return FloatComplexTy; 3673 case DoubleRank: return DoubleComplexTy; 3674 case LongDoubleRank: return LongDoubleComplexTy; 3675 } 3676 } 3677 3678 assert(Domain->isRealFloatingType() && "Unknown domain!"); 3679 switch (EltRank) { 3680 case HalfRank: llvm_unreachable("Half ranks are not valid here"); 3681 case FloatRank: return FloatTy; 3682 case DoubleRank: return DoubleTy; 3683 case LongDoubleRank: return LongDoubleTy; 3684 } 3685 llvm_unreachable("getFloatingRank(): illegal value for rank"); 3686} 3687 3688/// getFloatingTypeOrder - Compare the rank of the two specified floating 3689/// point types, ignoring the domain of the type (i.e. 'double' == 3690/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 3691/// LHS < RHS, return -1. 3692int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 3693 FloatingRank LHSR = getFloatingRank(LHS); 3694 FloatingRank RHSR = getFloatingRank(RHS); 3695 3696 if (LHSR == RHSR) 3697 return 0; 3698 if (LHSR > RHSR) 3699 return 1; 3700 return -1; 3701} 3702 3703/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 3704/// routine will assert if passed a built-in type that isn't an integer or enum, 3705/// or if it is not canonicalized. 3706unsigned ASTContext::getIntegerRank(const Type *T) const { 3707 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 3708 3709 switch (cast<BuiltinType>(T)->getKind()) { 3710 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 3711 case BuiltinType::Bool: 3712 return 1 + (getIntWidth(BoolTy) << 3); 3713 case BuiltinType::Char_S: 3714 case BuiltinType::Char_U: 3715 case BuiltinType::SChar: 3716 case BuiltinType::UChar: 3717 return 2 + (getIntWidth(CharTy) << 3); 3718 case BuiltinType::Short: 3719 case BuiltinType::UShort: 3720 return 3 + (getIntWidth(ShortTy) << 3); 3721 case BuiltinType::Int: 3722 case BuiltinType::UInt: 3723 return 4 + (getIntWidth(IntTy) << 3); 3724 case BuiltinType::Long: 3725 case BuiltinType::ULong: 3726 return 5 + (getIntWidth(LongTy) << 3); 3727 case BuiltinType::LongLong: 3728 case BuiltinType::ULongLong: 3729 return 6 + (getIntWidth(LongLongTy) << 3); 3730 case BuiltinType::Int128: 3731 case BuiltinType::UInt128: 3732 return 7 + (getIntWidth(Int128Ty) << 3); 3733 } 3734} 3735 3736/// \brief Whether this is a promotable bitfield reference according 3737/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3738/// 3739/// \returns the type this bit-field will promote to, or NULL if no 3740/// promotion occurs. 3741QualType ASTContext::isPromotableBitField(Expr *E) const { 3742 if (E->isTypeDependent() || E->isValueDependent()) 3743 return QualType(); 3744 3745 FieldDecl *Field = E->getBitField(); 3746 if (!Field) 3747 return QualType(); 3748 3749 QualType FT = Field->getType(); 3750 3751 uint64_t BitWidth = Field->getBitWidthValue(*this); 3752 uint64_t IntSize = getTypeSize(IntTy); 3753 // GCC extension compatibility: if the bit-field size is less than or equal 3754 // to the size of int, it gets promoted no matter what its type is. 3755 // For instance, unsigned long bf : 4 gets promoted to signed int. 3756 if (BitWidth < IntSize) 3757 return IntTy; 3758 3759 if (BitWidth == IntSize) 3760 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3761 3762 // Types bigger than int are not subject to promotions, and therefore act 3763 // like the base type. 3764 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3765 // is ridiculous. 3766 return QualType(); 3767} 3768 3769/// getPromotedIntegerType - Returns the type that Promotable will 3770/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3771/// integer type. 3772QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 3773 assert(!Promotable.isNull()); 3774 assert(Promotable->isPromotableIntegerType()); 3775 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3776 return ET->getDecl()->getPromotionType(); 3777 3778 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 3779 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 3780 // (3.9.1) can be converted to a prvalue of the first of the following 3781 // types that can represent all the values of its underlying type: 3782 // int, unsigned int, long int, unsigned long int, long long int, or 3783 // unsigned long long int [...] 3784 // FIXME: Is there some better way to compute this? 3785 if (BT->getKind() == BuiltinType::WChar_S || 3786 BT->getKind() == BuiltinType::WChar_U || 3787 BT->getKind() == BuiltinType::Char16 || 3788 BT->getKind() == BuiltinType::Char32) { 3789 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 3790 uint64_t FromSize = getTypeSize(BT); 3791 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 3792 LongLongTy, UnsignedLongLongTy }; 3793 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 3794 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 3795 if (FromSize < ToSize || 3796 (FromSize == ToSize && 3797 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 3798 return PromoteTypes[Idx]; 3799 } 3800 llvm_unreachable("char type should fit into long long"); 3801 } 3802 } 3803 3804 // At this point, we should have a signed or unsigned integer type. 3805 if (Promotable->isSignedIntegerType()) 3806 return IntTy; 3807 uint64_t PromotableSize = getTypeSize(Promotable); 3808 uint64_t IntSize = getTypeSize(IntTy); 3809 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 3810 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 3811} 3812 3813/// \brief Recurses in pointer/array types until it finds an objc retainable 3814/// type and returns its ownership. 3815Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 3816 while (!T.isNull()) { 3817 if (T.getObjCLifetime() != Qualifiers::OCL_None) 3818 return T.getObjCLifetime(); 3819 if (T->isArrayType()) 3820 T = getBaseElementType(T); 3821 else if (const PointerType *PT = T->getAs<PointerType>()) 3822 T = PT->getPointeeType(); 3823 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3824 T = RT->getPointeeType(); 3825 else 3826 break; 3827 } 3828 3829 return Qualifiers::OCL_None; 3830} 3831 3832/// getIntegerTypeOrder - Returns the highest ranked integer type: 3833/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 3834/// LHS < RHS, return -1. 3835int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 3836 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 3837 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 3838 if (LHSC == RHSC) return 0; 3839 3840 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 3841 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 3842 3843 unsigned LHSRank = getIntegerRank(LHSC); 3844 unsigned RHSRank = getIntegerRank(RHSC); 3845 3846 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 3847 if (LHSRank == RHSRank) return 0; 3848 return LHSRank > RHSRank ? 1 : -1; 3849 } 3850 3851 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3852 if (LHSUnsigned) { 3853 // If the unsigned [LHS] type is larger, return it. 3854 if (LHSRank >= RHSRank) 3855 return 1; 3856 3857 // If the signed type can represent all values of the unsigned type, it 3858 // wins. Because we are dealing with 2's complement and types that are 3859 // powers of two larger than each other, this is always safe. 3860 return -1; 3861 } 3862 3863 // If the unsigned [RHS] type is larger, return it. 3864 if (RHSRank >= LHSRank) 3865 return -1; 3866 3867 // If the signed type can represent all values of the unsigned type, it 3868 // wins. Because we are dealing with 2's complement and types that are 3869 // powers of two larger than each other, this is always safe. 3870 return 1; 3871} 3872 3873static RecordDecl * 3874CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 3875 DeclContext *DC, IdentifierInfo *Id) { 3876 SourceLocation Loc; 3877 if (Ctx.getLangOpts().CPlusPlus) 3878 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3879 else 3880 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3881} 3882 3883// getCFConstantStringType - Return the type used for constant CFStrings. 3884QualType ASTContext::getCFConstantStringType() const { 3885 if (!CFConstantStringTypeDecl) { 3886 CFConstantStringTypeDecl = 3887 CreateRecordDecl(*this, TTK_Struct, TUDecl, 3888 &Idents.get("NSConstantString")); 3889 CFConstantStringTypeDecl->startDefinition(); 3890 3891 QualType FieldTypes[4]; 3892 3893 // const int *isa; 3894 FieldTypes[0] = getPointerType(IntTy.withConst()); 3895 // int flags; 3896 FieldTypes[1] = IntTy; 3897 // const char *str; 3898 FieldTypes[2] = getPointerType(CharTy.withConst()); 3899 // long length; 3900 FieldTypes[3] = LongTy; 3901 3902 // Create fields 3903 for (unsigned i = 0; i < 4; ++i) { 3904 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 3905 SourceLocation(), 3906 SourceLocation(), 0, 3907 FieldTypes[i], /*TInfo=*/0, 3908 /*BitWidth=*/0, 3909 /*Mutable=*/false, 3910 ICIS_NoInit); 3911 Field->setAccess(AS_public); 3912 CFConstantStringTypeDecl->addDecl(Field); 3913 } 3914 3915 CFConstantStringTypeDecl->completeDefinition(); 3916 } 3917 3918 return getTagDeclType(CFConstantStringTypeDecl); 3919} 3920 3921void ASTContext::setCFConstantStringType(QualType T) { 3922 const RecordType *Rec = T->getAs<RecordType>(); 3923 assert(Rec && "Invalid CFConstantStringType"); 3924 CFConstantStringTypeDecl = Rec->getDecl(); 3925} 3926 3927QualType ASTContext::getBlockDescriptorType() const { 3928 if (BlockDescriptorType) 3929 return getTagDeclType(BlockDescriptorType); 3930 3931 RecordDecl *T; 3932 // FIXME: Needs the FlagAppleBlock bit. 3933 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3934 &Idents.get("__block_descriptor")); 3935 T->startDefinition(); 3936 3937 QualType FieldTypes[] = { 3938 UnsignedLongTy, 3939 UnsignedLongTy, 3940 }; 3941 3942 const char *FieldNames[] = { 3943 "reserved", 3944 "Size" 3945 }; 3946 3947 for (size_t i = 0; i < 2; ++i) { 3948 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3949 SourceLocation(), 3950 &Idents.get(FieldNames[i]), 3951 FieldTypes[i], /*TInfo=*/0, 3952 /*BitWidth=*/0, 3953 /*Mutable=*/false, 3954 ICIS_NoInit); 3955 Field->setAccess(AS_public); 3956 T->addDecl(Field); 3957 } 3958 3959 T->completeDefinition(); 3960 3961 BlockDescriptorType = T; 3962 3963 return getTagDeclType(BlockDescriptorType); 3964} 3965 3966QualType ASTContext::getBlockDescriptorExtendedType() const { 3967 if (BlockDescriptorExtendedType) 3968 return getTagDeclType(BlockDescriptorExtendedType); 3969 3970 RecordDecl *T; 3971 // FIXME: Needs the FlagAppleBlock bit. 3972 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3973 &Idents.get("__block_descriptor_withcopydispose")); 3974 T->startDefinition(); 3975 3976 QualType FieldTypes[] = { 3977 UnsignedLongTy, 3978 UnsignedLongTy, 3979 getPointerType(VoidPtrTy), 3980 getPointerType(VoidPtrTy) 3981 }; 3982 3983 const char *FieldNames[] = { 3984 "reserved", 3985 "Size", 3986 "CopyFuncPtr", 3987 "DestroyFuncPtr" 3988 }; 3989 3990 for (size_t i = 0; i < 4; ++i) { 3991 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3992 SourceLocation(), 3993 &Idents.get(FieldNames[i]), 3994 FieldTypes[i], /*TInfo=*/0, 3995 /*BitWidth=*/0, 3996 /*Mutable=*/false, 3997 ICIS_NoInit); 3998 Field->setAccess(AS_public); 3999 T->addDecl(Field); 4000 } 4001 4002 T->completeDefinition(); 4003 4004 BlockDescriptorExtendedType = T; 4005 4006 return getTagDeclType(BlockDescriptorExtendedType); 4007} 4008 4009bool ASTContext::BlockRequiresCopying(QualType Ty) const { 4010 if (Ty->isObjCRetainableType()) 4011 return true; 4012 if (getLangOpts().CPlusPlus) { 4013 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4014 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4015 return RD->hasConstCopyConstructor(); 4016 4017 } 4018 } 4019 return false; 4020} 4021 4022QualType 4023ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const { 4024 // type = struct __Block_byref_1_X { 4025 // void *__isa; 4026 // struct __Block_byref_1_X *__forwarding; 4027 // unsigned int __flags; 4028 // unsigned int __size; 4029 // void *__copy_helper; // as needed 4030 // void *__destroy_help // as needed 4031 // int X; 4032 // } * 4033 4034 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 4035 4036 // FIXME: Move up 4037 SmallString<36> Name; 4038 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 4039 ++UniqueBlockByRefTypeID << '_' << DeclName; 4040 RecordDecl *T; 4041 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str())); 4042 T->startDefinition(); 4043 QualType Int32Ty = IntTy; 4044 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 4045 QualType FieldTypes[] = { 4046 getPointerType(VoidPtrTy), 4047 getPointerType(getTagDeclType(T)), 4048 Int32Ty, 4049 Int32Ty, 4050 getPointerType(VoidPtrTy), 4051 getPointerType(VoidPtrTy), 4052 Ty 4053 }; 4054 4055 StringRef FieldNames[] = { 4056 "__isa", 4057 "__forwarding", 4058 "__flags", 4059 "__size", 4060 "__copy_helper", 4061 "__destroy_helper", 4062 DeclName, 4063 }; 4064 4065 for (size_t i = 0; i < 7; ++i) { 4066 if (!HasCopyAndDispose && i >=4 && i <= 5) 4067 continue; 4068 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4069 SourceLocation(), 4070 &Idents.get(FieldNames[i]), 4071 FieldTypes[i], /*TInfo=*/0, 4072 /*BitWidth=*/0, /*Mutable=*/false, 4073 ICIS_NoInit); 4074 Field->setAccess(AS_public); 4075 T->addDecl(Field); 4076 } 4077 4078 T->completeDefinition(); 4079 4080 return getPointerType(getTagDeclType(T)); 4081} 4082 4083TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4084 if (!ObjCInstanceTypeDecl) 4085 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 4086 getTranslationUnitDecl(), 4087 SourceLocation(), 4088 SourceLocation(), 4089 &Idents.get("instancetype"), 4090 getTrivialTypeSourceInfo(getObjCIdType())); 4091 return ObjCInstanceTypeDecl; 4092} 4093 4094// This returns true if a type has been typedefed to BOOL: 4095// typedef <type> BOOL; 4096static bool isTypeTypedefedAsBOOL(QualType T) { 4097 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4098 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4099 return II->isStr("BOOL"); 4100 4101 return false; 4102} 4103 4104/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4105/// purpose. 4106CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4107 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4108 return CharUnits::Zero(); 4109 4110 CharUnits sz = getTypeSizeInChars(type); 4111 4112 // Make all integer and enum types at least as large as an int 4113 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4114 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4115 // Treat arrays as pointers, since that's how they're passed in. 4116 else if (type->isArrayType()) 4117 sz = getTypeSizeInChars(VoidPtrTy); 4118 return sz; 4119} 4120 4121static inline 4122std::string charUnitsToString(const CharUnits &CU) { 4123 return llvm::itostr(CU.getQuantity()); 4124} 4125 4126/// getObjCEncodingForBlock - Return the encoded type for this block 4127/// declaration. 4128std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4129 std::string S; 4130 4131 const BlockDecl *Decl = Expr->getBlockDecl(); 4132 QualType BlockTy = 4133 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4134 // Encode result type. 4135 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 4136 // Compute size of all parameters. 4137 // Start with computing size of a pointer in number of bytes. 4138 // FIXME: There might(should) be a better way of doing this computation! 4139 SourceLocation Loc; 4140 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4141 CharUnits ParmOffset = PtrSize; 4142 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4143 E = Decl->param_end(); PI != E; ++PI) { 4144 QualType PType = (*PI)->getType(); 4145 CharUnits sz = getObjCEncodingTypeSize(PType); 4146 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4147 ParmOffset += sz; 4148 } 4149 // Size of the argument frame 4150 S += charUnitsToString(ParmOffset); 4151 // Block pointer and offset. 4152 S += "@?0"; 4153 4154 // Argument types. 4155 ParmOffset = PtrSize; 4156 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4157 Decl->param_end(); PI != E; ++PI) { 4158 ParmVarDecl *PVDecl = *PI; 4159 QualType PType = PVDecl->getOriginalType(); 4160 if (const ArrayType *AT = 4161 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4162 // Use array's original type only if it has known number of 4163 // elements. 4164 if (!isa<ConstantArrayType>(AT)) 4165 PType = PVDecl->getType(); 4166 } else if (PType->isFunctionType()) 4167 PType = PVDecl->getType(); 4168 getObjCEncodingForType(PType, S); 4169 S += charUnitsToString(ParmOffset); 4170 ParmOffset += getObjCEncodingTypeSize(PType); 4171 } 4172 4173 return S; 4174} 4175 4176bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4177 std::string& S) { 4178 // Encode result type. 4179 getObjCEncodingForType(Decl->getResultType(), S); 4180 CharUnits ParmOffset; 4181 // Compute size of all parameters. 4182 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4183 E = Decl->param_end(); PI != E; ++PI) { 4184 QualType PType = (*PI)->getType(); 4185 CharUnits sz = getObjCEncodingTypeSize(PType); 4186 if (sz.isZero()) 4187 return true; 4188 4189 assert (sz.isPositive() && 4190 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4191 ParmOffset += sz; 4192 } 4193 S += charUnitsToString(ParmOffset); 4194 ParmOffset = CharUnits::Zero(); 4195 4196 // Argument types. 4197 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4198 E = Decl->param_end(); PI != E; ++PI) { 4199 ParmVarDecl *PVDecl = *PI; 4200 QualType PType = PVDecl->getOriginalType(); 4201 if (const ArrayType *AT = 4202 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4203 // Use array's original type only if it has known number of 4204 // elements. 4205 if (!isa<ConstantArrayType>(AT)) 4206 PType = PVDecl->getType(); 4207 } else if (PType->isFunctionType()) 4208 PType = PVDecl->getType(); 4209 getObjCEncodingForType(PType, S); 4210 S += charUnitsToString(ParmOffset); 4211 ParmOffset += getObjCEncodingTypeSize(PType); 4212 } 4213 4214 return false; 4215} 4216 4217/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4218/// method parameter or return type. If Extended, include class names and 4219/// block object types. 4220void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4221 QualType T, std::string& S, 4222 bool Extended) const { 4223 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4224 getObjCEncodingForTypeQualifier(QT, S); 4225 // Encode parameter type. 4226 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4227 true /*OutermostType*/, 4228 false /*EncodingProperty*/, 4229 false /*StructField*/, 4230 Extended /*EncodeBlockParameters*/, 4231 Extended /*EncodeClassNames*/); 4232} 4233 4234/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4235/// declaration. 4236bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4237 std::string& S, 4238 bool Extended) const { 4239 // FIXME: This is not very efficient. 4240 // Encode return type. 4241 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4242 Decl->getResultType(), S, Extended); 4243 // Compute size of all parameters. 4244 // Start with computing size of a pointer in number of bytes. 4245 // FIXME: There might(should) be a better way of doing this computation! 4246 SourceLocation Loc; 4247 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4248 // The first two arguments (self and _cmd) are pointers; account for 4249 // their size. 4250 CharUnits ParmOffset = 2 * PtrSize; 4251 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4252 E = Decl->sel_param_end(); PI != E; ++PI) { 4253 QualType PType = (*PI)->getType(); 4254 CharUnits sz = getObjCEncodingTypeSize(PType); 4255 if (sz.isZero()) 4256 return true; 4257 4258 assert (sz.isPositive() && 4259 "getObjCEncodingForMethodDecl - Incomplete param type"); 4260 ParmOffset += sz; 4261 } 4262 S += charUnitsToString(ParmOffset); 4263 S += "@0:"; 4264 S += charUnitsToString(PtrSize); 4265 4266 // Argument types. 4267 ParmOffset = 2 * PtrSize; 4268 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4269 E = Decl->sel_param_end(); PI != E; ++PI) { 4270 const ParmVarDecl *PVDecl = *PI; 4271 QualType PType = PVDecl->getOriginalType(); 4272 if (const ArrayType *AT = 4273 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4274 // Use array's original type only if it has known number of 4275 // elements. 4276 if (!isa<ConstantArrayType>(AT)) 4277 PType = PVDecl->getType(); 4278 } else if (PType->isFunctionType()) 4279 PType = PVDecl->getType(); 4280 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4281 PType, S, Extended); 4282 S += charUnitsToString(ParmOffset); 4283 ParmOffset += getObjCEncodingTypeSize(PType); 4284 } 4285 4286 return false; 4287} 4288 4289/// getObjCEncodingForPropertyDecl - Return the encoded type for this 4290/// property declaration. If non-NULL, Container must be either an 4291/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4292/// NULL when getting encodings for protocol properties. 4293/// Property attributes are stored as a comma-delimited C string. The simple 4294/// attributes readonly and bycopy are encoded as single characters. The 4295/// parametrized attributes, getter=name, setter=name, and ivar=name, are 4296/// encoded as single characters, followed by an identifier. Property types 4297/// are also encoded as a parametrized attribute. The characters used to encode 4298/// these attributes are defined by the following enumeration: 4299/// @code 4300/// enum PropertyAttributes { 4301/// kPropertyReadOnly = 'R', // property is read-only. 4302/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4303/// kPropertyByref = '&', // property is a reference to the value last assigned 4304/// kPropertyDynamic = 'D', // property is dynamic 4305/// kPropertyGetter = 'G', // followed by getter selector name 4306/// kPropertySetter = 'S', // followed by setter selector name 4307/// kPropertyInstanceVariable = 'V' // followed by instance variable name 4308/// kPropertyType = 'T' // followed by old-style type encoding. 4309/// kPropertyWeak = 'W' // 'weak' property 4310/// kPropertyStrong = 'P' // property GC'able 4311/// kPropertyNonAtomic = 'N' // property non-atomic 4312/// }; 4313/// @endcode 4314void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4315 const Decl *Container, 4316 std::string& S) const { 4317 // Collect information from the property implementation decl(s). 4318 bool Dynamic = false; 4319 ObjCPropertyImplDecl *SynthesizePID = 0; 4320 4321 // FIXME: Duplicated code due to poor abstraction. 4322 if (Container) { 4323 if (const ObjCCategoryImplDecl *CID = 4324 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4325 for (ObjCCategoryImplDecl::propimpl_iterator 4326 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4327 i != e; ++i) { 4328 ObjCPropertyImplDecl *PID = *i; 4329 if (PID->getPropertyDecl() == PD) { 4330 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4331 Dynamic = true; 4332 } else { 4333 SynthesizePID = PID; 4334 } 4335 } 4336 } 4337 } else { 4338 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4339 for (ObjCCategoryImplDecl::propimpl_iterator 4340 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4341 i != e; ++i) { 4342 ObjCPropertyImplDecl *PID = *i; 4343 if (PID->getPropertyDecl() == PD) { 4344 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4345 Dynamic = true; 4346 } else { 4347 SynthesizePID = PID; 4348 } 4349 } 4350 } 4351 } 4352 } 4353 4354 // FIXME: This is not very efficient. 4355 S = "T"; 4356 4357 // Encode result type. 4358 // GCC has some special rules regarding encoding of properties which 4359 // closely resembles encoding of ivars. 4360 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4361 true /* outermost type */, 4362 true /* encoding for property */); 4363 4364 if (PD->isReadOnly()) { 4365 S += ",R"; 4366 } else { 4367 switch (PD->getSetterKind()) { 4368 case ObjCPropertyDecl::Assign: break; 4369 case ObjCPropertyDecl::Copy: S += ",C"; break; 4370 case ObjCPropertyDecl::Retain: S += ",&"; break; 4371 case ObjCPropertyDecl::Weak: S += ",W"; break; 4372 } 4373 } 4374 4375 // It really isn't clear at all what this means, since properties 4376 // are "dynamic by default". 4377 if (Dynamic) 4378 S += ",D"; 4379 4380 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4381 S += ",N"; 4382 4383 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4384 S += ",G"; 4385 S += PD->getGetterName().getAsString(); 4386 } 4387 4388 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4389 S += ",S"; 4390 S += PD->getSetterName().getAsString(); 4391 } 4392 4393 if (SynthesizePID) { 4394 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4395 S += ",V"; 4396 S += OID->getNameAsString(); 4397 } 4398 4399 // FIXME: OBJCGC: weak & strong 4400} 4401 4402/// getLegacyIntegralTypeEncoding - 4403/// Another legacy compatibility encoding: 32-bit longs are encoded as 4404/// 'l' or 'L' , but not always. For typedefs, we need to use 4405/// 'i' or 'I' instead if encoding a struct field, or a pointer! 4406/// 4407void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 4408 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 4409 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 4410 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 4411 PointeeTy = UnsignedIntTy; 4412 else 4413 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 4414 PointeeTy = IntTy; 4415 } 4416 } 4417} 4418 4419void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 4420 const FieldDecl *Field) const { 4421 // We follow the behavior of gcc, expanding structures which are 4422 // directly pointed to, and expanding embedded structures. Note that 4423 // these rules are sufficient to prevent recursive encoding of the 4424 // same type. 4425 getObjCEncodingForTypeImpl(T, S, true, true, Field, 4426 true /* outermost type */); 4427} 4428 4429static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 4430 switch (T->getAs<BuiltinType>()->getKind()) { 4431 default: llvm_unreachable("Unhandled builtin type kind"); 4432 case BuiltinType::Void: return 'v'; 4433 case BuiltinType::Bool: return 'B'; 4434 case BuiltinType::Char_U: 4435 case BuiltinType::UChar: return 'C'; 4436 case BuiltinType::UShort: return 'S'; 4437 case BuiltinType::UInt: return 'I'; 4438 case BuiltinType::ULong: 4439 return C->getIntWidth(T) == 32 ? 'L' : 'Q'; 4440 case BuiltinType::UInt128: return 'T'; 4441 case BuiltinType::ULongLong: return 'Q'; 4442 case BuiltinType::Char_S: 4443 case BuiltinType::SChar: return 'c'; 4444 case BuiltinType::Short: return 's'; 4445 case BuiltinType::WChar_S: 4446 case BuiltinType::WChar_U: 4447 case BuiltinType::Int: return 'i'; 4448 case BuiltinType::Long: 4449 return C->getIntWidth(T) == 32 ? 'l' : 'q'; 4450 case BuiltinType::LongLong: return 'q'; 4451 case BuiltinType::Int128: return 't'; 4452 case BuiltinType::Float: return 'f'; 4453 case BuiltinType::Double: return 'd'; 4454 case BuiltinType::LongDouble: return 'D'; 4455 } 4456} 4457 4458static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 4459 EnumDecl *Enum = ET->getDecl(); 4460 4461 // The encoding of an non-fixed enum type is always 'i', regardless of size. 4462 if (!Enum->isFixed()) 4463 return 'i'; 4464 4465 // The encoding of a fixed enum type matches its fixed underlying type. 4466 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType()); 4467} 4468 4469static void EncodeBitField(const ASTContext *Ctx, std::string& S, 4470 QualType T, const FieldDecl *FD) { 4471 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 4472 S += 'b'; 4473 // The NeXT runtime encodes bit fields as b followed by the number of bits. 4474 // The GNU runtime requires more information; bitfields are encoded as b, 4475 // then the offset (in bits) of the first element, then the type of the 4476 // bitfield, then the size in bits. For example, in this structure: 4477 // 4478 // struct 4479 // { 4480 // int integer; 4481 // int flags:2; 4482 // }; 4483 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 4484 // runtime, but b32i2 for the GNU runtime. The reason for this extra 4485 // information is not especially sensible, but we're stuck with it for 4486 // compatibility with GCC, although providing it breaks anything that 4487 // actually uses runtime introspection and wants to work on both runtimes... 4488 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 4489 const RecordDecl *RD = FD->getParent(); 4490 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 4491 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 4492 if (const EnumType *ET = T->getAs<EnumType>()) 4493 S += ObjCEncodingForEnumType(Ctx, ET); 4494 else 4495 S += ObjCEncodingForPrimitiveKind(Ctx, T); 4496 } 4497 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 4498} 4499 4500// FIXME: Use SmallString for accumulating string. 4501void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 4502 bool ExpandPointedToStructures, 4503 bool ExpandStructures, 4504 const FieldDecl *FD, 4505 bool OutermostType, 4506 bool EncodingProperty, 4507 bool StructField, 4508 bool EncodeBlockParameters, 4509 bool EncodeClassNames) const { 4510 if (T->getAs<BuiltinType>()) { 4511 if (FD && FD->isBitField()) 4512 return EncodeBitField(this, S, T, FD); 4513 S += ObjCEncodingForPrimitiveKind(this, T); 4514 return; 4515 } 4516 4517 if (const ComplexType *CT = T->getAs<ComplexType>()) { 4518 S += 'j'; 4519 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 4520 false); 4521 return; 4522 } 4523 4524 // encoding for pointer or r3eference types. 4525 QualType PointeeTy; 4526 if (const PointerType *PT = T->getAs<PointerType>()) { 4527 if (PT->isObjCSelType()) { 4528 S += ':'; 4529 return; 4530 } 4531 PointeeTy = PT->getPointeeType(); 4532 } 4533 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4534 PointeeTy = RT->getPointeeType(); 4535 if (!PointeeTy.isNull()) { 4536 bool isReadOnly = false; 4537 // For historical/compatibility reasons, the read-only qualifier of the 4538 // pointee gets emitted _before_ the '^'. The read-only qualifier of 4539 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 4540 // Also, do not emit the 'r' for anything but the outermost type! 4541 if (isa<TypedefType>(T.getTypePtr())) { 4542 if (OutermostType && T.isConstQualified()) { 4543 isReadOnly = true; 4544 S += 'r'; 4545 } 4546 } else if (OutermostType) { 4547 QualType P = PointeeTy; 4548 while (P->getAs<PointerType>()) 4549 P = P->getAs<PointerType>()->getPointeeType(); 4550 if (P.isConstQualified()) { 4551 isReadOnly = true; 4552 S += 'r'; 4553 } 4554 } 4555 if (isReadOnly) { 4556 // Another legacy compatibility encoding. Some ObjC qualifier and type 4557 // combinations need to be rearranged. 4558 // Rewrite "in const" from "nr" to "rn" 4559 if (StringRef(S).endswith("nr")) 4560 S.replace(S.end()-2, S.end(), "rn"); 4561 } 4562 4563 if (PointeeTy->isCharType()) { 4564 // char pointer types should be encoded as '*' unless it is a 4565 // type that has been typedef'd to 'BOOL'. 4566 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 4567 S += '*'; 4568 return; 4569 } 4570 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 4571 // GCC binary compat: Need to convert "struct objc_class *" to "#". 4572 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 4573 S += '#'; 4574 return; 4575 } 4576 // GCC binary compat: Need to convert "struct objc_object *" to "@". 4577 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 4578 S += '@'; 4579 return; 4580 } 4581 // fall through... 4582 } 4583 S += '^'; 4584 getLegacyIntegralTypeEncoding(PointeeTy); 4585 4586 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 4587 NULL); 4588 return; 4589 } 4590 4591 if (const ArrayType *AT = 4592 // Ignore type qualifiers etc. 4593 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 4594 if (isa<IncompleteArrayType>(AT) && !StructField) { 4595 // Incomplete arrays are encoded as a pointer to the array element. 4596 S += '^'; 4597 4598 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4599 false, ExpandStructures, FD); 4600 } else { 4601 S += '['; 4602 4603 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4604 if (getTypeSize(CAT->getElementType()) == 0) 4605 S += '0'; 4606 else 4607 S += llvm::utostr(CAT->getSize().getZExtValue()); 4608 } else { 4609 //Variable length arrays are encoded as a regular array with 0 elements. 4610 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 4611 "Unknown array type!"); 4612 S += '0'; 4613 } 4614 4615 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4616 false, ExpandStructures, FD); 4617 S += ']'; 4618 } 4619 return; 4620 } 4621 4622 if (T->getAs<FunctionType>()) { 4623 S += '?'; 4624 return; 4625 } 4626 4627 if (const RecordType *RTy = T->getAs<RecordType>()) { 4628 RecordDecl *RDecl = RTy->getDecl(); 4629 S += RDecl->isUnion() ? '(' : '{'; 4630 // Anonymous structures print as '?' 4631 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 4632 S += II->getName(); 4633 if (ClassTemplateSpecializationDecl *Spec 4634 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 4635 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 4636 std::string TemplateArgsStr 4637 = TemplateSpecializationType::PrintTemplateArgumentList( 4638 TemplateArgs.data(), 4639 TemplateArgs.size(), 4640 (*this).getPrintingPolicy()); 4641 4642 S += TemplateArgsStr; 4643 } 4644 } else { 4645 S += '?'; 4646 } 4647 if (ExpandStructures) { 4648 S += '='; 4649 if (!RDecl->isUnion()) { 4650 getObjCEncodingForStructureImpl(RDecl, S, FD); 4651 } else { 4652 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4653 FieldEnd = RDecl->field_end(); 4654 Field != FieldEnd; ++Field) { 4655 if (FD) { 4656 S += '"'; 4657 S += Field->getNameAsString(); 4658 S += '"'; 4659 } 4660 4661 // Special case bit-fields. 4662 if (Field->isBitField()) { 4663 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 4664 *Field); 4665 } else { 4666 QualType qt = Field->getType(); 4667 getLegacyIntegralTypeEncoding(qt); 4668 getObjCEncodingForTypeImpl(qt, S, false, true, 4669 FD, /*OutermostType*/false, 4670 /*EncodingProperty*/false, 4671 /*StructField*/true); 4672 } 4673 } 4674 } 4675 } 4676 S += RDecl->isUnion() ? ')' : '}'; 4677 return; 4678 } 4679 4680 if (const EnumType *ET = T->getAs<EnumType>()) { 4681 if (FD && FD->isBitField()) 4682 EncodeBitField(this, S, T, FD); 4683 else 4684 S += ObjCEncodingForEnumType(this, ET); 4685 return; 4686 } 4687 4688 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 4689 S += "@?"; // Unlike a pointer-to-function, which is "^?". 4690 if (EncodeBlockParameters) { 4691 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>(); 4692 4693 S += '<'; 4694 // Block return type 4695 getObjCEncodingForTypeImpl(FT->getResultType(), S, 4696 ExpandPointedToStructures, ExpandStructures, 4697 FD, 4698 false /* OutermostType */, 4699 EncodingProperty, 4700 false /* StructField */, 4701 EncodeBlockParameters, 4702 EncodeClassNames); 4703 // Block self 4704 S += "@?"; 4705 // Block parameters 4706 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 4707 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 4708 E = FPT->arg_type_end(); I && (I != E); ++I) { 4709 getObjCEncodingForTypeImpl(*I, S, 4710 ExpandPointedToStructures, 4711 ExpandStructures, 4712 FD, 4713 false /* OutermostType */, 4714 EncodingProperty, 4715 false /* StructField */, 4716 EncodeBlockParameters, 4717 EncodeClassNames); 4718 } 4719 } 4720 S += '>'; 4721 } 4722 return; 4723 } 4724 4725 // Ignore protocol qualifiers when mangling at this level. 4726 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 4727 T = OT->getBaseType(); 4728 4729 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4730 // @encode(class_name) 4731 ObjCInterfaceDecl *OI = OIT->getDecl(); 4732 S += '{'; 4733 const IdentifierInfo *II = OI->getIdentifier(); 4734 S += II->getName(); 4735 S += '='; 4736 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4737 DeepCollectObjCIvars(OI, true, Ivars); 4738 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4739 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4740 if (Field->isBitField()) 4741 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4742 else 4743 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4744 } 4745 S += '}'; 4746 return; 4747 } 4748 4749 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4750 if (OPT->isObjCIdType()) { 4751 S += '@'; 4752 return; 4753 } 4754 4755 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4756 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4757 // Since this is a binary compatibility issue, need to consult with runtime 4758 // folks. Fortunately, this is a *very* obsure construct. 4759 S += '#'; 4760 return; 4761 } 4762 4763 if (OPT->isObjCQualifiedIdType()) { 4764 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4765 ExpandPointedToStructures, 4766 ExpandStructures, FD); 4767 if (FD || EncodingProperty || EncodeClassNames) { 4768 // Note that we do extended encoding of protocol qualifer list 4769 // Only when doing ivar or property encoding. 4770 S += '"'; 4771 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4772 E = OPT->qual_end(); I != E; ++I) { 4773 S += '<'; 4774 S += (*I)->getNameAsString(); 4775 S += '>'; 4776 } 4777 S += '"'; 4778 } 4779 return; 4780 } 4781 4782 QualType PointeeTy = OPT->getPointeeType(); 4783 if (!EncodingProperty && 4784 isa<TypedefType>(PointeeTy.getTypePtr())) { 4785 // Another historical/compatibility reason. 4786 // We encode the underlying type which comes out as 4787 // {...}; 4788 S += '^'; 4789 getObjCEncodingForTypeImpl(PointeeTy, S, 4790 false, ExpandPointedToStructures, 4791 NULL); 4792 return; 4793 } 4794 4795 S += '@'; 4796 if (OPT->getInterfaceDecl() && 4797 (FD || EncodingProperty || EncodeClassNames)) { 4798 S += '"'; 4799 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 4800 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4801 E = OPT->qual_end(); I != E; ++I) { 4802 S += '<'; 4803 S += (*I)->getNameAsString(); 4804 S += '>'; 4805 } 4806 S += '"'; 4807 } 4808 return; 4809 } 4810 4811 // gcc just blithely ignores member pointers. 4812 // TODO: maybe there should be a mangling for these 4813 if (T->getAs<MemberPointerType>()) 4814 return; 4815 4816 if (T->isVectorType()) { 4817 // This matches gcc's encoding, even though technically it is 4818 // insufficient. 4819 // FIXME. We should do a better job than gcc. 4820 return; 4821 } 4822 4823 llvm_unreachable("@encode for type not implemented!"); 4824} 4825 4826void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 4827 std::string &S, 4828 const FieldDecl *FD, 4829 bool includeVBases) const { 4830 assert(RDecl && "Expected non-null RecordDecl"); 4831 assert(!RDecl->isUnion() && "Should not be called for unions"); 4832 if (!RDecl->getDefinition()) 4833 return; 4834 4835 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 4836 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 4837 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 4838 4839 if (CXXRec) { 4840 for (CXXRecordDecl::base_class_iterator 4841 BI = CXXRec->bases_begin(), 4842 BE = CXXRec->bases_end(); BI != BE; ++BI) { 4843 if (!BI->isVirtual()) { 4844 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4845 if (base->isEmpty()) 4846 continue; 4847 uint64_t offs = layout.getBaseClassOffsetInBits(base); 4848 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4849 std::make_pair(offs, base)); 4850 } 4851 } 4852 } 4853 4854 unsigned i = 0; 4855 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4856 FieldEnd = RDecl->field_end(); 4857 Field != FieldEnd; ++Field, ++i) { 4858 uint64_t offs = layout.getFieldOffset(i); 4859 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4860 std::make_pair(offs, *Field)); 4861 } 4862 4863 if (CXXRec && includeVBases) { 4864 for (CXXRecordDecl::base_class_iterator 4865 BI = CXXRec->vbases_begin(), 4866 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 4867 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4868 if (base->isEmpty()) 4869 continue; 4870 uint64_t offs = layout.getVBaseClassOffsetInBits(base); 4871 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 4872 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 4873 std::make_pair(offs, base)); 4874 } 4875 } 4876 4877 CharUnits size; 4878 if (CXXRec) { 4879 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 4880 } else { 4881 size = layout.getSize(); 4882 } 4883 4884 uint64_t CurOffs = 0; 4885 std::multimap<uint64_t, NamedDecl *>::iterator 4886 CurLayObj = FieldOrBaseOffsets.begin(); 4887 4888 if (CXXRec && CXXRec->isDynamicClass() && 4889 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 4890 if (FD) { 4891 S += "\"_vptr$"; 4892 std::string recname = CXXRec->getNameAsString(); 4893 if (recname.empty()) recname = "?"; 4894 S += recname; 4895 S += '"'; 4896 } 4897 S += "^^?"; 4898 CurOffs += getTypeSize(VoidPtrTy); 4899 } 4900 4901 if (!RDecl->hasFlexibleArrayMember()) { 4902 // Mark the end of the structure. 4903 uint64_t offs = toBits(size); 4904 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4905 std::make_pair(offs, (NamedDecl*)0)); 4906 } 4907 4908 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 4909 assert(CurOffs <= CurLayObj->first); 4910 4911 if (CurOffs < CurLayObj->first) { 4912 uint64_t padding = CurLayObj->first - CurOffs; 4913 // FIXME: There doesn't seem to be a way to indicate in the encoding that 4914 // packing/alignment of members is different that normal, in which case 4915 // the encoding will be out-of-sync with the real layout. 4916 // If the runtime switches to just consider the size of types without 4917 // taking into account alignment, we could make padding explicit in the 4918 // encoding (e.g. using arrays of chars). The encoding strings would be 4919 // longer then though. 4920 CurOffs += padding; 4921 } 4922 4923 NamedDecl *dcl = CurLayObj->second; 4924 if (dcl == 0) 4925 break; // reached end of structure. 4926 4927 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 4928 // We expand the bases without their virtual bases since those are going 4929 // in the initial structure. Note that this differs from gcc which 4930 // expands virtual bases each time one is encountered in the hierarchy, 4931 // making the encoding type bigger than it really is. 4932 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false); 4933 assert(!base->isEmpty()); 4934 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 4935 } else { 4936 FieldDecl *field = cast<FieldDecl>(dcl); 4937 if (FD) { 4938 S += '"'; 4939 S += field->getNameAsString(); 4940 S += '"'; 4941 } 4942 4943 if (field->isBitField()) { 4944 EncodeBitField(this, S, field->getType(), field); 4945 CurOffs += field->getBitWidthValue(*this); 4946 } else { 4947 QualType qt = field->getType(); 4948 getLegacyIntegralTypeEncoding(qt); 4949 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 4950 /*OutermostType*/false, 4951 /*EncodingProperty*/false, 4952 /*StructField*/true); 4953 CurOffs += getTypeSize(field->getType()); 4954 } 4955 } 4956 } 4957} 4958 4959void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 4960 std::string& S) const { 4961 if (QT & Decl::OBJC_TQ_In) 4962 S += 'n'; 4963 if (QT & Decl::OBJC_TQ_Inout) 4964 S += 'N'; 4965 if (QT & Decl::OBJC_TQ_Out) 4966 S += 'o'; 4967 if (QT & Decl::OBJC_TQ_Bycopy) 4968 S += 'O'; 4969 if (QT & Decl::OBJC_TQ_Byref) 4970 S += 'R'; 4971 if (QT & Decl::OBJC_TQ_Oneway) 4972 S += 'V'; 4973} 4974 4975TypedefDecl *ASTContext::getObjCIdDecl() const { 4976 if (!ObjCIdDecl) { 4977 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0); 4978 T = getObjCObjectPointerType(T); 4979 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T); 4980 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4981 getTranslationUnitDecl(), 4982 SourceLocation(), SourceLocation(), 4983 &Idents.get("id"), IdInfo); 4984 } 4985 4986 return ObjCIdDecl; 4987} 4988 4989TypedefDecl *ASTContext::getObjCSelDecl() const { 4990 if (!ObjCSelDecl) { 4991 QualType SelT = getPointerType(ObjCBuiltinSelTy); 4992 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT); 4993 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4994 getTranslationUnitDecl(), 4995 SourceLocation(), SourceLocation(), 4996 &Idents.get("SEL"), SelInfo); 4997 } 4998 return ObjCSelDecl; 4999} 5000 5001TypedefDecl *ASTContext::getObjCClassDecl() const { 5002 if (!ObjCClassDecl) { 5003 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0); 5004 T = getObjCObjectPointerType(T); 5005 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T); 5006 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5007 getTranslationUnitDecl(), 5008 SourceLocation(), SourceLocation(), 5009 &Idents.get("Class"), ClassInfo); 5010 } 5011 5012 return ObjCClassDecl; 5013} 5014 5015ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5016 if (!ObjCProtocolClassDecl) { 5017 ObjCProtocolClassDecl 5018 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5019 SourceLocation(), 5020 &Idents.get("Protocol"), 5021 /*PrevDecl=*/0, 5022 SourceLocation(), true); 5023 } 5024 5025 return ObjCProtocolClassDecl; 5026} 5027 5028//===----------------------------------------------------------------------===// 5029// __builtin_va_list Construction Functions 5030//===----------------------------------------------------------------------===// 5031 5032static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5033 // typedef char* __builtin_va_list; 5034 QualType CharPtrType = Context->getPointerType(Context->CharTy); 5035 TypeSourceInfo *TInfo 5036 = Context->getTrivialTypeSourceInfo(CharPtrType); 5037 5038 TypedefDecl *VaListTypeDecl 5039 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5040 Context->getTranslationUnitDecl(), 5041 SourceLocation(), SourceLocation(), 5042 &Context->Idents.get("__builtin_va_list"), 5043 TInfo); 5044 return VaListTypeDecl; 5045} 5046 5047static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5048 // typedef void* __builtin_va_list; 5049 QualType VoidPtrType = Context->getPointerType(Context->VoidTy); 5050 TypeSourceInfo *TInfo 5051 = Context->getTrivialTypeSourceInfo(VoidPtrType); 5052 5053 TypedefDecl *VaListTypeDecl 5054 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5055 Context->getTranslationUnitDecl(), 5056 SourceLocation(), SourceLocation(), 5057 &Context->Idents.get("__builtin_va_list"), 5058 TInfo); 5059 return VaListTypeDecl; 5060} 5061 5062static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5063 // typedef struct __va_list_tag { 5064 RecordDecl *VaListTagDecl; 5065 5066 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5067 Context->getTranslationUnitDecl(), 5068 &Context->Idents.get("__va_list_tag")); 5069 VaListTagDecl->startDefinition(); 5070 5071 const size_t NumFields = 5; 5072 QualType FieldTypes[NumFields]; 5073 const char *FieldNames[NumFields]; 5074 5075 // unsigned char gpr; 5076 FieldTypes[0] = Context->UnsignedCharTy; 5077 FieldNames[0] = "gpr"; 5078 5079 // unsigned char fpr; 5080 FieldTypes[1] = Context->UnsignedCharTy; 5081 FieldNames[1] = "fpr"; 5082 5083 // unsigned short reserved; 5084 FieldTypes[2] = Context->UnsignedShortTy; 5085 FieldNames[2] = "reserved"; 5086 5087 // void* overflow_arg_area; 5088 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5089 FieldNames[3] = "overflow_arg_area"; 5090 5091 // void* reg_save_area; 5092 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5093 FieldNames[4] = "reg_save_area"; 5094 5095 // Create fields 5096 for (unsigned i = 0; i < NumFields; ++i) { 5097 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5098 SourceLocation(), 5099 SourceLocation(), 5100 &Context->Idents.get(FieldNames[i]), 5101 FieldTypes[i], /*TInfo=*/0, 5102 /*BitWidth=*/0, 5103 /*Mutable=*/false, 5104 ICIS_NoInit); 5105 Field->setAccess(AS_public); 5106 VaListTagDecl->addDecl(Field); 5107 } 5108 VaListTagDecl->completeDefinition(); 5109 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5110 5111 // } __va_list_tag; 5112 TypedefDecl *VaListTagTypedefDecl 5113 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5114 Context->getTranslationUnitDecl(), 5115 SourceLocation(), SourceLocation(), 5116 &Context->Idents.get("__va_list_tag"), 5117 Context->getTrivialTypeSourceInfo(VaListTagType)); 5118 QualType VaListTagTypedefType = 5119 Context->getTypedefType(VaListTagTypedefDecl); 5120 5121 // typedef __va_list_tag __builtin_va_list[1]; 5122 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5123 QualType VaListTagArrayType 5124 = Context->getConstantArrayType(VaListTagTypedefType, 5125 Size, ArrayType::Normal, 0); 5126 TypeSourceInfo *TInfo 5127 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5128 TypedefDecl *VaListTypedefDecl 5129 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5130 Context->getTranslationUnitDecl(), 5131 SourceLocation(), SourceLocation(), 5132 &Context->Idents.get("__builtin_va_list"), 5133 TInfo); 5134 5135 return VaListTypedefDecl; 5136} 5137 5138static TypedefDecl * 5139CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 5140 // typedef struct __va_list_tag { 5141 RecordDecl *VaListTagDecl; 5142 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5143 Context->getTranslationUnitDecl(), 5144 &Context->Idents.get("__va_list_tag")); 5145 VaListTagDecl->startDefinition(); 5146 5147 const size_t NumFields = 4; 5148 QualType FieldTypes[NumFields]; 5149 const char *FieldNames[NumFields]; 5150 5151 // unsigned gp_offset; 5152 FieldTypes[0] = Context->UnsignedIntTy; 5153 FieldNames[0] = "gp_offset"; 5154 5155 // unsigned fp_offset; 5156 FieldTypes[1] = Context->UnsignedIntTy; 5157 FieldNames[1] = "fp_offset"; 5158 5159 // void* overflow_arg_area; 5160 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5161 FieldNames[2] = "overflow_arg_area"; 5162 5163 // void* reg_save_area; 5164 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5165 FieldNames[3] = "reg_save_area"; 5166 5167 // Create fields 5168 for (unsigned i = 0; i < NumFields; ++i) { 5169 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5170 VaListTagDecl, 5171 SourceLocation(), 5172 SourceLocation(), 5173 &Context->Idents.get(FieldNames[i]), 5174 FieldTypes[i], /*TInfo=*/0, 5175 /*BitWidth=*/0, 5176 /*Mutable=*/false, 5177 ICIS_NoInit); 5178 Field->setAccess(AS_public); 5179 VaListTagDecl->addDecl(Field); 5180 } 5181 VaListTagDecl->completeDefinition(); 5182 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5183 5184 // } __va_list_tag; 5185 TypedefDecl *VaListTagTypedefDecl 5186 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5187 Context->getTranslationUnitDecl(), 5188 SourceLocation(), SourceLocation(), 5189 &Context->Idents.get("__va_list_tag"), 5190 Context->getTrivialTypeSourceInfo(VaListTagType)); 5191 QualType VaListTagTypedefType = 5192 Context->getTypedefType(VaListTagTypedefDecl); 5193 5194 // typedef __va_list_tag __builtin_va_list[1]; 5195 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5196 QualType VaListTagArrayType 5197 = Context->getConstantArrayType(VaListTagTypedefType, 5198 Size, ArrayType::Normal,0); 5199 TypeSourceInfo *TInfo 5200 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5201 TypedefDecl *VaListTypedefDecl 5202 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5203 Context->getTranslationUnitDecl(), 5204 SourceLocation(), SourceLocation(), 5205 &Context->Idents.get("__builtin_va_list"), 5206 TInfo); 5207 5208 return VaListTypedefDecl; 5209} 5210 5211static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 5212 // typedef int __builtin_va_list[4]; 5213 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 5214 QualType IntArrayType 5215 = Context->getConstantArrayType(Context->IntTy, 5216 Size, ArrayType::Normal, 0); 5217 TypedefDecl *VaListTypedefDecl 5218 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5219 Context->getTranslationUnitDecl(), 5220 SourceLocation(), SourceLocation(), 5221 &Context->Idents.get("__builtin_va_list"), 5222 Context->getTrivialTypeSourceInfo(IntArrayType)); 5223 5224 return VaListTypedefDecl; 5225} 5226 5227static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 5228 TargetInfo::BuiltinVaListKind Kind) { 5229 switch (Kind) { 5230 case TargetInfo::CharPtrBuiltinVaList: 5231 return CreateCharPtrBuiltinVaListDecl(Context); 5232 case TargetInfo::VoidPtrBuiltinVaList: 5233 return CreateVoidPtrBuiltinVaListDecl(Context); 5234 case TargetInfo::PowerABIBuiltinVaList: 5235 return CreatePowerABIBuiltinVaListDecl(Context); 5236 case TargetInfo::X86_64ABIBuiltinVaList: 5237 return CreateX86_64ABIBuiltinVaListDecl(Context); 5238 case TargetInfo::PNaClABIBuiltinVaList: 5239 return CreatePNaClABIBuiltinVaListDecl(Context); 5240 } 5241 5242 llvm_unreachable("Unhandled __builtin_va_list type kind"); 5243} 5244 5245TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 5246 if (!BuiltinVaListDecl) 5247 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 5248 5249 return BuiltinVaListDecl; 5250} 5251 5252void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 5253 assert(ObjCConstantStringType.isNull() && 5254 "'NSConstantString' type already set!"); 5255 5256 ObjCConstantStringType = getObjCInterfaceType(Decl); 5257} 5258 5259/// \brief Retrieve the template name that corresponds to a non-empty 5260/// lookup. 5261TemplateName 5262ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 5263 UnresolvedSetIterator End) const { 5264 unsigned size = End - Begin; 5265 assert(size > 1 && "set is not overloaded!"); 5266 5267 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 5268 size * sizeof(FunctionTemplateDecl*)); 5269 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 5270 5271 NamedDecl **Storage = OT->getStorage(); 5272 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 5273 NamedDecl *D = *I; 5274 assert(isa<FunctionTemplateDecl>(D) || 5275 (isa<UsingShadowDecl>(D) && 5276 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 5277 *Storage++ = D; 5278 } 5279 5280 return TemplateName(OT); 5281} 5282 5283/// \brief Retrieve the template name that represents a qualified 5284/// template name such as \c std::vector. 5285TemplateName 5286ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 5287 bool TemplateKeyword, 5288 TemplateDecl *Template) const { 5289 assert(NNS && "Missing nested-name-specifier in qualified template name"); 5290 5291 // FIXME: Canonicalization? 5292 llvm::FoldingSetNodeID ID; 5293 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 5294 5295 void *InsertPos = 0; 5296 QualifiedTemplateName *QTN = 5297 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5298 if (!QTN) { 5299 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 5300 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 5301 } 5302 5303 return TemplateName(QTN); 5304} 5305 5306/// \brief Retrieve the template name that represents a dependent 5307/// template name such as \c MetaFun::template apply. 5308TemplateName 5309ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5310 const IdentifierInfo *Name) const { 5311 assert((!NNS || NNS->isDependent()) && 5312 "Nested name specifier must be dependent"); 5313 5314 llvm::FoldingSetNodeID ID; 5315 DependentTemplateName::Profile(ID, NNS, Name); 5316 5317 void *InsertPos = 0; 5318 DependentTemplateName *QTN = 5319 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5320 5321 if (QTN) 5322 return TemplateName(QTN); 5323 5324 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5325 if (CanonNNS == NNS) { 5326 QTN = new (*this,4) DependentTemplateName(NNS, Name); 5327 } else { 5328 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 5329 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 5330 DependentTemplateName *CheckQTN = 5331 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5332 assert(!CheckQTN && "Dependent type name canonicalization broken"); 5333 (void)CheckQTN; 5334 } 5335 5336 DependentTemplateNames.InsertNode(QTN, InsertPos); 5337 return TemplateName(QTN); 5338} 5339 5340/// \brief Retrieve the template name that represents a dependent 5341/// template name such as \c MetaFun::template operator+. 5342TemplateName 5343ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5344 OverloadedOperatorKind Operator) const { 5345 assert((!NNS || NNS->isDependent()) && 5346 "Nested name specifier must be dependent"); 5347 5348 llvm::FoldingSetNodeID ID; 5349 DependentTemplateName::Profile(ID, NNS, Operator); 5350 5351 void *InsertPos = 0; 5352 DependentTemplateName *QTN 5353 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5354 5355 if (QTN) 5356 return TemplateName(QTN); 5357 5358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5359 if (CanonNNS == NNS) { 5360 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 5361 } else { 5362 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 5363 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 5364 5365 DependentTemplateName *CheckQTN 5366 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5367 assert(!CheckQTN && "Dependent template name canonicalization broken"); 5368 (void)CheckQTN; 5369 } 5370 5371 DependentTemplateNames.InsertNode(QTN, InsertPos); 5372 return TemplateName(QTN); 5373} 5374 5375TemplateName 5376ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 5377 TemplateName replacement) const { 5378 llvm::FoldingSetNodeID ID; 5379 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 5380 5381 void *insertPos = 0; 5382 SubstTemplateTemplateParmStorage *subst 5383 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 5384 5385 if (!subst) { 5386 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 5387 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 5388 } 5389 5390 return TemplateName(subst); 5391} 5392 5393TemplateName 5394ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 5395 const TemplateArgument &ArgPack) const { 5396 ASTContext &Self = const_cast<ASTContext &>(*this); 5397 llvm::FoldingSetNodeID ID; 5398 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 5399 5400 void *InsertPos = 0; 5401 SubstTemplateTemplateParmPackStorage *Subst 5402 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 5403 5404 if (!Subst) { 5405 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 5406 ArgPack.pack_size(), 5407 ArgPack.pack_begin()); 5408 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 5409 } 5410 5411 return TemplateName(Subst); 5412} 5413 5414/// getFromTargetType - Given one of the integer types provided by 5415/// TargetInfo, produce the corresponding type. The unsigned @p Type 5416/// is actually a value of type @c TargetInfo::IntType. 5417CanQualType ASTContext::getFromTargetType(unsigned Type) const { 5418 switch (Type) { 5419 case TargetInfo::NoInt: return CanQualType(); 5420 case TargetInfo::SignedShort: return ShortTy; 5421 case TargetInfo::UnsignedShort: return UnsignedShortTy; 5422 case TargetInfo::SignedInt: return IntTy; 5423 case TargetInfo::UnsignedInt: return UnsignedIntTy; 5424 case TargetInfo::SignedLong: return LongTy; 5425 case TargetInfo::UnsignedLong: return UnsignedLongTy; 5426 case TargetInfo::SignedLongLong: return LongLongTy; 5427 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 5428 } 5429 5430 llvm_unreachable("Unhandled TargetInfo::IntType value"); 5431} 5432 5433//===----------------------------------------------------------------------===// 5434// Type Predicates. 5435//===----------------------------------------------------------------------===// 5436 5437/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 5438/// garbage collection attribute. 5439/// 5440Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 5441 if (getLangOpts().getGC() == LangOptions::NonGC) 5442 return Qualifiers::GCNone; 5443 5444 assert(getLangOpts().ObjC1); 5445 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 5446 5447 // Default behaviour under objective-C's gc is for ObjC pointers 5448 // (or pointers to them) be treated as though they were declared 5449 // as __strong. 5450 if (GCAttrs == Qualifiers::GCNone) { 5451 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 5452 return Qualifiers::Strong; 5453 else if (Ty->isPointerType()) 5454 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 5455 } else { 5456 // It's not valid to set GC attributes on anything that isn't a 5457 // pointer. 5458#ifndef NDEBUG 5459 QualType CT = Ty->getCanonicalTypeInternal(); 5460 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 5461 CT = AT->getElementType(); 5462 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 5463#endif 5464 } 5465 return GCAttrs; 5466} 5467 5468//===----------------------------------------------------------------------===// 5469// Type Compatibility Testing 5470//===----------------------------------------------------------------------===// 5471 5472/// areCompatVectorTypes - Return true if the two specified vector types are 5473/// compatible. 5474static bool areCompatVectorTypes(const VectorType *LHS, 5475 const VectorType *RHS) { 5476 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 5477 return LHS->getElementType() == RHS->getElementType() && 5478 LHS->getNumElements() == RHS->getNumElements(); 5479} 5480 5481bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 5482 QualType SecondVec) { 5483 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 5484 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 5485 5486 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 5487 return true; 5488 5489 // Treat Neon vector types and most AltiVec vector types as if they are the 5490 // equivalent GCC vector types. 5491 const VectorType *First = FirstVec->getAs<VectorType>(); 5492 const VectorType *Second = SecondVec->getAs<VectorType>(); 5493 if (First->getNumElements() == Second->getNumElements() && 5494 hasSameType(First->getElementType(), Second->getElementType()) && 5495 First->getVectorKind() != VectorType::AltiVecPixel && 5496 First->getVectorKind() != VectorType::AltiVecBool && 5497 Second->getVectorKind() != VectorType::AltiVecPixel && 5498 Second->getVectorKind() != VectorType::AltiVecBool) 5499 return true; 5500 5501 return false; 5502} 5503 5504//===----------------------------------------------------------------------===// 5505// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 5506//===----------------------------------------------------------------------===// 5507 5508/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 5509/// inheritance hierarchy of 'rProto'. 5510bool 5511ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 5512 ObjCProtocolDecl *rProto) const { 5513 if (declaresSameEntity(lProto, rProto)) 5514 return true; 5515 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 5516 E = rProto->protocol_end(); PI != E; ++PI) 5517 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 5518 return true; 5519 return false; 5520} 5521 5522/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 5523/// return true if lhs's protocols conform to rhs's protocol; false 5524/// otherwise. 5525bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 5526 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 5527 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 5528 return false; 5529} 5530 5531/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 5532/// Class<p1, ...>. 5533bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 5534 QualType rhs) { 5535 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 5536 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5537 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 5538 5539 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5540 E = lhsQID->qual_end(); I != E; ++I) { 5541 bool match = false; 5542 ObjCProtocolDecl *lhsProto = *I; 5543 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5544 E = rhsOPT->qual_end(); J != E; ++J) { 5545 ObjCProtocolDecl *rhsProto = *J; 5546 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 5547 match = true; 5548 break; 5549 } 5550 } 5551 if (!match) 5552 return false; 5553 } 5554 return true; 5555} 5556 5557/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 5558/// ObjCQualifiedIDType. 5559bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 5560 bool compare) { 5561 // Allow id<P..> and an 'id' or void* type in all cases. 5562 if (lhs->isVoidPointerType() || 5563 lhs->isObjCIdType() || lhs->isObjCClassType()) 5564 return true; 5565 else if (rhs->isVoidPointerType() || 5566 rhs->isObjCIdType() || rhs->isObjCClassType()) 5567 return true; 5568 5569 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 5570 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5571 5572 if (!rhsOPT) return false; 5573 5574 if (rhsOPT->qual_empty()) { 5575 // If the RHS is a unqualified interface pointer "NSString*", 5576 // make sure we check the class hierarchy. 5577 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5578 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5579 E = lhsQID->qual_end(); I != E; ++I) { 5580 // when comparing an id<P> on lhs with a static type on rhs, 5581 // see if static class implements all of id's protocols, directly or 5582 // through its super class and categories. 5583 if (!rhsID->ClassImplementsProtocol(*I, true)) 5584 return false; 5585 } 5586 } 5587 // If there are no qualifiers and no interface, we have an 'id'. 5588 return true; 5589 } 5590 // Both the right and left sides have qualifiers. 5591 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5592 E = lhsQID->qual_end(); I != E; ++I) { 5593 ObjCProtocolDecl *lhsProto = *I; 5594 bool match = false; 5595 5596 // when comparing an id<P> on lhs with a static type on rhs, 5597 // see if static class implements all of id's protocols, directly or 5598 // through its super class and categories. 5599 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5600 E = rhsOPT->qual_end(); J != E; ++J) { 5601 ObjCProtocolDecl *rhsProto = *J; 5602 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5603 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5604 match = true; 5605 break; 5606 } 5607 } 5608 // If the RHS is a qualified interface pointer "NSString<P>*", 5609 // make sure we check the class hierarchy. 5610 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5611 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5612 E = lhsQID->qual_end(); I != E; ++I) { 5613 // when comparing an id<P> on lhs with a static type on rhs, 5614 // see if static class implements all of id's protocols, directly or 5615 // through its super class and categories. 5616 if (rhsID->ClassImplementsProtocol(*I, true)) { 5617 match = true; 5618 break; 5619 } 5620 } 5621 } 5622 if (!match) 5623 return false; 5624 } 5625 5626 return true; 5627 } 5628 5629 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 5630 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 5631 5632 if (const ObjCObjectPointerType *lhsOPT = 5633 lhs->getAsObjCInterfacePointerType()) { 5634 // If both the right and left sides have qualifiers. 5635 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 5636 E = lhsOPT->qual_end(); I != E; ++I) { 5637 ObjCProtocolDecl *lhsProto = *I; 5638 bool match = false; 5639 5640 // when comparing an id<P> on rhs with a static type on lhs, 5641 // see if static class implements all of id's protocols, directly or 5642 // through its super class and categories. 5643 // First, lhs protocols in the qualifier list must be found, direct 5644 // or indirect in rhs's qualifier list or it is a mismatch. 5645 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5646 E = rhsQID->qual_end(); J != E; ++J) { 5647 ObjCProtocolDecl *rhsProto = *J; 5648 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5649 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5650 match = true; 5651 break; 5652 } 5653 } 5654 if (!match) 5655 return false; 5656 } 5657 5658 // Static class's protocols, or its super class or category protocols 5659 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 5660 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 5661 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5662 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 5663 // This is rather dubious but matches gcc's behavior. If lhs has 5664 // no type qualifier and its class has no static protocol(s) 5665 // assume that it is mismatch. 5666 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 5667 return false; 5668 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5669 LHSInheritedProtocols.begin(), 5670 E = LHSInheritedProtocols.end(); I != E; ++I) { 5671 bool match = false; 5672 ObjCProtocolDecl *lhsProto = (*I); 5673 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5674 E = rhsQID->qual_end(); J != E; ++J) { 5675 ObjCProtocolDecl *rhsProto = *J; 5676 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5677 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5678 match = true; 5679 break; 5680 } 5681 } 5682 if (!match) 5683 return false; 5684 } 5685 } 5686 return true; 5687 } 5688 return false; 5689} 5690 5691/// canAssignObjCInterfaces - Return true if the two interface types are 5692/// compatible for assignment from RHS to LHS. This handles validation of any 5693/// protocol qualifiers on the LHS or RHS. 5694/// 5695bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 5696 const ObjCObjectPointerType *RHSOPT) { 5697 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5698 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5699 5700 // If either type represents the built-in 'id' or 'Class' types, return true. 5701 if (LHS->isObjCUnqualifiedIdOrClass() || 5702 RHS->isObjCUnqualifiedIdOrClass()) 5703 return true; 5704 5705 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 5706 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5707 QualType(RHSOPT,0), 5708 false); 5709 5710 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 5711 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 5712 QualType(RHSOPT,0)); 5713 5714 // If we have 2 user-defined types, fall into that path. 5715 if (LHS->getInterface() && RHS->getInterface()) 5716 return canAssignObjCInterfaces(LHS, RHS); 5717 5718 return false; 5719} 5720 5721/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 5722/// for providing type-safety for objective-c pointers used to pass/return 5723/// arguments in block literals. When passed as arguments, passing 'A*' where 5724/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 5725/// not OK. For the return type, the opposite is not OK. 5726bool ASTContext::canAssignObjCInterfacesInBlockPointer( 5727 const ObjCObjectPointerType *LHSOPT, 5728 const ObjCObjectPointerType *RHSOPT, 5729 bool BlockReturnType) { 5730 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 5731 return true; 5732 5733 if (LHSOPT->isObjCBuiltinType()) { 5734 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 5735 } 5736 5737 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 5738 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5739 QualType(RHSOPT,0), 5740 false); 5741 5742 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 5743 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 5744 if (LHS && RHS) { // We have 2 user-defined types. 5745 if (LHS != RHS) { 5746 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 5747 return BlockReturnType; 5748 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 5749 return !BlockReturnType; 5750 } 5751 else 5752 return true; 5753 } 5754 return false; 5755} 5756 5757/// getIntersectionOfProtocols - This routine finds the intersection of set 5758/// of protocols inherited from two distinct objective-c pointer objects. 5759/// It is used to build composite qualifier list of the composite type of 5760/// the conditional expression involving two objective-c pointer objects. 5761static 5762void getIntersectionOfProtocols(ASTContext &Context, 5763 const ObjCObjectPointerType *LHSOPT, 5764 const ObjCObjectPointerType *RHSOPT, 5765 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 5766 5767 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5768 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5769 assert(LHS->getInterface() && "LHS must have an interface base"); 5770 assert(RHS->getInterface() && "RHS must have an interface base"); 5771 5772 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 5773 unsigned LHSNumProtocols = LHS->getNumProtocols(); 5774 if (LHSNumProtocols > 0) 5775 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 5776 else { 5777 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5778 Context.CollectInheritedProtocols(LHS->getInterface(), 5779 LHSInheritedProtocols); 5780 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 5781 LHSInheritedProtocols.end()); 5782 } 5783 5784 unsigned RHSNumProtocols = RHS->getNumProtocols(); 5785 if (RHSNumProtocols > 0) { 5786 ObjCProtocolDecl **RHSProtocols = 5787 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 5788 for (unsigned i = 0; i < RHSNumProtocols; ++i) 5789 if (InheritedProtocolSet.count(RHSProtocols[i])) 5790 IntersectionOfProtocols.push_back(RHSProtocols[i]); 5791 } else { 5792 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 5793 Context.CollectInheritedProtocols(RHS->getInterface(), 5794 RHSInheritedProtocols); 5795 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5796 RHSInheritedProtocols.begin(), 5797 E = RHSInheritedProtocols.end(); I != E; ++I) 5798 if (InheritedProtocolSet.count((*I))) 5799 IntersectionOfProtocols.push_back((*I)); 5800 } 5801} 5802 5803/// areCommonBaseCompatible - Returns common base class of the two classes if 5804/// one found. Note that this is O'2 algorithm. But it will be called as the 5805/// last type comparison in a ?-exp of ObjC pointer types before a 5806/// warning is issued. So, its invokation is extremely rare. 5807QualType ASTContext::areCommonBaseCompatible( 5808 const ObjCObjectPointerType *Lptr, 5809 const ObjCObjectPointerType *Rptr) { 5810 const ObjCObjectType *LHS = Lptr->getObjectType(); 5811 const ObjCObjectType *RHS = Rptr->getObjectType(); 5812 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 5813 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 5814 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 5815 return QualType(); 5816 5817 do { 5818 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 5819 if (canAssignObjCInterfaces(LHS, RHS)) { 5820 SmallVector<ObjCProtocolDecl *, 8> Protocols; 5821 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 5822 5823 QualType Result = QualType(LHS, 0); 5824 if (!Protocols.empty()) 5825 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 5826 Result = getObjCObjectPointerType(Result); 5827 return Result; 5828 } 5829 } while ((LDecl = LDecl->getSuperClass())); 5830 5831 return QualType(); 5832} 5833 5834bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 5835 const ObjCObjectType *RHS) { 5836 assert(LHS->getInterface() && "LHS is not an interface type"); 5837 assert(RHS->getInterface() && "RHS is not an interface type"); 5838 5839 // Verify that the base decls are compatible: the RHS must be a subclass of 5840 // the LHS. 5841 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 5842 return false; 5843 5844 // RHS must have a superset of the protocols in the LHS. If the LHS is not 5845 // protocol qualified at all, then we are good. 5846 if (LHS->getNumProtocols() == 0) 5847 return true; 5848 5849 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 5850 // more detailed analysis is required. 5851 if (RHS->getNumProtocols() == 0) { 5852 // OK, if LHS is a superclass of RHS *and* 5853 // this superclass is assignment compatible with LHS. 5854 // false otherwise. 5855 bool IsSuperClass = 5856 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 5857 if (IsSuperClass) { 5858 // OK if conversion of LHS to SuperClass results in narrowing of types 5859 // ; i.e., SuperClass may implement at least one of the protocols 5860 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 5861 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 5862 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 5863 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 5864 // If super class has no protocols, it is not a match. 5865 if (SuperClassInheritedProtocols.empty()) 5866 return false; 5867 5868 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5869 LHSPE = LHS->qual_end(); 5870 LHSPI != LHSPE; LHSPI++) { 5871 bool SuperImplementsProtocol = false; 5872 ObjCProtocolDecl *LHSProto = (*LHSPI); 5873 5874 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5875 SuperClassInheritedProtocols.begin(), 5876 E = SuperClassInheritedProtocols.end(); I != E; ++I) { 5877 ObjCProtocolDecl *SuperClassProto = (*I); 5878 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 5879 SuperImplementsProtocol = true; 5880 break; 5881 } 5882 } 5883 if (!SuperImplementsProtocol) 5884 return false; 5885 } 5886 return true; 5887 } 5888 return false; 5889 } 5890 5891 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5892 LHSPE = LHS->qual_end(); 5893 LHSPI != LHSPE; LHSPI++) { 5894 bool RHSImplementsProtocol = false; 5895 5896 // If the RHS doesn't implement the protocol on the left, the types 5897 // are incompatible. 5898 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 5899 RHSPE = RHS->qual_end(); 5900 RHSPI != RHSPE; RHSPI++) { 5901 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 5902 RHSImplementsProtocol = true; 5903 break; 5904 } 5905 } 5906 // FIXME: For better diagnostics, consider passing back the protocol name. 5907 if (!RHSImplementsProtocol) 5908 return false; 5909 } 5910 // The RHS implements all protocols listed on the LHS. 5911 return true; 5912} 5913 5914bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 5915 // get the "pointed to" types 5916 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 5917 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 5918 5919 if (!LHSOPT || !RHSOPT) 5920 return false; 5921 5922 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 5923 canAssignObjCInterfaces(RHSOPT, LHSOPT); 5924} 5925 5926bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 5927 return canAssignObjCInterfaces( 5928 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 5929 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 5930} 5931 5932/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 5933/// both shall have the identically qualified version of a compatible type. 5934/// C99 6.2.7p1: Two types have compatible types if their types are the 5935/// same. See 6.7.[2,3,5] for additional rules. 5936bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 5937 bool CompareUnqualified) { 5938 if (getLangOpts().CPlusPlus) 5939 return hasSameType(LHS, RHS); 5940 5941 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 5942} 5943 5944bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 5945 return typesAreCompatible(LHS, RHS); 5946} 5947 5948bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 5949 return !mergeTypes(LHS, RHS, true).isNull(); 5950} 5951 5952/// mergeTransparentUnionType - if T is a transparent union type and a member 5953/// of T is compatible with SubType, return the merged type, else return 5954/// QualType() 5955QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 5956 bool OfBlockPointer, 5957 bool Unqualified) { 5958 if (const RecordType *UT = T->getAsUnionType()) { 5959 RecordDecl *UD = UT->getDecl(); 5960 if (UD->hasAttr<TransparentUnionAttr>()) { 5961 for (RecordDecl::field_iterator it = UD->field_begin(), 5962 itend = UD->field_end(); it != itend; ++it) { 5963 QualType ET = it->getType().getUnqualifiedType(); 5964 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 5965 if (!MT.isNull()) 5966 return MT; 5967 } 5968 } 5969 } 5970 5971 return QualType(); 5972} 5973 5974/// mergeFunctionArgumentTypes - merge two types which appear as function 5975/// argument types 5976QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 5977 bool OfBlockPointer, 5978 bool Unqualified) { 5979 // GNU extension: two types are compatible if they appear as a function 5980 // argument, one of the types is a transparent union type and the other 5981 // type is compatible with a union member 5982 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 5983 Unqualified); 5984 if (!lmerge.isNull()) 5985 return lmerge; 5986 5987 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 5988 Unqualified); 5989 if (!rmerge.isNull()) 5990 return rmerge; 5991 5992 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 5993} 5994 5995QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 5996 bool OfBlockPointer, 5997 bool Unqualified) { 5998 const FunctionType *lbase = lhs->getAs<FunctionType>(); 5999 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6000 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6001 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6002 bool allLTypes = true; 6003 bool allRTypes = true; 6004 6005 // Check return type 6006 QualType retType; 6007 if (OfBlockPointer) { 6008 QualType RHS = rbase->getResultType(); 6009 QualType LHS = lbase->getResultType(); 6010 bool UnqualifiedResult = Unqualified; 6011 if (!UnqualifiedResult) 6012 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6013 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6014 } 6015 else 6016 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false, 6017 Unqualified); 6018 if (retType.isNull()) return QualType(); 6019 6020 if (Unqualified) 6021 retType = retType.getUnqualifiedType(); 6022 6023 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 6024 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 6025 if (Unqualified) { 6026 LRetType = LRetType.getUnqualifiedType(); 6027 RRetType = RRetType.getUnqualifiedType(); 6028 } 6029 6030 if (getCanonicalType(retType) != LRetType) 6031 allLTypes = false; 6032 if (getCanonicalType(retType) != RRetType) 6033 allRTypes = false; 6034 6035 // FIXME: double check this 6036 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6037 // rbase->getRegParmAttr() != 0 && 6038 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6039 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6040 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6041 6042 // Compatible functions must have compatible calling conventions 6043 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC())) 6044 return QualType(); 6045 6046 // Regparm is part of the calling convention. 6047 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6048 return QualType(); 6049 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6050 return QualType(); 6051 6052 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6053 return QualType(); 6054 6055 // functypes which return are preferred over those that do not. 6056 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn()) 6057 allLTypes = false; 6058 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()) 6059 allRTypes = false; 6060 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6061 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6062 6063 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6064 6065 if (lproto && rproto) { // two C99 style function prototypes 6066 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6067 "C++ shouldn't be here"); 6068 unsigned lproto_nargs = lproto->getNumArgs(); 6069 unsigned rproto_nargs = rproto->getNumArgs(); 6070 6071 // Compatible functions must have the same number of arguments 6072 if (lproto_nargs != rproto_nargs) 6073 return QualType(); 6074 6075 // Variadic and non-variadic functions aren't compatible 6076 if (lproto->isVariadic() != rproto->isVariadic()) 6077 return QualType(); 6078 6079 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6080 return QualType(); 6081 6082 if (LangOpts.ObjCAutoRefCount && 6083 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6084 return QualType(); 6085 6086 // Check argument compatibility 6087 SmallVector<QualType, 10> types; 6088 for (unsigned i = 0; i < lproto_nargs; i++) { 6089 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 6090 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 6091 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 6092 OfBlockPointer, 6093 Unqualified); 6094 if (argtype.isNull()) return QualType(); 6095 6096 if (Unqualified) 6097 argtype = argtype.getUnqualifiedType(); 6098 6099 types.push_back(argtype); 6100 if (Unqualified) { 6101 largtype = largtype.getUnqualifiedType(); 6102 rargtype = rargtype.getUnqualifiedType(); 6103 } 6104 6105 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 6106 allLTypes = false; 6107 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 6108 allRTypes = false; 6109 } 6110 6111 if (allLTypes) return lhs; 6112 if (allRTypes) return rhs; 6113 6114 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 6115 EPI.ExtInfo = einfo; 6116 return getFunctionType(retType, types.begin(), types.size(), EPI); 6117 } 6118 6119 if (lproto) allRTypes = false; 6120 if (rproto) allLTypes = false; 6121 6122 const FunctionProtoType *proto = lproto ? lproto : rproto; 6123 if (proto) { 6124 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 6125 if (proto->isVariadic()) return QualType(); 6126 // Check that the types are compatible with the types that 6127 // would result from default argument promotions (C99 6.7.5.3p15). 6128 // The only types actually affected are promotable integer 6129 // types and floats, which would be passed as a different 6130 // type depending on whether the prototype is visible. 6131 unsigned proto_nargs = proto->getNumArgs(); 6132 for (unsigned i = 0; i < proto_nargs; ++i) { 6133 QualType argTy = proto->getArgType(i); 6134 6135 // Look at the promotion type of enum types, since that is the type used 6136 // to pass enum values. 6137 if (const EnumType *Enum = argTy->getAs<EnumType>()) 6138 argTy = Enum->getDecl()->getPromotionType(); 6139 6140 if (argTy->isPromotableIntegerType() || 6141 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 6142 return QualType(); 6143 } 6144 6145 if (allLTypes) return lhs; 6146 if (allRTypes) return rhs; 6147 6148 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 6149 EPI.ExtInfo = einfo; 6150 return getFunctionType(retType, proto->arg_type_begin(), 6151 proto->getNumArgs(), EPI); 6152 } 6153 6154 if (allLTypes) return lhs; 6155 if (allRTypes) return rhs; 6156 return getFunctionNoProtoType(retType, einfo); 6157} 6158 6159QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 6160 bool OfBlockPointer, 6161 bool Unqualified, bool BlockReturnType) { 6162 // C++ [expr]: If an expression initially has the type "reference to T", the 6163 // type is adjusted to "T" prior to any further analysis, the expression 6164 // designates the object or function denoted by the reference, and the 6165 // expression is an lvalue unless the reference is an rvalue reference and 6166 // the expression is a function call (possibly inside parentheses). 6167 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 6168 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 6169 6170 if (Unqualified) { 6171 LHS = LHS.getUnqualifiedType(); 6172 RHS = RHS.getUnqualifiedType(); 6173 } 6174 6175 QualType LHSCan = getCanonicalType(LHS), 6176 RHSCan = getCanonicalType(RHS); 6177 6178 // If two types are identical, they are compatible. 6179 if (LHSCan == RHSCan) 6180 return LHS; 6181 6182 // If the qualifiers are different, the types aren't compatible... mostly. 6183 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6184 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6185 if (LQuals != RQuals) { 6186 // If any of these qualifiers are different, we have a type 6187 // mismatch. 6188 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6189 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 6190 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 6191 return QualType(); 6192 6193 // Exactly one GC qualifier difference is allowed: __strong is 6194 // okay if the other type has no GC qualifier but is an Objective 6195 // C object pointer (i.e. implicitly strong by default). We fix 6196 // this by pretending that the unqualified type was actually 6197 // qualified __strong. 6198 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6199 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6200 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6201 6202 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6203 return QualType(); 6204 6205 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 6206 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 6207 } 6208 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 6209 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 6210 } 6211 return QualType(); 6212 } 6213 6214 // Okay, qualifiers are equal. 6215 6216 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 6217 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 6218 6219 // We want to consider the two function types to be the same for these 6220 // comparisons, just force one to the other. 6221 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 6222 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 6223 6224 // Same as above for arrays 6225 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 6226 LHSClass = Type::ConstantArray; 6227 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 6228 RHSClass = Type::ConstantArray; 6229 6230 // ObjCInterfaces are just specialized ObjCObjects. 6231 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 6232 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 6233 6234 // Canonicalize ExtVector -> Vector. 6235 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 6236 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 6237 6238 // If the canonical type classes don't match. 6239 if (LHSClass != RHSClass) { 6240 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 6241 // a signed integer type, or an unsigned integer type. 6242 // Compatibility is based on the underlying type, not the promotion 6243 // type. 6244 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 6245 QualType TINT = ETy->getDecl()->getIntegerType(); 6246 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType())) 6247 return RHS; 6248 } 6249 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 6250 QualType TINT = ETy->getDecl()->getIntegerType(); 6251 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType())) 6252 return LHS; 6253 } 6254 // allow block pointer type to match an 'id' type. 6255 if (OfBlockPointer && !BlockReturnType) { 6256 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 6257 return LHS; 6258 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 6259 return RHS; 6260 } 6261 6262 return QualType(); 6263 } 6264 6265 // The canonical type classes match. 6266 switch (LHSClass) { 6267#define TYPE(Class, Base) 6268#define ABSTRACT_TYPE(Class, Base) 6269#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 6270#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6271#define DEPENDENT_TYPE(Class, Base) case Type::Class: 6272#include "clang/AST/TypeNodes.def" 6273 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 6274 6275 case Type::LValueReference: 6276 case Type::RValueReference: 6277 case Type::MemberPointer: 6278 llvm_unreachable("C++ should never be in mergeTypes"); 6279 6280 case Type::ObjCInterface: 6281 case Type::IncompleteArray: 6282 case Type::VariableArray: 6283 case Type::FunctionProto: 6284 case Type::ExtVector: 6285 llvm_unreachable("Types are eliminated above"); 6286 6287 case Type::Pointer: 6288 { 6289 // Merge two pointer types, while trying to preserve typedef info 6290 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 6291 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 6292 if (Unqualified) { 6293 LHSPointee = LHSPointee.getUnqualifiedType(); 6294 RHSPointee = RHSPointee.getUnqualifiedType(); 6295 } 6296 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 6297 Unqualified); 6298 if (ResultType.isNull()) return QualType(); 6299 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6300 return LHS; 6301 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6302 return RHS; 6303 return getPointerType(ResultType); 6304 } 6305 case Type::BlockPointer: 6306 { 6307 // Merge two block pointer types, while trying to preserve typedef info 6308 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 6309 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 6310 if (Unqualified) { 6311 LHSPointee = LHSPointee.getUnqualifiedType(); 6312 RHSPointee = RHSPointee.getUnqualifiedType(); 6313 } 6314 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 6315 Unqualified); 6316 if (ResultType.isNull()) return QualType(); 6317 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6318 return LHS; 6319 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6320 return RHS; 6321 return getBlockPointerType(ResultType); 6322 } 6323 case Type::Atomic: 6324 { 6325 // Merge two pointer types, while trying to preserve typedef info 6326 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 6327 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 6328 if (Unqualified) { 6329 LHSValue = LHSValue.getUnqualifiedType(); 6330 RHSValue = RHSValue.getUnqualifiedType(); 6331 } 6332 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 6333 Unqualified); 6334 if (ResultType.isNull()) return QualType(); 6335 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 6336 return LHS; 6337 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 6338 return RHS; 6339 return getAtomicType(ResultType); 6340 } 6341 case Type::ConstantArray: 6342 { 6343 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 6344 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 6345 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 6346 return QualType(); 6347 6348 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 6349 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 6350 if (Unqualified) { 6351 LHSElem = LHSElem.getUnqualifiedType(); 6352 RHSElem = RHSElem.getUnqualifiedType(); 6353 } 6354 6355 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 6356 if (ResultType.isNull()) return QualType(); 6357 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6358 return LHS; 6359 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6360 return RHS; 6361 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 6362 ArrayType::ArraySizeModifier(), 0); 6363 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 6364 ArrayType::ArraySizeModifier(), 0); 6365 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 6366 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 6367 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6368 return LHS; 6369 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6370 return RHS; 6371 if (LVAT) { 6372 // FIXME: This isn't correct! But tricky to implement because 6373 // the array's size has to be the size of LHS, but the type 6374 // has to be different. 6375 return LHS; 6376 } 6377 if (RVAT) { 6378 // FIXME: This isn't correct! But tricky to implement because 6379 // the array's size has to be the size of RHS, but the type 6380 // has to be different. 6381 return RHS; 6382 } 6383 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 6384 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 6385 return getIncompleteArrayType(ResultType, 6386 ArrayType::ArraySizeModifier(), 0); 6387 } 6388 case Type::FunctionNoProto: 6389 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 6390 case Type::Record: 6391 case Type::Enum: 6392 return QualType(); 6393 case Type::Builtin: 6394 // Only exactly equal builtin types are compatible, which is tested above. 6395 return QualType(); 6396 case Type::Complex: 6397 // Distinct complex types are incompatible. 6398 return QualType(); 6399 case Type::Vector: 6400 // FIXME: The merged type should be an ExtVector! 6401 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 6402 RHSCan->getAs<VectorType>())) 6403 return LHS; 6404 return QualType(); 6405 case Type::ObjCObject: { 6406 // Check if the types are assignment compatible. 6407 // FIXME: This should be type compatibility, e.g. whether 6408 // "LHS x; RHS x;" at global scope is legal. 6409 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 6410 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 6411 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 6412 return LHS; 6413 6414 return QualType(); 6415 } 6416 case Type::ObjCObjectPointer: { 6417 if (OfBlockPointer) { 6418 if (canAssignObjCInterfacesInBlockPointer( 6419 LHS->getAs<ObjCObjectPointerType>(), 6420 RHS->getAs<ObjCObjectPointerType>(), 6421 BlockReturnType)) 6422 return LHS; 6423 return QualType(); 6424 } 6425 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 6426 RHS->getAs<ObjCObjectPointerType>())) 6427 return LHS; 6428 6429 return QualType(); 6430 } 6431 } 6432 6433 llvm_unreachable("Invalid Type::Class!"); 6434} 6435 6436bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 6437 const FunctionProtoType *FromFunctionType, 6438 const FunctionProtoType *ToFunctionType) { 6439 if (FromFunctionType->hasAnyConsumedArgs() != 6440 ToFunctionType->hasAnyConsumedArgs()) 6441 return false; 6442 FunctionProtoType::ExtProtoInfo FromEPI = 6443 FromFunctionType->getExtProtoInfo(); 6444 FunctionProtoType::ExtProtoInfo ToEPI = 6445 ToFunctionType->getExtProtoInfo(); 6446 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments) 6447 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 6448 ArgIdx != NumArgs; ++ArgIdx) { 6449 if (FromEPI.ConsumedArguments[ArgIdx] != 6450 ToEPI.ConsumedArguments[ArgIdx]) 6451 return false; 6452 } 6453 return true; 6454} 6455 6456/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 6457/// 'RHS' attributes and returns the merged version; including for function 6458/// return types. 6459QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 6460 QualType LHSCan = getCanonicalType(LHS), 6461 RHSCan = getCanonicalType(RHS); 6462 // If two types are identical, they are compatible. 6463 if (LHSCan == RHSCan) 6464 return LHS; 6465 if (RHSCan->isFunctionType()) { 6466 if (!LHSCan->isFunctionType()) 6467 return QualType(); 6468 QualType OldReturnType = 6469 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 6470 QualType NewReturnType = 6471 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 6472 QualType ResReturnType = 6473 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 6474 if (ResReturnType.isNull()) 6475 return QualType(); 6476 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 6477 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 6478 // In either case, use OldReturnType to build the new function type. 6479 const FunctionType *F = LHS->getAs<FunctionType>(); 6480 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 6481 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6482 EPI.ExtInfo = getFunctionExtInfo(LHS); 6483 QualType ResultType 6484 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 6485 FPT->getNumArgs(), EPI); 6486 return ResultType; 6487 } 6488 } 6489 return QualType(); 6490 } 6491 6492 // If the qualifiers are different, the types can still be merged. 6493 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6494 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6495 if (LQuals != RQuals) { 6496 // If any of these qualifiers are different, we have a type mismatch. 6497 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6498 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 6499 return QualType(); 6500 6501 // Exactly one GC qualifier difference is allowed: __strong is 6502 // okay if the other type has no GC qualifier but is an Objective 6503 // C object pointer (i.e. implicitly strong by default). We fix 6504 // this by pretending that the unqualified type was actually 6505 // qualified __strong. 6506 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6507 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6508 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6509 6510 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6511 return QualType(); 6512 6513 if (GC_L == Qualifiers::Strong) 6514 return LHS; 6515 if (GC_R == Qualifiers::Strong) 6516 return RHS; 6517 return QualType(); 6518 } 6519 6520 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 6521 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6522 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6523 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 6524 if (ResQT == LHSBaseQT) 6525 return LHS; 6526 if (ResQT == RHSBaseQT) 6527 return RHS; 6528 } 6529 return QualType(); 6530} 6531 6532//===----------------------------------------------------------------------===// 6533// Integer Predicates 6534//===----------------------------------------------------------------------===// 6535 6536unsigned ASTContext::getIntWidth(QualType T) const { 6537 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6538 T = ET->getDecl()->getIntegerType(); 6539 if (T->isBooleanType()) 6540 return 1; 6541 // For builtin types, just use the standard type sizing method 6542 return (unsigned)getTypeSize(T); 6543} 6544 6545QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 6546 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 6547 6548 // Turn <4 x signed int> -> <4 x unsigned int> 6549 if (const VectorType *VTy = T->getAs<VectorType>()) 6550 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 6551 VTy->getNumElements(), VTy->getVectorKind()); 6552 6553 // For enums, we return the unsigned version of the base type. 6554 if (const EnumType *ETy = T->getAs<EnumType>()) 6555 T = ETy->getDecl()->getIntegerType(); 6556 6557 const BuiltinType *BTy = T->getAs<BuiltinType>(); 6558 assert(BTy && "Unexpected signed integer type"); 6559 switch (BTy->getKind()) { 6560 case BuiltinType::Char_S: 6561 case BuiltinType::SChar: 6562 return UnsignedCharTy; 6563 case BuiltinType::Short: 6564 return UnsignedShortTy; 6565 case BuiltinType::Int: 6566 return UnsignedIntTy; 6567 case BuiltinType::Long: 6568 return UnsignedLongTy; 6569 case BuiltinType::LongLong: 6570 return UnsignedLongLongTy; 6571 case BuiltinType::Int128: 6572 return UnsignedInt128Ty; 6573 default: 6574 llvm_unreachable("Unexpected signed integer type"); 6575 } 6576} 6577 6578ASTMutationListener::~ASTMutationListener() { } 6579 6580 6581//===----------------------------------------------------------------------===// 6582// Builtin Type Computation 6583//===----------------------------------------------------------------------===// 6584 6585/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 6586/// pointer over the consumed characters. This returns the resultant type. If 6587/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 6588/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 6589/// a vector of "i*". 6590/// 6591/// RequiresICE is filled in on return to indicate whether the value is required 6592/// to be an Integer Constant Expression. 6593static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 6594 ASTContext::GetBuiltinTypeError &Error, 6595 bool &RequiresICE, 6596 bool AllowTypeModifiers) { 6597 // Modifiers. 6598 int HowLong = 0; 6599 bool Signed = false, Unsigned = false; 6600 RequiresICE = false; 6601 6602 // Read the prefixed modifiers first. 6603 bool Done = false; 6604 while (!Done) { 6605 switch (*Str++) { 6606 default: Done = true; --Str; break; 6607 case 'I': 6608 RequiresICE = true; 6609 break; 6610 case 'S': 6611 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 6612 assert(!Signed && "Can't use 'S' modifier multiple times!"); 6613 Signed = true; 6614 break; 6615 case 'U': 6616 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 6617 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 6618 Unsigned = true; 6619 break; 6620 case 'L': 6621 assert(HowLong <= 2 && "Can't have LLLL modifier"); 6622 ++HowLong; 6623 break; 6624 } 6625 } 6626 6627 QualType Type; 6628 6629 // Read the base type. 6630 switch (*Str++) { 6631 default: llvm_unreachable("Unknown builtin type letter!"); 6632 case 'v': 6633 assert(HowLong == 0 && !Signed && !Unsigned && 6634 "Bad modifiers used with 'v'!"); 6635 Type = Context.VoidTy; 6636 break; 6637 case 'f': 6638 assert(HowLong == 0 && !Signed && !Unsigned && 6639 "Bad modifiers used with 'f'!"); 6640 Type = Context.FloatTy; 6641 break; 6642 case 'd': 6643 assert(HowLong < 2 && !Signed && !Unsigned && 6644 "Bad modifiers used with 'd'!"); 6645 if (HowLong) 6646 Type = Context.LongDoubleTy; 6647 else 6648 Type = Context.DoubleTy; 6649 break; 6650 case 's': 6651 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 6652 if (Unsigned) 6653 Type = Context.UnsignedShortTy; 6654 else 6655 Type = Context.ShortTy; 6656 break; 6657 case 'i': 6658 if (HowLong == 3) 6659 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 6660 else if (HowLong == 2) 6661 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 6662 else if (HowLong == 1) 6663 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 6664 else 6665 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 6666 break; 6667 case 'c': 6668 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 6669 if (Signed) 6670 Type = Context.SignedCharTy; 6671 else if (Unsigned) 6672 Type = Context.UnsignedCharTy; 6673 else 6674 Type = Context.CharTy; 6675 break; 6676 case 'b': // boolean 6677 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 6678 Type = Context.BoolTy; 6679 break; 6680 case 'z': // size_t. 6681 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 6682 Type = Context.getSizeType(); 6683 break; 6684 case 'F': 6685 Type = Context.getCFConstantStringType(); 6686 break; 6687 case 'G': 6688 Type = Context.getObjCIdType(); 6689 break; 6690 case 'H': 6691 Type = Context.getObjCSelType(); 6692 break; 6693 case 'a': 6694 Type = Context.getBuiltinVaListType(); 6695 assert(!Type.isNull() && "builtin va list type not initialized!"); 6696 break; 6697 case 'A': 6698 // This is a "reference" to a va_list; however, what exactly 6699 // this means depends on how va_list is defined. There are two 6700 // different kinds of va_list: ones passed by value, and ones 6701 // passed by reference. An example of a by-value va_list is 6702 // x86, where va_list is a char*. An example of by-ref va_list 6703 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 6704 // we want this argument to be a char*&; for x86-64, we want 6705 // it to be a __va_list_tag*. 6706 Type = Context.getBuiltinVaListType(); 6707 assert(!Type.isNull() && "builtin va list type not initialized!"); 6708 if (Type->isArrayType()) 6709 Type = Context.getArrayDecayedType(Type); 6710 else 6711 Type = Context.getLValueReferenceType(Type); 6712 break; 6713 case 'V': { 6714 char *End; 6715 unsigned NumElements = strtoul(Str, &End, 10); 6716 assert(End != Str && "Missing vector size"); 6717 Str = End; 6718 6719 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 6720 RequiresICE, false); 6721 assert(!RequiresICE && "Can't require vector ICE"); 6722 6723 // TODO: No way to make AltiVec vectors in builtins yet. 6724 Type = Context.getVectorType(ElementType, NumElements, 6725 VectorType::GenericVector); 6726 break; 6727 } 6728 case 'E': { 6729 char *End; 6730 6731 unsigned NumElements = strtoul(Str, &End, 10); 6732 assert(End != Str && "Missing vector size"); 6733 6734 Str = End; 6735 6736 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6737 false); 6738 Type = Context.getExtVectorType(ElementType, NumElements); 6739 break; 6740 } 6741 case 'X': { 6742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6743 false); 6744 assert(!RequiresICE && "Can't require complex ICE"); 6745 Type = Context.getComplexType(ElementType); 6746 break; 6747 } 6748 case 'Y' : { 6749 Type = Context.getPointerDiffType(); 6750 break; 6751 } 6752 case 'P': 6753 Type = Context.getFILEType(); 6754 if (Type.isNull()) { 6755 Error = ASTContext::GE_Missing_stdio; 6756 return QualType(); 6757 } 6758 break; 6759 case 'J': 6760 if (Signed) 6761 Type = Context.getsigjmp_bufType(); 6762 else 6763 Type = Context.getjmp_bufType(); 6764 6765 if (Type.isNull()) { 6766 Error = ASTContext::GE_Missing_setjmp; 6767 return QualType(); 6768 } 6769 break; 6770 case 'K': 6771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 6772 Type = Context.getucontext_tType(); 6773 6774 if (Type.isNull()) { 6775 Error = ASTContext::GE_Missing_ucontext; 6776 return QualType(); 6777 } 6778 break; 6779 } 6780 6781 // If there are modifiers and if we're allowed to parse them, go for it. 6782 Done = !AllowTypeModifiers; 6783 while (!Done) { 6784 switch (char c = *Str++) { 6785 default: Done = true; --Str; break; 6786 case '*': 6787 case '&': { 6788 // Both pointers and references can have their pointee types 6789 // qualified with an address space. 6790 char *End; 6791 unsigned AddrSpace = strtoul(Str, &End, 10); 6792 if (End != Str && AddrSpace != 0) { 6793 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 6794 Str = End; 6795 } 6796 if (c == '*') 6797 Type = Context.getPointerType(Type); 6798 else 6799 Type = Context.getLValueReferenceType(Type); 6800 break; 6801 } 6802 // FIXME: There's no way to have a built-in with an rvalue ref arg. 6803 case 'C': 6804 Type = Type.withConst(); 6805 break; 6806 case 'D': 6807 Type = Context.getVolatileType(Type); 6808 break; 6809 case 'R': 6810 Type = Type.withRestrict(); 6811 break; 6812 } 6813 } 6814 6815 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 6816 "Integer constant 'I' type must be an integer"); 6817 6818 return Type; 6819} 6820 6821/// GetBuiltinType - Return the type for the specified builtin. 6822QualType ASTContext::GetBuiltinType(unsigned Id, 6823 GetBuiltinTypeError &Error, 6824 unsigned *IntegerConstantArgs) const { 6825 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 6826 6827 SmallVector<QualType, 8> ArgTypes; 6828 6829 bool RequiresICE = false; 6830 Error = GE_None; 6831 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 6832 RequiresICE, true); 6833 if (Error != GE_None) 6834 return QualType(); 6835 6836 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 6837 6838 while (TypeStr[0] && TypeStr[0] != '.') { 6839 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 6840 if (Error != GE_None) 6841 return QualType(); 6842 6843 // If this argument is required to be an IntegerConstantExpression and the 6844 // caller cares, fill in the bitmask we return. 6845 if (RequiresICE && IntegerConstantArgs) 6846 *IntegerConstantArgs |= 1 << ArgTypes.size(); 6847 6848 // Do array -> pointer decay. The builtin should use the decayed type. 6849 if (Ty->isArrayType()) 6850 Ty = getArrayDecayedType(Ty); 6851 6852 ArgTypes.push_back(Ty); 6853 } 6854 6855 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 6856 "'.' should only occur at end of builtin type list!"); 6857 6858 FunctionType::ExtInfo EI; 6859 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 6860 6861 bool Variadic = (TypeStr[0] == '.'); 6862 6863 // We really shouldn't be making a no-proto type here, especially in C++. 6864 if (ArgTypes.empty() && Variadic) 6865 return getFunctionNoProtoType(ResType, EI); 6866 6867 FunctionProtoType::ExtProtoInfo EPI; 6868 EPI.ExtInfo = EI; 6869 EPI.Variadic = Variadic; 6870 6871 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI); 6872} 6873 6874GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 6875 GVALinkage External = GVA_StrongExternal; 6876 6877 Linkage L = FD->getLinkage(); 6878 switch (L) { 6879 case NoLinkage: 6880 case InternalLinkage: 6881 case UniqueExternalLinkage: 6882 return GVA_Internal; 6883 6884 case ExternalLinkage: 6885 switch (FD->getTemplateSpecializationKind()) { 6886 case TSK_Undeclared: 6887 case TSK_ExplicitSpecialization: 6888 External = GVA_StrongExternal; 6889 break; 6890 6891 case TSK_ExplicitInstantiationDefinition: 6892 return GVA_ExplicitTemplateInstantiation; 6893 6894 case TSK_ExplicitInstantiationDeclaration: 6895 case TSK_ImplicitInstantiation: 6896 External = GVA_TemplateInstantiation; 6897 break; 6898 } 6899 } 6900 6901 if (!FD->isInlined()) 6902 return External; 6903 6904 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 6905 // GNU or C99 inline semantics. Determine whether this symbol should be 6906 // externally visible. 6907 if (FD->isInlineDefinitionExternallyVisible()) 6908 return External; 6909 6910 // C99 inline semantics, where the symbol is not externally visible. 6911 return GVA_C99Inline; 6912 } 6913 6914 // C++0x [temp.explicit]p9: 6915 // [ Note: The intent is that an inline function that is the subject of 6916 // an explicit instantiation declaration will still be implicitly 6917 // instantiated when used so that the body can be considered for 6918 // inlining, but that no out-of-line copy of the inline function would be 6919 // generated in the translation unit. -- end note ] 6920 if (FD->getTemplateSpecializationKind() 6921 == TSK_ExplicitInstantiationDeclaration) 6922 return GVA_C99Inline; 6923 6924 return GVA_CXXInline; 6925} 6926 6927GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 6928 // If this is a static data member, compute the kind of template 6929 // specialization. Otherwise, this variable is not part of a 6930 // template. 6931 TemplateSpecializationKind TSK = TSK_Undeclared; 6932 if (VD->isStaticDataMember()) 6933 TSK = VD->getTemplateSpecializationKind(); 6934 6935 Linkage L = VD->getLinkage(); 6936 if (L == ExternalLinkage && getLangOpts().CPlusPlus && 6937 VD->getType()->getLinkage() == UniqueExternalLinkage) 6938 L = UniqueExternalLinkage; 6939 6940 switch (L) { 6941 case NoLinkage: 6942 case InternalLinkage: 6943 case UniqueExternalLinkage: 6944 return GVA_Internal; 6945 6946 case ExternalLinkage: 6947 switch (TSK) { 6948 case TSK_Undeclared: 6949 case TSK_ExplicitSpecialization: 6950 return GVA_StrongExternal; 6951 6952 case TSK_ExplicitInstantiationDeclaration: 6953 llvm_unreachable("Variable should not be instantiated"); 6954 // Fall through to treat this like any other instantiation. 6955 6956 case TSK_ExplicitInstantiationDefinition: 6957 return GVA_ExplicitTemplateInstantiation; 6958 6959 case TSK_ImplicitInstantiation: 6960 return GVA_TemplateInstantiation; 6961 } 6962 } 6963 6964 llvm_unreachable("Invalid Linkage!"); 6965} 6966 6967bool ASTContext::DeclMustBeEmitted(const Decl *D) { 6968 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6969 if (!VD->isFileVarDecl()) 6970 return false; 6971 } else if (!isa<FunctionDecl>(D)) 6972 return false; 6973 6974 // Weak references don't produce any output by themselves. 6975 if (D->hasAttr<WeakRefAttr>()) 6976 return false; 6977 6978 // Aliases and used decls are required. 6979 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 6980 return true; 6981 6982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6983 // Forward declarations aren't required. 6984 if (!FD->doesThisDeclarationHaveABody()) 6985 return FD->doesDeclarationForceExternallyVisibleDefinition(); 6986 6987 // Constructors and destructors are required. 6988 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 6989 return true; 6990 6991 // The key function for a class is required. 6992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6993 const CXXRecordDecl *RD = MD->getParent(); 6994 if (MD->isOutOfLine() && RD->isDynamicClass()) { 6995 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 6996 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 6997 return true; 6998 } 6999 } 7000 7001 GVALinkage Linkage = GetGVALinkageForFunction(FD); 7002 7003 // static, static inline, always_inline, and extern inline functions can 7004 // always be deferred. Normal inline functions can be deferred in C99/C++. 7005 // Implicit template instantiations can also be deferred in C++. 7006 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 7007 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 7008 return false; 7009 return true; 7010 } 7011 7012 const VarDecl *VD = cast<VarDecl>(D); 7013 assert(VD->isFileVarDecl() && "Expected file scoped var"); 7014 7015 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 7016 return false; 7017 7018 // Structs that have non-trivial constructors or destructors are required. 7019 7020 // FIXME: Handle references. 7021 // FIXME: Be more selective about which constructors we care about. 7022 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 7023 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 7024 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() && 7025 RD->hasTrivialCopyConstructor() && 7026 RD->hasTrivialMoveConstructor() && 7027 RD->hasTrivialDestructor())) 7028 return true; 7029 } 7030 } 7031 7032 GVALinkage L = GetGVALinkageForVariable(VD); 7033 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 7034 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 7035 return false; 7036 } 7037 7038 return true; 7039} 7040 7041CallingConv ASTContext::getDefaultMethodCallConv() { 7042 // Pass through to the C++ ABI object 7043 return ABI->getDefaultMethodCallConv(); 7044} 7045 7046bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 7047 // Pass through to the C++ ABI object 7048 return ABI->isNearlyEmpty(RD); 7049} 7050 7051MangleContext *ASTContext::createMangleContext() { 7052 switch (Target->getCXXABI()) { 7053 case CXXABI_ARM: 7054 case CXXABI_Itanium: 7055 return createItaniumMangleContext(*this, getDiagnostics()); 7056 case CXXABI_Microsoft: 7057 return createMicrosoftMangleContext(*this, getDiagnostics()); 7058 } 7059 llvm_unreachable("Unsupported ABI"); 7060} 7061 7062CXXABI::~CXXABI() {} 7063 7064size_t ASTContext::getSideTableAllocatedMemory() const { 7065 return ASTRecordLayouts.getMemorySize() 7066 + llvm::capacity_in_bytes(ObjCLayouts) 7067 + llvm::capacity_in_bytes(KeyFunctions) 7068 + llvm::capacity_in_bytes(ObjCImpls) 7069 + llvm::capacity_in_bytes(BlockVarCopyInits) 7070 + llvm::capacity_in_bytes(DeclAttrs) 7071 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember) 7072 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) 7073 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) 7074 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) 7075 + llvm::capacity_in_bytes(OverriddenMethods) 7076 + llvm::capacity_in_bytes(Types) 7077 + llvm::capacity_in_bytes(VariableArrayTypes) 7078 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 7079} 7080 7081unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) { 7082 CXXRecordDecl *Lambda = CallOperator->getParent(); 7083 return LambdaMangleContexts[Lambda->getDeclContext()] 7084 .getManglingNumber(CallOperator); 7085} 7086 7087 7088void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 7089 ParamIndices[D] = index; 7090} 7091 7092unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 7093 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 7094 assert(I != ParamIndices.end() && 7095 "ParmIndices lacks entry set by ParmVarDecl"); 7096 return I->second; 7097} 7098