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