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