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