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/DeclContextInternals.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExternalASTSource.h" 28 #include "clang/AST/Mangle.h" 29 #include "clang/AST/MangleNumberingContext.h" 30 #include "clang/AST/RecordLayout.h" 31 #include "clang/AST/RecursiveASTVisitor.h" 32 #include "clang/AST/TypeLoc.h" 33 #include "clang/AST/VTableBuilder.h" 34 #include "clang/Basic/Builtins.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/TargetInfo.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/Triple.h" 39 #include "llvm/Support/Capacity.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <map> 43 44 using namespace clang; 45 46 unsigned ASTContext::NumImplicitDefaultConstructors; 47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 48 unsigned ASTContext::NumImplicitCopyConstructors; 49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 50 unsigned ASTContext::NumImplicitMoveConstructors; 51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 52 unsigned ASTContext::NumImplicitCopyAssignmentOperators; 53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 54 unsigned ASTContext::NumImplicitMoveAssignmentOperators; 55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 56 unsigned ASTContext::NumImplicitDestructors; 57 unsigned ASTContext::NumImplicitDestructorsDeclared; 58 59 enum FloatingRank { 60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 61 }; 62 63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 64 if (!CommentsLoaded && ExternalSource) { 65 ExternalSource->ReadComments(); 66 67 #ifndef NDEBUG 68 ArrayRef<RawComment *> RawComments = Comments.getComments(); 69 assert(std::is_sorted(RawComments.begin(), RawComments.end(), 70 BeforeThanCompare<RawComment>(SourceMgr))); 71 #endif 72 73 CommentsLoaded = true; 74 } 75 76 assert(D); 77 78 // User can not attach documentation to implicit declarations. 79 if (D->isImplicit()) 80 return nullptr; 81 82 // User can not attach documentation to implicit instantiations. 83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 85 return nullptr; 86 } 87 88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 89 if (VD->isStaticDataMember() && 90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 91 return nullptr; 92 } 93 94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 96 return nullptr; 97 } 98 99 if (const ClassTemplateSpecializationDecl *CTSD = 100 dyn_cast<ClassTemplateSpecializationDecl>(D)) { 101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 102 if (TSK == TSK_ImplicitInstantiation || 103 TSK == TSK_Undeclared) 104 return nullptr; 105 } 106 107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 109 return nullptr; 110 } 111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 112 // When tag declaration (but not definition!) is part of the 113 // decl-specifier-seq of some other declaration, it doesn't get comment 114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 115 return nullptr; 116 } 117 // TODO: handle comments for function parameters properly. 118 if (isa<ParmVarDecl>(D)) 119 return nullptr; 120 121 // TODO: we could look up template parameter documentation in the template 122 // documentation. 123 if (isa<TemplateTypeParmDecl>(D) || 124 isa<NonTypeTemplateParmDecl>(D) || 125 isa<TemplateTemplateParmDecl>(D)) 126 return nullptr; 127 128 ArrayRef<RawComment *> RawComments = Comments.getComments(); 129 130 // If there are no comments anywhere, we won't find anything. 131 if (RawComments.empty()) 132 return nullptr; 133 134 // Find declaration location. 135 // For Objective-C declarations we generally don't expect to have multiple 136 // declarators, thus use declaration starting location as the "declaration 137 // location". 138 // For all other declarations multiple declarators are used quite frequently, 139 // so we use the location of the identifier as the "declaration location". 140 SourceLocation DeclLoc; 141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 142 isa<ObjCPropertyDecl>(D) || 143 isa<RedeclarableTemplateDecl>(D) || 144 isa<ClassTemplateSpecializationDecl>(D)) 145 DeclLoc = D->getLocStart(); 146 else { 147 DeclLoc = D->getLocation(); 148 if (DeclLoc.isMacroID()) { 149 if (isa<TypedefDecl>(D)) { 150 // If location of the typedef name is in a macro, it is because being 151 // declared via a macro. Try using declaration's starting location as 152 // the "declaration location". 153 DeclLoc = D->getLocStart(); 154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 155 // If location of the tag decl is inside a macro, but the spelling of 156 // the tag name comes from a macro argument, it looks like a special 157 // macro like NS_ENUM is being used to define the tag decl. In that 158 // case, adjust the source location to the expansion loc so that we can 159 // attach the comment to the tag decl. 160 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 161 TD->isCompleteDefinition()) 162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc); 163 } 164 } 165 } 166 167 // If the declaration doesn't map directly to a location in a file, we 168 // can't find the comment. 169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 170 return nullptr; 171 172 // Find the comment that occurs just after this declaration. 173 ArrayRef<RawComment *>::iterator Comment; 174 { 175 // When searching for comments during parsing, the comment we are looking 176 // for is usually among the last two comments we parsed -- check them 177 // first. 178 RawComment CommentAtDeclLoc( 179 SourceMgr, SourceRange(DeclLoc), false, 180 LangOpts.CommentOpts.ParseAllComments); 181 BeforeThanCompare<RawComment> Compare(SourceMgr); 182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 184 if (!Found && RawComments.size() >= 2) { 185 MaybeBeforeDecl--; 186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 187 } 188 189 if (Found) { 190 Comment = MaybeBeforeDecl + 1; 191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 192 &CommentAtDeclLoc, Compare)); 193 } else { 194 // Slow path. 195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 196 &CommentAtDeclLoc, Compare); 197 } 198 } 199 200 // Decompose the location for the declaration and find the beginning of the 201 // file buffer. 202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 203 204 // First check whether we have a trailing comment. 205 if (Comment != RawComments.end() && 206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() && 207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 209 std::pair<FileID, unsigned> CommentBeginDecomp 210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 211 // Check that Doxygen trailing comment comes after the declaration, starts 212 // on the same line and in the same file as the declaration. 213 if (DeclLocDecomp.first == CommentBeginDecomp.first && 214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 215 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 216 CommentBeginDecomp.second)) { 217 return *Comment; 218 } 219 } 220 221 // The comment just after the declaration was not a trailing comment. 222 // Let's look at the previous comment. 223 if (Comment == RawComments.begin()) 224 return nullptr; 225 --Comment; 226 227 // Check that we actually have a non-member Doxygen comment. 228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment()) 229 return nullptr; 230 231 // Decompose the end of the comment. 232 std::pair<FileID, unsigned> CommentEndDecomp 233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 234 235 // If the comment and the declaration aren't in the same file, then they 236 // aren't related. 237 if (DeclLocDecomp.first != CommentEndDecomp.first) 238 return nullptr; 239 240 // Get the corresponding buffer. 241 bool Invalid = false; 242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 243 &Invalid).data(); 244 if (Invalid) 245 return nullptr; 246 247 // Extract text between the comment and declaration. 248 StringRef Text(Buffer + CommentEndDecomp.second, 249 DeclLocDecomp.second - CommentEndDecomp.second); 250 251 // There should be no other declarations or preprocessor directives between 252 // comment and declaration. 253 if (Text.find_first_of(";{}#@") != StringRef::npos) 254 return nullptr; 255 256 return *Comment; 257 } 258 259 namespace { 260 /// If we have a 'templated' declaration for a template, adjust 'D' to 261 /// refer to the actual template. 262 /// If we have an implicit instantiation, adjust 'D' to refer to template. 263 const Decl *adjustDeclToTemplate(const Decl *D) { 264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 265 // Is this function declaration part of a function template? 266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 267 return FTD; 268 269 // Nothing to do if function is not an implicit instantiation. 270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 271 return D; 272 273 // Function is an implicit instantiation of a function template? 274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 275 return FTD; 276 277 // Function is instantiated from a member definition of a class template? 278 if (const FunctionDecl *MemberDecl = 279 FD->getInstantiatedFromMemberFunction()) 280 return MemberDecl; 281 282 return D; 283 } 284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 285 // Static data member is instantiated from a member definition of a class 286 // template? 287 if (VD->isStaticDataMember()) 288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 289 return MemberDecl; 290 291 return D; 292 } 293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 294 // Is this class declaration part of a class template? 295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 296 return CTD; 297 298 // Class is an implicit instantiation of a class template or partial 299 // specialization? 300 if (const ClassTemplateSpecializationDecl *CTSD = 301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 303 return D; 304 llvm::PointerUnion<ClassTemplateDecl *, 305 ClassTemplatePartialSpecializationDecl *> 306 PU = CTSD->getSpecializedTemplateOrPartial(); 307 return PU.is<ClassTemplateDecl*>() ? 308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) : 309 static_cast<const Decl*>( 310 PU.get<ClassTemplatePartialSpecializationDecl *>()); 311 } 312 313 // Class is instantiated from a member definition of a class template? 314 if (const MemberSpecializationInfo *Info = 315 CRD->getMemberSpecializationInfo()) 316 return Info->getInstantiatedFrom(); 317 318 return D; 319 } 320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 321 // Enum is instantiated from a member definition of a class template? 322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 323 return MemberDecl; 324 325 return D; 326 } 327 // FIXME: Adjust alias templates? 328 return D; 329 } 330 } // anonymous namespace 331 332 const RawComment *ASTContext::getRawCommentForAnyRedecl( 333 const Decl *D, 334 const Decl **OriginalDecl) const { 335 D = adjustDeclToTemplate(D); 336 337 // Check whether we have cached a comment for this declaration already. 338 { 339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 340 RedeclComments.find(D); 341 if (Pos != RedeclComments.end()) { 342 const RawCommentAndCacheFlags &Raw = Pos->second; 343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 344 if (OriginalDecl) 345 *OriginalDecl = Raw.getOriginalDecl(); 346 return Raw.getRaw(); 347 } 348 } 349 } 350 351 // Search for comments attached to declarations in the redeclaration chain. 352 const RawComment *RC = nullptr; 353 const Decl *OriginalDeclForRC = nullptr; 354 for (auto I : D->redecls()) { 355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 356 RedeclComments.find(I); 357 if (Pos != RedeclComments.end()) { 358 const RawCommentAndCacheFlags &Raw = Pos->second; 359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 360 RC = Raw.getRaw(); 361 OriginalDeclForRC = Raw.getOriginalDecl(); 362 break; 363 } 364 } else { 365 RC = getRawCommentForDeclNoCache(I); 366 OriginalDeclForRC = I; 367 RawCommentAndCacheFlags Raw; 368 if (RC) { 369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32) 370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530 371 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 372 Raw.setRaw(RC); 373 } else 374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 375 Raw.setOriginalDecl(I); 376 RedeclComments[I] = Raw; 377 if (RC) 378 break; 379 } 380 } 381 382 // If we found a comment, it should be a documentation comment. 383 assert(!RC || RC->isDocumentation()); 384 385 if (OriginalDecl) 386 *OriginalDecl = OriginalDeclForRC; 387 388 // Update cache for every declaration in the redeclaration chain. 389 RawCommentAndCacheFlags Raw; 390 Raw.setRaw(RC); 391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 392 Raw.setOriginalDecl(OriginalDeclForRC); 393 394 for (auto I : D->redecls()) { 395 RawCommentAndCacheFlags &R = RedeclComments[I]; 396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 397 R = Raw; 398 } 399 400 return RC; 401 } 402 403 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 404 SmallVectorImpl<const NamedDecl *> &Redeclared) { 405 const DeclContext *DC = ObjCMethod->getDeclContext(); 406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) { 407 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 408 if (!ID) 409 return; 410 // Add redeclared method here. 411 for (const auto *Ext : ID->known_extensions()) { 412 if (ObjCMethodDecl *RedeclaredMethod = 413 Ext->getMethod(ObjCMethod->getSelector(), 414 ObjCMethod->isInstanceMethod())) 415 Redeclared.push_back(RedeclaredMethod); 416 } 417 } 418 } 419 420 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 421 const Decl *D) const { 422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo; 423 ThisDeclInfo->CommentDecl = D; 424 ThisDeclInfo->IsFilled = false; 425 ThisDeclInfo->fill(); 426 ThisDeclInfo->CommentDecl = FC->getDecl(); 427 if (!ThisDeclInfo->TemplateParameters) 428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 429 comments::FullComment *CFC = 430 new (*this) comments::FullComment(FC->getBlocks(), 431 ThisDeclInfo); 432 return CFC; 433 } 434 435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 436 const RawComment *RC = getRawCommentForDeclNoCache(D); 437 return RC ? RC->parse(*this, nullptr, D) : nullptr; 438 } 439 440 comments::FullComment *ASTContext::getCommentForDecl( 441 const Decl *D, 442 const Preprocessor *PP) const { 443 if (D->isInvalidDecl()) 444 return nullptr; 445 D = adjustDeclToTemplate(D); 446 447 const Decl *Canonical = D->getCanonicalDecl(); 448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 449 ParsedComments.find(Canonical); 450 451 if (Pos != ParsedComments.end()) { 452 if (Canonical != D) { 453 comments::FullComment *FC = Pos->second; 454 comments::FullComment *CFC = cloneFullComment(FC, D); 455 return CFC; 456 } 457 return Pos->second; 458 } 459 460 const Decl *OriginalDecl; 461 462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 463 if (!RC) { 464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 465 SmallVector<const NamedDecl*, 8> Overridden; 466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D); 467 if (OMD && OMD->isPropertyAccessor()) 468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 470 return cloneFullComment(FC, D); 471 if (OMD) 472 addRedeclaredMethods(OMD, Overridden); 473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 474 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 476 return cloneFullComment(FC, D); 477 } 478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 479 // Attach any tag type's documentation to its typedef if latter 480 // does not have one of its own. 481 QualType QT = TD->getUnderlyingType(); 482 if (const TagType *TT = QT->getAs<TagType>()) 483 if (const Decl *TD = TT->getDecl()) 484 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 485 return cloneFullComment(FC, D); 486 } 487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 488 while (IC->getSuperClass()) { 489 IC = IC->getSuperClass(); 490 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 491 return cloneFullComment(FC, D); 492 } 493 } 494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { 495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 496 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 497 return cloneFullComment(FC, D); 498 } 499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 500 if (!(RD = RD->getDefinition())) 501 return nullptr; 502 // Check non-virtual bases. 503 for (const auto &I : RD->bases()) { 504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 505 continue; 506 QualType Ty = I.getType(); 507 if (Ty.isNull()) 508 continue; 509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 510 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 511 continue; 512 513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 514 return cloneFullComment(FC, D); 515 } 516 } 517 // Check virtual bases. 518 for (const auto &I : RD->vbases()) { 519 if (I.getAccessSpecifier() != AS_public) 520 continue; 521 QualType Ty = I.getType(); 522 if (Ty.isNull()) 523 continue; 524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 525 if (!(VirtualBase= VirtualBase->getDefinition())) 526 continue; 527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 528 return cloneFullComment(FC, D); 529 } 530 } 531 } 532 return nullptr; 533 } 534 535 // If the RawComment was attached to other redeclaration of this Decl, we 536 // should parse the comment in context of that other Decl. This is important 537 // because comments can contain references to parameter names which can be 538 // different across redeclarations. 539 if (D != OriginalDecl) 540 return getCommentForDecl(OriginalDecl, PP); 541 542 comments::FullComment *FC = RC->parse(*this, PP, D); 543 ParsedComments[Canonical] = FC; 544 return FC; 545 } 546 547 void 548 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 549 TemplateTemplateParmDecl *Parm) { 550 ID.AddInteger(Parm->getDepth()); 551 ID.AddInteger(Parm->getPosition()); 552 ID.AddBoolean(Parm->isParameterPack()); 553 554 TemplateParameterList *Params = Parm->getTemplateParameters(); 555 ID.AddInteger(Params->size()); 556 for (TemplateParameterList::const_iterator P = Params->begin(), 557 PEnd = Params->end(); 558 P != PEnd; ++P) { 559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 560 ID.AddInteger(0); 561 ID.AddBoolean(TTP->isParameterPack()); 562 continue; 563 } 564 565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 566 ID.AddInteger(1); 567 ID.AddBoolean(NTTP->isParameterPack()); 568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 569 if (NTTP->isExpandedParameterPack()) { 570 ID.AddBoolean(true); 571 ID.AddInteger(NTTP->getNumExpansionTypes()); 572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 573 QualType T = NTTP->getExpansionType(I); 574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 575 } 576 } else 577 ID.AddBoolean(false); 578 continue; 579 } 580 581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 582 ID.AddInteger(2); 583 Profile(ID, TTP); 584 } 585 } 586 587 TemplateTemplateParmDecl * 588 ASTContext::getCanonicalTemplateTemplateParmDecl( 589 TemplateTemplateParmDecl *TTP) const { 590 // Check if we already have a canonical template template parameter. 591 llvm::FoldingSetNodeID ID; 592 CanonicalTemplateTemplateParm::Profile(ID, TTP); 593 void *InsertPos = nullptr; 594 CanonicalTemplateTemplateParm *Canonical 595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 596 if (Canonical) 597 return Canonical->getParam(); 598 599 // Build a canonical template parameter list. 600 TemplateParameterList *Params = TTP->getTemplateParameters(); 601 SmallVector<NamedDecl *, 4> CanonParams; 602 CanonParams.reserve(Params->size()); 603 for (TemplateParameterList::const_iterator P = Params->begin(), 604 PEnd = Params->end(); 605 P != PEnd; ++P) { 606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 607 CanonParams.push_back( 608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 609 SourceLocation(), 610 SourceLocation(), 611 TTP->getDepth(), 612 TTP->getIndex(), nullptr, false, 613 TTP->isParameterPack())); 614 else if (NonTypeTemplateParmDecl *NTTP 615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 616 QualType T = getCanonicalType(NTTP->getType()); 617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 618 NonTypeTemplateParmDecl *Param; 619 if (NTTP->isExpandedParameterPack()) { 620 SmallVector<QualType, 2> ExpandedTypes; 621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 624 ExpandedTInfos.push_back( 625 getTrivialTypeSourceInfo(ExpandedTypes.back())); 626 } 627 628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 629 SourceLocation(), 630 SourceLocation(), 631 NTTP->getDepth(), 632 NTTP->getPosition(), nullptr, 633 T, 634 TInfo, 635 ExpandedTypes, 636 ExpandedTInfos); 637 } else { 638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 639 SourceLocation(), 640 SourceLocation(), 641 NTTP->getDepth(), 642 NTTP->getPosition(), nullptr, 643 T, 644 NTTP->isParameterPack(), 645 TInfo); 646 } 647 CanonParams.push_back(Param); 648 649 } else 650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 651 cast<TemplateTemplateParmDecl>(*P))); 652 } 653 654 assert(!TTP->getRequiresClause() && 655 "Unexpected requires-clause on template template-parameter"); 656 Expr *const CanonRequiresClause = nullptr; 657 658 TemplateTemplateParmDecl *CanonTTP 659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 660 SourceLocation(), TTP->getDepth(), 661 TTP->getPosition(), 662 TTP->isParameterPack(), 663 nullptr, 664 TemplateParameterList::Create(*this, SourceLocation(), 665 SourceLocation(), 666 CanonParams, 667 SourceLocation(), 668 CanonRequiresClause)); 669 670 // Get the new insert position for the node we care about. 671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 672 assert(!Canonical && "Shouldn't be in the map!"); 673 (void)Canonical; 674 675 // Create the canonical template template parameter entry. 676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 678 return CanonTTP; 679 } 680 681 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 682 if (!LangOpts.CPlusPlus) return nullptr; 683 684 switch (T.getCXXABI().getKind()) { 685 case TargetCXXABI::GenericARM: // Same as Itanium at this level 686 case TargetCXXABI::iOS: 687 case TargetCXXABI::iOS64: 688 case TargetCXXABI::WatchOS: 689 case TargetCXXABI::GenericAArch64: 690 case TargetCXXABI::GenericMIPS: 691 case TargetCXXABI::GenericItanium: 692 case TargetCXXABI::WebAssembly: 693 return CreateItaniumCXXABI(*this); 694 case TargetCXXABI::Microsoft: 695 return CreateMicrosoftCXXABI(*this); 696 } 697 llvm_unreachable("Invalid CXXABI type!"); 698 } 699 700 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 701 const LangOptions &LOpts) { 702 if (LOpts.FakeAddressSpaceMap) { 703 // The fake address space map must have a distinct entry for each 704 // language-specific address space. 705 static const unsigned FakeAddrSpaceMap[] = { 706 1, // opencl_global 707 2, // opencl_local 708 3, // opencl_constant 709 4, // opencl_generic 710 5, // cuda_device 711 6, // cuda_constant 712 7 // cuda_shared 713 }; 714 return &FakeAddrSpaceMap; 715 } else { 716 return &T.getAddressSpaceMap(); 717 } 718 } 719 720 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 721 const LangOptions &LangOpts) { 722 switch (LangOpts.getAddressSpaceMapMangling()) { 723 case LangOptions::ASMM_Target: 724 return TI.useAddressSpaceMapMangling(); 725 case LangOptions::ASMM_On: 726 return true; 727 case LangOptions::ASMM_Off: 728 return false; 729 } 730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 731 } 732 733 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 734 IdentifierTable &idents, SelectorTable &sels, 735 Builtin::Context &builtins) 736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), 737 DependentTemplateSpecializationTypes(this_()), 738 SubstTemplateTemplateParmPacks(this_()), 739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr), 740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr), 741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), 742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr), 743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr), 744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr), 745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr), 746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr), 747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(), 748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr), 749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts), 750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr), 752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr), 754 Listener(nullptr), Comments(SM), CommentsLoaded(false), 755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) { 756 TUDecl = TranslationUnitDecl::Create(*this); 757 } 758 759 ASTContext::~ASTContext() { 760 ReleaseParentMapEntries(); 761 762 // Release the DenseMaps associated with DeclContext objects. 763 // FIXME: Is this the ideal solution? 764 ReleaseDeclContextMaps(); 765 766 // Call all of the deallocation functions on all of their targets. 767 for (auto &Pair : Deallocations) 768 (Pair.first)(Pair.second); 769 770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 771 // because they can contain DenseMaps. 772 for (llvm::DenseMap<const ObjCContainerDecl*, 773 const ASTRecordLayout*>::iterator 774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 775 // Increment in loop to prevent using deallocated memory. 776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 777 R->Destroy(*this); 778 779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 781 // Increment in loop to prevent using deallocated memory. 782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 783 R->Destroy(*this); 784 } 785 786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 787 AEnd = DeclAttrs.end(); 788 A != AEnd; ++A) 789 A->second->~AttrVec(); 790 791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair : 792 MaterializedTemporaryValues) 793 MTVPair.second->~APValue(); 794 795 for (const auto &Value : ModuleInitializers) 796 Value.second->~PerModuleInitializers(); 797 } 798 799 void ASTContext::ReleaseParentMapEntries() { 800 if (!PointerParents) return; 801 for (const auto &Entry : *PointerParents) { 802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 803 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 804 } else if (Entry.second.is<ParentVector *>()) { 805 delete Entry.second.get<ParentVector *>(); 806 } 807 } 808 for (const auto &Entry : *OtherParents) { 809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 810 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 811 } else if (Entry.second.is<ParentVector *>()) { 812 delete Entry.second.get<ParentVector *>(); 813 } 814 } 815 } 816 817 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 818 Deallocations.push_back({Callback, Data}); 819 } 820 821 void 822 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 823 ExternalSource = std::move(Source); 824 } 825 826 void ASTContext::PrintStats() const { 827 llvm::errs() << "\n*** AST Context Stats:\n"; 828 llvm::errs() << " " << Types.size() << " types total.\n"; 829 830 unsigned counts[] = { 831 #define TYPE(Name, Parent) 0, 832 #define ABSTRACT_TYPE(Name, Parent) 833 #include "clang/AST/TypeNodes.def" 834 0 // Extra 835 }; 836 837 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 838 Type *T = Types[i]; 839 counts[(unsigned)T->getTypeClass()]++; 840 } 841 842 unsigned Idx = 0; 843 unsigned TotalBytes = 0; 844 #define TYPE(Name, Parent) \ 845 if (counts[Idx]) \ 846 llvm::errs() << " " << counts[Idx] << " " << #Name \ 847 << " types\n"; \ 848 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 849 ++Idx; 850 #define ABSTRACT_TYPE(Name, Parent) 851 #include "clang/AST/TypeNodes.def" 852 853 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 854 855 // Implicit special member functions. 856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 857 << NumImplicitDefaultConstructors 858 << " implicit default constructors created\n"; 859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 860 << NumImplicitCopyConstructors 861 << " implicit copy constructors created\n"; 862 if (getLangOpts().CPlusPlus) 863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 864 << NumImplicitMoveConstructors 865 << " implicit move constructors created\n"; 866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 867 << NumImplicitCopyAssignmentOperators 868 << " implicit copy assignment operators created\n"; 869 if (getLangOpts().CPlusPlus) 870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 871 << NumImplicitMoveAssignmentOperators 872 << " implicit move assignment operators created\n"; 873 llvm::errs() << NumImplicitDestructorsDeclared << "/" 874 << NumImplicitDestructors 875 << " implicit destructors created\n"; 876 877 if (ExternalSource) { 878 llvm::errs() << "\n"; 879 ExternalSource->PrintStats(); 880 } 881 882 BumpAlloc.PrintStats(); 883 } 884 885 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 886 bool NotifyListeners) { 887 if (NotifyListeners) 888 if (auto *Listener = getASTMutationListener()) 889 Listener->RedefinedHiddenDefinition(ND, M); 890 891 if (getLangOpts().ModulesLocalVisibility) 892 MergedDefModules[ND].push_back(M); 893 else 894 ND->setHidden(false); 895 } 896 897 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 898 auto It = MergedDefModules.find(ND); 899 if (It == MergedDefModules.end()) 900 return; 901 902 auto &Merged = It->second; 903 llvm::DenseSet<Module*> Found; 904 for (Module *&M : Merged) 905 if (!Found.insert(M).second) 906 M = nullptr; 907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 908 } 909 910 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 911 if (LazyInitializers.empty()) 912 return; 913 914 auto *Source = Ctx.getExternalSource(); 915 assert(Source && "lazy initializers but no external source"); 916 917 auto LazyInits = std::move(LazyInitializers); 918 LazyInitializers.clear(); 919 920 for (auto ID : LazyInits) 921 Initializers.push_back(Source->GetExternalDecl(ID)); 922 923 assert(LazyInitializers.empty() && 924 "GetExternalDecl for lazy module initializer added more inits"); 925 } 926 927 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 928 // One special case: if we add a module initializer that imports another 929 // module, and that module's only initializer is an ImportDecl, simplify. 930 if (auto *ID = dyn_cast<ImportDecl>(D)) { 931 auto It = ModuleInitializers.find(ID->getImportedModule()); 932 933 // Maybe the ImportDecl does nothing at all. (Common case.) 934 if (It == ModuleInitializers.end()) 935 return; 936 937 // Maybe the ImportDecl only imports another ImportDecl. 938 auto &Imported = *It->second; 939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 940 Imported.resolve(*this); 941 auto *OnlyDecl = Imported.Initializers.front(); 942 if (isa<ImportDecl>(OnlyDecl)) 943 D = OnlyDecl; 944 } 945 } 946 947 auto *&Inits = ModuleInitializers[M]; 948 if (!Inits) 949 Inits = new (*this) PerModuleInitializers; 950 Inits->Initializers.push_back(D); 951 } 952 953 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 954 auto *&Inits = ModuleInitializers[M]; 955 if (!Inits) 956 Inits = new (*this) PerModuleInitializers; 957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 958 IDs.begin(), IDs.end()); 959 } 960 961 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) { 962 auto It = ModuleInitializers.find(M); 963 if (It == ModuleInitializers.end()) 964 return None; 965 966 auto *Inits = It->second; 967 Inits->resolve(*this); 968 return Inits->Initializers; 969 } 970 971 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 972 if (!ExternCContext) 973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 974 975 return ExternCContext; 976 } 977 978 BuiltinTemplateDecl * 979 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 980 const IdentifierInfo *II) const { 981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 982 BuiltinTemplate->setImplicit(); 983 TUDecl->addDecl(BuiltinTemplate); 984 985 return BuiltinTemplate; 986 } 987 988 BuiltinTemplateDecl * 989 ASTContext::getMakeIntegerSeqDecl() const { 990 if (!MakeIntegerSeqDecl) 991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 992 getMakeIntegerSeqName()); 993 return MakeIntegerSeqDecl; 994 } 995 996 BuiltinTemplateDecl * 997 ASTContext::getTypePackElementDecl() const { 998 if (!TypePackElementDecl) 999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1000 getTypePackElementName()); 1001 return TypePackElementDecl; 1002 } 1003 1004 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1005 RecordDecl::TagKind TK) const { 1006 SourceLocation Loc; 1007 RecordDecl *NewDecl; 1008 if (getLangOpts().CPlusPlus) 1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1010 Loc, &Idents.get(Name)); 1011 else 1012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1013 &Idents.get(Name)); 1014 NewDecl->setImplicit(); 1015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1017 return NewDecl; 1018 } 1019 1020 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1021 StringRef Name) const { 1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1023 TypedefDecl *NewDecl = TypedefDecl::Create( 1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1026 NewDecl->setImplicit(); 1027 return NewDecl; 1028 } 1029 1030 TypedefDecl *ASTContext::getInt128Decl() const { 1031 if (!Int128Decl) 1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1033 return Int128Decl; 1034 } 1035 1036 TypedefDecl *ASTContext::getUInt128Decl() const { 1037 if (!UInt128Decl) 1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1039 return UInt128Decl; 1040 } 1041 1042 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 1044 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1045 Types.push_back(Ty); 1046 } 1047 1048 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1049 const TargetInfo *AuxTarget) { 1050 assert((!this->Target || this->Target == &Target) && 1051 "Incorrect target reinitialization"); 1052 assert(VoidTy.isNull() && "Context reinitialized?"); 1053 1054 this->Target = &Target; 1055 this->AuxTarget = AuxTarget; 1056 1057 ABI.reset(createCXXABI(Target)); 1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1060 1061 // C99 6.2.5p19. 1062 InitBuiltinType(VoidTy, BuiltinType::Void); 1063 1064 // C99 6.2.5p2. 1065 InitBuiltinType(BoolTy, BuiltinType::Bool); 1066 // C99 6.2.5p3. 1067 if (LangOpts.CharIsSigned) 1068 InitBuiltinType(CharTy, BuiltinType::Char_S); 1069 else 1070 InitBuiltinType(CharTy, BuiltinType::Char_U); 1071 // C99 6.2.5p4. 1072 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1073 InitBuiltinType(ShortTy, BuiltinType::Short); 1074 InitBuiltinType(IntTy, BuiltinType::Int); 1075 InitBuiltinType(LongTy, BuiltinType::Long); 1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1077 1078 // C99 6.2.5p6. 1079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1084 1085 // C99 6.2.5p10. 1086 InitBuiltinType(FloatTy, BuiltinType::Float); 1087 InitBuiltinType(DoubleTy, BuiltinType::Double); 1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1089 1090 // GNU extension, __float128 for IEEE quadruple precision 1091 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1092 1093 // GNU extension, 128-bit integers. 1094 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1096 1097 // C++ 3.9.1p5 1098 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1100 else // -fshort-wchar makes wchar_t be unsigned. 1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1102 if (LangOpts.CPlusPlus && LangOpts.WChar) 1103 WideCharTy = WCharTy; 1104 else { 1105 // C99 (or C++ using -fno-wchar). 1106 WideCharTy = getFromTargetType(Target.getWCharType()); 1107 } 1108 1109 WIntTy = getFromTargetType(Target.getWIntType()); 1110 1111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1112 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1113 else // C99 1114 Char16Ty = getFromTargetType(Target.getChar16Type()); 1115 1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1117 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1118 else // C99 1119 Char32Ty = getFromTargetType(Target.getChar32Type()); 1120 1121 // Placeholder type for type-dependent expressions whose type is 1122 // completely unknown. No code should ever check a type against 1123 // DependentTy and users should never see it; however, it is here to 1124 // help diagnose failures to properly check for type-dependent 1125 // expressions. 1126 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1127 1128 // Placeholder type for functions. 1129 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1130 1131 // Placeholder type for bound members. 1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1133 1134 // Placeholder type for pseudo-objects. 1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1136 1137 // "any" type; useful for debugger-like clients. 1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1139 1140 // Placeholder type for unbridged ARC casts. 1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1142 1143 // Placeholder type for builtin functions. 1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1145 1146 // Placeholder type for OMP array sections. 1147 if (LangOpts.OpenMP) 1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1149 1150 // C99 6.2.5p11. 1151 FloatComplexTy = getComplexType(FloatTy); 1152 DoubleComplexTy = getComplexType(DoubleTy); 1153 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1154 Float128ComplexTy = getComplexType(Float128Ty); 1155 1156 // Builtin types for 'id', 'Class', and 'SEL'. 1157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1160 1161 if (LangOpts.OpenCL) { 1162 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1163 InitBuiltinType(SingletonId, BuiltinType::Id); 1164 #include "clang/Basic/OpenCLImageTypes.def" 1165 1166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange); 1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1172 } 1173 1174 // Builtin type for __objc_yes and __objc_no 1175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1176 SignedCharTy : BoolTy); 1177 1178 ObjCConstantStringType = QualType(); 1179 1180 ObjCSuperType = QualType(); 1181 1182 // void * type 1183 VoidPtrTy = getPointerType(VoidTy); 1184 1185 // nullptr type (C++0x 2.14.7) 1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1187 1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1189 InitBuiltinType(HalfTy, BuiltinType::Half); 1190 1191 // Builtin type used to help define __builtin_va_list. 1192 VaListTagDecl = nullptr; 1193 } 1194 1195 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1196 return SourceMgr.getDiagnostics(); 1197 } 1198 1199 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1200 AttrVec *&Result = DeclAttrs[D]; 1201 if (!Result) { 1202 void *Mem = Allocate(sizeof(AttrVec)); 1203 Result = new (Mem) AttrVec; 1204 } 1205 1206 return *Result; 1207 } 1208 1209 /// \brief Erase the attributes corresponding to the given declaration. 1210 void ASTContext::eraseDeclAttrs(const Decl *D) { 1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1212 if (Pos != DeclAttrs.end()) { 1213 Pos->second->~AttrVec(); 1214 DeclAttrs.erase(Pos); 1215 } 1216 } 1217 1218 // FIXME: Remove ? 1219 MemberSpecializationInfo * 1220 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1221 assert(Var->isStaticDataMember() && "Not a static data member"); 1222 return getTemplateOrSpecializationInfo(Var) 1223 .dyn_cast<MemberSpecializationInfo *>(); 1224 } 1225 1226 ASTContext::TemplateOrSpecializationInfo 1227 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1229 TemplateOrInstantiation.find(Var); 1230 if (Pos == TemplateOrInstantiation.end()) 1231 return TemplateOrSpecializationInfo(); 1232 1233 return Pos->second; 1234 } 1235 1236 void 1237 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1238 TemplateSpecializationKind TSK, 1239 SourceLocation PointOfInstantiation) { 1240 assert(Inst->isStaticDataMember() && "Not a static data member"); 1241 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1243 Tmpl, TSK, PointOfInstantiation)); 1244 } 1245 1246 void 1247 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1248 TemplateOrSpecializationInfo TSI) { 1249 assert(!TemplateOrInstantiation[Inst] && 1250 "Already noted what the variable was instantiated from"); 1251 TemplateOrInstantiation[Inst] = TSI; 1252 } 1253 1254 FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1255 const FunctionDecl *FD){ 1256 assert(FD && "Specialization is 0"); 1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1258 = ClassScopeSpecializationPattern.find(FD); 1259 if (Pos == ClassScopeSpecializationPattern.end()) 1260 return nullptr; 1261 1262 return Pos->second; 1263 } 1264 1265 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1266 FunctionDecl *Pattern) { 1267 assert(FD && "Specialization is 0"); 1268 assert(Pattern && "Class scope specialization pattern is 0"); 1269 ClassScopeSpecializationPattern[FD] = Pattern; 1270 } 1271 1272 NamedDecl * 1273 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 1274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 1275 = InstantiatedFromUsingDecl.find(UUD); 1276 if (Pos == InstantiatedFromUsingDecl.end()) 1277 return nullptr; 1278 1279 return Pos->second; 1280 } 1281 1282 void 1283 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 1284 assert((isa<UsingDecl>(Pattern) || 1285 isa<UnresolvedUsingValueDecl>(Pattern) || 1286 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1287 "pattern decl is not a using decl"); 1288 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1289 InstantiatedFromUsingDecl[Inst] = Pattern; 1290 } 1291 1292 UsingShadowDecl * 1293 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1294 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1295 = InstantiatedFromUsingShadowDecl.find(Inst); 1296 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1297 return nullptr; 1298 1299 return Pos->second; 1300 } 1301 1302 void 1303 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1304 UsingShadowDecl *Pattern) { 1305 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1306 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1307 } 1308 1309 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1310 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1311 = InstantiatedFromUnnamedFieldDecl.find(Field); 1312 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1313 return nullptr; 1314 1315 return Pos->second; 1316 } 1317 1318 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1319 FieldDecl *Tmpl) { 1320 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1321 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1322 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1323 "Already noted what unnamed field was instantiated from"); 1324 1325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1326 } 1327 1328 ASTContext::overridden_cxx_method_iterator 1329 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1330 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1331 OverriddenMethods.find(Method->getCanonicalDecl()); 1332 if (Pos == OverriddenMethods.end()) 1333 return nullptr; 1334 return Pos->second.begin(); 1335 } 1336 1337 ASTContext::overridden_cxx_method_iterator 1338 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1339 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1340 OverriddenMethods.find(Method->getCanonicalDecl()); 1341 if (Pos == OverriddenMethods.end()) 1342 return nullptr; 1343 return Pos->second.end(); 1344 } 1345 1346 unsigned 1347 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1348 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1349 OverriddenMethods.find(Method->getCanonicalDecl()); 1350 if (Pos == OverriddenMethods.end()) 1351 return 0; 1352 return Pos->second.size(); 1353 } 1354 1355 ASTContext::overridden_method_range 1356 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1357 return overridden_method_range(overridden_methods_begin(Method), 1358 overridden_methods_end(Method)); 1359 } 1360 1361 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1362 const CXXMethodDecl *Overridden) { 1363 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1364 OverriddenMethods[Method].push_back(Overridden); 1365 } 1366 1367 void ASTContext::getOverriddenMethods( 1368 const NamedDecl *D, 1369 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1370 assert(D); 1371 1372 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1373 Overridden.append(overridden_methods_begin(CXXMethod), 1374 overridden_methods_end(CXXMethod)); 1375 return; 1376 } 1377 1378 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 1379 if (!Method) 1380 return; 1381 1382 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1383 Method->getOverriddenMethods(OverDecls); 1384 Overridden.append(OverDecls.begin(), OverDecls.end()); 1385 } 1386 1387 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1388 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1389 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1390 if (!FirstLocalImport) { 1391 FirstLocalImport = Import; 1392 LastLocalImport = Import; 1393 return; 1394 } 1395 1396 LastLocalImport->NextLocalImport = Import; 1397 LastLocalImport = Import; 1398 } 1399 1400 //===----------------------------------------------------------------------===// 1401 // Type Sizing and Analysis 1402 //===----------------------------------------------------------------------===// 1403 1404 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1405 /// scalar floating point type. 1406 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1407 const BuiltinType *BT = T->getAs<BuiltinType>(); 1408 assert(BT && "Not a floating point type!"); 1409 switch (BT->getKind()) { 1410 default: llvm_unreachable("Not a floating point type!"); 1411 case BuiltinType::Half: return Target->getHalfFormat(); 1412 case BuiltinType::Float: return Target->getFloatFormat(); 1413 case BuiltinType::Double: return Target->getDoubleFormat(); 1414 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1415 case BuiltinType::Float128: return Target->getFloat128Format(); 1416 } 1417 } 1418 1419 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1420 unsigned Align = Target->getCharWidth(); 1421 1422 bool UseAlignAttrOnly = false; 1423 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1424 Align = AlignFromAttr; 1425 1426 // __attribute__((aligned)) can increase or decrease alignment 1427 // *except* on a struct or struct member, where it only increases 1428 // alignment unless 'packed' is also specified. 1429 // 1430 // It is an error for alignas to decrease alignment, so we can 1431 // ignore that possibility; Sema should diagnose it. 1432 if (isa<FieldDecl>(D)) { 1433 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1434 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1435 } else { 1436 UseAlignAttrOnly = true; 1437 } 1438 } 1439 else if (isa<FieldDecl>(D)) 1440 UseAlignAttrOnly = 1441 D->hasAttr<PackedAttr>() || 1442 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1443 1444 // If we're using the align attribute only, just ignore everything 1445 // else about the declaration and its type. 1446 if (UseAlignAttrOnly) { 1447 // do nothing 1448 1449 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1450 QualType T = VD->getType(); 1451 if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 1452 if (ForAlignof) 1453 T = RT->getPointeeType(); 1454 else 1455 T = getPointerType(RT->getPointeeType()); 1456 } 1457 QualType BaseT = getBaseElementType(T); 1458 if (!BaseT->isIncompleteType() && !T->isFunctionType()) { 1459 // Adjust alignments of declarations with array type by the 1460 // large-array alignment on the target. 1461 if (const ArrayType *arrayType = getAsArrayType(T)) { 1462 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1463 if (!ForAlignof && MinWidth) { 1464 if (isa<VariableArrayType>(arrayType)) 1465 Align = std::max(Align, Target->getLargeArrayAlign()); 1466 else if (isa<ConstantArrayType>(arrayType) && 1467 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1468 Align = std::max(Align, Target->getLargeArrayAlign()); 1469 } 1470 } 1471 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1472 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1473 if (VD->hasGlobalStorage() && !ForAlignof) 1474 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1475 } 1476 } 1477 1478 // Fields can be subject to extra alignment constraints, like if 1479 // the field is packed, the struct is packed, or the struct has a 1480 // a max-field-alignment constraint (#pragma pack). So calculate 1481 // the actual alignment of the field within the struct, and then 1482 // (as we're expected to) constrain that by the alignment of the type. 1483 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 1484 const RecordDecl *Parent = Field->getParent(); 1485 // We can only produce a sensible answer if the record is valid. 1486 if (!Parent->isInvalidDecl()) { 1487 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1488 1489 // Start with the record's overall alignment. 1490 unsigned FieldAlign = toBits(Layout.getAlignment()); 1491 1492 // Use the GCD of that and the offset within the record. 1493 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1494 if (Offset > 0) { 1495 // Alignment is always a power of 2, so the GCD will be a power of 2, 1496 // which means we get to do this crazy thing instead of Euclid's. 1497 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1498 if (LowBitOfOffset < FieldAlign) 1499 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1500 } 1501 1502 Align = std::min(Align, FieldAlign); 1503 } 1504 } 1505 } 1506 1507 return toCharUnitsFromBits(Align); 1508 } 1509 1510 // getTypeInfoDataSizeInChars - Return the size of a type, in 1511 // chars. If the type is a record, its data size is returned. This is 1512 // the size of the memcpy that's performed when assigning this type 1513 // using a trivial copy/move assignment operator. 1514 std::pair<CharUnits, CharUnits> 1515 ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1516 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1517 1518 // In C++, objects can sometimes be allocated into the tail padding 1519 // of a base-class subobject. We decide whether that's possible 1520 // during class layout, so here we can just trust the layout results. 1521 if (getLangOpts().CPlusPlus) { 1522 if (const RecordType *RT = T->getAs<RecordType>()) { 1523 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1524 sizeAndAlign.first = layout.getDataSize(); 1525 } 1526 } 1527 1528 return sizeAndAlign; 1529 } 1530 1531 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1532 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1533 std::pair<CharUnits, CharUnits> 1534 static getConstantArrayInfoInChars(const ASTContext &Context, 1535 const ConstantArrayType *CAT) { 1536 std::pair<CharUnits, CharUnits> EltInfo = 1537 Context.getTypeInfoInChars(CAT->getElementType()); 1538 uint64_t Size = CAT->getSize().getZExtValue(); 1539 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1540 (uint64_t)(-1)/Size) && 1541 "Overflow in array type char size evaluation"); 1542 uint64_t Width = EltInfo.first.getQuantity() * Size; 1543 unsigned Align = EltInfo.second.getQuantity(); 1544 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1545 Context.getTargetInfo().getPointerWidth(0) == 64) 1546 Width = llvm::alignTo(Width, Align); 1547 return std::make_pair(CharUnits::fromQuantity(Width), 1548 CharUnits::fromQuantity(Align)); 1549 } 1550 1551 std::pair<CharUnits, CharUnits> 1552 ASTContext::getTypeInfoInChars(const Type *T) const { 1553 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) 1554 return getConstantArrayInfoInChars(*this, CAT); 1555 TypeInfo Info = getTypeInfo(T); 1556 return std::make_pair(toCharUnitsFromBits(Info.Width), 1557 toCharUnitsFromBits(Info.Align)); 1558 } 1559 1560 std::pair<CharUnits, CharUnits> 1561 ASTContext::getTypeInfoInChars(QualType T) const { 1562 return getTypeInfoInChars(T.getTypePtr()); 1563 } 1564 1565 bool ASTContext::isAlignmentRequired(const Type *T) const { 1566 return getTypeInfo(T).AlignIsRequired; 1567 } 1568 1569 bool ASTContext::isAlignmentRequired(QualType T) const { 1570 return isAlignmentRequired(T.getTypePtr()); 1571 } 1572 1573 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const { 1574 // An alignment on a typedef overrides anything else. 1575 if (auto *TT = T->getAs<TypedefType>()) 1576 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1577 return Align; 1578 1579 // If we have an (array of) complete type, we're done. 1580 T = getBaseElementType(T); 1581 if (!T->isIncompleteType()) 1582 return getTypeAlign(T); 1583 1584 // If we had an array type, its element type might be a typedef 1585 // type with an alignment attribute. 1586 if (auto *TT = T->getAs<TypedefType>()) 1587 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1588 return Align; 1589 1590 // Otherwise, see if the declaration of the type had an attribute. 1591 if (auto *TT = T->getAs<TagType>()) 1592 return TT->getDecl()->getMaxAlignment(); 1593 1594 return 0; 1595 } 1596 1597 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1598 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1599 if (I != MemoizedTypeInfo.end()) 1600 return I->second; 1601 1602 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1603 TypeInfo TI = getTypeInfoImpl(T); 1604 MemoizedTypeInfo[T] = TI; 1605 return TI; 1606 } 1607 1608 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1609 /// method does not work on incomplete types. 1610 /// 1611 /// FIXME: Pointers into different addr spaces could have different sizes and 1612 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1613 /// should take a QualType, &c. 1614 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1615 uint64_t Width = 0; 1616 unsigned Align = 8; 1617 bool AlignIsRequired = false; 1618 switch (T->getTypeClass()) { 1619 #define TYPE(Class, Base) 1620 #define ABSTRACT_TYPE(Class, Base) 1621 #define NON_CANONICAL_TYPE(Class, Base) 1622 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1623 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1624 case Type::Class: \ 1625 assert(!T->isDependentType() && "should not see dependent types here"); \ 1626 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1627 #include "clang/AST/TypeNodes.def" 1628 llvm_unreachable("Should not see dependent types"); 1629 1630 case Type::FunctionNoProto: 1631 case Type::FunctionProto: 1632 // GCC extension: alignof(function) = 32 bits 1633 Width = 0; 1634 Align = 32; 1635 break; 1636 1637 case Type::IncompleteArray: 1638 case Type::VariableArray: 1639 Width = 0; 1640 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1641 break; 1642 1643 case Type::ConstantArray: { 1644 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1645 1646 TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); 1647 uint64_t Size = CAT->getSize().getZExtValue(); 1648 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1649 "Overflow in array type bit size evaluation"); 1650 Width = EltInfo.Width * Size; 1651 Align = EltInfo.Align; 1652 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1653 getTargetInfo().getPointerWidth(0) == 64) 1654 Width = llvm::alignTo(Width, Align); 1655 break; 1656 } 1657 case Type::ExtVector: 1658 case Type::Vector: { 1659 const VectorType *VT = cast<VectorType>(T); 1660 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1661 Width = EltInfo.Width * VT->getNumElements(); 1662 Align = Width; 1663 // If the alignment is not a power of 2, round up to the next power of 2. 1664 // This happens for non-power-of-2 length vectors. 1665 if (Align & (Align-1)) { 1666 Align = llvm::NextPowerOf2(Align); 1667 Width = llvm::alignTo(Width, Align); 1668 } 1669 // Adjust the alignment based on the target max. 1670 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1671 if (TargetVectorAlign && TargetVectorAlign < Align) 1672 Align = TargetVectorAlign; 1673 break; 1674 } 1675 1676 case Type::Builtin: 1677 switch (cast<BuiltinType>(T)->getKind()) { 1678 default: llvm_unreachable("Unknown builtin type!"); 1679 case BuiltinType::Void: 1680 // GCC extension: alignof(void) = 8 bits. 1681 Width = 0; 1682 Align = 8; 1683 break; 1684 1685 case BuiltinType::Bool: 1686 Width = Target->getBoolWidth(); 1687 Align = Target->getBoolAlign(); 1688 break; 1689 case BuiltinType::Char_S: 1690 case BuiltinType::Char_U: 1691 case BuiltinType::UChar: 1692 case BuiltinType::SChar: 1693 Width = Target->getCharWidth(); 1694 Align = Target->getCharAlign(); 1695 break; 1696 case BuiltinType::WChar_S: 1697 case BuiltinType::WChar_U: 1698 Width = Target->getWCharWidth(); 1699 Align = Target->getWCharAlign(); 1700 break; 1701 case BuiltinType::Char16: 1702 Width = Target->getChar16Width(); 1703 Align = Target->getChar16Align(); 1704 break; 1705 case BuiltinType::Char32: 1706 Width = Target->getChar32Width(); 1707 Align = Target->getChar32Align(); 1708 break; 1709 case BuiltinType::UShort: 1710 case BuiltinType::Short: 1711 Width = Target->getShortWidth(); 1712 Align = Target->getShortAlign(); 1713 break; 1714 case BuiltinType::UInt: 1715 case BuiltinType::Int: 1716 Width = Target->getIntWidth(); 1717 Align = Target->getIntAlign(); 1718 break; 1719 case BuiltinType::ULong: 1720 case BuiltinType::Long: 1721 Width = Target->getLongWidth(); 1722 Align = Target->getLongAlign(); 1723 break; 1724 case BuiltinType::ULongLong: 1725 case BuiltinType::LongLong: 1726 Width = Target->getLongLongWidth(); 1727 Align = Target->getLongLongAlign(); 1728 break; 1729 case BuiltinType::Int128: 1730 case BuiltinType::UInt128: 1731 Width = 128; 1732 Align = 128; // int128_t is 128-bit aligned on all targets. 1733 break; 1734 case BuiltinType::Half: 1735 Width = Target->getHalfWidth(); 1736 Align = Target->getHalfAlign(); 1737 break; 1738 case BuiltinType::Float: 1739 Width = Target->getFloatWidth(); 1740 Align = Target->getFloatAlign(); 1741 break; 1742 case BuiltinType::Double: 1743 Width = Target->getDoubleWidth(); 1744 Align = Target->getDoubleAlign(); 1745 break; 1746 case BuiltinType::LongDouble: 1747 Width = Target->getLongDoubleWidth(); 1748 Align = Target->getLongDoubleAlign(); 1749 break; 1750 case BuiltinType::Float128: 1751 Width = Target->getFloat128Width(); 1752 Align = Target->getFloat128Align(); 1753 break; 1754 case BuiltinType::NullPtr: 1755 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1756 Align = Target->getPointerAlign(0); // == sizeof(void*) 1757 break; 1758 case BuiltinType::ObjCId: 1759 case BuiltinType::ObjCClass: 1760 case BuiltinType::ObjCSel: 1761 Width = Target->getPointerWidth(0); 1762 Align = Target->getPointerAlign(0); 1763 break; 1764 case BuiltinType::OCLSampler: { 1765 auto AS = getTargetAddressSpace(LangAS::opencl_constant); 1766 Width = Target->getPointerWidth(AS); 1767 Align = Target->getPointerAlign(AS); 1768 break; 1769 } 1770 case BuiltinType::OCLEvent: 1771 case BuiltinType::OCLClkEvent: 1772 case BuiltinType::OCLQueue: 1773 case BuiltinType::OCLNDRange: 1774 case BuiltinType::OCLReserveID: 1775 // Currently these types are pointers to opaque types. 1776 Width = Target->getPointerWidth(0); 1777 Align = Target->getPointerAlign(0); 1778 break; 1779 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1780 case BuiltinType::Id: 1781 #include "clang/Basic/OpenCLImageTypes.def" 1782 { 1783 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace()); 1784 Width = Target->getPointerWidth(AS); 1785 Align = Target->getPointerAlign(AS); 1786 } 1787 } 1788 break; 1789 case Type::ObjCObjectPointer: 1790 Width = Target->getPointerWidth(0); 1791 Align = Target->getPointerAlign(0); 1792 break; 1793 case Type::BlockPointer: { 1794 unsigned AS = getTargetAddressSpace( 1795 cast<BlockPointerType>(T)->getPointeeType()); 1796 Width = Target->getPointerWidth(AS); 1797 Align = Target->getPointerAlign(AS); 1798 break; 1799 } 1800 case Type::LValueReference: 1801 case Type::RValueReference: { 1802 // alignof and sizeof should never enter this code path here, so we go 1803 // the pointer route. 1804 unsigned AS = getTargetAddressSpace( 1805 cast<ReferenceType>(T)->getPointeeType()); 1806 Width = Target->getPointerWidth(AS); 1807 Align = Target->getPointerAlign(AS); 1808 break; 1809 } 1810 case Type::Pointer: { 1811 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1812 Width = Target->getPointerWidth(AS); 1813 Align = Target->getPointerAlign(AS); 1814 break; 1815 } 1816 case Type::MemberPointer: { 1817 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1818 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT); 1819 break; 1820 } 1821 case Type::Complex: { 1822 // Complex types have the same alignment as their elements, but twice the 1823 // size. 1824 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 1825 Width = EltInfo.Width * 2; 1826 Align = EltInfo.Align; 1827 break; 1828 } 1829 case Type::ObjCObject: 1830 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1831 case Type::Adjusted: 1832 case Type::Decayed: 1833 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 1834 case Type::ObjCInterface: { 1835 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1836 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1837 Width = toBits(Layout.getSize()); 1838 Align = toBits(Layout.getAlignment()); 1839 break; 1840 } 1841 case Type::Record: 1842 case Type::Enum: { 1843 const TagType *TT = cast<TagType>(T); 1844 1845 if (TT->getDecl()->isInvalidDecl()) { 1846 Width = 8; 1847 Align = 8; 1848 break; 1849 } 1850 1851 if (const EnumType *ET = dyn_cast<EnumType>(TT)) { 1852 const EnumDecl *ED = ET->getDecl(); 1853 TypeInfo Info = 1854 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 1855 if (unsigned AttrAlign = ED->getMaxAlignment()) { 1856 Info.Align = AttrAlign; 1857 Info.AlignIsRequired = true; 1858 } 1859 return Info; 1860 } 1861 1862 const RecordType *RT = cast<RecordType>(TT); 1863 const RecordDecl *RD = RT->getDecl(); 1864 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 1865 Width = toBits(Layout.getSize()); 1866 Align = toBits(Layout.getAlignment()); 1867 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 1868 break; 1869 } 1870 1871 case Type::SubstTemplateTypeParm: 1872 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1873 getReplacementType().getTypePtr()); 1874 1875 case Type::Auto: { 1876 const AutoType *A = cast<AutoType>(T); 1877 assert(!A->getDeducedType().isNull() && 1878 "cannot request the size of an undeduced or dependent auto type"); 1879 return getTypeInfo(A->getDeducedType().getTypePtr()); 1880 } 1881 1882 case Type::Paren: 1883 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1884 1885 case Type::ObjCTypeParam: 1886 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 1887 1888 case Type::Typedef: { 1889 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1890 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1891 // If the typedef has an aligned attribute on it, it overrides any computed 1892 // alignment we have. This violates the GCC documentation (which says that 1893 // attribute(aligned) can only round up) but matches its implementation. 1894 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 1895 Align = AttrAlign; 1896 AlignIsRequired = true; 1897 } else { 1898 Align = Info.Align; 1899 AlignIsRequired = Info.AlignIsRequired; 1900 } 1901 Width = Info.Width; 1902 break; 1903 } 1904 1905 case Type::Elaborated: 1906 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1907 1908 case Type::Attributed: 1909 return getTypeInfo( 1910 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1911 1912 case Type::Atomic: { 1913 // Start with the base type information. 1914 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1915 Width = Info.Width; 1916 Align = Info.Align; 1917 1918 // If the size of the type doesn't exceed the platform's max 1919 // atomic promotion width, make the size and alignment more 1920 // favorable to atomic operations: 1921 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) { 1922 // Round the size up to a power of 2. 1923 if (!llvm::isPowerOf2_64(Width)) 1924 Width = llvm::NextPowerOf2(Width); 1925 1926 // Set the alignment equal to the size. 1927 Align = static_cast<unsigned>(Width); 1928 } 1929 } 1930 break; 1931 1932 case Type::Pipe: { 1933 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType()); 1934 Width = Info.Width; 1935 Align = Info.Align; 1936 } 1937 1938 } 1939 1940 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1941 return TypeInfo(Width, Align, AlignIsRequired); 1942 } 1943 1944 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 1945 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 1946 // Target ppc64 with QPX: simd default alignment for pointer to double is 32. 1947 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 || 1948 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) && 1949 getTargetInfo().getABI() == "elfv1-qpx" && 1950 T->isSpecificBuiltinType(BuiltinType::Double)) 1951 SimdAlign = 256; 1952 return SimdAlign; 1953 } 1954 1955 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1956 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1957 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1958 } 1959 1960 /// toBits - Convert a size in characters to a size in characters. 1961 int64_t ASTContext::toBits(CharUnits CharSize) const { 1962 return CharSize.getQuantity() * getCharWidth(); 1963 } 1964 1965 /// getTypeSizeInChars - Return the size of the specified type, in characters. 1966 /// This method does not work on incomplete types. 1967 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1968 return getTypeInfoInChars(T).first; 1969 } 1970 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1971 return getTypeInfoInChars(T).first; 1972 } 1973 1974 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1975 /// characters. This method does not work on incomplete types. 1976 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1977 return toCharUnitsFromBits(getTypeAlign(T)); 1978 } 1979 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1980 return toCharUnitsFromBits(getTypeAlign(T)); 1981 } 1982 1983 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1984 /// type for the current target in bits. This can be different than the ABI 1985 /// alignment in cases where it is beneficial for performance to overalign 1986 /// a data type. 1987 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1988 TypeInfo TI = getTypeInfo(T); 1989 unsigned ABIAlign = TI.Align; 1990 1991 T = T->getBaseElementTypeUnsafe(); 1992 1993 // The preferred alignment of member pointers is that of a pointer. 1994 if (T->isMemberPointerType()) 1995 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 1996 1997 if (!Target->allowsLargerPreferedTypeAlignment()) 1998 return ABIAlign; 1999 2000 // Double and long long should be naturally aligned if possible. 2001 if (const ComplexType *CT = T->getAs<ComplexType>()) 2002 T = CT->getElementType().getTypePtr(); 2003 if (const EnumType *ET = T->getAs<EnumType>()) 2004 T = ET->getDecl()->getIntegerType().getTypePtr(); 2005 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2006 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2007 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 2008 // Don't increase the alignment if an alignment attribute was specified on a 2009 // typedef declaration. 2010 if (!TI.AlignIsRequired) 2011 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2012 2013 return ABIAlign; 2014 } 2015 2016 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2017 /// for __attribute__((aligned)) on this target, to be used if no alignment 2018 /// value is specified. 2019 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2020 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2021 } 2022 2023 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2024 /// to a global variable of the specified type. 2025 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2026 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 2027 } 2028 2029 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2030 /// should be given to a global variable of the specified type. 2031 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2032 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2033 } 2034 2035 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2036 CharUnits Offset = CharUnits::Zero(); 2037 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2038 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2039 Offset += Layout->getBaseClassOffset(Base); 2040 Layout = &getASTRecordLayout(Base); 2041 } 2042 return Offset; 2043 } 2044 2045 /// DeepCollectObjCIvars - 2046 /// This routine first collects all declared, but not synthesized, ivars in 2047 /// super class and then collects all ivars, including those synthesized for 2048 /// current class. This routine is used for implementation of current class 2049 /// when all ivars, declared and synthesized are known. 2050 /// 2051 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2052 bool leafClass, 2053 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2054 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2055 DeepCollectObjCIvars(SuperClass, false, Ivars); 2056 if (!leafClass) { 2057 for (const auto *I : OI->ivars()) 2058 Ivars.push_back(I); 2059 } else { 2060 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2061 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2062 Iv= Iv->getNextIvar()) 2063 Ivars.push_back(Iv); 2064 } 2065 } 2066 2067 /// CollectInheritedProtocols - Collect all protocols in current class and 2068 /// those inherited by it. 2069 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2070 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2071 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2072 // We can use protocol_iterator here instead of 2073 // all_referenced_protocol_iterator since we are walking all categories. 2074 for (auto *Proto : OI->all_referenced_protocols()) { 2075 CollectInheritedProtocols(Proto, Protocols); 2076 } 2077 2078 // Categories of this Interface. 2079 for (const auto *Cat : OI->visible_categories()) 2080 CollectInheritedProtocols(Cat, Protocols); 2081 2082 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2083 while (SD) { 2084 CollectInheritedProtocols(SD, Protocols); 2085 SD = SD->getSuperClass(); 2086 } 2087 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2088 for (auto *Proto : OC->protocols()) { 2089 CollectInheritedProtocols(Proto, Protocols); 2090 } 2091 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2092 // Insert the protocol. 2093 if (!Protocols.insert( 2094 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2095 return; 2096 2097 for (auto *Proto : OP->protocols()) 2098 CollectInheritedProtocols(Proto, Protocols); 2099 } 2100 } 2101 2102 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2103 unsigned count = 0; 2104 // Count ivars declared in class extension. 2105 for (const auto *Ext : OI->known_extensions()) 2106 count += Ext->ivar_size(); 2107 2108 // Count ivar defined in this class's implementation. This 2109 // includes synthesized ivars. 2110 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2111 count += ImplDecl->ivar_size(); 2112 2113 return count; 2114 } 2115 2116 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2117 if (!E) 2118 return false; 2119 2120 // nullptr_t is always treated as null. 2121 if (E->getType()->isNullPtrType()) return true; 2122 2123 if (E->getType()->isAnyPointerType() && 2124 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2125 Expr::NPC_ValueDependentIsNull)) 2126 return true; 2127 2128 // Unfortunately, __null has type 'int'. 2129 if (isa<GNUNullExpr>(E)) return true; 2130 2131 return false; 2132 } 2133 2134 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 2135 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2136 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2137 I = ObjCImpls.find(D); 2138 if (I != ObjCImpls.end()) 2139 return cast<ObjCImplementationDecl>(I->second); 2140 return nullptr; 2141 } 2142 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 2143 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2144 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2145 I = ObjCImpls.find(D); 2146 if (I != ObjCImpls.end()) 2147 return cast<ObjCCategoryImplDecl>(I->second); 2148 return nullptr; 2149 } 2150 2151 /// \brief Set the implementation of ObjCInterfaceDecl. 2152 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2153 ObjCImplementationDecl *ImplD) { 2154 assert(IFaceD && ImplD && "Passed null params"); 2155 ObjCImpls[IFaceD] = ImplD; 2156 } 2157 /// \brief Set the implementation of ObjCCategoryDecl. 2158 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2159 ObjCCategoryImplDecl *ImplD) { 2160 assert(CatD && ImplD && "Passed null params"); 2161 ObjCImpls[CatD] = ImplD; 2162 } 2163 2164 const ObjCMethodDecl * 2165 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2166 return ObjCMethodRedecls.lookup(MD); 2167 } 2168 2169 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2170 const ObjCMethodDecl *Redecl) { 2171 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2172 ObjCMethodRedecls[MD] = Redecl; 2173 } 2174 2175 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2176 const NamedDecl *ND) const { 2177 if (const ObjCInterfaceDecl *ID = 2178 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2179 return ID; 2180 if (const ObjCCategoryDecl *CD = 2181 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2182 return CD->getClassInterface(); 2183 if (const ObjCImplDecl *IMD = 2184 dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2185 return IMD->getClassInterface(); 2186 2187 return nullptr; 2188 } 2189 2190 /// \brief Get the copy initialization expression of VarDecl,or NULL if 2191 /// none exists. 2192 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 2193 assert(VD && "Passed null params"); 2194 assert(VD->hasAttr<BlocksAttr>() && 2195 "getBlockVarCopyInits - not __block var"); 2196 llvm::DenseMap<const VarDecl*, Expr*>::iterator 2197 I = BlockVarCopyInits.find(VD); 2198 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr; 2199 } 2200 2201 /// \brief Set the copy inialization expression of a block var decl. 2202 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 2203 assert(VD && Init && "Passed null params"); 2204 assert(VD->hasAttr<BlocksAttr>() && 2205 "setBlockVarCopyInits - not __block var"); 2206 BlockVarCopyInits[VD] = Init; 2207 } 2208 2209 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2210 unsigned DataSize) const { 2211 if (!DataSize) 2212 DataSize = TypeLoc::getFullDataSizeForType(T); 2213 else 2214 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2215 "incorrect data size provided to CreateTypeSourceInfo!"); 2216 2217 TypeSourceInfo *TInfo = 2218 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2219 new (TInfo) TypeSourceInfo(T); 2220 return TInfo; 2221 } 2222 2223 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2224 SourceLocation L) const { 2225 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2226 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2227 return DI; 2228 } 2229 2230 const ASTRecordLayout & 2231 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2232 return getObjCLayout(D, nullptr); 2233 } 2234 2235 const ASTRecordLayout & 2236 ASTContext::getASTObjCImplementationLayout( 2237 const ObjCImplementationDecl *D) const { 2238 return getObjCLayout(D->getClassInterface(), D); 2239 } 2240 2241 //===----------------------------------------------------------------------===// 2242 // Type creation/memoization methods 2243 //===----------------------------------------------------------------------===// 2244 2245 QualType 2246 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2247 unsigned fastQuals = quals.getFastQualifiers(); 2248 quals.removeFastQualifiers(); 2249 2250 // Check if we've already instantiated this type. 2251 llvm::FoldingSetNodeID ID; 2252 ExtQuals::Profile(ID, baseType, quals); 2253 void *insertPos = nullptr; 2254 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2255 assert(eq->getQualifiers() == quals); 2256 return QualType(eq, fastQuals); 2257 } 2258 2259 // If the base type is not canonical, make the appropriate canonical type. 2260 QualType canon; 2261 if (!baseType->isCanonicalUnqualified()) { 2262 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2263 canonSplit.Quals.addConsistentQualifiers(quals); 2264 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2265 2266 // Re-find the insert position. 2267 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2268 } 2269 2270 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2271 ExtQualNodes.InsertNode(eq, insertPos); 2272 return QualType(eq, fastQuals); 2273 } 2274 2275 QualType 2276 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 2277 QualType CanT = getCanonicalType(T); 2278 if (CanT.getAddressSpace() == AddressSpace) 2279 return T; 2280 2281 // If we are composing extended qualifiers together, merge together 2282 // into one ExtQuals node. 2283 QualifierCollector Quals; 2284 const Type *TypeNode = Quals.strip(T); 2285 2286 // If this type already has an address space specified, it cannot get 2287 // another one. 2288 assert(!Quals.hasAddressSpace() && 2289 "Type cannot be in multiple addr spaces!"); 2290 Quals.addAddressSpace(AddressSpace); 2291 2292 return getExtQualType(TypeNode, Quals); 2293 } 2294 2295 QualType ASTContext::getObjCGCQualType(QualType T, 2296 Qualifiers::GC GCAttr) const { 2297 QualType CanT = getCanonicalType(T); 2298 if (CanT.getObjCGCAttr() == GCAttr) 2299 return T; 2300 2301 if (const PointerType *ptr = T->getAs<PointerType>()) { 2302 QualType Pointee = ptr->getPointeeType(); 2303 if (Pointee->isAnyPointerType()) { 2304 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2305 return getPointerType(ResultType); 2306 } 2307 } 2308 2309 // If we are composing extended qualifiers together, merge together 2310 // into one ExtQuals node. 2311 QualifierCollector Quals; 2312 const Type *TypeNode = Quals.strip(T); 2313 2314 // If this type already has an ObjCGC specified, it cannot get 2315 // another one. 2316 assert(!Quals.hasObjCGCAttr() && 2317 "Type cannot have multiple ObjCGCs!"); 2318 Quals.addObjCGCAttr(GCAttr); 2319 2320 return getExtQualType(TypeNode, Quals); 2321 } 2322 2323 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2324 FunctionType::ExtInfo Info) { 2325 if (T->getExtInfo() == Info) 2326 return T; 2327 2328 QualType Result; 2329 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2330 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2331 } else { 2332 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2333 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2334 EPI.ExtInfo = Info; 2335 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2336 } 2337 2338 return cast<FunctionType>(Result.getTypePtr()); 2339 } 2340 2341 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2342 QualType ResultType) { 2343 FD = FD->getMostRecentDecl(); 2344 while (true) { 2345 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 2346 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2347 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2348 if (FunctionDecl *Next = FD->getPreviousDecl()) 2349 FD = Next; 2350 else 2351 break; 2352 } 2353 if (ASTMutationListener *L = getASTMutationListener()) 2354 L->DeducedReturnType(FD, ResultType); 2355 } 2356 2357 /// Get a function type and produce the equivalent function type with the 2358 /// specified exception specification. Type sugar that can be present on a 2359 /// declaration of a function with an exception specification is permitted 2360 /// and preserved. Other type sugar (for instance, typedefs) is not. 2361 static QualType getFunctionTypeWithExceptionSpec( 2362 ASTContext &Context, QualType Orig, 2363 const FunctionProtoType::ExceptionSpecInfo &ESI) { 2364 // Might have some parens. 2365 if (auto *PT = dyn_cast<ParenType>(Orig)) 2366 return Context.getParenType( 2367 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI)); 2368 2369 // Might have a calling-convention attribute. 2370 if (auto *AT = dyn_cast<AttributedType>(Orig)) 2371 return Context.getAttributedType( 2372 AT->getAttrKind(), 2373 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI), 2374 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(), 2375 ESI)); 2376 2377 // Anything else must be a function type. Rebuild it with the new exception 2378 // specification. 2379 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig); 2380 return Context.getFunctionType( 2381 Proto->getReturnType(), Proto->getParamTypes(), 2382 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2383 } 2384 2385 void ASTContext::adjustExceptionSpec( 2386 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 2387 bool AsWritten) { 2388 // Update the type. 2389 QualType Updated = 2390 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI); 2391 FD->setType(Updated); 2392 2393 if (!AsWritten) 2394 return; 2395 2396 // Update the type in the type source information too. 2397 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 2398 // If the type and the type-as-written differ, we may need to update 2399 // the type-as-written too. 2400 if (TSInfo->getType() != FD->getType()) 2401 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI); 2402 2403 // FIXME: When we get proper type location information for exceptions, 2404 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 2405 // up the TypeSourceInfo; 2406 assert(TypeLoc::getFullDataSizeForType(Updated) == 2407 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 2408 "TypeLoc size mismatch from updating exception specification"); 2409 TSInfo->overrideType(Updated); 2410 } 2411 } 2412 2413 /// getComplexType - Return the uniqued reference to the type for a complex 2414 /// number with the specified element type. 2415 QualType ASTContext::getComplexType(QualType T) const { 2416 // Unique pointers, to guarantee there is only one pointer of a particular 2417 // structure. 2418 llvm::FoldingSetNodeID ID; 2419 ComplexType::Profile(ID, T); 2420 2421 void *InsertPos = nullptr; 2422 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2423 return QualType(CT, 0); 2424 2425 // If the pointee type isn't canonical, this won't be a canonical type either, 2426 // so fill in the canonical type field. 2427 QualType Canonical; 2428 if (!T.isCanonical()) { 2429 Canonical = getComplexType(getCanonicalType(T)); 2430 2431 // Get the new insert position for the node we care about. 2432 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2433 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2434 } 2435 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2436 Types.push_back(New); 2437 ComplexTypes.InsertNode(New, InsertPos); 2438 return QualType(New, 0); 2439 } 2440 2441 /// getPointerType - Return the uniqued reference to the type for a pointer to 2442 /// the specified type. 2443 QualType ASTContext::getPointerType(QualType T) const { 2444 // Unique pointers, to guarantee there is only one pointer of a particular 2445 // structure. 2446 llvm::FoldingSetNodeID ID; 2447 PointerType::Profile(ID, T); 2448 2449 void *InsertPos = nullptr; 2450 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2451 return QualType(PT, 0); 2452 2453 // If the pointee type isn't canonical, this won't be a canonical type either, 2454 // so fill in the canonical type field. 2455 QualType Canonical; 2456 if (!T.isCanonical()) { 2457 Canonical = getPointerType(getCanonicalType(T)); 2458 2459 // Get the new insert position for the node we care about. 2460 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2461 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2462 } 2463 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2464 Types.push_back(New); 2465 PointerTypes.InsertNode(New, InsertPos); 2466 return QualType(New, 0); 2467 } 2468 2469 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2470 llvm::FoldingSetNodeID ID; 2471 AdjustedType::Profile(ID, Orig, New); 2472 void *InsertPos = nullptr; 2473 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2474 if (AT) 2475 return QualType(AT, 0); 2476 2477 QualType Canonical = getCanonicalType(New); 2478 2479 // Get the new insert position for the node we care about. 2480 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2481 assert(!AT && "Shouldn't be in the map!"); 2482 2483 AT = new (*this, TypeAlignment) 2484 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2485 Types.push_back(AT); 2486 AdjustedTypes.InsertNode(AT, InsertPos); 2487 return QualType(AT, 0); 2488 } 2489 2490 QualType ASTContext::getDecayedType(QualType T) const { 2491 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2492 2493 QualType Decayed; 2494 2495 // C99 6.7.5.3p7: 2496 // A declaration of a parameter as "array of type" shall be 2497 // adjusted to "qualified pointer to type", where the type 2498 // qualifiers (if any) are those specified within the [ and ] of 2499 // the array type derivation. 2500 if (T->isArrayType()) 2501 Decayed = getArrayDecayedType(T); 2502 2503 // C99 6.7.5.3p8: 2504 // A declaration of a parameter as "function returning type" 2505 // shall be adjusted to "pointer to function returning type", as 2506 // in 6.3.2.1. 2507 if (T->isFunctionType()) 2508 Decayed = getPointerType(T); 2509 2510 llvm::FoldingSetNodeID ID; 2511 AdjustedType::Profile(ID, T, Decayed); 2512 void *InsertPos = nullptr; 2513 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2514 if (AT) 2515 return QualType(AT, 0); 2516 2517 QualType Canonical = getCanonicalType(Decayed); 2518 2519 // Get the new insert position for the node we care about. 2520 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2521 assert(!AT && "Shouldn't be in the map!"); 2522 2523 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2524 Types.push_back(AT); 2525 AdjustedTypes.InsertNode(AT, InsertPos); 2526 return QualType(AT, 0); 2527 } 2528 2529 /// getBlockPointerType - Return the uniqued reference to the type for 2530 /// a pointer to the specified block. 2531 QualType ASTContext::getBlockPointerType(QualType T) const { 2532 assert(T->isFunctionType() && "block of function types only"); 2533 // Unique pointers, to guarantee there is only one block of a particular 2534 // structure. 2535 llvm::FoldingSetNodeID ID; 2536 BlockPointerType::Profile(ID, T); 2537 2538 void *InsertPos = nullptr; 2539 if (BlockPointerType *PT = 2540 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2541 return QualType(PT, 0); 2542 2543 // If the block pointee type isn't canonical, this won't be a canonical 2544 // type either so fill in the canonical type field. 2545 QualType Canonical; 2546 if (!T.isCanonical()) { 2547 Canonical = getBlockPointerType(getCanonicalType(T)); 2548 2549 // Get the new insert position for the node we care about. 2550 BlockPointerType *NewIP = 2551 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2553 } 2554 BlockPointerType *New 2555 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2556 Types.push_back(New); 2557 BlockPointerTypes.InsertNode(New, InsertPos); 2558 return QualType(New, 0); 2559 } 2560 2561 /// getLValueReferenceType - Return the uniqued reference to the type for an 2562 /// lvalue reference to the specified type. 2563 QualType 2564 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2565 assert(getCanonicalType(T) != OverloadTy && 2566 "Unresolved overloaded function type"); 2567 2568 // Unique pointers, to guarantee there is only one pointer of a particular 2569 // structure. 2570 llvm::FoldingSetNodeID ID; 2571 ReferenceType::Profile(ID, T, SpelledAsLValue); 2572 2573 void *InsertPos = nullptr; 2574 if (LValueReferenceType *RT = 2575 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2576 return QualType(RT, 0); 2577 2578 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2579 2580 // If the referencee type isn't canonical, this won't be a canonical type 2581 // either, so fill in the canonical type field. 2582 QualType Canonical; 2583 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2584 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2585 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2586 2587 // Get the new insert position for the node we care about. 2588 LValueReferenceType *NewIP = 2589 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2590 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2591 } 2592 2593 LValueReferenceType *New 2594 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2595 SpelledAsLValue); 2596 Types.push_back(New); 2597 LValueReferenceTypes.InsertNode(New, InsertPos); 2598 2599 return QualType(New, 0); 2600 } 2601 2602 /// getRValueReferenceType - Return the uniqued reference to the type for an 2603 /// rvalue reference to the specified type. 2604 QualType ASTContext::getRValueReferenceType(QualType T) const { 2605 // Unique pointers, to guarantee there is only one pointer of a particular 2606 // structure. 2607 llvm::FoldingSetNodeID ID; 2608 ReferenceType::Profile(ID, T, false); 2609 2610 void *InsertPos = nullptr; 2611 if (RValueReferenceType *RT = 2612 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2613 return QualType(RT, 0); 2614 2615 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2616 2617 // If the referencee type isn't canonical, this won't be a canonical type 2618 // either, so fill in the canonical type field. 2619 QualType Canonical; 2620 if (InnerRef || !T.isCanonical()) { 2621 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2622 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2623 2624 // Get the new insert position for the node we care about. 2625 RValueReferenceType *NewIP = 2626 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2627 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2628 } 2629 2630 RValueReferenceType *New 2631 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2632 Types.push_back(New); 2633 RValueReferenceTypes.InsertNode(New, InsertPos); 2634 return QualType(New, 0); 2635 } 2636 2637 /// getMemberPointerType - Return the uniqued reference to the type for a 2638 /// member pointer to the specified type, in the specified class. 2639 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2640 // Unique pointers, to guarantee there is only one pointer of a particular 2641 // structure. 2642 llvm::FoldingSetNodeID ID; 2643 MemberPointerType::Profile(ID, T, Cls); 2644 2645 void *InsertPos = nullptr; 2646 if (MemberPointerType *PT = 2647 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2648 return QualType(PT, 0); 2649 2650 // If the pointee or class type isn't canonical, this won't be a canonical 2651 // type either, so fill in the canonical type field. 2652 QualType Canonical; 2653 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2654 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2655 2656 // Get the new insert position for the node we care about. 2657 MemberPointerType *NewIP = 2658 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2659 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2660 } 2661 MemberPointerType *New 2662 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 2663 Types.push_back(New); 2664 MemberPointerTypes.InsertNode(New, InsertPos); 2665 return QualType(New, 0); 2666 } 2667 2668 /// getConstantArrayType - Return the unique reference to the type for an 2669 /// array of the specified element type. 2670 QualType ASTContext::getConstantArrayType(QualType EltTy, 2671 const llvm::APInt &ArySizeIn, 2672 ArrayType::ArraySizeModifier ASM, 2673 unsigned IndexTypeQuals) const { 2674 assert((EltTy->isDependentType() || 2675 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 2676 "Constant array of VLAs is illegal!"); 2677 2678 // Convert the array size into a canonical width matching the pointer size for 2679 // the target. 2680 llvm::APInt ArySize(ArySizeIn); 2681 ArySize = 2682 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 2683 2684 llvm::FoldingSetNodeID ID; 2685 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 2686 2687 void *InsertPos = nullptr; 2688 if (ConstantArrayType *ATP = 2689 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 2690 return QualType(ATP, 0); 2691 2692 // If the element type isn't canonical or has qualifiers, this won't 2693 // be a canonical type either, so fill in the canonical type field. 2694 QualType Canon; 2695 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2696 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2697 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 2698 ASM, IndexTypeQuals); 2699 Canon = getQualifiedType(Canon, canonSplit.Quals); 2700 2701 // Get the new insert position for the node we care about. 2702 ConstantArrayType *NewIP = 2703 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2704 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2705 } 2706 2707 ConstantArrayType *New = new(*this,TypeAlignment) 2708 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2709 ConstantArrayTypes.InsertNode(New, InsertPos); 2710 Types.push_back(New); 2711 return QualType(New, 0); 2712 } 2713 2714 /// getVariableArrayDecayedType - Turns the given type, which may be 2715 /// variably-modified, into the corresponding type with all the known 2716 /// sizes replaced with [*]. 2717 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2718 // Vastly most common case. 2719 if (!type->isVariablyModifiedType()) return type; 2720 2721 QualType result; 2722 2723 SplitQualType split = type.getSplitDesugaredType(); 2724 const Type *ty = split.Ty; 2725 switch (ty->getTypeClass()) { 2726 #define TYPE(Class, Base) 2727 #define ABSTRACT_TYPE(Class, Base) 2728 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2729 #include "clang/AST/TypeNodes.def" 2730 llvm_unreachable("didn't desugar past all non-canonical types?"); 2731 2732 // These types should never be variably-modified. 2733 case Type::Builtin: 2734 case Type::Complex: 2735 case Type::Vector: 2736 case Type::ExtVector: 2737 case Type::DependentSizedExtVector: 2738 case Type::ObjCObject: 2739 case Type::ObjCInterface: 2740 case Type::ObjCObjectPointer: 2741 case Type::Record: 2742 case Type::Enum: 2743 case Type::UnresolvedUsing: 2744 case Type::TypeOfExpr: 2745 case Type::TypeOf: 2746 case Type::Decltype: 2747 case Type::UnaryTransform: 2748 case Type::DependentName: 2749 case Type::InjectedClassName: 2750 case Type::TemplateSpecialization: 2751 case Type::DependentTemplateSpecialization: 2752 case Type::TemplateTypeParm: 2753 case Type::SubstTemplateTypeParmPack: 2754 case Type::Auto: 2755 case Type::PackExpansion: 2756 llvm_unreachable("type should never be variably-modified"); 2757 2758 // These types can be variably-modified but should never need to 2759 // further decay. 2760 case Type::FunctionNoProto: 2761 case Type::FunctionProto: 2762 case Type::BlockPointer: 2763 case Type::MemberPointer: 2764 case Type::Pipe: 2765 return type; 2766 2767 // These types can be variably-modified. All these modifications 2768 // preserve structure except as noted by comments. 2769 // TODO: if we ever care about optimizing VLAs, there are no-op 2770 // optimizations available here. 2771 case Type::Pointer: 2772 result = getPointerType(getVariableArrayDecayedType( 2773 cast<PointerType>(ty)->getPointeeType())); 2774 break; 2775 2776 case Type::LValueReference: { 2777 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2778 result = getLValueReferenceType( 2779 getVariableArrayDecayedType(lv->getPointeeType()), 2780 lv->isSpelledAsLValue()); 2781 break; 2782 } 2783 2784 case Type::RValueReference: { 2785 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2786 result = getRValueReferenceType( 2787 getVariableArrayDecayedType(lv->getPointeeType())); 2788 break; 2789 } 2790 2791 case Type::Atomic: { 2792 const AtomicType *at = cast<AtomicType>(ty); 2793 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2794 break; 2795 } 2796 2797 case Type::ConstantArray: { 2798 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2799 result = getConstantArrayType( 2800 getVariableArrayDecayedType(cat->getElementType()), 2801 cat->getSize(), 2802 cat->getSizeModifier(), 2803 cat->getIndexTypeCVRQualifiers()); 2804 break; 2805 } 2806 2807 case Type::DependentSizedArray: { 2808 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2809 result = getDependentSizedArrayType( 2810 getVariableArrayDecayedType(dat->getElementType()), 2811 dat->getSizeExpr(), 2812 dat->getSizeModifier(), 2813 dat->getIndexTypeCVRQualifiers(), 2814 dat->getBracketsRange()); 2815 break; 2816 } 2817 2818 // Turn incomplete types into [*] types. 2819 case Type::IncompleteArray: { 2820 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2821 result = getVariableArrayType( 2822 getVariableArrayDecayedType(iat->getElementType()), 2823 /*size*/ nullptr, 2824 ArrayType::Normal, 2825 iat->getIndexTypeCVRQualifiers(), 2826 SourceRange()); 2827 break; 2828 } 2829 2830 // Turn VLA types into [*] types. 2831 case Type::VariableArray: { 2832 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2833 result = getVariableArrayType( 2834 getVariableArrayDecayedType(vat->getElementType()), 2835 /*size*/ nullptr, 2836 ArrayType::Star, 2837 vat->getIndexTypeCVRQualifiers(), 2838 vat->getBracketsRange()); 2839 break; 2840 } 2841 } 2842 2843 // Apply the top-level qualifiers from the original. 2844 return getQualifiedType(result, split.Quals); 2845 } 2846 2847 /// getVariableArrayType - Returns a non-unique reference to the type for a 2848 /// variable array of the specified element type. 2849 QualType ASTContext::getVariableArrayType(QualType EltTy, 2850 Expr *NumElts, 2851 ArrayType::ArraySizeModifier ASM, 2852 unsigned IndexTypeQuals, 2853 SourceRange Brackets) const { 2854 // Since we don't unique expressions, it isn't possible to unique VLA's 2855 // that have an expression provided for their size. 2856 QualType Canon; 2857 2858 // Be sure to pull qualifiers off the element type. 2859 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2860 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2861 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2862 IndexTypeQuals, Brackets); 2863 Canon = getQualifiedType(Canon, canonSplit.Quals); 2864 } 2865 2866 VariableArrayType *New = new(*this, TypeAlignment) 2867 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2868 2869 VariableArrayTypes.push_back(New); 2870 Types.push_back(New); 2871 return QualType(New, 0); 2872 } 2873 2874 /// getDependentSizedArrayType - Returns a non-unique reference to 2875 /// the type for a dependently-sized array of the specified element 2876 /// type. 2877 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2878 Expr *numElements, 2879 ArrayType::ArraySizeModifier ASM, 2880 unsigned elementTypeQuals, 2881 SourceRange brackets) const { 2882 assert((!numElements || numElements->isTypeDependent() || 2883 numElements->isValueDependent()) && 2884 "Size must be type- or value-dependent!"); 2885 2886 // Dependently-sized array types that do not have a specified number 2887 // of elements will have their sizes deduced from a dependent 2888 // initializer. We do no canonicalization here at all, which is okay 2889 // because they can't be used in most locations. 2890 if (!numElements) { 2891 DependentSizedArrayType *newType 2892 = new (*this, TypeAlignment) 2893 DependentSizedArrayType(*this, elementType, QualType(), 2894 numElements, ASM, elementTypeQuals, 2895 brackets); 2896 Types.push_back(newType); 2897 return QualType(newType, 0); 2898 } 2899 2900 // Otherwise, we actually build a new type every time, but we 2901 // also build a canonical type. 2902 2903 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2904 2905 void *insertPos = nullptr; 2906 llvm::FoldingSetNodeID ID; 2907 DependentSizedArrayType::Profile(ID, *this, 2908 QualType(canonElementType.Ty, 0), 2909 ASM, elementTypeQuals, numElements); 2910 2911 // Look for an existing type with these properties. 2912 DependentSizedArrayType *canonTy = 2913 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2914 2915 // If we don't have one, build one. 2916 if (!canonTy) { 2917 canonTy = new (*this, TypeAlignment) 2918 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2919 QualType(), numElements, ASM, elementTypeQuals, 2920 brackets); 2921 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2922 Types.push_back(canonTy); 2923 } 2924 2925 // Apply qualifiers from the element type to the array. 2926 QualType canon = getQualifiedType(QualType(canonTy,0), 2927 canonElementType.Quals); 2928 2929 // If we didn't need extra canonicalization for the element type or the size 2930 // expression, then just use that as our result. 2931 if (QualType(canonElementType.Ty, 0) == elementType && 2932 canonTy->getSizeExpr() == numElements) 2933 return canon; 2934 2935 // Otherwise, we need to build a type which follows the spelling 2936 // of the element type. 2937 DependentSizedArrayType *sugaredType 2938 = new (*this, TypeAlignment) 2939 DependentSizedArrayType(*this, elementType, canon, numElements, 2940 ASM, elementTypeQuals, brackets); 2941 Types.push_back(sugaredType); 2942 return QualType(sugaredType, 0); 2943 } 2944 2945 QualType ASTContext::getIncompleteArrayType(QualType elementType, 2946 ArrayType::ArraySizeModifier ASM, 2947 unsigned elementTypeQuals) const { 2948 llvm::FoldingSetNodeID ID; 2949 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2950 2951 void *insertPos = nullptr; 2952 if (IncompleteArrayType *iat = 2953 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2954 return QualType(iat, 0); 2955 2956 // If the element type isn't canonical, this won't be a canonical type 2957 // either, so fill in the canonical type field. We also have to pull 2958 // qualifiers off the element type. 2959 QualType canon; 2960 2961 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2962 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2963 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2964 ASM, elementTypeQuals); 2965 canon = getQualifiedType(canon, canonSplit.Quals); 2966 2967 // Get the new insert position for the node we care about. 2968 IncompleteArrayType *existing = 2969 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2970 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2971 } 2972 2973 IncompleteArrayType *newType = new (*this, TypeAlignment) 2974 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2975 2976 IncompleteArrayTypes.InsertNode(newType, insertPos); 2977 Types.push_back(newType); 2978 return QualType(newType, 0); 2979 } 2980 2981 /// getVectorType - Return the unique reference to a vector type of 2982 /// the specified element type and size. VectorType must be a built-in type. 2983 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2984 VectorType::VectorKind VecKind) const { 2985 assert(vecType->isBuiltinType()); 2986 2987 // Check if we've already instantiated a vector of this type. 2988 llvm::FoldingSetNodeID ID; 2989 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2990 2991 void *InsertPos = nullptr; 2992 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2993 return QualType(VTP, 0); 2994 2995 // If the element type isn't canonical, this won't be a canonical type either, 2996 // so fill in the canonical type field. 2997 QualType Canonical; 2998 if (!vecType.isCanonical()) { 2999 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3000 3001 // Get the new insert position for the node we care about. 3002 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3003 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3004 } 3005 VectorType *New = new (*this, TypeAlignment) 3006 VectorType(vecType, NumElts, Canonical, VecKind); 3007 VectorTypes.InsertNode(New, InsertPos); 3008 Types.push_back(New); 3009 return QualType(New, 0); 3010 } 3011 3012 /// getExtVectorType - Return the unique reference to an extended vector type of 3013 /// the specified element type and size. VectorType must be a built-in type. 3014 QualType 3015 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3016 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3017 3018 // Check if we've already instantiated a vector of this type. 3019 llvm::FoldingSetNodeID ID; 3020 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3021 VectorType::GenericVector); 3022 void *InsertPos = nullptr; 3023 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3024 return QualType(VTP, 0); 3025 3026 // If the element type isn't canonical, this won't be a canonical type either, 3027 // so fill in the canonical type field. 3028 QualType Canonical; 3029 if (!vecType.isCanonical()) { 3030 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3031 3032 // Get the new insert position for the node we care about. 3033 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3034 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3035 } 3036 ExtVectorType *New = new (*this, TypeAlignment) 3037 ExtVectorType(vecType, NumElts, Canonical); 3038 VectorTypes.InsertNode(New, InsertPos); 3039 Types.push_back(New); 3040 return QualType(New, 0); 3041 } 3042 3043 QualType 3044 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3045 Expr *SizeExpr, 3046 SourceLocation AttrLoc) const { 3047 llvm::FoldingSetNodeID ID; 3048 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3049 SizeExpr); 3050 3051 void *InsertPos = nullptr; 3052 DependentSizedExtVectorType *Canon 3053 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3054 DependentSizedExtVectorType *New; 3055 if (Canon) { 3056 // We already have a canonical version of this array type; use it as 3057 // the canonical type for a newly-built type. 3058 New = new (*this, TypeAlignment) 3059 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3060 SizeExpr, AttrLoc); 3061 } else { 3062 QualType CanonVecTy = getCanonicalType(vecType); 3063 if (CanonVecTy == vecType) { 3064 New = new (*this, TypeAlignment) 3065 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3066 AttrLoc); 3067 3068 DependentSizedExtVectorType *CanonCheck 3069 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3070 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3071 (void)CanonCheck; 3072 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3073 } else { 3074 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3075 SourceLocation()); 3076 New = new (*this, TypeAlignment) 3077 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 3078 } 3079 } 3080 3081 Types.push_back(New); 3082 return QualType(New, 0); 3083 } 3084 3085 /// \brief Determine whether \p T is canonical as the result type of a function. 3086 static bool isCanonicalResultType(QualType T) { 3087 return T.isCanonical() && 3088 (T.getObjCLifetime() == Qualifiers::OCL_None || 3089 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 3090 } 3091 3092 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 3093 /// 3094 QualType 3095 ASTContext::getFunctionNoProtoType(QualType ResultTy, 3096 const FunctionType::ExtInfo &Info) const { 3097 // Unique functions, to guarantee there is only one function of a particular 3098 // structure. 3099 llvm::FoldingSetNodeID ID; 3100 FunctionNoProtoType::Profile(ID, ResultTy, Info); 3101 3102 void *InsertPos = nullptr; 3103 if (FunctionNoProtoType *FT = 3104 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3105 return QualType(FT, 0); 3106 3107 QualType Canonical; 3108 if (!isCanonicalResultType(ResultTy)) { 3109 Canonical = 3110 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 3111 3112 // Get the new insert position for the node we care about. 3113 FunctionNoProtoType *NewIP = 3114 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3115 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3116 } 3117 3118 FunctionNoProtoType *New = new (*this, TypeAlignment) 3119 FunctionNoProtoType(ResultTy, Canonical, Info); 3120 Types.push_back(New); 3121 FunctionNoProtoTypes.InsertNode(New, InsertPos); 3122 return QualType(New, 0); 3123 } 3124 3125 CanQualType 3126 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 3127 CanQualType CanResultType = getCanonicalType(ResultType); 3128 3129 // Canonical result types do not have ARC lifetime qualifiers. 3130 if (CanResultType.getQualifiers().hasObjCLifetime()) { 3131 Qualifiers Qs = CanResultType.getQualifiers(); 3132 Qs.removeObjCLifetime(); 3133 return CanQualType::CreateUnsafe( 3134 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 3135 } 3136 3137 return CanResultType; 3138 } 3139 3140 static bool isCanonicalExceptionSpecification( 3141 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 3142 if (ESI.Type == EST_None) 3143 return true; 3144 if (!NoexceptInType) 3145 return false; 3146 3147 // C++17 onwards: exception specification is part of the type, as a simple 3148 // boolean "can this function type throw". 3149 if (ESI.Type == EST_BasicNoexcept) 3150 return true; 3151 3152 // A dynamic exception specification is canonical if it only contains pack 3153 // expansions (so we can't tell whether it's non-throwing). 3154 if (ESI.Type == EST_Dynamic) { 3155 for (QualType ET : ESI.Exceptions) 3156 if (!ET->getAs<PackExpansionType>()) 3157 return false; 3158 return true; 3159 } 3160 3161 // A noexcept(expr) specification is canonical if expr is value-dependent. 3162 if (ESI.Type == EST_ComputedNoexcept) 3163 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent(); 3164 3165 return false; 3166 } 3167 3168 QualType 3169 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray, 3170 const FunctionProtoType::ExtProtoInfo &EPI) const { 3171 size_t NumArgs = ArgArray.size(); 3172 3173 // Unique functions, to guarantee there is only one function of a particular 3174 // structure. 3175 llvm::FoldingSetNodeID ID; 3176 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 3177 *this); 3178 3179 void *InsertPos = nullptr; 3180 if (FunctionProtoType *FTP = 3181 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3182 return QualType(FTP, 0); 3183 3184 bool NoexceptInType = getLangOpts().CPlusPlus1z; 3185 3186 bool IsCanonicalExceptionSpec = 3187 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 3188 3189 // Determine whether the type being created is already canonical or not. 3190 bool isCanonical = IsCanonicalExceptionSpec && 3191 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 3192 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 3193 if (!ArgArray[i].isCanonicalAsParam()) 3194 isCanonical = false; 3195 3196 // If this type isn't canonical, get the canonical version of it. 3197 // The exception spec is not part of the canonical type. 3198 QualType Canonical; 3199 if (!isCanonical) { 3200 SmallVector<QualType, 16> CanonicalArgs; 3201 CanonicalArgs.reserve(NumArgs); 3202 for (unsigned i = 0; i != NumArgs; ++i) 3203 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 3204 3205 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 3206 CanonicalEPI.HasTrailingReturn = false; 3207 3208 if (IsCanonicalExceptionSpec) { 3209 // Exception spec is already OK. 3210 } else if (NoexceptInType) { 3211 switch (EPI.ExceptionSpec.Type) { 3212 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 3213 // We don't know yet. It shouldn't matter what we pick here; no-one 3214 // should ever look at this. 3215 LLVM_FALLTHROUGH; 3216 case EST_None: case EST_MSAny: case EST_Dynamic: 3217 // If we get here for EST_Dynamic, there is at least one 3218 // non-pack-expansion type, so this is not non-throwing. 3219 CanonicalEPI.ExceptionSpec.Type = EST_None; 3220 break; 3221 3222 case EST_DynamicNone: case EST_BasicNoexcept: 3223 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 3224 break; 3225 3226 case EST_ComputedNoexcept: 3227 llvm::APSInt Value(1); 3228 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr; 3229 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr, 3230 /*IsEvaluated*/false)) { 3231 // This noexcept specification is invalid. 3232 // FIXME: Should this be able to happen? 3233 CanonicalEPI.ExceptionSpec.Type = EST_None; 3234 break; 3235 } 3236 3237 CanonicalEPI.ExceptionSpec.Type = 3238 Value.getBoolValue() ? EST_BasicNoexcept : EST_None; 3239 break; 3240 } 3241 assert(isCanonicalExceptionSpecification(CanonicalEPI.ExceptionSpec, 3242 NoexceptInType)); 3243 } else { 3244 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 3245 } 3246 3247 // Adjust the canonical function result type. 3248 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 3249 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI); 3250 3251 // Get the new insert position for the node we care about. 3252 FunctionProtoType *NewIP = 3253 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3254 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3255 } 3256 3257 // FunctionProtoType objects are allocated with extra bytes after 3258 // them for three variable size arrays at the end: 3259 // - parameter types 3260 // - exception types 3261 // - extended parameter information 3262 // Instead of the exception types, there could be a noexcept 3263 // expression, or information used to resolve the exception 3264 // specification. 3265 size_t Size = sizeof(FunctionProtoType) + 3266 NumArgs * sizeof(QualType); 3267 3268 if (EPI.ExceptionSpec.Type == EST_Dynamic) { 3269 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType); 3270 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) { 3271 Size += sizeof(Expr*); 3272 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { 3273 Size += 2 * sizeof(FunctionDecl*); 3274 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { 3275 Size += sizeof(FunctionDecl*); 3276 } 3277 3278 // Put the ExtParameterInfos last. If all were equal, it would make 3279 // more sense to put these before the exception specification, because 3280 // it's much easier to skip past them compared to the elaborate switch 3281 // required to skip the exception specification. However, all is not 3282 // equal; ExtParameterInfos are used to model very uncommon features, 3283 // and it's better not to burden the more common paths. 3284 if (EPI.ExtParameterInfos) { 3285 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo); 3286 } 3287 3288 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 3289 FunctionProtoType::ExtProtoInfo newEPI = EPI; 3290 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 3291 Types.push_back(FTP); 3292 FunctionProtoTypes.InsertNode(FTP, InsertPos); 3293 return QualType(FTP, 0); 3294 } 3295 3296 /// Return pipe type for the specified type. 3297 QualType ASTContext::getPipeType(QualType T) const { 3298 llvm::FoldingSetNodeID ID; 3299 PipeType::Profile(ID, T); 3300 3301 void *InsertPos = 0; 3302 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 3303 return QualType(PT, 0); 3304 3305 // If the pipe element type isn't canonical, this won't be a canonical type 3306 // either, so fill in the canonical type field. 3307 QualType Canonical; 3308 if (!T.isCanonical()) { 3309 Canonical = getPipeType(getCanonicalType(T)); 3310 3311 // Get the new insert position for the node we care about. 3312 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 3313 assert(!NewIP && "Shouldn't be in the map!"); 3314 (void)NewIP; 3315 } 3316 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical); 3317 Types.push_back(New); 3318 PipeTypes.InsertNode(New, InsertPos); 3319 return QualType(New, 0); 3320 } 3321 3322 #ifndef NDEBUG 3323 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 3324 if (!isa<CXXRecordDecl>(D)) return false; 3325 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 3326 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 3327 return true; 3328 if (RD->getDescribedClassTemplate() && 3329 !isa<ClassTemplateSpecializationDecl>(RD)) 3330 return true; 3331 return false; 3332 } 3333 #endif 3334 3335 /// getInjectedClassNameType - Return the unique reference to the 3336 /// injected class name type for the specified templated declaration. 3337 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 3338 QualType TST) const { 3339 assert(NeedsInjectedClassNameType(Decl)); 3340 if (Decl->TypeForDecl) { 3341 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3342 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 3343 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 3344 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3345 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3346 } else { 3347 Type *newType = 3348 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 3349 Decl->TypeForDecl = newType; 3350 Types.push_back(newType); 3351 } 3352 return QualType(Decl->TypeForDecl, 0); 3353 } 3354 3355 /// getTypeDeclType - Return the unique reference to the type for the 3356 /// specified type declaration. 3357 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 3358 assert(Decl && "Passed null for Decl param"); 3359 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 3360 3361 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 3362 return getTypedefType(Typedef); 3363 3364 assert(!isa<TemplateTypeParmDecl>(Decl) && 3365 "Template type parameter types are always available."); 3366 3367 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 3368 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 3369 assert(!NeedsInjectedClassNameType(Record)); 3370 return getRecordType(Record); 3371 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 3372 assert(Enum->isFirstDecl() && "enum has previous declaration"); 3373 return getEnumType(Enum); 3374 } else if (const UnresolvedUsingTypenameDecl *Using = 3375 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 3376 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 3377 Decl->TypeForDecl = newType; 3378 Types.push_back(newType); 3379 } else 3380 llvm_unreachable("TypeDecl without a type?"); 3381 3382 return QualType(Decl->TypeForDecl, 0); 3383 } 3384 3385 /// getTypedefType - Return the unique reference to the type for the 3386 /// specified typedef name decl. 3387 QualType 3388 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 3389 QualType Canonical) const { 3390 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3391 3392 if (Canonical.isNull()) 3393 Canonical = getCanonicalType(Decl->getUnderlyingType()); 3394 TypedefType *newType = new(*this, TypeAlignment) 3395 TypedefType(Type::Typedef, Decl, Canonical); 3396 Decl->TypeForDecl = newType; 3397 Types.push_back(newType); 3398 return QualType(newType, 0); 3399 } 3400 3401 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 3402 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3403 3404 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 3405 if (PrevDecl->TypeForDecl) 3406 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3407 3408 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 3409 Decl->TypeForDecl = newType; 3410 Types.push_back(newType); 3411 return QualType(newType, 0); 3412 } 3413 3414 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3415 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3416 3417 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3418 if (PrevDecl->TypeForDecl) 3419 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3420 3421 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 3422 Decl->TypeForDecl = newType; 3423 Types.push_back(newType); 3424 return QualType(newType, 0); 3425 } 3426 3427 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3428 QualType modifiedType, 3429 QualType equivalentType) { 3430 llvm::FoldingSetNodeID id; 3431 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3432 3433 void *insertPos = nullptr; 3434 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3435 if (type) return QualType(type, 0); 3436 3437 QualType canon = getCanonicalType(equivalentType); 3438 type = new (*this, TypeAlignment) 3439 AttributedType(canon, attrKind, modifiedType, equivalentType); 3440 3441 Types.push_back(type); 3442 AttributedTypes.InsertNode(type, insertPos); 3443 3444 return QualType(type, 0); 3445 } 3446 3447 /// \brief Retrieve a substitution-result type. 3448 QualType 3449 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3450 QualType Replacement) const { 3451 assert(Replacement.isCanonical() 3452 && "replacement types must always be canonical"); 3453 3454 llvm::FoldingSetNodeID ID; 3455 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3456 void *InsertPos = nullptr; 3457 SubstTemplateTypeParmType *SubstParm 3458 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3459 3460 if (!SubstParm) { 3461 SubstParm = new (*this, TypeAlignment) 3462 SubstTemplateTypeParmType(Parm, Replacement); 3463 Types.push_back(SubstParm); 3464 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3465 } 3466 3467 return QualType(SubstParm, 0); 3468 } 3469 3470 /// \brief Retrieve a 3471 QualType ASTContext::getSubstTemplateTypeParmPackType( 3472 const TemplateTypeParmType *Parm, 3473 const TemplateArgument &ArgPack) { 3474 #ifndef NDEBUG 3475 for (const auto &P : ArgPack.pack_elements()) { 3476 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3477 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3478 } 3479 #endif 3480 3481 llvm::FoldingSetNodeID ID; 3482 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3483 void *InsertPos = nullptr; 3484 if (SubstTemplateTypeParmPackType *SubstParm 3485 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3486 return QualType(SubstParm, 0); 3487 3488 QualType Canon; 3489 if (!Parm->isCanonicalUnqualified()) { 3490 Canon = getCanonicalType(QualType(Parm, 0)); 3491 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3492 ArgPack); 3493 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3494 } 3495 3496 SubstTemplateTypeParmPackType *SubstParm 3497 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3498 ArgPack); 3499 Types.push_back(SubstParm); 3500 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3501 return QualType(SubstParm, 0); 3502 } 3503 3504 /// \brief Retrieve the template type parameter type for a template 3505 /// parameter or parameter pack with the given depth, index, and (optionally) 3506 /// name. 3507 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3508 bool ParameterPack, 3509 TemplateTypeParmDecl *TTPDecl) const { 3510 llvm::FoldingSetNodeID ID; 3511 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3512 void *InsertPos = nullptr; 3513 TemplateTypeParmType *TypeParm 3514 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3515 3516 if (TypeParm) 3517 return QualType(TypeParm, 0); 3518 3519 if (TTPDecl) { 3520 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3521 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3522 3523 TemplateTypeParmType *TypeCheck 3524 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3525 assert(!TypeCheck && "Template type parameter canonical type broken"); 3526 (void)TypeCheck; 3527 } else 3528 TypeParm = new (*this, TypeAlignment) 3529 TemplateTypeParmType(Depth, Index, ParameterPack); 3530 3531 Types.push_back(TypeParm); 3532 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3533 3534 return QualType(TypeParm, 0); 3535 } 3536 3537 TypeSourceInfo * 3538 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3539 SourceLocation NameLoc, 3540 const TemplateArgumentListInfo &Args, 3541 QualType Underlying) const { 3542 assert(!Name.getAsDependentTemplateName() && 3543 "No dependent template names here!"); 3544 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3545 3546 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3547 TemplateSpecializationTypeLoc TL = 3548 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3549 TL.setTemplateKeywordLoc(SourceLocation()); 3550 TL.setTemplateNameLoc(NameLoc); 3551 TL.setLAngleLoc(Args.getLAngleLoc()); 3552 TL.setRAngleLoc(Args.getRAngleLoc()); 3553 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3554 TL.setArgLocInfo(i, Args[i].getLocInfo()); 3555 return DI; 3556 } 3557 3558 QualType 3559 ASTContext::getTemplateSpecializationType(TemplateName Template, 3560 const TemplateArgumentListInfo &Args, 3561 QualType Underlying) const { 3562 assert(!Template.getAsDependentTemplateName() && 3563 "No dependent template names here!"); 3564 3565 SmallVector<TemplateArgument, 4> ArgVec; 3566 ArgVec.reserve(Args.size()); 3567 for (const TemplateArgumentLoc &Arg : Args.arguments()) 3568 ArgVec.push_back(Arg.getArgument()); 3569 3570 return getTemplateSpecializationType(Template, ArgVec, Underlying); 3571 } 3572 3573 #ifndef NDEBUG 3574 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 3575 for (const TemplateArgument &Arg : Args) 3576 if (Arg.isPackExpansion()) 3577 return true; 3578 3579 return true; 3580 } 3581 #endif 3582 3583 QualType 3584 ASTContext::getTemplateSpecializationType(TemplateName Template, 3585 ArrayRef<TemplateArgument> Args, 3586 QualType Underlying) const { 3587 assert(!Template.getAsDependentTemplateName() && 3588 "No dependent template names here!"); 3589 // Look through qualified template names. 3590 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3591 Template = TemplateName(QTN->getTemplateDecl()); 3592 3593 bool IsTypeAlias = 3594 Template.getAsTemplateDecl() && 3595 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 3596 QualType CanonType; 3597 if (!Underlying.isNull()) 3598 CanonType = getCanonicalType(Underlying); 3599 else { 3600 // We can get here with an alias template when the specialization contains 3601 // a pack expansion that does not match up with a parameter pack. 3602 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 3603 "Caller must compute aliased type"); 3604 IsTypeAlias = false; 3605 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 3606 } 3607 3608 // Allocate the (non-canonical) template specialization type, but don't 3609 // try to unique it: these types typically have location information that 3610 // we don't unique and don't want to lose. 3611 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 3612 sizeof(TemplateArgument) * Args.size() + 3613 (IsTypeAlias? sizeof(QualType) : 0), 3614 TypeAlignment); 3615 TemplateSpecializationType *Spec 3616 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 3617 IsTypeAlias ? Underlying : QualType()); 3618 3619 Types.push_back(Spec); 3620 return QualType(Spec, 0); 3621 } 3622 3623 QualType ASTContext::getCanonicalTemplateSpecializationType( 3624 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 3625 assert(!Template.getAsDependentTemplateName() && 3626 "No dependent template names here!"); 3627 3628 // Look through qualified template names. 3629 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3630 Template = TemplateName(QTN->getTemplateDecl()); 3631 3632 // Build the canonical template specialization type. 3633 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 3634 SmallVector<TemplateArgument, 4> CanonArgs; 3635 unsigned NumArgs = Args.size(); 3636 CanonArgs.reserve(NumArgs); 3637 for (const TemplateArgument &Arg : Args) 3638 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 3639 3640 // Determine whether this canonical template specialization type already 3641 // exists. 3642 llvm::FoldingSetNodeID ID; 3643 TemplateSpecializationType::Profile(ID, CanonTemplate, 3644 CanonArgs, *this); 3645 3646 void *InsertPos = nullptr; 3647 TemplateSpecializationType *Spec 3648 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3649 3650 if (!Spec) { 3651 // Allocate a new canonical template specialization type. 3652 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 3653 sizeof(TemplateArgument) * NumArgs), 3654 TypeAlignment); 3655 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 3656 CanonArgs, 3657 QualType(), QualType()); 3658 Types.push_back(Spec); 3659 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 3660 } 3661 3662 assert(Spec->isDependentType() && 3663 "Non-dependent template-id type must have a canonical type"); 3664 return QualType(Spec, 0); 3665 } 3666 3667 QualType 3668 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 3669 NestedNameSpecifier *NNS, 3670 QualType NamedType) const { 3671 llvm::FoldingSetNodeID ID; 3672 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 3673 3674 void *InsertPos = nullptr; 3675 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3676 if (T) 3677 return QualType(T, 0); 3678 3679 QualType Canon = NamedType; 3680 if (!Canon.isCanonical()) { 3681 Canon = getCanonicalType(NamedType); 3682 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3683 assert(!CheckT && "Elaborated canonical type broken"); 3684 (void)CheckT; 3685 } 3686 3687 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon); 3688 Types.push_back(T); 3689 ElaboratedTypes.InsertNode(T, InsertPos); 3690 return QualType(T, 0); 3691 } 3692 3693 QualType 3694 ASTContext::getParenType(QualType InnerType) const { 3695 llvm::FoldingSetNodeID ID; 3696 ParenType::Profile(ID, InnerType); 3697 3698 void *InsertPos = nullptr; 3699 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3700 if (T) 3701 return QualType(T, 0); 3702 3703 QualType Canon = InnerType; 3704 if (!Canon.isCanonical()) { 3705 Canon = getCanonicalType(InnerType); 3706 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3707 assert(!CheckT && "Paren canonical type broken"); 3708 (void)CheckT; 3709 } 3710 3711 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 3712 Types.push_back(T); 3713 ParenTypes.InsertNode(T, InsertPos); 3714 return QualType(T, 0); 3715 } 3716 3717 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 3718 NestedNameSpecifier *NNS, 3719 const IdentifierInfo *Name, 3720 QualType Canon) const { 3721 if (Canon.isNull()) { 3722 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3723 ElaboratedTypeKeyword CanonKeyword = Keyword; 3724 if (Keyword == ETK_None) 3725 CanonKeyword = ETK_Typename; 3726 3727 if (CanonNNS != NNS || CanonKeyword != Keyword) 3728 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 3729 } 3730 3731 llvm::FoldingSetNodeID ID; 3732 DependentNameType::Profile(ID, Keyword, NNS, Name); 3733 3734 void *InsertPos = nullptr; 3735 DependentNameType *T 3736 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 3737 if (T) 3738 return QualType(T, 0); 3739 3740 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 3741 Types.push_back(T); 3742 DependentNameTypes.InsertNode(T, InsertPos); 3743 return QualType(T, 0); 3744 } 3745 3746 QualType 3747 ASTContext::getDependentTemplateSpecializationType( 3748 ElaboratedTypeKeyword Keyword, 3749 NestedNameSpecifier *NNS, 3750 const IdentifierInfo *Name, 3751 const TemplateArgumentListInfo &Args) const { 3752 // TODO: avoid this copy 3753 SmallVector<TemplateArgument, 16> ArgCopy; 3754 for (unsigned I = 0, E = Args.size(); I != E; ++I) 3755 ArgCopy.push_back(Args[I].getArgument()); 3756 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 3757 } 3758 3759 QualType 3760 ASTContext::getDependentTemplateSpecializationType( 3761 ElaboratedTypeKeyword Keyword, 3762 NestedNameSpecifier *NNS, 3763 const IdentifierInfo *Name, 3764 ArrayRef<TemplateArgument> Args) const { 3765 assert((!NNS || NNS->isDependent()) && 3766 "nested-name-specifier must be dependent"); 3767 3768 llvm::FoldingSetNodeID ID; 3769 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 3770 Name, Args); 3771 3772 void *InsertPos = nullptr; 3773 DependentTemplateSpecializationType *T 3774 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3775 if (T) 3776 return QualType(T, 0); 3777 3778 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3779 3780 ElaboratedTypeKeyword CanonKeyword = Keyword; 3781 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 3782 3783 bool AnyNonCanonArgs = false; 3784 unsigned NumArgs = Args.size(); 3785 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 3786 for (unsigned I = 0; I != NumArgs; ++I) { 3787 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 3788 if (!CanonArgs[I].structurallyEquals(Args[I])) 3789 AnyNonCanonArgs = true; 3790 } 3791 3792 QualType Canon; 3793 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 3794 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 3795 Name, 3796 CanonArgs); 3797 3798 // Find the insert position again. 3799 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3800 } 3801 3802 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3803 sizeof(TemplateArgument) * NumArgs), 3804 TypeAlignment); 3805 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3806 Name, Args, Canon); 3807 Types.push_back(T); 3808 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3809 return QualType(T, 0); 3810 } 3811 3812 QualType ASTContext::getPackExpansionType(QualType Pattern, 3813 Optional<unsigned> NumExpansions) { 3814 llvm::FoldingSetNodeID ID; 3815 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3816 3817 assert(Pattern->containsUnexpandedParameterPack() && 3818 "Pack expansions must expand one or more parameter packs"); 3819 void *InsertPos = nullptr; 3820 PackExpansionType *T 3821 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3822 if (T) 3823 return QualType(T, 0); 3824 3825 QualType Canon; 3826 if (!Pattern.isCanonical()) { 3827 Canon = getCanonicalType(Pattern); 3828 // The canonical type might not contain an unexpanded parameter pack, if it 3829 // contains an alias template specialization which ignores one of its 3830 // parameters. 3831 if (Canon->containsUnexpandedParameterPack()) { 3832 Canon = getPackExpansionType(Canon, NumExpansions); 3833 3834 // Find the insert position again, in case we inserted an element into 3835 // PackExpansionTypes and invalidated our insert position. 3836 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3837 } 3838 } 3839 3840 T = new (*this, TypeAlignment) 3841 PackExpansionType(Pattern, Canon, NumExpansions); 3842 Types.push_back(T); 3843 PackExpansionTypes.InsertNode(T, InsertPos); 3844 return QualType(T, 0); 3845 } 3846 3847 /// CmpProtocolNames - Comparison predicate for sorting protocols 3848 /// alphabetically. 3849 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 3850 ObjCProtocolDecl *const *RHS) { 3851 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 3852 } 3853 3854 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 3855 if (Protocols.empty()) return true; 3856 3857 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3858 return false; 3859 3860 for (unsigned i = 1; i != Protocols.size(); ++i) 3861 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 3862 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3863 return false; 3864 return true; 3865 } 3866 3867 static void 3868 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 3869 // Sort protocols, keyed by name. 3870 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 3871 3872 // Canonicalize. 3873 for (ObjCProtocolDecl *&P : Protocols) 3874 P = P->getCanonicalDecl(); 3875 3876 // Remove duplicates. 3877 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 3878 Protocols.erase(ProtocolsEnd, Protocols.end()); 3879 } 3880 3881 QualType ASTContext::getObjCObjectType(QualType BaseType, 3882 ObjCProtocolDecl * const *Protocols, 3883 unsigned NumProtocols) const { 3884 return getObjCObjectType(BaseType, { }, 3885 llvm::makeArrayRef(Protocols, NumProtocols), 3886 /*isKindOf=*/false); 3887 } 3888 3889 QualType ASTContext::getObjCObjectType( 3890 QualType baseType, 3891 ArrayRef<QualType> typeArgs, 3892 ArrayRef<ObjCProtocolDecl *> protocols, 3893 bool isKindOf) const { 3894 // If the base type is an interface and there aren't any protocols or 3895 // type arguments to add, then the interface type will do just fine. 3896 if (typeArgs.empty() && protocols.empty() && !isKindOf && 3897 isa<ObjCInterfaceType>(baseType)) 3898 return baseType; 3899 3900 // Look in the folding set for an existing type. 3901 llvm::FoldingSetNodeID ID; 3902 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 3903 void *InsertPos = nullptr; 3904 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3905 return QualType(QT, 0); 3906 3907 // Determine the type arguments to be used for canonicalization, 3908 // which may be explicitly specified here or written on the base 3909 // type. 3910 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 3911 if (effectiveTypeArgs.empty()) { 3912 if (auto baseObject = baseType->getAs<ObjCObjectType>()) 3913 effectiveTypeArgs = baseObject->getTypeArgs(); 3914 } 3915 3916 // Build the canonical type, which has the canonical base type and a 3917 // sorted-and-uniqued list of protocols and the type arguments 3918 // canonicalized. 3919 QualType canonical; 3920 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 3921 effectiveTypeArgs.end(), 3922 [&](QualType type) { 3923 return type.isCanonical(); 3924 }); 3925 bool protocolsSorted = areSortedAndUniqued(protocols); 3926 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 3927 // Determine the canonical type arguments. 3928 ArrayRef<QualType> canonTypeArgs; 3929 SmallVector<QualType, 4> canonTypeArgsVec; 3930 if (!typeArgsAreCanonical) { 3931 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 3932 for (auto typeArg : effectiveTypeArgs) 3933 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 3934 canonTypeArgs = canonTypeArgsVec; 3935 } else { 3936 canonTypeArgs = effectiveTypeArgs; 3937 } 3938 3939 ArrayRef<ObjCProtocolDecl *> canonProtocols; 3940 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 3941 if (!protocolsSorted) { 3942 canonProtocolsVec.append(protocols.begin(), protocols.end()); 3943 SortAndUniqueProtocols(canonProtocolsVec); 3944 canonProtocols = canonProtocolsVec; 3945 } else { 3946 canonProtocols = protocols; 3947 } 3948 3949 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 3950 canonProtocols, isKindOf); 3951 3952 // Regenerate InsertPos. 3953 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3954 } 3955 3956 unsigned size = sizeof(ObjCObjectTypeImpl); 3957 size += typeArgs.size() * sizeof(QualType); 3958 size += protocols.size() * sizeof(ObjCProtocolDecl *); 3959 void *mem = Allocate(size, TypeAlignment); 3960 ObjCObjectTypeImpl *T = 3961 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 3962 isKindOf); 3963 3964 Types.push_back(T); 3965 ObjCObjectTypes.InsertNode(T, InsertPos); 3966 return QualType(T, 0); 3967 } 3968 3969 /// Apply Objective-C protocol qualifiers to the given type. 3970 /// If this is for the canonical type of a type parameter, we can apply 3971 /// protocol qualifiers on the ObjCObjectPointerType. 3972 QualType 3973 ASTContext::applyObjCProtocolQualifiers(QualType type, 3974 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 3975 bool allowOnPointerType) const { 3976 hasError = false; 3977 3978 if (const ObjCTypeParamType *objT = 3979 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 3980 return getObjCTypeParamType(objT->getDecl(), protocols); 3981 } 3982 3983 // Apply protocol qualifiers to ObjCObjectPointerType. 3984 if (allowOnPointerType) { 3985 if (const ObjCObjectPointerType *objPtr = 3986 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 3987 const ObjCObjectType *objT = objPtr->getObjectType(); 3988 // Merge protocol lists and construct ObjCObjectType. 3989 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 3990 protocolsVec.append(objT->qual_begin(), 3991 objT->qual_end()); 3992 protocolsVec.append(protocols.begin(), protocols.end()); 3993 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 3994 type = getObjCObjectType( 3995 objT->getBaseType(), 3996 objT->getTypeArgsAsWritten(), 3997 protocols, 3998 objT->isKindOfTypeAsWritten()); 3999 return getObjCObjectPointerType(type); 4000 } 4001 } 4002 4003 // Apply protocol qualifiers to ObjCObjectType. 4004 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 4005 // FIXME: Check for protocols to which the class type is already 4006 // known to conform. 4007 4008 return getObjCObjectType(objT->getBaseType(), 4009 objT->getTypeArgsAsWritten(), 4010 protocols, 4011 objT->isKindOfTypeAsWritten()); 4012 } 4013 4014 // If the canonical type is ObjCObjectType, ... 4015 if (type->isObjCObjectType()) { 4016 // Silently overwrite any existing protocol qualifiers. 4017 // TODO: determine whether that's the right thing to do. 4018 4019 // FIXME: Check for protocols to which the class type is already 4020 // known to conform. 4021 return getObjCObjectType(type, { }, protocols, false); 4022 } 4023 4024 // id<protocol-list> 4025 if (type->isObjCIdType()) { 4026 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>(); 4027 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols, 4028 objPtr->isKindOfType()); 4029 return getObjCObjectPointerType(type); 4030 } 4031 4032 // Class<protocol-list> 4033 if (type->isObjCClassType()) { 4034 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>(); 4035 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols, 4036 objPtr->isKindOfType()); 4037 return getObjCObjectPointerType(type); 4038 } 4039 4040 hasError = true; 4041 return type; 4042 } 4043 4044 QualType 4045 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 4046 ArrayRef<ObjCProtocolDecl *> protocols, 4047 QualType Canonical) const { 4048 // Look in the folding set for an existing type. 4049 llvm::FoldingSetNodeID ID; 4050 ObjCTypeParamType::Profile(ID, Decl, protocols); 4051 void *InsertPos = nullptr; 4052 if (ObjCTypeParamType *TypeParam = 4053 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 4054 return QualType(TypeParam, 0); 4055 4056 if (Canonical.isNull()) { 4057 // We canonicalize to the underlying type. 4058 Canonical = getCanonicalType(Decl->getUnderlyingType()); 4059 if (!protocols.empty()) { 4060 // Apply the protocol qualifers. 4061 bool hasError; 4062 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError, 4063 true/*allowOnPointerType*/); 4064 assert(!hasError && "Error when apply protocol qualifier to bound type"); 4065 } 4066 } 4067 4068 unsigned size = sizeof(ObjCTypeParamType); 4069 size += protocols.size() * sizeof(ObjCProtocolDecl *); 4070 void *mem = Allocate(size, TypeAlignment); 4071 ObjCTypeParamType *newType = new (mem) 4072 ObjCTypeParamType(Decl, Canonical, protocols); 4073 4074 Types.push_back(newType); 4075 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 4076 return QualType(newType, 0); 4077 } 4078 4079 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 4080 /// protocol list adopt all protocols in QT's qualified-id protocol 4081 /// list. 4082 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 4083 ObjCInterfaceDecl *IC) { 4084 if (!QT->isObjCQualifiedIdType()) 4085 return false; 4086 4087 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) { 4088 // If both the right and left sides have qualifiers. 4089 for (auto *Proto : OPT->quals()) { 4090 if (!IC->ClassImplementsProtocol(Proto, false)) 4091 return false; 4092 } 4093 return true; 4094 } 4095 return false; 4096 } 4097 4098 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 4099 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 4100 /// of protocols. 4101 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 4102 ObjCInterfaceDecl *IDecl) { 4103 if (!QT->isObjCQualifiedIdType()) 4104 return false; 4105 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 4106 if (!OPT) 4107 return false; 4108 if (!IDecl->hasDefinition()) 4109 return false; 4110 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 4111 CollectInheritedProtocols(IDecl, InheritedProtocols); 4112 if (InheritedProtocols.empty()) 4113 return false; 4114 // Check that if every protocol in list of id<plist> conforms to a protcol 4115 // of IDecl's, then bridge casting is ok. 4116 bool Conforms = false; 4117 for (auto *Proto : OPT->quals()) { 4118 Conforms = false; 4119 for (auto *PI : InheritedProtocols) { 4120 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 4121 Conforms = true; 4122 break; 4123 } 4124 } 4125 if (!Conforms) 4126 break; 4127 } 4128 if (Conforms) 4129 return true; 4130 4131 for (auto *PI : InheritedProtocols) { 4132 // If both the right and left sides have qualifiers. 4133 bool Adopts = false; 4134 for (auto *Proto : OPT->quals()) { 4135 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 4136 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 4137 break; 4138 } 4139 if (!Adopts) 4140 return false; 4141 } 4142 return true; 4143 } 4144 4145 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 4146 /// the given object type. 4147 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 4148 llvm::FoldingSetNodeID ID; 4149 ObjCObjectPointerType::Profile(ID, ObjectT); 4150 4151 void *InsertPos = nullptr; 4152 if (ObjCObjectPointerType *QT = 4153 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 4154 return QualType(QT, 0); 4155 4156 // Find the canonical object type. 4157 QualType Canonical; 4158 if (!ObjectT.isCanonical()) { 4159 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 4160 4161 // Regenerate InsertPos. 4162 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 4163 } 4164 4165 // No match. 4166 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 4167 ObjCObjectPointerType *QType = 4168 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 4169 4170 Types.push_back(QType); 4171 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 4172 return QualType(QType, 0); 4173 } 4174 4175 /// getObjCInterfaceType - Return the unique reference to the type for the 4176 /// specified ObjC interface decl. The list of protocols is optional. 4177 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 4178 ObjCInterfaceDecl *PrevDecl) const { 4179 if (Decl->TypeForDecl) 4180 return QualType(Decl->TypeForDecl, 0); 4181 4182 if (PrevDecl) { 4183 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 4184 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4185 return QualType(PrevDecl->TypeForDecl, 0); 4186 } 4187 4188 // Prefer the definition, if there is one. 4189 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 4190 Decl = Def; 4191 4192 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 4193 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 4194 Decl->TypeForDecl = T; 4195 Types.push_back(T); 4196 return QualType(T, 0); 4197 } 4198 4199 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 4200 /// TypeOfExprType AST's (since expression's are never shared). For example, 4201 /// multiple declarations that refer to "typeof(x)" all contain different 4202 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 4203 /// on canonical type's (which are always unique). 4204 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 4205 TypeOfExprType *toe; 4206 if (tofExpr->isTypeDependent()) { 4207 llvm::FoldingSetNodeID ID; 4208 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 4209 4210 void *InsertPos = nullptr; 4211 DependentTypeOfExprType *Canon 4212 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 4213 if (Canon) { 4214 // We already have a "canonical" version of an identical, dependent 4215 // typeof(expr) type. Use that as our canonical type. 4216 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 4217 QualType((TypeOfExprType*)Canon, 0)); 4218 } else { 4219 // Build a new, canonical typeof(expr) type. 4220 Canon 4221 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 4222 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 4223 toe = Canon; 4224 } 4225 } else { 4226 QualType Canonical = getCanonicalType(tofExpr->getType()); 4227 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 4228 } 4229 Types.push_back(toe); 4230 return QualType(toe, 0); 4231 } 4232 4233 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 4234 /// TypeOfType nodes. The only motivation to unique these nodes would be 4235 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 4236 /// an issue. This doesn't affect the type checker, since it operates 4237 /// on canonical types (which are always unique). 4238 QualType ASTContext::getTypeOfType(QualType tofType) const { 4239 QualType Canonical = getCanonicalType(tofType); 4240 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 4241 Types.push_back(tot); 4242 return QualType(tot, 0); 4243 } 4244 4245 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType 4246 /// nodes. This would never be helpful, since each such type has its own 4247 /// expression, and would not give a significant memory saving, since there 4248 /// is an Expr tree under each such type. 4249 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 4250 DecltypeType *dt; 4251 4252 // C++11 [temp.type]p2: 4253 // If an expression e involves a template parameter, decltype(e) denotes a 4254 // unique dependent type. Two such decltype-specifiers refer to the same 4255 // type only if their expressions are equivalent (14.5.6.1). 4256 if (e->isInstantiationDependent()) { 4257 llvm::FoldingSetNodeID ID; 4258 DependentDecltypeType::Profile(ID, *this, e); 4259 4260 void *InsertPos = nullptr; 4261 DependentDecltypeType *Canon 4262 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 4263 if (!Canon) { 4264 // Build a new, canonical typeof(expr) type. 4265 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 4266 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 4267 } 4268 dt = new (*this, TypeAlignment) 4269 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 4270 } else { 4271 dt = new (*this, TypeAlignment) 4272 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 4273 } 4274 Types.push_back(dt); 4275 return QualType(dt, 0); 4276 } 4277 4278 /// getUnaryTransformationType - We don't unique these, since the memory 4279 /// savings are minimal and these are rare. 4280 QualType ASTContext::getUnaryTransformType(QualType BaseType, 4281 QualType UnderlyingType, 4282 UnaryTransformType::UTTKind Kind) 4283 const { 4284 UnaryTransformType *ut = nullptr; 4285 4286 if (BaseType->isDependentType()) { 4287 // Look in the folding set for an existing type. 4288 llvm::FoldingSetNodeID ID; 4289 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 4290 4291 void *InsertPos = nullptr; 4292 DependentUnaryTransformType *Canon 4293 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 4294 4295 if (!Canon) { 4296 // Build a new, canonical __underlying_type(type) type. 4297 Canon = new (*this, TypeAlignment) 4298 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 4299 Kind); 4300 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 4301 } 4302 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4303 QualType(), Kind, 4304 QualType(Canon, 0)); 4305 } else { 4306 QualType CanonType = getCanonicalType(UnderlyingType); 4307 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4308 UnderlyingType, Kind, 4309 CanonType); 4310 } 4311 Types.push_back(ut); 4312 return QualType(ut, 0); 4313 } 4314 4315 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 4316 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 4317 /// canonical deduced-but-dependent 'auto' type. 4318 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 4319 bool IsDependent) const { 4320 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent) 4321 return getAutoDeductType(); 4322 4323 // Look in the folding set for an existing type. 4324 void *InsertPos = nullptr; 4325 llvm::FoldingSetNodeID ID; 4326 AutoType::Profile(ID, DeducedType, Keyword, IsDependent); 4327 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4328 return QualType(AT, 0); 4329 4330 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType, 4331 Keyword, 4332 IsDependent); 4333 Types.push_back(AT); 4334 if (InsertPos) 4335 AutoTypes.InsertNode(AT, InsertPos); 4336 return QualType(AT, 0); 4337 } 4338 4339 /// getAtomicType - Return the uniqued reference to the atomic type for 4340 /// the given value type. 4341 QualType ASTContext::getAtomicType(QualType T) const { 4342 // Unique pointers, to guarantee there is only one pointer of a particular 4343 // structure. 4344 llvm::FoldingSetNodeID ID; 4345 AtomicType::Profile(ID, T); 4346 4347 void *InsertPos = nullptr; 4348 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 4349 return QualType(AT, 0); 4350 4351 // If the atomic value type isn't canonical, this won't be a canonical type 4352 // either, so fill in the canonical type field. 4353 QualType Canonical; 4354 if (!T.isCanonical()) { 4355 Canonical = getAtomicType(getCanonicalType(T)); 4356 4357 // Get the new insert position for the node we care about. 4358 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 4359 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4360 } 4361 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 4362 Types.push_back(New); 4363 AtomicTypes.InsertNode(New, InsertPos); 4364 return QualType(New, 0); 4365 } 4366 4367 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 4368 QualType ASTContext::getAutoDeductType() const { 4369 if (AutoDeductTy.isNull()) 4370 AutoDeductTy = QualType( 4371 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto, 4372 /*dependent*/false), 4373 0); 4374 return AutoDeductTy; 4375 } 4376 4377 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 4378 QualType ASTContext::getAutoRRefDeductType() const { 4379 if (AutoRRefDeductTy.isNull()) 4380 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 4381 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 4382 return AutoRRefDeductTy; 4383 } 4384 4385 /// getTagDeclType - Return the unique reference to the type for the 4386 /// specified TagDecl (struct/union/class/enum) decl. 4387 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 4388 assert (Decl); 4389 // FIXME: What is the design on getTagDeclType when it requires casting 4390 // away const? mutable? 4391 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 4392 } 4393 4394 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 4395 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 4396 /// needs to agree with the definition in <stddef.h>. 4397 CanQualType ASTContext::getSizeType() const { 4398 return getFromTargetType(Target->getSizeType()); 4399 } 4400 4401 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 4402 CanQualType ASTContext::getIntMaxType() const { 4403 return getFromTargetType(Target->getIntMaxType()); 4404 } 4405 4406 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 4407 CanQualType ASTContext::getUIntMaxType() const { 4408 return getFromTargetType(Target->getUIntMaxType()); 4409 } 4410 4411 /// getSignedWCharType - Return the type of "signed wchar_t". 4412 /// Used when in C++, as a GCC extension. 4413 QualType ASTContext::getSignedWCharType() const { 4414 // FIXME: derive from "Target" ? 4415 return WCharTy; 4416 } 4417 4418 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 4419 /// Used when in C++, as a GCC extension. 4420 QualType ASTContext::getUnsignedWCharType() const { 4421 // FIXME: derive from "Target" ? 4422 return UnsignedIntTy; 4423 } 4424 4425 QualType ASTContext::getIntPtrType() const { 4426 return getFromTargetType(Target->getIntPtrType()); 4427 } 4428 4429 QualType ASTContext::getUIntPtrType() const { 4430 return getCorrespondingUnsignedType(getIntPtrType()); 4431 } 4432 4433 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 4434 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 4435 QualType ASTContext::getPointerDiffType() const { 4436 return getFromTargetType(Target->getPtrDiffType(0)); 4437 } 4438 4439 /// \brief Return the unique type for "pid_t" defined in 4440 /// <sys/types.h>. We need this to compute the correct type for vfork(). 4441 QualType ASTContext::getProcessIDType() const { 4442 return getFromTargetType(Target->getProcessIDType()); 4443 } 4444 4445 //===----------------------------------------------------------------------===// 4446 // Type Operators 4447 //===----------------------------------------------------------------------===// 4448 4449 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 4450 // Push qualifiers into arrays, and then discard any remaining 4451 // qualifiers. 4452 T = getCanonicalType(T); 4453 T = getVariableArrayDecayedType(T); 4454 const Type *Ty = T.getTypePtr(); 4455 QualType Result; 4456 if (isa<ArrayType>(Ty)) { 4457 Result = getArrayDecayedType(QualType(Ty,0)); 4458 } else if (isa<FunctionType>(Ty)) { 4459 Result = getPointerType(QualType(Ty, 0)); 4460 } else { 4461 Result = QualType(Ty, 0); 4462 } 4463 4464 return CanQualType::CreateUnsafe(Result); 4465 } 4466 4467 QualType ASTContext::getUnqualifiedArrayType(QualType type, 4468 Qualifiers &quals) { 4469 SplitQualType splitType = type.getSplitUnqualifiedType(); 4470 4471 // FIXME: getSplitUnqualifiedType() actually walks all the way to 4472 // the unqualified desugared type and then drops it on the floor. 4473 // We then have to strip that sugar back off with 4474 // getUnqualifiedDesugaredType(), which is silly. 4475 const ArrayType *AT = 4476 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 4477 4478 // If we don't have an array, just use the results in splitType. 4479 if (!AT) { 4480 quals = splitType.Quals; 4481 return QualType(splitType.Ty, 0); 4482 } 4483 4484 // Otherwise, recurse on the array's element type. 4485 QualType elementType = AT->getElementType(); 4486 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 4487 4488 // If that didn't change the element type, AT has no qualifiers, so we 4489 // can just use the results in splitType. 4490 if (elementType == unqualElementType) { 4491 assert(quals.empty()); // from the recursive call 4492 quals = splitType.Quals; 4493 return QualType(splitType.Ty, 0); 4494 } 4495 4496 // Otherwise, add in the qualifiers from the outermost type, then 4497 // build the type back up. 4498 quals.addConsistentQualifiers(splitType.Quals); 4499 4500 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4501 return getConstantArrayType(unqualElementType, CAT->getSize(), 4502 CAT->getSizeModifier(), 0); 4503 } 4504 4505 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 4506 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 4507 } 4508 4509 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 4510 return getVariableArrayType(unqualElementType, 4511 VAT->getSizeExpr(), 4512 VAT->getSizeModifier(), 4513 VAT->getIndexTypeCVRQualifiers(), 4514 VAT->getBracketsRange()); 4515 } 4516 4517 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 4518 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 4519 DSAT->getSizeModifier(), 0, 4520 SourceRange()); 4521 } 4522 4523 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 4524 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 4525 /// they point to and return true. If T1 and T2 aren't pointer types 4526 /// or pointer-to-member types, or if they are not similar at this 4527 /// level, returns false and leaves T1 and T2 unchanged. Top-level 4528 /// qualifiers on T1 and T2 are ignored. This function will typically 4529 /// be called in a loop that successively "unwraps" pointer and 4530 /// pointer-to-member types to compare them at each level. 4531 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 4532 const PointerType *T1PtrType = T1->getAs<PointerType>(), 4533 *T2PtrType = T2->getAs<PointerType>(); 4534 if (T1PtrType && T2PtrType) { 4535 T1 = T1PtrType->getPointeeType(); 4536 T2 = T2PtrType->getPointeeType(); 4537 return true; 4538 } 4539 4540 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 4541 *T2MPType = T2->getAs<MemberPointerType>(); 4542 if (T1MPType && T2MPType && 4543 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 4544 QualType(T2MPType->getClass(), 0))) { 4545 T1 = T1MPType->getPointeeType(); 4546 T2 = T2MPType->getPointeeType(); 4547 return true; 4548 } 4549 4550 if (getLangOpts().ObjC1) { 4551 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 4552 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 4553 if (T1OPType && T2OPType) { 4554 T1 = T1OPType->getPointeeType(); 4555 T2 = T2OPType->getPointeeType(); 4556 return true; 4557 } 4558 } 4559 4560 // FIXME: Block pointers, too? 4561 4562 return false; 4563 } 4564 4565 DeclarationNameInfo 4566 ASTContext::getNameForTemplate(TemplateName Name, 4567 SourceLocation NameLoc) const { 4568 switch (Name.getKind()) { 4569 case TemplateName::QualifiedTemplate: 4570 case TemplateName::Template: 4571 // DNInfo work in progress: CHECKME: what about DNLoc? 4572 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 4573 NameLoc); 4574 4575 case TemplateName::OverloadedTemplate: { 4576 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 4577 // DNInfo work in progress: CHECKME: what about DNLoc? 4578 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 4579 } 4580 4581 case TemplateName::DependentTemplate: { 4582 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4583 DeclarationName DName; 4584 if (DTN->isIdentifier()) { 4585 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 4586 return DeclarationNameInfo(DName, NameLoc); 4587 } else { 4588 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 4589 // DNInfo work in progress: FIXME: source locations? 4590 DeclarationNameLoc DNLoc; 4591 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 4592 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 4593 return DeclarationNameInfo(DName, NameLoc, DNLoc); 4594 } 4595 } 4596 4597 case TemplateName::SubstTemplateTemplateParm: { 4598 SubstTemplateTemplateParmStorage *subst 4599 = Name.getAsSubstTemplateTemplateParm(); 4600 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 4601 NameLoc); 4602 } 4603 4604 case TemplateName::SubstTemplateTemplateParmPack: { 4605 SubstTemplateTemplateParmPackStorage *subst 4606 = Name.getAsSubstTemplateTemplateParmPack(); 4607 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 4608 NameLoc); 4609 } 4610 } 4611 4612 llvm_unreachable("bad template name kind!"); 4613 } 4614 4615 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 4616 switch (Name.getKind()) { 4617 case TemplateName::QualifiedTemplate: 4618 case TemplateName::Template: { 4619 TemplateDecl *Template = Name.getAsTemplateDecl(); 4620 if (TemplateTemplateParmDecl *TTP 4621 = dyn_cast<TemplateTemplateParmDecl>(Template)) 4622 Template = getCanonicalTemplateTemplateParmDecl(TTP); 4623 4624 // The canonical template name is the canonical template declaration. 4625 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 4626 } 4627 4628 case TemplateName::OverloadedTemplate: 4629 llvm_unreachable("cannot canonicalize overloaded template"); 4630 4631 case TemplateName::DependentTemplate: { 4632 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4633 assert(DTN && "Non-dependent template names must refer to template decls."); 4634 return DTN->CanonicalTemplateName; 4635 } 4636 4637 case TemplateName::SubstTemplateTemplateParm: { 4638 SubstTemplateTemplateParmStorage *subst 4639 = Name.getAsSubstTemplateTemplateParm(); 4640 return getCanonicalTemplateName(subst->getReplacement()); 4641 } 4642 4643 case TemplateName::SubstTemplateTemplateParmPack: { 4644 SubstTemplateTemplateParmPackStorage *subst 4645 = Name.getAsSubstTemplateTemplateParmPack(); 4646 TemplateTemplateParmDecl *canonParameter 4647 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 4648 TemplateArgument canonArgPack 4649 = getCanonicalTemplateArgument(subst->getArgumentPack()); 4650 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 4651 } 4652 } 4653 4654 llvm_unreachable("bad template name!"); 4655 } 4656 4657 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4658 X = getCanonicalTemplateName(X); 4659 Y = getCanonicalTemplateName(Y); 4660 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4661 } 4662 4663 TemplateArgument 4664 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4665 switch (Arg.getKind()) { 4666 case TemplateArgument::Null: 4667 return Arg; 4668 4669 case TemplateArgument::Expression: 4670 return Arg; 4671 4672 case TemplateArgument::Declaration: { 4673 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4674 return TemplateArgument(D, Arg.getParamTypeForDecl()); 4675 } 4676 4677 case TemplateArgument::NullPtr: 4678 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4679 /*isNullPtr*/true); 4680 4681 case TemplateArgument::Template: 4682 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4683 4684 case TemplateArgument::TemplateExpansion: 4685 return TemplateArgument(getCanonicalTemplateName( 4686 Arg.getAsTemplateOrTemplatePattern()), 4687 Arg.getNumTemplateExpansions()); 4688 4689 case TemplateArgument::Integral: 4690 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4691 4692 case TemplateArgument::Type: 4693 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4694 4695 case TemplateArgument::Pack: { 4696 if (Arg.pack_size() == 0) 4697 return Arg; 4698 4699 TemplateArgument *CanonArgs 4700 = new (*this) TemplateArgument[Arg.pack_size()]; 4701 unsigned Idx = 0; 4702 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4703 AEnd = Arg.pack_end(); 4704 A != AEnd; (void)++A, ++Idx) 4705 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4706 4707 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 4708 } 4709 } 4710 4711 // Silence GCC warning 4712 llvm_unreachable("Unhandled template argument kind"); 4713 } 4714 4715 NestedNameSpecifier * 4716 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4717 if (!NNS) 4718 return nullptr; 4719 4720 switch (NNS->getKind()) { 4721 case NestedNameSpecifier::Identifier: 4722 // Canonicalize the prefix but keep the identifier the same. 4723 return NestedNameSpecifier::Create(*this, 4724 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4725 NNS->getAsIdentifier()); 4726 4727 case NestedNameSpecifier::Namespace: 4728 // A namespace is canonical; build a nested-name-specifier with 4729 // this namespace and no prefix. 4730 return NestedNameSpecifier::Create(*this, nullptr, 4731 NNS->getAsNamespace()->getOriginalNamespace()); 4732 4733 case NestedNameSpecifier::NamespaceAlias: 4734 // A namespace is canonical; build a nested-name-specifier with 4735 // this namespace and no prefix. 4736 return NestedNameSpecifier::Create(*this, nullptr, 4737 NNS->getAsNamespaceAlias()->getNamespace() 4738 ->getOriginalNamespace()); 4739 4740 case NestedNameSpecifier::TypeSpec: 4741 case NestedNameSpecifier::TypeSpecWithTemplate: { 4742 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4743 4744 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4745 // break it apart into its prefix and identifier, then reconsititute those 4746 // as the canonical nested-name-specifier. This is required to canonicalize 4747 // a dependent nested-name-specifier involving typedefs of dependent-name 4748 // types, e.g., 4749 // typedef typename T::type T1; 4750 // typedef typename T1::type T2; 4751 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4752 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4753 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4754 4755 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4756 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4757 // first place? 4758 return NestedNameSpecifier::Create(*this, nullptr, false, 4759 const_cast<Type *>(T.getTypePtr())); 4760 } 4761 4762 case NestedNameSpecifier::Global: 4763 case NestedNameSpecifier::Super: 4764 // The global specifier and __super specifer are canonical and unique. 4765 return NNS; 4766 } 4767 4768 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4769 } 4770 4771 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4772 // Handle the non-qualified case efficiently. 4773 if (!T.hasLocalQualifiers()) { 4774 // Handle the common positive case fast. 4775 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4776 return AT; 4777 } 4778 4779 // Handle the common negative case fast. 4780 if (!isa<ArrayType>(T.getCanonicalType())) 4781 return nullptr; 4782 4783 // Apply any qualifiers from the array type to the element type. This 4784 // implements C99 6.7.3p8: "If the specification of an array type includes 4785 // any type qualifiers, the element type is so qualified, not the array type." 4786 4787 // If we get here, we either have type qualifiers on the type, or we have 4788 // sugar such as a typedef in the way. If we have type qualifiers on the type 4789 // we must propagate them down into the element type. 4790 4791 SplitQualType split = T.getSplitDesugaredType(); 4792 Qualifiers qs = split.Quals; 4793 4794 // If we have a simple case, just return now. 4795 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4796 if (!ATy || qs.empty()) 4797 return ATy; 4798 4799 // Otherwise, we have an array and we have qualifiers on it. Push the 4800 // qualifiers into the array element type and return a new array type. 4801 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4802 4803 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4804 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4805 CAT->getSizeModifier(), 4806 CAT->getIndexTypeCVRQualifiers())); 4807 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4808 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4809 IAT->getSizeModifier(), 4810 IAT->getIndexTypeCVRQualifiers())); 4811 4812 if (const DependentSizedArrayType *DSAT 4813 = dyn_cast<DependentSizedArrayType>(ATy)) 4814 return cast<ArrayType>( 4815 getDependentSizedArrayType(NewEltTy, 4816 DSAT->getSizeExpr(), 4817 DSAT->getSizeModifier(), 4818 DSAT->getIndexTypeCVRQualifiers(), 4819 DSAT->getBracketsRange())); 4820 4821 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4822 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4823 VAT->getSizeExpr(), 4824 VAT->getSizeModifier(), 4825 VAT->getIndexTypeCVRQualifiers(), 4826 VAT->getBracketsRange())); 4827 } 4828 4829 QualType ASTContext::getAdjustedParameterType(QualType T) const { 4830 if (T->isArrayType() || T->isFunctionType()) 4831 return getDecayedType(T); 4832 return T; 4833 } 4834 4835 QualType ASTContext::getSignatureParameterType(QualType T) const { 4836 T = getVariableArrayDecayedType(T); 4837 T = getAdjustedParameterType(T); 4838 return T.getUnqualifiedType(); 4839 } 4840 4841 QualType ASTContext::getExceptionObjectType(QualType T) const { 4842 // C++ [except.throw]p3: 4843 // A throw-expression initializes a temporary object, called the exception 4844 // object, the type of which is determined by removing any top-level 4845 // cv-qualifiers from the static type of the operand of throw and adjusting 4846 // the type from "array of T" or "function returning T" to "pointer to T" 4847 // or "pointer to function returning T", [...] 4848 T = getVariableArrayDecayedType(T); 4849 if (T->isArrayType() || T->isFunctionType()) 4850 T = getDecayedType(T); 4851 return T.getUnqualifiedType(); 4852 } 4853 4854 /// getArrayDecayedType - Return the properly qualified result of decaying the 4855 /// specified array type to a pointer. This operation is non-trivial when 4856 /// handling typedefs etc. The canonical type of "T" must be an array type, 4857 /// this returns a pointer to a properly qualified element of the array. 4858 /// 4859 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4860 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4861 // Get the element type with 'getAsArrayType' so that we don't lose any 4862 // typedefs in the element type of the array. This also handles propagation 4863 // of type qualifiers from the array type into the element type if present 4864 // (C99 6.7.3p8). 4865 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4866 assert(PrettyArrayType && "Not an array type!"); 4867 4868 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 4869 4870 // int x[restrict 4] -> int *restrict 4871 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 4872 } 4873 4874 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 4875 return getBaseElementType(array->getElementType()); 4876 } 4877 4878 QualType ASTContext::getBaseElementType(QualType type) const { 4879 Qualifiers qs; 4880 while (true) { 4881 SplitQualType split = type.getSplitDesugaredType(); 4882 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 4883 if (!array) break; 4884 4885 type = array->getElementType(); 4886 qs.addConsistentQualifiers(split.Quals); 4887 } 4888 4889 return getQualifiedType(type, qs); 4890 } 4891 4892 /// getConstantArrayElementCount - Returns number of constant array elements. 4893 uint64_t 4894 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 4895 uint64_t ElementCount = 1; 4896 do { 4897 ElementCount *= CA->getSize().getZExtValue(); 4898 CA = dyn_cast_or_null<ConstantArrayType>( 4899 CA->getElementType()->getAsArrayTypeUnsafe()); 4900 } while (CA); 4901 return ElementCount; 4902 } 4903 4904 /// getFloatingRank - Return a relative rank for floating point types. 4905 /// This routine will assert if passed a built-in type that isn't a float. 4906 static FloatingRank getFloatingRank(QualType T) { 4907 if (const ComplexType *CT = T->getAs<ComplexType>()) 4908 return getFloatingRank(CT->getElementType()); 4909 4910 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 4911 switch (T->getAs<BuiltinType>()->getKind()) { 4912 default: llvm_unreachable("getFloatingRank(): not a floating type"); 4913 case BuiltinType::Half: return HalfRank; 4914 case BuiltinType::Float: return FloatRank; 4915 case BuiltinType::Double: return DoubleRank; 4916 case BuiltinType::LongDouble: return LongDoubleRank; 4917 case BuiltinType::Float128: return Float128Rank; 4918 } 4919 } 4920 4921 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 4922 /// point or a complex type (based on typeDomain/typeSize). 4923 /// 'typeDomain' is a real floating point or complex type. 4924 /// 'typeSize' is a real floating point or complex type. 4925 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 4926 QualType Domain) const { 4927 FloatingRank EltRank = getFloatingRank(Size); 4928 if (Domain->isComplexType()) { 4929 switch (EltRank) { 4930 case HalfRank: llvm_unreachable("Complex half is not supported"); 4931 case FloatRank: return FloatComplexTy; 4932 case DoubleRank: return DoubleComplexTy; 4933 case LongDoubleRank: return LongDoubleComplexTy; 4934 case Float128Rank: return Float128ComplexTy; 4935 } 4936 } 4937 4938 assert(Domain->isRealFloatingType() && "Unknown domain!"); 4939 switch (EltRank) { 4940 case HalfRank: return HalfTy; 4941 case FloatRank: return FloatTy; 4942 case DoubleRank: return DoubleTy; 4943 case LongDoubleRank: return LongDoubleTy; 4944 case Float128Rank: return Float128Ty; 4945 } 4946 llvm_unreachable("getFloatingRank(): illegal value for rank"); 4947 } 4948 4949 /// getFloatingTypeOrder - Compare the rank of the two specified floating 4950 /// point types, ignoring the domain of the type (i.e. 'double' == 4951 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 4952 /// LHS < RHS, return -1. 4953 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 4954 FloatingRank LHSR = getFloatingRank(LHS); 4955 FloatingRank RHSR = getFloatingRank(RHS); 4956 4957 if (LHSR == RHSR) 4958 return 0; 4959 if (LHSR > RHSR) 4960 return 1; 4961 return -1; 4962 } 4963 4964 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 4965 /// routine will assert if passed a built-in type that isn't an integer or enum, 4966 /// or if it is not canonicalized. 4967 unsigned ASTContext::getIntegerRank(const Type *T) const { 4968 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 4969 4970 switch (cast<BuiltinType>(T)->getKind()) { 4971 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 4972 case BuiltinType::Bool: 4973 return 1 + (getIntWidth(BoolTy) << 3); 4974 case BuiltinType::Char_S: 4975 case BuiltinType::Char_U: 4976 case BuiltinType::SChar: 4977 case BuiltinType::UChar: 4978 return 2 + (getIntWidth(CharTy) << 3); 4979 case BuiltinType::Short: 4980 case BuiltinType::UShort: 4981 return 3 + (getIntWidth(ShortTy) << 3); 4982 case BuiltinType::Int: 4983 case BuiltinType::UInt: 4984 return 4 + (getIntWidth(IntTy) << 3); 4985 case BuiltinType::Long: 4986 case BuiltinType::ULong: 4987 return 5 + (getIntWidth(LongTy) << 3); 4988 case BuiltinType::LongLong: 4989 case BuiltinType::ULongLong: 4990 return 6 + (getIntWidth(LongLongTy) << 3); 4991 case BuiltinType::Int128: 4992 case BuiltinType::UInt128: 4993 return 7 + (getIntWidth(Int128Ty) << 3); 4994 } 4995 } 4996 4997 /// \brief Whether this is a promotable bitfield reference according 4998 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 4999 /// 5000 /// \returns the type this bit-field will promote to, or NULL if no 5001 /// promotion occurs. 5002 QualType ASTContext::isPromotableBitField(Expr *E) const { 5003 if (E->isTypeDependent() || E->isValueDependent()) 5004 return QualType(); 5005 5006 // FIXME: We should not do this unless E->refersToBitField() is true. This 5007 // matters in C where getSourceBitField() will find bit-fields for various 5008 // cases where the source expression is not a bit-field designator. 5009 5010 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 5011 if (!Field) 5012 return QualType(); 5013 5014 QualType FT = Field->getType(); 5015 5016 uint64_t BitWidth = Field->getBitWidthValue(*this); 5017 uint64_t IntSize = getTypeSize(IntTy); 5018 // C++ [conv.prom]p5: 5019 // A prvalue for an integral bit-field can be converted to a prvalue of type 5020 // int if int can represent all the values of the bit-field; otherwise, it 5021 // can be converted to unsigned int if unsigned int can represent all the 5022 // values of the bit-field. If the bit-field is larger yet, no integral 5023 // promotion applies to it. 5024 // C11 6.3.1.1/2: 5025 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 5026 // If an int can represent all values of the original type (as restricted by 5027 // the width, for a bit-field), the value is converted to an int; otherwise, 5028 // it is converted to an unsigned int. 5029 // 5030 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 5031 // We perform that promotion here to match GCC and C++. 5032 if (BitWidth < IntSize) 5033 return IntTy; 5034 5035 if (BitWidth == IntSize) 5036 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 5037 5038 // Types bigger than int are not subject to promotions, and therefore act 5039 // like the base type. GCC has some weird bugs in this area that we 5040 // deliberately do not follow (GCC follows a pre-standard resolution to 5041 // C's DR315 which treats bit-width as being part of the type, and this leaks 5042 // into their semantics in some cases). 5043 return QualType(); 5044 } 5045 5046 /// getPromotedIntegerType - Returns the type that Promotable will 5047 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 5048 /// integer type. 5049 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 5050 assert(!Promotable.isNull()); 5051 assert(Promotable->isPromotableIntegerType()); 5052 if (const EnumType *ET = Promotable->getAs<EnumType>()) 5053 return ET->getDecl()->getPromotionType(); 5054 5055 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 5056 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 5057 // (3.9.1) can be converted to a prvalue of the first of the following 5058 // types that can represent all the values of its underlying type: 5059 // int, unsigned int, long int, unsigned long int, long long int, or 5060 // unsigned long long int [...] 5061 // FIXME: Is there some better way to compute this? 5062 if (BT->getKind() == BuiltinType::WChar_S || 5063 BT->getKind() == BuiltinType::WChar_U || 5064 BT->getKind() == BuiltinType::Char16 || 5065 BT->getKind() == BuiltinType::Char32) { 5066 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 5067 uint64_t FromSize = getTypeSize(BT); 5068 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 5069 LongLongTy, UnsignedLongLongTy }; 5070 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 5071 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 5072 if (FromSize < ToSize || 5073 (FromSize == ToSize && 5074 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 5075 return PromoteTypes[Idx]; 5076 } 5077 llvm_unreachable("char type should fit into long long"); 5078 } 5079 } 5080 5081 // At this point, we should have a signed or unsigned integer type. 5082 if (Promotable->isSignedIntegerType()) 5083 return IntTy; 5084 uint64_t PromotableSize = getIntWidth(Promotable); 5085 uint64_t IntSize = getIntWidth(IntTy); 5086 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 5087 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 5088 } 5089 5090 /// \brief Recurses in pointer/array types until it finds an objc retainable 5091 /// type and returns its ownership. 5092 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 5093 while (!T.isNull()) { 5094 if (T.getObjCLifetime() != Qualifiers::OCL_None) 5095 return T.getObjCLifetime(); 5096 if (T->isArrayType()) 5097 T = getBaseElementType(T); 5098 else if (const PointerType *PT = T->getAs<PointerType>()) 5099 T = PT->getPointeeType(); 5100 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 5101 T = RT->getPointeeType(); 5102 else 5103 break; 5104 } 5105 5106 return Qualifiers::OCL_None; 5107 } 5108 5109 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 5110 // Incomplete enum types are not treated as integer types. 5111 // FIXME: In C++, enum types are never integer types. 5112 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 5113 return ET->getDecl()->getIntegerType().getTypePtr(); 5114 return nullptr; 5115 } 5116 5117 /// getIntegerTypeOrder - Returns the highest ranked integer type: 5118 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 5119 /// LHS < RHS, return -1. 5120 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 5121 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 5122 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 5123 5124 // Unwrap enums to their underlying type. 5125 if (const EnumType *ET = dyn_cast<EnumType>(LHSC)) 5126 LHSC = getIntegerTypeForEnum(ET); 5127 if (const EnumType *ET = dyn_cast<EnumType>(RHSC)) 5128 RHSC = getIntegerTypeForEnum(ET); 5129 5130 if (LHSC == RHSC) return 0; 5131 5132 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 5133 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 5134 5135 unsigned LHSRank = getIntegerRank(LHSC); 5136 unsigned RHSRank = getIntegerRank(RHSC); 5137 5138 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 5139 if (LHSRank == RHSRank) return 0; 5140 return LHSRank > RHSRank ? 1 : -1; 5141 } 5142 5143 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 5144 if (LHSUnsigned) { 5145 // If the unsigned [LHS] type is larger, return it. 5146 if (LHSRank >= RHSRank) 5147 return 1; 5148 5149 // If the signed type can represent all values of the unsigned type, it 5150 // wins. Because we are dealing with 2's complement and types that are 5151 // powers of two larger than each other, this is always safe. 5152 return -1; 5153 } 5154 5155 // If the unsigned [RHS] type is larger, return it. 5156 if (RHSRank >= LHSRank) 5157 return -1; 5158 5159 // If the signed type can represent all values of the unsigned type, it 5160 // wins. Because we are dealing with 2's complement and types that are 5161 // powers of two larger than each other, this is always safe. 5162 return 1; 5163 } 5164 5165 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 5166 if (!CFConstantStringTypeDecl) { 5167 assert(!CFConstantStringTagDecl && 5168 "tag and typedef should be initialized together"); 5169 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 5170 CFConstantStringTagDecl->startDefinition(); 5171 5172 QualType FieldTypes[4]; 5173 const char *FieldNames[4]; 5174 5175 // const int *isa; 5176 FieldTypes[0] = getPointerType(IntTy.withConst()); 5177 FieldNames[0] = "isa"; 5178 // int flags; 5179 FieldTypes[1] = IntTy; 5180 FieldNames[1] = "flags"; 5181 // const char *str; 5182 FieldTypes[2] = getPointerType(CharTy.withConst()); 5183 FieldNames[2] = "str"; 5184 // long length; 5185 FieldTypes[3] = LongTy; 5186 FieldNames[3] = "length"; 5187 5188 // Create fields 5189 for (unsigned i = 0; i < 4; ++i) { 5190 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, 5191 SourceLocation(), 5192 SourceLocation(), 5193 &Idents.get(FieldNames[i]), 5194 FieldTypes[i], /*TInfo=*/nullptr, 5195 /*BitWidth=*/nullptr, 5196 /*Mutable=*/false, 5197 ICIS_NoInit); 5198 Field->setAccess(AS_public); 5199 CFConstantStringTagDecl->addDecl(Field); 5200 } 5201 5202 CFConstantStringTagDecl->completeDefinition(); 5203 // This type is designed to be compatible with NSConstantString, but cannot 5204 // use the same name, since NSConstantString is an interface. 5205 auto tagType = getTagDeclType(CFConstantStringTagDecl); 5206 CFConstantStringTypeDecl = 5207 buildImplicitTypedef(tagType, "__NSConstantString"); 5208 } 5209 5210 return CFConstantStringTypeDecl; 5211 } 5212 5213 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 5214 if (!CFConstantStringTagDecl) 5215 getCFConstantStringDecl(); // Build the tag and the typedef. 5216 return CFConstantStringTagDecl; 5217 } 5218 5219 // getCFConstantStringType - Return the type used for constant CFStrings. 5220 QualType ASTContext::getCFConstantStringType() const { 5221 return getTypedefType(getCFConstantStringDecl()); 5222 } 5223 5224 QualType ASTContext::getObjCSuperType() const { 5225 if (ObjCSuperType.isNull()) { 5226 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 5227 TUDecl->addDecl(ObjCSuperTypeDecl); 5228 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 5229 } 5230 return ObjCSuperType; 5231 } 5232 5233 void ASTContext::setCFConstantStringType(QualType T) { 5234 const TypedefType *TD = T->getAs<TypedefType>(); 5235 assert(TD && "Invalid CFConstantStringType"); 5236 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 5237 auto TagType = 5238 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>(); 5239 assert(TagType && "Invalid CFConstantStringType"); 5240 CFConstantStringTagDecl = TagType->getDecl(); 5241 } 5242 5243 QualType ASTContext::getBlockDescriptorType() const { 5244 if (BlockDescriptorType) 5245 return getTagDeclType(BlockDescriptorType); 5246 5247 RecordDecl *RD; 5248 // FIXME: Needs the FlagAppleBlock bit. 5249 RD = buildImplicitRecord("__block_descriptor"); 5250 RD->startDefinition(); 5251 5252 QualType FieldTypes[] = { 5253 UnsignedLongTy, 5254 UnsignedLongTy, 5255 }; 5256 5257 static const char *const FieldNames[] = { 5258 "reserved", 5259 "Size" 5260 }; 5261 5262 for (size_t i = 0; i < 2; ++i) { 5263 FieldDecl *Field = FieldDecl::Create( 5264 *this, RD, SourceLocation(), SourceLocation(), 5265 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5266 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 5267 Field->setAccess(AS_public); 5268 RD->addDecl(Field); 5269 } 5270 5271 RD->completeDefinition(); 5272 5273 BlockDescriptorType = RD; 5274 5275 return getTagDeclType(BlockDescriptorType); 5276 } 5277 5278 QualType ASTContext::getBlockDescriptorExtendedType() const { 5279 if (BlockDescriptorExtendedType) 5280 return getTagDeclType(BlockDescriptorExtendedType); 5281 5282 RecordDecl *RD; 5283 // FIXME: Needs the FlagAppleBlock bit. 5284 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 5285 RD->startDefinition(); 5286 5287 QualType FieldTypes[] = { 5288 UnsignedLongTy, 5289 UnsignedLongTy, 5290 getPointerType(VoidPtrTy), 5291 getPointerType(VoidPtrTy) 5292 }; 5293 5294 static const char *const FieldNames[] = { 5295 "reserved", 5296 "Size", 5297 "CopyFuncPtr", 5298 "DestroyFuncPtr" 5299 }; 5300 5301 for (size_t i = 0; i < 4; ++i) { 5302 FieldDecl *Field = FieldDecl::Create( 5303 *this, RD, SourceLocation(), SourceLocation(), 5304 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5305 /*BitWidth=*/nullptr, 5306 /*Mutable=*/false, ICIS_NoInit); 5307 Field->setAccess(AS_public); 5308 RD->addDecl(Field); 5309 } 5310 5311 RD->completeDefinition(); 5312 5313 BlockDescriptorExtendedType = RD; 5314 return getTagDeclType(BlockDescriptorExtendedType); 5315 } 5316 5317 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 5318 /// requires copy/dispose. Note that this must match the logic 5319 /// in buildByrefHelpers. 5320 bool ASTContext::BlockRequiresCopying(QualType Ty, 5321 const VarDecl *D) { 5322 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 5323 const Expr *copyExpr = getBlockVarCopyInits(D); 5324 if (!copyExpr && record->hasTrivialDestructor()) return false; 5325 5326 return true; 5327 } 5328 5329 if (!Ty->isObjCRetainableType()) return false; 5330 5331 Qualifiers qs = Ty.getQualifiers(); 5332 5333 // If we have lifetime, that dominates. 5334 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 5335 switch (lifetime) { 5336 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 5337 5338 // These are just bits as far as the runtime is concerned. 5339 case Qualifiers::OCL_ExplicitNone: 5340 case Qualifiers::OCL_Autoreleasing: 5341 return false; 5342 5343 // Tell the runtime that this is ARC __weak, called by the 5344 // byref routines. 5345 case Qualifiers::OCL_Weak: 5346 // ARC __strong __block variables need to be retained. 5347 case Qualifiers::OCL_Strong: 5348 return true; 5349 } 5350 llvm_unreachable("fell out of lifetime switch!"); 5351 } 5352 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 5353 Ty->isObjCObjectPointerType()); 5354 } 5355 5356 bool ASTContext::getByrefLifetime(QualType Ty, 5357 Qualifiers::ObjCLifetime &LifeTime, 5358 bool &HasByrefExtendedLayout) const { 5359 5360 if (!getLangOpts().ObjC1 || 5361 getLangOpts().getGC() != LangOptions::NonGC) 5362 return false; 5363 5364 HasByrefExtendedLayout = false; 5365 if (Ty->isRecordType()) { 5366 HasByrefExtendedLayout = true; 5367 LifeTime = Qualifiers::OCL_None; 5368 } else if ((LifeTime = Ty.getObjCLifetime())) { 5369 // Honor the ARC qualifiers. 5370 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 5371 // The MRR rule. 5372 LifeTime = Qualifiers::OCL_ExplicitNone; 5373 } else { 5374 LifeTime = Qualifiers::OCL_None; 5375 } 5376 return true; 5377 } 5378 5379 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 5380 if (!ObjCInstanceTypeDecl) 5381 ObjCInstanceTypeDecl = 5382 buildImplicitTypedef(getObjCIdType(), "instancetype"); 5383 return ObjCInstanceTypeDecl; 5384 } 5385 5386 // This returns true if a type has been typedefed to BOOL: 5387 // typedef <type> BOOL; 5388 static bool isTypeTypedefedAsBOOL(QualType T) { 5389 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 5390 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 5391 return II->isStr("BOOL"); 5392 5393 return false; 5394 } 5395 5396 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 5397 /// purpose. 5398 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 5399 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 5400 return CharUnits::Zero(); 5401 5402 CharUnits sz = getTypeSizeInChars(type); 5403 5404 // Make all integer and enum types at least as large as an int 5405 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 5406 sz = std::max(sz, getTypeSizeInChars(IntTy)); 5407 // Treat arrays as pointers, since that's how they're passed in. 5408 else if (type->isArrayType()) 5409 sz = getTypeSizeInChars(VoidPtrTy); 5410 return sz; 5411 } 5412 5413 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 5414 return getTargetInfo().getCXXABI().isMicrosoft() && 5415 VD->isStaticDataMember() && 5416 VD->getType()->isIntegralOrEnumerationType() && 5417 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 5418 } 5419 5420 ASTContext::InlineVariableDefinitionKind 5421 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 5422 if (!VD->isInline()) 5423 return InlineVariableDefinitionKind::None; 5424 5425 // In almost all cases, it's a weak definition. 5426 auto *First = VD->getFirstDecl(); 5427 if (!First->isConstexpr() || First->isInlineSpecified() || 5428 !VD->isStaticDataMember()) 5429 return InlineVariableDefinitionKind::Weak; 5430 5431 // If there's a file-context declaration in this translation unit, it's a 5432 // non-discardable definition. 5433 for (auto *D : VD->redecls()) 5434 if (D->getLexicalDeclContext()->isFileContext()) 5435 return InlineVariableDefinitionKind::Strong; 5436 5437 // If we've not seen one yet, we don't know. 5438 return InlineVariableDefinitionKind::WeakUnknown; 5439 } 5440 5441 static inline 5442 std::string charUnitsToString(const CharUnits &CU) { 5443 return llvm::itostr(CU.getQuantity()); 5444 } 5445 5446 /// getObjCEncodingForBlock - Return the encoded type for this block 5447 /// declaration. 5448 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 5449 std::string S; 5450 5451 const BlockDecl *Decl = Expr->getBlockDecl(); 5452 QualType BlockTy = 5453 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 5454 // Encode result type. 5455 if (getLangOpts().EncodeExtendedBlockSig) 5456 getObjCEncodingForMethodParameter( 5457 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 5458 true /*Extended*/); 5459 else 5460 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 5461 // Compute size of all parameters. 5462 // Start with computing size of a pointer in number of bytes. 5463 // FIXME: There might(should) be a better way of doing this computation! 5464 SourceLocation Loc; 5465 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 5466 CharUnits ParmOffset = PtrSize; 5467 for (auto PI : Decl->parameters()) { 5468 QualType PType = PI->getType(); 5469 CharUnits sz = getObjCEncodingTypeSize(PType); 5470 if (sz.isZero()) 5471 continue; 5472 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 5473 ParmOffset += sz; 5474 } 5475 // Size of the argument frame 5476 S += charUnitsToString(ParmOffset); 5477 // Block pointer and offset. 5478 S += "@?0"; 5479 5480 // Argument types. 5481 ParmOffset = PtrSize; 5482 for (auto PVDecl : Decl->parameters()) { 5483 QualType PType = PVDecl->getOriginalType(); 5484 if (const ArrayType *AT = 5485 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5486 // Use array's original type only if it has known number of 5487 // elements. 5488 if (!isa<ConstantArrayType>(AT)) 5489 PType = PVDecl->getType(); 5490 } else if (PType->isFunctionType()) 5491 PType = PVDecl->getType(); 5492 if (getLangOpts().EncodeExtendedBlockSig) 5493 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 5494 S, true /*Extended*/); 5495 else 5496 getObjCEncodingForType(PType, S); 5497 S += charUnitsToString(ParmOffset); 5498 ParmOffset += getObjCEncodingTypeSize(PType); 5499 } 5500 5501 return S; 5502 } 5503 5504 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 5505 std::string& S) { 5506 // Encode result type. 5507 getObjCEncodingForType(Decl->getReturnType(), S); 5508 CharUnits ParmOffset; 5509 // Compute size of all parameters. 5510 for (auto PI : Decl->parameters()) { 5511 QualType PType = PI->getType(); 5512 CharUnits sz = getObjCEncodingTypeSize(PType); 5513 if (sz.isZero()) 5514 continue; 5515 5516 assert (sz.isPositive() && 5517 "getObjCEncodingForFunctionDecl - Incomplete param type"); 5518 ParmOffset += sz; 5519 } 5520 S += charUnitsToString(ParmOffset); 5521 ParmOffset = CharUnits::Zero(); 5522 5523 // Argument types. 5524 for (auto PVDecl : Decl->parameters()) { 5525 QualType PType = PVDecl->getOriginalType(); 5526 if (const ArrayType *AT = 5527 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5528 // Use array's original type only if it has known number of 5529 // elements. 5530 if (!isa<ConstantArrayType>(AT)) 5531 PType = PVDecl->getType(); 5532 } else if (PType->isFunctionType()) 5533 PType = PVDecl->getType(); 5534 getObjCEncodingForType(PType, S); 5535 S += charUnitsToString(ParmOffset); 5536 ParmOffset += getObjCEncodingTypeSize(PType); 5537 } 5538 5539 return false; 5540 } 5541 5542 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 5543 /// method parameter or return type. If Extended, include class names and 5544 /// block object types. 5545 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 5546 QualType T, std::string& S, 5547 bool Extended) const { 5548 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 5549 getObjCEncodingForTypeQualifier(QT, S); 5550 // Encode parameter type. 5551 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5552 true /*OutermostType*/, 5553 false /*EncodingProperty*/, 5554 false /*StructField*/, 5555 Extended /*EncodeBlockParameters*/, 5556 Extended /*EncodeClassNames*/); 5557 } 5558 5559 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 5560 /// declaration. 5561 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 5562 std::string& S, 5563 bool Extended) const { 5564 // FIXME: This is not very efficient. 5565 // Encode return type. 5566 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 5567 Decl->getReturnType(), S, Extended); 5568 // Compute size of all parameters. 5569 // Start with computing size of a pointer in number of bytes. 5570 // FIXME: There might(should) be a better way of doing this computation! 5571 SourceLocation Loc; 5572 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 5573 // The first two arguments (self and _cmd) are pointers; account for 5574 // their size. 5575 CharUnits ParmOffset = 2 * PtrSize; 5576 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5577 E = Decl->sel_param_end(); PI != E; ++PI) { 5578 QualType PType = (*PI)->getType(); 5579 CharUnits sz = getObjCEncodingTypeSize(PType); 5580 if (sz.isZero()) 5581 continue; 5582 5583 assert (sz.isPositive() && 5584 "getObjCEncodingForMethodDecl - Incomplete param type"); 5585 ParmOffset += sz; 5586 } 5587 S += charUnitsToString(ParmOffset); 5588 S += "@0:"; 5589 S += charUnitsToString(PtrSize); 5590 5591 // Argument types. 5592 ParmOffset = 2 * PtrSize; 5593 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5594 E = Decl->sel_param_end(); PI != E; ++PI) { 5595 const ParmVarDecl *PVDecl = *PI; 5596 QualType PType = PVDecl->getOriginalType(); 5597 if (const ArrayType *AT = 5598 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5599 // Use array's original type only if it has known number of 5600 // elements. 5601 if (!isa<ConstantArrayType>(AT)) 5602 PType = PVDecl->getType(); 5603 } else if (PType->isFunctionType()) 5604 PType = PVDecl->getType(); 5605 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 5606 PType, S, Extended); 5607 S += charUnitsToString(ParmOffset); 5608 ParmOffset += getObjCEncodingTypeSize(PType); 5609 } 5610 5611 return false; 5612 } 5613 5614 ObjCPropertyImplDecl * 5615 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 5616 const ObjCPropertyDecl *PD, 5617 const Decl *Container) const { 5618 if (!Container) 5619 return nullptr; 5620 if (const ObjCCategoryImplDecl *CID = 5621 dyn_cast<ObjCCategoryImplDecl>(Container)) { 5622 for (auto *PID : CID->property_impls()) 5623 if (PID->getPropertyDecl() == PD) 5624 return PID; 5625 } else { 5626 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 5627 for (auto *PID : OID->property_impls()) 5628 if (PID->getPropertyDecl() == PD) 5629 return PID; 5630 } 5631 return nullptr; 5632 } 5633 5634 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 5635 /// property declaration. If non-NULL, Container must be either an 5636 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 5637 /// NULL when getting encodings for protocol properties. 5638 /// Property attributes are stored as a comma-delimited C string. The simple 5639 /// attributes readonly and bycopy are encoded as single characters. The 5640 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 5641 /// encoded as single characters, followed by an identifier. Property types 5642 /// are also encoded as a parametrized attribute. The characters used to encode 5643 /// these attributes are defined by the following enumeration: 5644 /// @code 5645 /// enum PropertyAttributes { 5646 /// kPropertyReadOnly = 'R', // property is read-only. 5647 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 5648 /// kPropertyByref = '&', // property is a reference to the value last assigned 5649 /// kPropertyDynamic = 'D', // property is dynamic 5650 /// kPropertyGetter = 'G', // followed by getter selector name 5651 /// kPropertySetter = 'S', // followed by setter selector name 5652 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 5653 /// kPropertyType = 'T' // followed by old-style type encoding. 5654 /// kPropertyWeak = 'W' // 'weak' property 5655 /// kPropertyStrong = 'P' // property GC'able 5656 /// kPropertyNonAtomic = 'N' // property non-atomic 5657 /// }; 5658 /// @endcode 5659 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 5660 const Decl *Container, 5661 std::string& S) const { 5662 // Collect information from the property implementation decl(s). 5663 bool Dynamic = false; 5664 ObjCPropertyImplDecl *SynthesizePID = nullptr; 5665 5666 if (ObjCPropertyImplDecl *PropertyImpDecl = 5667 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 5668 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 5669 Dynamic = true; 5670 else 5671 SynthesizePID = PropertyImpDecl; 5672 } 5673 5674 // FIXME: This is not very efficient. 5675 S = "T"; 5676 5677 // Encode result type. 5678 // GCC has some special rules regarding encoding of properties which 5679 // closely resembles encoding of ivars. 5680 getObjCEncodingForPropertyType(PD->getType(), S); 5681 5682 if (PD->isReadOnly()) { 5683 S += ",R"; 5684 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 5685 S += ",C"; 5686 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 5687 S += ",&"; 5688 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 5689 S += ",W"; 5690 } else { 5691 switch (PD->getSetterKind()) { 5692 case ObjCPropertyDecl::Assign: break; 5693 case ObjCPropertyDecl::Copy: S += ",C"; break; 5694 case ObjCPropertyDecl::Retain: S += ",&"; break; 5695 case ObjCPropertyDecl::Weak: S += ",W"; break; 5696 } 5697 } 5698 5699 // It really isn't clear at all what this means, since properties 5700 // are "dynamic by default". 5701 if (Dynamic) 5702 S += ",D"; 5703 5704 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 5705 S += ",N"; 5706 5707 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 5708 S += ",G"; 5709 S += PD->getGetterName().getAsString(); 5710 } 5711 5712 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 5713 S += ",S"; 5714 S += PD->getSetterName().getAsString(); 5715 } 5716 5717 if (SynthesizePID) { 5718 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 5719 S += ",V"; 5720 S += OID->getNameAsString(); 5721 } 5722 5723 // FIXME: OBJCGC: weak & strong 5724 } 5725 5726 /// getLegacyIntegralTypeEncoding - 5727 /// Another legacy compatibility encoding: 32-bit longs are encoded as 5728 /// 'l' or 'L' , but not always. For typedefs, we need to use 5729 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 5730 /// 5731 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5732 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5733 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5734 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5735 PointeeTy = UnsignedIntTy; 5736 else 5737 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5738 PointeeTy = IntTy; 5739 } 5740 } 5741 } 5742 5743 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5744 const FieldDecl *Field, 5745 QualType *NotEncodedT) const { 5746 // We follow the behavior of gcc, expanding structures which are 5747 // directly pointed to, and expanding embedded structures. Note that 5748 // these rules are sufficient to prevent recursive encoding of the 5749 // same type. 5750 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5751 true /* outermost type */, false, false, 5752 false, false, false, NotEncodedT); 5753 } 5754 5755 void ASTContext::getObjCEncodingForPropertyType(QualType T, 5756 std::string& S) const { 5757 // Encode result type. 5758 // GCC has some special rules regarding encoding of properties which 5759 // closely resembles encoding of ivars. 5760 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5761 true /* outermost type */, 5762 true /* encoding property */); 5763 } 5764 5765 static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5766 BuiltinType::Kind kind) { 5767 switch (kind) { 5768 case BuiltinType::Void: return 'v'; 5769 case BuiltinType::Bool: return 'B'; 5770 case BuiltinType::Char_U: 5771 case BuiltinType::UChar: return 'C'; 5772 case BuiltinType::Char16: 5773 case BuiltinType::UShort: return 'S'; 5774 case BuiltinType::Char32: 5775 case BuiltinType::UInt: return 'I'; 5776 case BuiltinType::ULong: 5777 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5778 case BuiltinType::UInt128: return 'T'; 5779 case BuiltinType::ULongLong: return 'Q'; 5780 case BuiltinType::Char_S: 5781 case BuiltinType::SChar: return 'c'; 5782 case BuiltinType::Short: return 's'; 5783 case BuiltinType::WChar_S: 5784 case BuiltinType::WChar_U: 5785 case BuiltinType::Int: return 'i'; 5786 case BuiltinType::Long: 5787 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5788 case BuiltinType::LongLong: return 'q'; 5789 case BuiltinType::Int128: return 't'; 5790 case BuiltinType::Float: return 'f'; 5791 case BuiltinType::Double: return 'd'; 5792 case BuiltinType::LongDouble: return 'D'; 5793 case BuiltinType::NullPtr: return '*'; // like char* 5794 5795 case BuiltinType::Float128: 5796 case BuiltinType::Half: 5797 // FIXME: potentially need @encodes for these! 5798 return ' '; 5799 5800 case BuiltinType::ObjCId: 5801 case BuiltinType::ObjCClass: 5802 case BuiltinType::ObjCSel: 5803 llvm_unreachable("@encoding ObjC primitive type"); 5804 5805 // OpenCL and placeholder types don't need @encodings. 5806 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5807 case BuiltinType::Id: 5808 #include "clang/Basic/OpenCLImageTypes.def" 5809 case BuiltinType::OCLEvent: 5810 case BuiltinType::OCLClkEvent: 5811 case BuiltinType::OCLQueue: 5812 case BuiltinType::OCLNDRange: 5813 case BuiltinType::OCLReserveID: 5814 case BuiltinType::OCLSampler: 5815 case BuiltinType::Dependent: 5816 #define BUILTIN_TYPE(KIND, ID) 5817 #define PLACEHOLDER_TYPE(KIND, ID) \ 5818 case BuiltinType::KIND: 5819 #include "clang/AST/BuiltinTypes.def" 5820 llvm_unreachable("invalid builtin type for @encode"); 5821 } 5822 llvm_unreachable("invalid BuiltinType::Kind value"); 5823 } 5824 5825 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5826 EnumDecl *Enum = ET->getDecl(); 5827 5828 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5829 if (!Enum->isFixed()) 5830 return 'i'; 5831 5832 // The encoding of a fixed enum type matches its fixed underlying type. 5833 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5834 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5835 } 5836 5837 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5838 QualType T, const FieldDecl *FD) { 5839 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5840 S += 'b'; 5841 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5842 // The GNU runtime requires more information; bitfields are encoded as b, 5843 // then the offset (in bits) of the first element, then the type of the 5844 // bitfield, then the size in bits. For example, in this structure: 5845 // 5846 // struct 5847 // { 5848 // int integer; 5849 // int flags:2; 5850 // }; 5851 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5852 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5853 // information is not especially sensible, but we're stuck with it for 5854 // compatibility with GCC, although providing it breaks anything that 5855 // actually uses runtime introspection and wants to work on both runtimes... 5856 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5857 const RecordDecl *RD = FD->getParent(); 5858 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 5859 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 5860 if (const EnumType *ET = T->getAs<EnumType>()) 5861 S += ObjCEncodingForEnumType(Ctx, ET); 5862 else { 5863 const BuiltinType *BT = T->castAs<BuiltinType>(); 5864 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 5865 } 5866 } 5867 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 5868 } 5869 5870 // FIXME: Use SmallString for accumulating string. 5871 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 5872 bool ExpandPointedToStructures, 5873 bool ExpandStructures, 5874 const FieldDecl *FD, 5875 bool OutermostType, 5876 bool EncodingProperty, 5877 bool StructField, 5878 bool EncodeBlockParameters, 5879 bool EncodeClassNames, 5880 bool EncodePointerToObjCTypedef, 5881 QualType *NotEncodedT) const { 5882 CanQualType CT = getCanonicalType(T); 5883 switch (CT->getTypeClass()) { 5884 case Type::Builtin: 5885 case Type::Enum: 5886 if (FD && FD->isBitField()) 5887 return EncodeBitField(this, S, T, FD); 5888 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 5889 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 5890 else 5891 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 5892 return; 5893 5894 case Type::Complex: { 5895 const ComplexType *CT = T->castAs<ComplexType>(); 5896 S += 'j'; 5897 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 5898 return; 5899 } 5900 5901 case Type::Atomic: { 5902 const AtomicType *AT = T->castAs<AtomicType>(); 5903 S += 'A'; 5904 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 5905 return; 5906 } 5907 5908 // encoding for pointer or reference types. 5909 case Type::Pointer: 5910 case Type::LValueReference: 5911 case Type::RValueReference: { 5912 QualType PointeeTy; 5913 if (isa<PointerType>(CT)) { 5914 const PointerType *PT = T->castAs<PointerType>(); 5915 if (PT->isObjCSelType()) { 5916 S += ':'; 5917 return; 5918 } 5919 PointeeTy = PT->getPointeeType(); 5920 } else { 5921 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 5922 } 5923 5924 bool isReadOnly = false; 5925 // For historical/compatibility reasons, the read-only qualifier of the 5926 // pointee gets emitted _before_ the '^'. The read-only qualifier of 5927 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 5928 // Also, do not emit the 'r' for anything but the outermost type! 5929 if (isa<TypedefType>(T.getTypePtr())) { 5930 if (OutermostType && T.isConstQualified()) { 5931 isReadOnly = true; 5932 S += 'r'; 5933 } 5934 } else if (OutermostType) { 5935 QualType P = PointeeTy; 5936 while (P->getAs<PointerType>()) 5937 P = P->getAs<PointerType>()->getPointeeType(); 5938 if (P.isConstQualified()) { 5939 isReadOnly = true; 5940 S += 'r'; 5941 } 5942 } 5943 if (isReadOnly) { 5944 // Another legacy compatibility encoding. Some ObjC qualifier and type 5945 // combinations need to be rearranged. 5946 // Rewrite "in const" from "nr" to "rn" 5947 if (StringRef(S).endswith("nr")) 5948 S.replace(S.end()-2, S.end(), "rn"); 5949 } 5950 5951 if (PointeeTy->isCharType()) { 5952 // char pointer types should be encoded as '*' unless it is a 5953 // type that has been typedef'd to 'BOOL'. 5954 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 5955 S += '*'; 5956 return; 5957 } 5958 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 5959 // GCC binary compat: Need to convert "struct objc_class *" to "#". 5960 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 5961 S += '#'; 5962 return; 5963 } 5964 // GCC binary compat: Need to convert "struct objc_object *" to "@". 5965 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 5966 S += '@'; 5967 return; 5968 } 5969 // fall through... 5970 } 5971 S += '^'; 5972 getLegacyIntegralTypeEncoding(PointeeTy); 5973 5974 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 5975 nullptr, false, false, false, false, false, false, 5976 NotEncodedT); 5977 return; 5978 } 5979 5980 case Type::ConstantArray: 5981 case Type::IncompleteArray: 5982 case Type::VariableArray: { 5983 const ArrayType *AT = cast<ArrayType>(CT); 5984 5985 if (isa<IncompleteArrayType>(AT) && !StructField) { 5986 // Incomplete arrays are encoded as a pointer to the array element. 5987 S += '^'; 5988 5989 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5990 false, ExpandStructures, FD); 5991 } else { 5992 S += '['; 5993 5994 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 5995 S += llvm::utostr(CAT->getSize().getZExtValue()); 5996 else { 5997 //Variable length arrays are encoded as a regular array with 0 elements. 5998 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 5999 "Unknown array type!"); 6000 S += '0'; 6001 } 6002 6003 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6004 false, ExpandStructures, FD, 6005 false, false, false, false, false, false, 6006 NotEncodedT); 6007 S += ']'; 6008 } 6009 return; 6010 } 6011 6012 case Type::FunctionNoProto: 6013 case Type::FunctionProto: 6014 S += '?'; 6015 return; 6016 6017 case Type::Record: { 6018 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 6019 S += RDecl->isUnion() ? '(' : '{'; 6020 // Anonymous structures print as '?' 6021 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 6022 S += II->getName(); 6023 if (ClassTemplateSpecializationDecl *Spec 6024 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 6025 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 6026 llvm::raw_string_ostream OS(S); 6027 TemplateSpecializationType::PrintTemplateArgumentList(OS, 6028 TemplateArgs.asArray(), 6029 (*this).getPrintingPolicy()); 6030 } 6031 } else { 6032 S += '?'; 6033 } 6034 if (ExpandStructures) { 6035 S += '='; 6036 if (!RDecl->isUnion()) { 6037 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 6038 } else { 6039 for (const auto *Field : RDecl->fields()) { 6040 if (FD) { 6041 S += '"'; 6042 S += Field->getNameAsString(); 6043 S += '"'; 6044 } 6045 6046 // Special case bit-fields. 6047 if (Field->isBitField()) { 6048 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 6049 Field); 6050 } else { 6051 QualType qt = Field->getType(); 6052 getLegacyIntegralTypeEncoding(qt); 6053 getObjCEncodingForTypeImpl(qt, S, false, true, 6054 FD, /*OutermostType*/false, 6055 /*EncodingProperty*/false, 6056 /*StructField*/true, 6057 false, false, false, NotEncodedT); 6058 } 6059 } 6060 } 6061 } 6062 S += RDecl->isUnion() ? ')' : '}'; 6063 return; 6064 } 6065 6066 case Type::BlockPointer: { 6067 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 6068 S += "@?"; // Unlike a pointer-to-function, which is "^?". 6069 if (EncodeBlockParameters) { 6070 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 6071 6072 S += '<'; 6073 // Block return type 6074 getObjCEncodingForTypeImpl( 6075 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 6076 FD, false /* OutermostType */, EncodingProperty, 6077 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 6078 NotEncodedT); 6079 // Block self 6080 S += "@?"; 6081 // Block parameters 6082 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 6083 for (const auto &I : FPT->param_types()) 6084 getObjCEncodingForTypeImpl( 6085 I, S, ExpandPointedToStructures, ExpandStructures, FD, 6086 false /* OutermostType */, EncodingProperty, 6087 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 6088 false, NotEncodedT); 6089 } 6090 S += '>'; 6091 } 6092 return; 6093 } 6094 6095 case Type::ObjCObject: { 6096 // hack to match legacy encoding of *id and *Class 6097 QualType Ty = getObjCObjectPointerType(CT); 6098 if (Ty->isObjCIdType()) { 6099 S += "{objc_object=}"; 6100 return; 6101 } 6102 else if (Ty->isObjCClassType()) { 6103 S += "{objc_class=}"; 6104 return; 6105 } 6106 } 6107 6108 case Type::ObjCInterface: { 6109 // Ignore protocol qualifiers when mangling at this level. 6110 // @encode(class_name) 6111 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 6112 S += '{'; 6113 S += OI->getObjCRuntimeNameAsString(); 6114 if (ExpandStructures) { 6115 S += '='; 6116 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6117 DeepCollectObjCIvars(OI, true, Ivars); 6118 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6119 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 6120 if (Field->isBitField()) 6121 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 6122 else 6123 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 6124 false, false, false, false, false, 6125 EncodePointerToObjCTypedef, 6126 NotEncodedT); 6127 } 6128 } 6129 S += '}'; 6130 return; 6131 } 6132 6133 case Type::ObjCObjectPointer: { 6134 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 6135 if (OPT->isObjCIdType()) { 6136 S += '@'; 6137 return; 6138 } 6139 6140 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 6141 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 6142 // Since this is a binary compatibility issue, need to consult with runtime 6143 // folks. Fortunately, this is a *very* obsure construct. 6144 S += '#'; 6145 return; 6146 } 6147 6148 if (OPT->isObjCQualifiedIdType()) { 6149 getObjCEncodingForTypeImpl(getObjCIdType(), S, 6150 ExpandPointedToStructures, 6151 ExpandStructures, FD); 6152 if (FD || EncodingProperty || EncodeClassNames) { 6153 // Note that we do extended encoding of protocol qualifer list 6154 // Only when doing ivar or property encoding. 6155 S += '"'; 6156 for (const auto *I : OPT->quals()) { 6157 S += '<'; 6158 S += I->getObjCRuntimeNameAsString(); 6159 S += '>'; 6160 } 6161 S += '"'; 6162 } 6163 return; 6164 } 6165 6166 QualType PointeeTy = OPT->getPointeeType(); 6167 if (!EncodingProperty && 6168 isa<TypedefType>(PointeeTy.getTypePtr()) && 6169 !EncodePointerToObjCTypedef) { 6170 // Another historical/compatibility reason. 6171 // We encode the underlying type which comes out as 6172 // {...}; 6173 S += '^'; 6174 if (FD && OPT->getInterfaceDecl()) { 6175 // Prevent recursive encoding of fields in some rare cases. 6176 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 6177 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6178 DeepCollectObjCIvars(OI, true, Ivars); 6179 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6180 if (cast<FieldDecl>(Ivars[i]) == FD) { 6181 S += '{'; 6182 S += OI->getObjCRuntimeNameAsString(); 6183 S += '}'; 6184 return; 6185 } 6186 } 6187 } 6188 getObjCEncodingForTypeImpl(PointeeTy, S, 6189 false, ExpandPointedToStructures, 6190 nullptr, 6191 false, false, false, false, false, 6192 /*EncodePointerToObjCTypedef*/true); 6193 return; 6194 } 6195 6196 S += '@'; 6197 if (OPT->getInterfaceDecl() && 6198 (FD || EncodingProperty || EncodeClassNames)) { 6199 S += '"'; 6200 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 6201 for (const auto *I : OPT->quals()) { 6202 S += '<'; 6203 S += I->getObjCRuntimeNameAsString(); 6204 S += '>'; 6205 } 6206 S += '"'; 6207 } 6208 return; 6209 } 6210 6211 // gcc just blithely ignores member pointers. 6212 // FIXME: we shoul do better than that. 'M' is available. 6213 case Type::MemberPointer: 6214 // This matches gcc's encoding, even though technically it is insufficient. 6215 //FIXME. We should do a better job than gcc. 6216 case Type::Vector: 6217 case Type::ExtVector: 6218 // Until we have a coherent encoding of these three types, issue warning. 6219 { if (NotEncodedT) 6220 *NotEncodedT = T; 6221 return; 6222 } 6223 6224 // We could see an undeduced auto type here during error recovery. 6225 // Just ignore it. 6226 case Type::Auto: 6227 return; 6228 6229 case Type::Pipe: 6230 #define ABSTRACT_TYPE(KIND, BASE) 6231 #define TYPE(KIND, BASE) 6232 #define DEPENDENT_TYPE(KIND, BASE) \ 6233 case Type::KIND: 6234 #define NON_CANONICAL_TYPE(KIND, BASE) \ 6235 case Type::KIND: 6236 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 6237 case Type::KIND: 6238 #include "clang/AST/TypeNodes.def" 6239 llvm_unreachable("@encode for dependent type!"); 6240 } 6241 llvm_unreachable("bad type kind!"); 6242 } 6243 6244 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 6245 std::string &S, 6246 const FieldDecl *FD, 6247 bool includeVBases, 6248 QualType *NotEncodedT) const { 6249 assert(RDecl && "Expected non-null RecordDecl"); 6250 assert(!RDecl->isUnion() && "Should not be called for unions"); 6251 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 6252 return; 6253 6254 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 6255 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 6256 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 6257 6258 if (CXXRec) { 6259 for (const auto &BI : CXXRec->bases()) { 6260 if (!BI.isVirtual()) { 6261 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6262 if (base->isEmpty()) 6263 continue; 6264 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 6265 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6266 std::make_pair(offs, base)); 6267 } 6268 } 6269 } 6270 6271 unsigned i = 0; 6272 for (auto *Field : RDecl->fields()) { 6273 uint64_t offs = layout.getFieldOffset(i); 6274 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6275 std::make_pair(offs, Field)); 6276 ++i; 6277 } 6278 6279 if (CXXRec && includeVBases) { 6280 for (const auto &BI : CXXRec->vbases()) { 6281 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6282 if (base->isEmpty()) 6283 continue; 6284 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 6285 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 6286 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 6287 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 6288 std::make_pair(offs, base)); 6289 } 6290 } 6291 6292 CharUnits size; 6293 if (CXXRec) { 6294 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 6295 } else { 6296 size = layout.getSize(); 6297 } 6298 6299 #ifndef NDEBUG 6300 uint64_t CurOffs = 0; 6301 #endif 6302 std::multimap<uint64_t, NamedDecl *>::iterator 6303 CurLayObj = FieldOrBaseOffsets.begin(); 6304 6305 if (CXXRec && CXXRec->isDynamicClass() && 6306 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 6307 if (FD) { 6308 S += "\"_vptr$"; 6309 std::string recname = CXXRec->getNameAsString(); 6310 if (recname.empty()) recname = "?"; 6311 S += recname; 6312 S += '"'; 6313 } 6314 S += "^^?"; 6315 #ifndef NDEBUG 6316 CurOffs += getTypeSize(VoidPtrTy); 6317 #endif 6318 } 6319 6320 if (!RDecl->hasFlexibleArrayMember()) { 6321 // Mark the end of the structure. 6322 uint64_t offs = toBits(size); 6323 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6324 std::make_pair(offs, nullptr)); 6325 } 6326 6327 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 6328 #ifndef NDEBUG 6329 assert(CurOffs <= CurLayObj->first); 6330 if (CurOffs < CurLayObj->first) { 6331 uint64_t padding = CurLayObj->first - CurOffs; 6332 // FIXME: There doesn't seem to be a way to indicate in the encoding that 6333 // packing/alignment of members is different that normal, in which case 6334 // the encoding will be out-of-sync with the real layout. 6335 // If the runtime switches to just consider the size of types without 6336 // taking into account alignment, we could make padding explicit in the 6337 // encoding (e.g. using arrays of chars). The encoding strings would be 6338 // longer then though. 6339 CurOffs += padding; 6340 } 6341 #endif 6342 6343 NamedDecl *dcl = CurLayObj->second; 6344 if (!dcl) 6345 break; // reached end of structure. 6346 6347 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 6348 // We expand the bases without their virtual bases since those are going 6349 // in the initial structure. Note that this differs from gcc which 6350 // expands virtual bases each time one is encountered in the hierarchy, 6351 // making the encoding type bigger than it really is. 6352 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 6353 NotEncodedT); 6354 assert(!base->isEmpty()); 6355 #ifndef NDEBUG 6356 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 6357 #endif 6358 } else { 6359 FieldDecl *field = cast<FieldDecl>(dcl); 6360 if (FD) { 6361 S += '"'; 6362 S += field->getNameAsString(); 6363 S += '"'; 6364 } 6365 6366 if (field->isBitField()) { 6367 EncodeBitField(this, S, field->getType(), field); 6368 #ifndef NDEBUG 6369 CurOffs += field->getBitWidthValue(*this); 6370 #endif 6371 } else { 6372 QualType qt = field->getType(); 6373 getLegacyIntegralTypeEncoding(qt); 6374 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 6375 /*OutermostType*/false, 6376 /*EncodingProperty*/false, 6377 /*StructField*/true, 6378 false, false, false, NotEncodedT); 6379 #ifndef NDEBUG 6380 CurOffs += getTypeSize(field->getType()); 6381 #endif 6382 } 6383 } 6384 } 6385 } 6386 6387 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 6388 std::string& S) const { 6389 if (QT & Decl::OBJC_TQ_In) 6390 S += 'n'; 6391 if (QT & Decl::OBJC_TQ_Inout) 6392 S += 'N'; 6393 if (QT & Decl::OBJC_TQ_Out) 6394 S += 'o'; 6395 if (QT & Decl::OBJC_TQ_Bycopy) 6396 S += 'O'; 6397 if (QT & Decl::OBJC_TQ_Byref) 6398 S += 'R'; 6399 if (QT & Decl::OBJC_TQ_Oneway) 6400 S += 'V'; 6401 } 6402 6403 TypedefDecl *ASTContext::getObjCIdDecl() const { 6404 if (!ObjCIdDecl) { 6405 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { }); 6406 T = getObjCObjectPointerType(T); 6407 ObjCIdDecl = buildImplicitTypedef(T, "id"); 6408 } 6409 return ObjCIdDecl; 6410 } 6411 6412 TypedefDecl *ASTContext::getObjCSelDecl() const { 6413 if (!ObjCSelDecl) { 6414 QualType T = getPointerType(ObjCBuiltinSelTy); 6415 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 6416 } 6417 return ObjCSelDecl; 6418 } 6419 6420 TypedefDecl *ASTContext::getObjCClassDecl() const { 6421 if (!ObjCClassDecl) { 6422 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { }); 6423 T = getObjCObjectPointerType(T); 6424 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 6425 } 6426 return ObjCClassDecl; 6427 } 6428 6429 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 6430 if (!ObjCProtocolClassDecl) { 6431 ObjCProtocolClassDecl 6432 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 6433 SourceLocation(), 6434 &Idents.get("Protocol"), 6435 /*typeParamList=*/nullptr, 6436 /*PrevDecl=*/nullptr, 6437 SourceLocation(), true); 6438 } 6439 6440 return ObjCProtocolClassDecl; 6441 } 6442 6443 //===----------------------------------------------------------------------===// 6444 // __builtin_va_list Construction Functions 6445 //===----------------------------------------------------------------------===// 6446 6447 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 6448 StringRef Name) { 6449 // typedef char* __builtin[_ms]_va_list; 6450 QualType T = Context->getPointerType(Context->CharTy); 6451 return Context->buildImplicitTypedef(T, Name); 6452 } 6453 6454 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 6455 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 6456 } 6457 6458 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 6459 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 6460 } 6461 6462 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 6463 // typedef void* __builtin_va_list; 6464 QualType T = Context->getPointerType(Context->VoidTy); 6465 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6466 } 6467 6468 static TypedefDecl * 6469 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 6470 // struct __va_list 6471 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 6472 if (Context->getLangOpts().CPlusPlus) { 6473 // namespace std { struct __va_list { 6474 NamespaceDecl *NS; 6475 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6476 Context->getTranslationUnitDecl(), 6477 /*Inline*/ false, SourceLocation(), 6478 SourceLocation(), &Context->Idents.get("std"), 6479 /*PrevDecl*/ nullptr); 6480 NS->setImplicit(); 6481 VaListTagDecl->setDeclContext(NS); 6482 } 6483 6484 VaListTagDecl->startDefinition(); 6485 6486 const size_t NumFields = 5; 6487 QualType FieldTypes[NumFields]; 6488 const char *FieldNames[NumFields]; 6489 6490 // void *__stack; 6491 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 6492 FieldNames[0] = "__stack"; 6493 6494 // void *__gr_top; 6495 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 6496 FieldNames[1] = "__gr_top"; 6497 6498 // void *__vr_top; 6499 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6500 FieldNames[2] = "__vr_top"; 6501 6502 // int __gr_offs; 6503 FieldTypes[3] = Context->IntTy; 6504 FieldNames[3] = "__gr_offs"; 6505 6506 // int __vr_offs; 6507 FieldTypes[4] = Context->IntTy; 6508 FieldNames[4] = "__vr_offs"; 6509 6510 // Create fields 6511 for (unsigned i = 0; i < NumFields; ++i) { 6512 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6513 VaListTagDecl, 6514 SourceLocation(), 6515 SourceLocation(), 6516 &Context->Idents.get(FieldNames[i]), 6517 FieldTypes[i], /*TInfo=*/nullptr, 6518 /*BitWidth=*/nullptr, 6519 /*Mutable=*/false, 6520 ICIS_NoInit); 6521 Field->setAccess(AS_public); 6522 VaListTagDecl->addDecl(Field); 6523 } 6524 VaListTagDecl->completeDefinition(); 6525 Context->VaListTagDecl = VaListTagDecl; 6526 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6527 6528 // } __builtin_va_list; 6529 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 6530 } 6531 6532 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 6533 // typedef struct __va_list_tag { 6534 RecordDecl *VaListTagDecl; 6535 6536 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6537 VaListTagDecl->startDefinition(); 6538 6539 const size_t NumFields = 5; 6540 QualType FieldTypes[NumFields]; 6541 const char *FieldNames[NumFields]; 6542 6543 // unsigned char gpr; 6544 FieldTypes[0] = Context->UnsignedCharTy; 6545 FieldNames[0] = "gpr"; 6546 6547 // unsigned char fpr; 6548 FieldTypes[1] = Context->UnsignedCharTy; 6549 FieldNames[1] = "fpr"; 6550 6551 // unsigned short reserved; 6552 FieldTypes[2] = Context->UnsignedShortTy; 6553 FieldNames[2] = "reserved"; 6554 6555 // void* overflow_arg_area; 6556 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6557 FieldNames[3] = "overflow_arg_area"; 6558 6559 // void* reg_save_area; 6560 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 6561 FieldNames[4] = "reg_save_area"; 6562 6563 // Create fields 6564 for (unsigned i = 0; i < NumFields; ++i) { 6565 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 6566 SourceLocation(), 6567 SourceLocation(), 6568 &Context->Idents.get(FieldNames[i]), 6569 FieldTypes[i], /*TInfo=*/nullptr, 6570 /*BitWidth=*/nullptr, 6571 /*Mutable=*/false, 6572 ICIS_NoInit); 6573 Field->setAccess(AS_public); 6574 VaListTagDecl->addDecl(Field); 6575 } 6576 VaListTagDecl->completeDefinition(); 6577 Context->VaListTagDecl = VaListTagDecl; 6578 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6579 6580 // } __va_list_tag; 6581 TypedefDecl *VaListTagTypedefDecl = 6582 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6583 6584 QualType VaListTagTypedefType = 6585 Context->getTypedefType(VaListTagTypedefDecl); 6586 6587 // typedef __va_list_tag __builtin_va_list[1]; 6588 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6589 QualType VaListTagArrayType 6590 = Context->getConstantArrayType(VaListTagTypedefType, 6591 Size, ArrayType::Normal, 0); 6592 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6593 } 6594 6595 static TypedefDecl * 6596 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 6597 // struct __va_list_tag { 6598 RecordDecl *VaListTagDecl; 6599 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6600 VaListTagDecl->startDefinition(); 6601 6602 const size_t NumFields = 4; 6603 QualType FieldTypes[NumFields]; 6604 const char *FieldNames[NumFields]; 6605 6606 // unsigned gp_offset; 6607 FieldTypes[0] = Context->UnsignedIntTy; 6608 FieldNames[0] = "gp_offset"; 6609 6610 // unsigned fp_offset; 6611 FieldTypes[1] = Context->UnsignedIntTy; 6612 FieldNames[1] = "fp_offset"; 6613 6614 // void* overflow_arg_area; 6615 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6616 FieldNames[2] = "overflow_arg_area"; 6617 6618 // void* reg_save_area; 6619 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6620 FieldNames[3] = "reg_save_area"; 6621 6622 // Create fields 6623 for (unsigned i = 0; i < NumFields; ++i) { 6624 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6625 VaListTagDecl, 6626 SourceLocation(), 6627 SourceLocation(), 6628 &Context->Idents.get(FieldNames[i]), 6629 FieldTypes[i], /*TInfo=*/nullptr, 6630 /*BitWidth=*/nullptr, 6631 /*Mutable=*/false, 6632 ICIS_NoInit); 6633 Field->setAccess(AS_public); 6634 VaListTagDecl->addDecl(Field); 6635 } 6636 VaListTagDecl->completeDefinition(); 6637 Context->VaListTagDecl = VaListTagDecl; 6638 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6639 6640 // }; 6641 6642 // typedef struct __va_list_tag __builtin_va_list[1]; 6643 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6644 QualType VaListTagArrayType = 6645 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 6646 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6647 } 6648 6649 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 6650 // typedef int __builtin_va_list[4]; 6651 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 6652 QualType IntArrayType = 6653 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0); 6654 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 6655 } 6656 6657 static TypedefDecl * 6658 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 6659 // struct __va_list 6660 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 6661 if (Context->getLangOpts().CPlusPlus) { 6662 // namespace std { struct __va_list { 6663 NamespaceDecl *NS; 6664 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6665 Context->getTranslationUnitDecl(), 6666 /*Inline*/false, SourceLocation(), 6667 SourceLocation(), &Context->Idents.get("std"), 6668 /*PrevDecl*/ nullptr); 6669 NS->setImplicit(); 6670 VaListDecl->setDeclContext(NS); 6671 } 6672 6673 VaListDecl->startDefinition(); 6674 6675 // void * __ap; 6676 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6677 VaListDecl, 6678 SourceLocation(), 6679 SourceLocation(), 6680 &Context->Idents.get("__ap"), 6681 Context->getPointerType(Context->VoidTy), 6682 /*TInfo=*/nullptr, 6683 /*BitWidth=*/nullptr, 6684 /*Mutable=*/false, 6685 ICIS_NoInit); 6686 Field->setAccess(AS_public); 6687 VaListDecl->addDecl(Field); 6688 6689 // }; 6690 VaListDecl->completeDefinition(); 6691 Context->VaListTagDecl = VaListDecl; 6692 6693 // typedef struct __va_list __builtin_va_list; 6694 QualType T = Context->getRecordType(VaListDecl); 6695 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6696 } 6697 6698 static TypedefDecl * 6699 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 6700 // struct __va_list_tag { 6701 RecordDecl *VaListTagDecl; 6702 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6703 VaListTagDecl->startDefinition(); 6704 6705 const size_t NumFields = 4; 6706 QualType FieldTypes[NumFields]; 6707 const char *FieldNames[NumFields]; 6708 6709 // long __gpr; 6710 FieldTypes[0] = Context->LongTy; 6711 FieldNames[0] = "__gpr"; 6712 6713 // long __fpr; 6714 FieldTypes[1] = Context->LongTy; 6715 FieldNames[1] = "__fpr"; 6716 6717 // void *__overflow_arg_area; 6718 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6719 FieldNames[2] = "__overflow_arg_area"; 6720 6721 // void *__reg_save_area; 6722 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6723 FieldNames[3] = "__reg_save_area"; 6724 6725 // Create fields 6726 for (unsigned i = 0; i < NumFields; ++i) { 6727 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6728 VaListTagDecl, 6729 SourceLocation(), 6730 SourceLocation(), 6731 &Context->Idents.get(FieldNames[i]), 6732 FieldTypes[i], /*TInfo=*/nullptr, 6733 /*BitWidth=*/nullptr, 6734 /*Mutable=*/false, 6735 ICIS_NoInit); 6736 Field->setAccess(AS_public); 6737 VaListTagDecl->addDecl(Field); 6738 } 6739 VaListTagDecl->completeDefinition(); 6740 Context->VaListTagDecl = VaListTagDecl; 6741 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6742 6743 // }; 6744 6745 // typedef __va_list_tag __builtin_va_list[1]; 6746 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6747 QualType VaListTagArrayType = 6748 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 6749 6750 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6751 } 6752 6753 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 6754 TargetInfo::BuiltinVaListKind Kind) { 6755 switch (Kind) { 6756 case TargetInfo::CharPtrBuiltinVaList: 6757 return CreateCharPtrBuiltinVaListDecl(Context); 6758 case TargetInfo::VoidPtrBuiltinVaList: 6759 return CreateVoidPtrBuiltinVaListDecl(Context); 6760 case TargetInfo::AArch64ABIBuiltinVaList: 6761 return CreateAArch64ABIBuiltinVaListDecl(Context); 6762 case TargetInfo::PowerABIBuiltinVaList: 6763 return CreatePowerABIBuiltinVaListDecl(Context); 6764 case TargetInfo::X86_64ABIBuiltinVaList: 6765 return CreateX86_64ABIBuiltinVaListDecl(Context); 6766 case TargetInfo::PNaClABIBuiltinVaList: 6767 return CreatePNaClABIBuiltinVaListDecl(Context); 6768 case TargetInfo::AAPCSABIBuiltinVaList: 6769 return CreateAAPCSABIBuiltinVaListDecl(Context); 6770 case TargetInfo::SystemZBuiltinVaList: 6771 return CreateSystemZBuiltinVaListDecl(Context); 6772 } 6773 6774 llvm_unreachable("Unhandled __builtin_va_list type kind"); 6775 } 6776 6777 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 6778 if (!BuiltinVaListDecl) { 6779 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 6780 assert(BuiltinVaListDecl->isImplicit()); 6781 } 6782 6783 return BuiltinVaListDecl; 6784 } 6785 6786 Decl *ASTContext::getVaListTagDecl() const { 6787 // Force the creation of VaListTagDecl by building the __builtin_va_list 6788 // declaration. 6789 if (!VaListTagDecl) 6790 (void)getBuiltinVaListDecl(); 6791 6792 return VaListTagDecl; 6793 } 6794 6795 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 6796 if (!BuiltinMSVaListDecl) 6797 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 6798 6799 return BuiltinMSVaListDecl; 6800 } 6801 6802 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 6803 assert(ObjCConstantStringType.isNull() && 6804 "'NSConstantString' type already set!"); 6805 6806 ObjCConstantStringType = getObjCInterfaceType(Decl); 6807 } 6808 6809 /// \brief Retrieve the template name that corresponds to a non-empty 6810 /// lookup. 6811 TemplateName 6812 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 6813 UnresolvedSetIterator End) const { 6814 unsigned size = End - Begin; 6815 assert(size > 1 && "set is not overloaded!"); 6816 6817 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 6818 size * sizeof(FunctionTemplateDecl*)); 6819 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 6820 6821 NamedDecl **Storage = OT->getStorage(); 6822 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 6823 NamedDecl *D = *I; 6824 assert(isa<FunctionTemplateDecl>(D) || 6825 (isa<UsingShadowDecl>(D) && 6826 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 6827 *Storage++ = D; 6828 } 6829 6830 return TemplateName(OT); 6831 } 6832 6833 /// \brief Retrieve the template name that represents a qualified 6834 /// template name such as \c std::vector. 6835 TemplateName 6836 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 6837 bool TemplateKeyword, 6838 TemplateDecl *Template) const { 6839 assert(NNS && "Missing nested-name-specifier in qualified template name"); 6840 6841 // FIXME: Canonicalization? 6842 llvm::FoldingSetNodeID ID; 6843 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 6844 6845 void *InsertPos = nullptr; 6846 QualifiedTemplateName *QTN = 6847 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6848 if (!QTN) { 6849 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>()) 6850 QualifiedTemplateName(NNS, TemplateKeyword, Template); 6851 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 6852 } 6853 6854 return TemplateName(QTN); 6855 } 6856 6857 /// \brief Retrieve the template name that represents a dependent 6858 /// template name such as \c MetaFun::template apply. 6859 TemplateName 6860 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6861 const IdentifierInfo *Name) const { 6862 assert((!NNS || NNS->isDependent()) && 6863 "Nested name specifier must be dependent"); 6864 6865 llvm::FoldingSetNodeID ID; 6866 DependentTemplateName::Profile(ID, NNS, Name); 6867 6868 void *InsertPos = nullptr; 6869 DependentTemplateName *QTN = 6870 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6871 6872 if (QTN) 6873 return TemplateName(QTN); 6874 6875 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6876 if (CanonNNS == NNS) { 6877 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6878 DependentTemplateName(NNS, Name); 6879 } else { 6880 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 6881 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6882 DependentTemplateName(NNS, Name, Canon); 6883 DependentTemplateName *CheckQTN = 6884 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6885 assert(!CheckQTN && "Dependent type name canonicalization broken"); 6886 (void)CheckQTN; 6887 } 6888 6889 DependentTemplateNames.InsertNode(QTN, InsertPos); 6890 return TemplateName(QTN); 6891 } 6892 6893 /// \brief Retrieve the template name that represents a dependent 6894 /// template name such as \c MetaFun::template operator+. 6895 TemplateName 6896 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6897 OverloadedOperatorKind Operator) const { 6898 assert((!NNS || NNS->isDependent()) && 6899 "Nested name specifier must be dependent"); 6900 6901 llvm::FoldingSetNodeID ID; 6902 DependentTemplateName::Profile(ID, NNS, Operator); 6903 6904 void *InsertPos = nullptr; 6905 DependentTemplateName *QTN 6906 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6907 6908 if (QTN) 6909 return TemplateName(QTN); 6910 6911 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6912 if (CanonNNS == NNS) { 6913 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6914 DependentTemplateName(NNS, Operator); 6915 } else { 6916 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 6917 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6918 DependentTemplateName(NNS, Operator, Canon); 6919 6920 DependentTemplateName *CheckQTN 6921 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6922 assert(!CheckQTN && "Dependent template name canonicalization broken"); 6923 (void)CheckQTN; 6924 } 6925 6926 DependentTemplateNames.InsertNode(QTN, InsertPos); 6927 return TemplateName(QTN); 6928 } 6929 6930 TemplateName 6931 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 6932 TemplateName replacement) const { 6933 llvm::FoldingSetNodeID ID; 6934 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 6935 6936 void *insertPos = nullptr; 6937 SubstTemplateTemplateParmStorage *subst 6938 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 6939 6940 if (!subst) { 6941 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 6942 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 6943 } 6944 6945 return TemplateName(subst); 6946 } 6947 6948 TemplateName 6949 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 6950 const TemplateArgument &ArgPack) const { 6951 ASTContext &Self = const_cast<ASTContext &>(*this); 6952 llvm::FoldingSetNodeID ID; 6953 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 6954 6955 void *InsertPos = nullptr; 6956 SubstTemplateTemplateParmPackStorage *Subst 6957 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 6958 6959 if (!Subst) { 6960 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 6961 ArgPack.pack_size(), 6962 ArgPack.pack_begin()); 6963 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 6964 } 6965 6966 return TemplateName(Subst); 6967 } 6968 6969 /// getFromTargetType - Given one of the integer types provided by 6970 /// TargetInfo, produce the corresponding type. The unsigned @p Type 6971 /// is actually a value of type @c TargetInfo::IntType. 6972 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 6973 switch (Type) { 6974 case TargetInfo::NoInt: return CanQualType(); 6975 case TargetInfo::SignedChar: return SignedCharTy; 6976 case TargetInfo::UnsignedChar: return UnsignedCharTy; 6977 case TargetInfo::SignedShort: return ShortTy; 6978 case TargetInfo::UnsignedShort: return UnsignedShortTy; 6979 case TargetInfo::SignedInt: return IntTy; 6980 case TargetInfo::UnsignedInt: return UnsignedIntTy; 6981 case TargetInfo::SignedLong: return LongTy; 6982 case TargetInfo::UnsignedLong: return UnsignedLongTy; 6983 case TargetInfo::SignedLongLong: return LongLongTy; 6984 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 6985 } 6986 6987 llvm_unreachable("Unhandled TargetInfo::IntType value"); 6988 } 6989 6990 //===----------------------------------------------------------------------===// 6991 // Type Predicates. 6992 //===----------------------------------------------------------------------===// 6993 6994 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 6995 /// garbage collection attribute. 6996 /// 6997 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 6998 if (getLangOpts().getGC() == LangOptions::NonGC) 6999 return Qualifiers::GCNone; 7000 7001 assert(getLangOpts().ObjC1); 7002 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 7003 7004 // Default behaviour under objective-C's gc is for ObjC pointers 7005 // (or pointers to them) be treated as though they were declared 7006 // as __strong. 7007 if (GCAttrs == Qualifiers::GCNone) { 7008 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 7009 return Qualifiers::Strong; 7010 else if (Ty->isPointerType()) 7011 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 7012 } else { 7013 // It's not valid to set GC attributes on anything that isn't a 7014 // pointer. 7015 #ifndef NDEBUG 7016 QualType CT = Ty->getCanonicalTypeInternal(); 7017 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 7018 CT = AT->getElementType(); 7019 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 7020 #endif 7021 } 7022 return GCAttrs; 7023 } 7024 7025 //===----------------------------------------------------------------------===// 7026 // Type Compatibility Testing 7027 //===----------------------------------------------------------------------===// 7028 7029 /// areCompatVectorTypes - Return true if the two specified vector types are 7030 /// compatible. 7031 static bool areCompatVectorTypes(const VectorType *LHS, 7032 const VectorType *RHS) { 7033 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 7034 return LHS->getElementType() == RHS->getElementType() && 7035 LHS->getNumElements() == RHS->getNumElements(); 7036 } 7037 7038 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 7039 QualType SecondVec) { 7040 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 7041 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 7042 7043 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 7044 return true; 7045 7046 // Treat Neon vector types and most AltiVec vector types as if they are the 7047 // equivalent GCC vector types. 7048 const VectorType *First = FirstVec->getAs<VectorType>(); 7049 const VectorType *Second = SecondVec->getAs<VectorType>(); 7050 if (First->getNumElements() == Second->getNumElements() && 7051 hasSameType(First->getElementType(), Second->getElementType()) && 7052 First->getVectorKind() != VectorType::AltiVecPixel && 7053 First->getVectorKind() != VectorType::AltiVecBool && 7054 Second->getVectorKind() != VectorType::AltiVecPixel && 7055 Second->getVectorKind() != VectorType::AltiVecBool) 7056 return true; 7057 7058 return false; 7059 } 7060 7061 //===----------------------------------------------------------------------===// 7062 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 7063 //===----------------------------------------------------------------------===// 7064 7065 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 7066 /// inheritance hierarchy of 'rProto'. 7067 bool 7068 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 7069 ObjCProtocolDecl *rProto) const { 7070 if (declaresSameEntity(lProto, rProto)) 7071 return true; 7072 for (auto *PI : rProto->protocols()) 7073 if (ProtocolCompatibleWithProtocol(lProto, PI)) 7074 return true; 7075 return false; 7076 } 7077 7078 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 7079 /// Class<pr1, ...>. 7080 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 7081 QualType rhs) { 7082 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 7083 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7084 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 7085 7086 for (auto *lhsProto : lhsQID->quals()) { 7087 bool match = false; 7088 for (auto *rhsProto : rhsOPT->quals()) { 7089 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 7090 match = true; 7091 break; 7092 } 7093 } 7094 if (!match) 7095 return false; 7096 } 7097 return true; 7098 } 7099 7100 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 7101 /// ObjCQualifiedIDType. 7102 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 7103 bool compare) { 7104 // Allow id<P..> and an 'id' or void* type in all cases. 7105 if (lhs->isVoidPointerType() || 7106 lhs->isObjCIdType() || lhs->isObjCClassType()) 7107 return true; 7108 else if (rhs->isVoidPointerType() || 7109 rhs->isObjCIdType() || rhs->isObjCClassType()) 7110 return true; 7111 7112 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 7113 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7114 7115 if (!rhsOPT) return false; 7116 7117 if (rhsOPT->qual_empty()) { 7118 // If the RHS is a unqualified interface pointer "NSString*", 7119 // make sure we check the class hierarchy. 7120 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7121 for (auto *I : lhsQID->quals()) { 7122 // when comparing an id<P> on lhs with a static type on rhs, 7123 // see if static class implements all of id's protocols, directly or 7124 // through its super class and categories. 7125 if (!rhsID->ClassImplementsProtocol(I, true)) 7126 return false; 7127 } 7128 } 7129 // If there are no qualifiers and no interface, we have an 'id'. 7130 return true; 7131 } 7132 // Both the right and left sides have qualifiers. 7133 for (auto *lhsProto : lhsQID->quals()) { 7134 bool match = false; 7135 7136 // when comparing an id<P> on lhs with a static type on rhs, 7137 // see if static class implements all of id's protocols, directly or 7138 // through its super class and categories. 7139 for (auto *rhsProto : rhsOPT->quals()) { 7140 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7141 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7142 match = true; 7143 break; 7144 } 7145 } 7146 // If the RHS is a qualified interface pointer "NSString<P>*", 7147 // make sure we check the class hierarchy. 7148 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7149 for (auto *I : lhsQID->quals()) { 7150 // when comparing an id<P> on lhs with a static type on rhs, 7151 // see if static class implements all of id's protocols, directly or 7152 // through its super class and categories. 7153 if (rhsID->ClassImplementsProtocol(I, true)) { 7154 match = true; 7155 break; 7156 } 7157 } 7158 } 7159 if (!match) 7160 return false; 7161 } 7162 7163 return true; 7164 } 7165 7166 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 7167 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 7168 7169 if (const ObjCObjectPointerType *lhsOPT = 7170 lhs->getAsObjCInterfacePointerType()) { 7171 // If both the right and left sides have qualifiers. 7172 for (auto *lhsProto : lhsOPT->quals()) { 7173 bool match = false; 7174 7175 // when comparing an id<P> on rhs with a static type on lhs, 7176 // see if static class implements all of id's protocols, directly or 7177 // through its super class and categories. 7178 // First, lhs protocols in the qualifier list must be found, direct 7179 // or indirect in rhs's qualifier list or it is a mismatch. 7180 for (auto *rhsProto : rhsQID->quals()) { 7181 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7182 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7183 match = true; 7184 break; 7185 } 7186 } 7187 if (!match) 7188 return false; 7189 } 7190 7191 // Static class's protocols, or its super class or category protocols 7192 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 7193 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 7194 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 7195 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 7196 // This is rather dubious but matches gcc's behavior. If lhs has 7197 // no type qualifier and its class has no static protocol(s) 7198 // assume that it is mismatch. 7199 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 7200 return false; 7201 for (auto *lhsProto : LHSInheritedProtocols) { 7202 bool match = false; 7203 for (auto *rhsProto : rhsQID->quals()) { 7204 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7205 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7206 match = true; 7207 break; 7208 } 7209 } 7210 if (!match) 7211 return false; 7212 } 7213 } 7214 return true; 7215 } 7216 return false; 7217 } 7218 7219 /// canAssignObjCInterfaces - Return true if the two interface types are 7220 /// compatible for assignment from RHS to LHS. This handles validation of any 7221 /// protocol qualifiers on the LHS or RHS. 7222 /// 7223 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 7224 const ObjCObjectPointerType *RHSOPT) { 7225 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7226 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7227 7228 // If either type represents the built-in 'id' or 'Class' types, return true. 7229 if (LHS->isObjCUnqualifiedIdOrClass() || 7230 RHS->isObjCUnqualifiedIdOrClass()) 7231 return true; 7232 7233 // Function object that propagates a successful result or handles 7234 // __kindof types. 7235 auto finish = [&](bool succeeded) -> bool { 7236 if (succeeded) 7237 return true; 7238 7239 if (!RHS->isKindOfType()) 7240 return false; 7241 7242 // Strip off __kindof and protocol qualifiers, then check whether 7243 // we can assign the other way. 7244 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7245 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 7246 }; 7247 7248 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 7249 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7250 QualType(RHSOPT,0), 7251 false)); 7252 } 7253 7254 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 7255 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 7256 QualType(RHSOPT,0))); 7257 } 7258 7259 // If we have 2 user-defined types, fall into that path. 7260 if (LHS->getInterface() && RHS->getInterface()) { 7261 return finish(canAssignObjCInterfaces(LHS, RHS)); 7262 } 7263 7264 return false; 7265 } 7266 7267 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 7268 /// for providing type-safety for objective-c pointers used to pass/return 7269 /// arguments in block literals. When passed as arguments, passing 'A*' where 7270 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 7271 /// not OK. For the return type, the opposite is not OK. 7272 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 7273 const ObjCObjectPointerType *LHSOPT, 7274 const ObjCObjectPointerType *RHSOPT, 7275 bool BlockReturnType) { 7276 7277 // Function object that propagates a successful result or handles 7278 // __kindof types. 7279 auto finish = [&](bool succeeded) -> bool { 7280 if (succeeded) 7281 return true; 7282 7283 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 7284 if (!Expected->isKindOfType()) 7285 return false; 7286 7287 // Strip off __kindof and protocol qualifiers, then check whether 7288 // we can assign the other way. 7289 return canAssignObjCInterfacesInBlockPointer( 7290 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7291 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 7292 BlockReturnType); 7293 }; 7294 7295 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 7296 return true; 7297 7298 if (LHSOPT->isObjCBuiltinType()) { 7299 return finish(RHSOPT->isObjCBuiltinType() || 7300 RHSOPT->isObjCQualifiedIdType()); 7301 } 7302 7303 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 7304 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7305 QualType(RHSOPT,0), 7306 false)); 7307 7308 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 7309 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 7310 if (LHS && RHS) { // We have 2 user-defined types. 7311 if (LHS != RHS) { 7312 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 7313 return finish(BlockReturnType); 7314 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 7315 return finish(!BlockReturnType); 7316 } 7317 else 7318 return true; 7319 } 7320 return false; 7321 } 7322 7323 /// Comparison routine for Objective-C protocols to be used with 7324 /// llvm::array_pod_sort. 7325 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 7326 ObjCProtocolDecl * const *rhs) { 7327 return (*lhs)->getName().compare((*rhs)->getName()); 7328 7329 } 7330 7331 /// getIntersectionOfProtocols - This routine finds the intersection of set 7332 /// of protocols inherited from two distinct objective-c pointer objects with 7333 /// the given common base. 7334 /// It is used to build composite qualifier list of the composite type of 7335 /// the conditional expression involving two objective-c pointer objects. 7336 static 7337 void getIntersectionOfProtocols(ASTContext &Context, 7338 const ObjCInterfaceDecl *CommonBase, 7339 const ObjCObjectPointerType *LHSOPT, 7340 const ObjCObjectPointerType *RHSOPT, 7341 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 7342 7343 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7344 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7345 assert(LHS->getInterface() && "LHS must have an interface base"); 7346 assert(RHS->getInterface() && "RHS must have an interface base"); 7347 7348 // Add all of the protocols for the LHS. 7349 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 7350 7351 // Start with the protocol qualifiers. 7352 for (auto proto : LHS->quals()) { 7353 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 7354 } 7355 7356 // Also add the protocols associated with the LHS interface. 7357 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 7358 7359 // Add all of the protocls for the RHS. 7360 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 7361 7362 // Start with the protocol qualifiers. 7363 for (auto proto : RHS->quals()) { 7364 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 7365 } 7366 7367 // Also add the protocols associated with the RHS interface. 7368 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 7369 7370 // Compute the intersection of the collected protocol sets. 7371 for (auto proto : LHSProtocolSet) { 7372 if (RHSProtocolSet.count(proto)) 7373 IntersectionSet.push_back(proto); 7374 } 7375 7376 // Compute the set of protocols that is implied by either the common type or 7377 // the protocols within the intersection. 7378 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 7379 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 7380 7381 // Remove any implied protocols from the list of inherited protocols. 7382 if (!ImpliedProtocols.empty()) { 7383 IntersectionSet.erase( 7384 std::remove_if(IntersectionSet.begin(), 7385 IntersectionSet.end(), 7386 [&](ObjCProtocolDecl *proto) -> bool { 7387 return ImpliedProtocols.count(proto) > 0; 7388 }), 7389 IntersectionSet.end()); 7390 } 7391 7392 // Sort the remaining protocols by name. 7393 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 7394 compareObjCProtocolsByName); 7395 } 7396 7397 /// Determine whether the first type is a subtype of the second. 7398 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 7399 QualType rhs) { 7400 // Common case: two object pointers. 7401 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 7402 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7403 if (lhsOPT && rhsOPT) 7404 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 7405 7406 // Two block pointers. 7407 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>(); 7408 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>(); 7409 if (lhsBlock && rhsBlock) 7410 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 7411 7412 // If either is an unqualified 'id' and the other is a block, it's 7413 // acceptable. 7414 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 7415 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 7416 return true; 7417 7418 return false; 7419 } 7420 7421 // Check that the given Objective-C type argument lists are equivalent. 7422 static bool sameObjCTypeArgs(ASTContext &ctx, 7423 const ObjCInterfaceDecl *iface, 7424 ArrayRef<QualType> lhsArgs, 7425 ArrayRef<QualType> rhsArgs, 7426 bool stripKindOf) { 7427 if (lhsArgs.size() != rhsArgs.size()) 7428 return false; 7429 7430 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 7431 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 7432 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 7433 continue; 7434 7435 switch (typeParams->begin()[i]->getVariance()) { 7436 case ObjCTypeParamVariance::Invariant: 7437 if (!stripKindOf || 7438 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 7439 rhsArgs[i].stripObjCKindOfType(ctx))) { 7440 return false; 7441 } 7442 break; 7443 7444 case ObjCTypeParamVariance::Covariant: 7445 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 7446 return false; 7447 break; 7448 7449 case ObjCTypeParamVariance::Contravariant: 7450 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 7451 return false; 7452 break; 7453 } 7454 } 7455 7456 return true; 7457 } 7458 7459 QualType ASTContext::areCommonBaseCompatible( 7460 const ObjCObjectPointerType *Lptr, 7461 const ObjCObjectPointerType *Rptr) { 7462 const ObjCObjectType *LHS = Lptr->getObjectType(); 7463 const ObjCObjectType *RHS = Rptr->getObjectType(); 7464 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 7465 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 7466 7467 if (!LDecl || !RDecl) 7468 return QualType(); 7469 7470 // When either LHS or RHS is a kindof type, we should return a kindof type. 7471 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 7472 // kindof(A). 7473 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 7474 7475 // Follow the left-hand side up the class hierarchy until we either hit a 7476 // root or find the RHS. Record the ancestors in case we don't find it. 7477 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 7478 LHSAncestors; 7479 while (true) { 7480 // Record this ancestor. We'll need this if the common type isn't in the 7481 // path from the LHS to the root. 7482 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 7483 7484 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 7485 // Get the type arguments. 7486 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 7487 bool anyChanges = false; 7488 if (LHS->isSpecialized() && RHS->isSpecialized()) { 7489 // Both have type arguments, compare them. 7490 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 7491 LHS->getTypeArgs(), RHS->getTypeArgs(), 7492 /*stripKindOf=*/true)) 7493 return QualType(); 7494 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 7495 // If only one has type arguments, the result will not have type 7496 // arguments. 7497 LHSTypeArgs = { }; 7498 anyChanges = true; 7499 } 7500 7501 // Compute the intersection of protocols. 7502 SmallVector<ObjCProtocolDecl *, 8> Protocols; 7503 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 7504 Protocols); 7505 if (!Protocols.empty()) 7506 anyChanges = true; 7507 7508 // If anything in the LHS will have changed, build a new result type. 7509 // If we need to return a kindof type but LHS is not a kindof type, we 7510 // build a new result type. 7511 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 7512 QualType Result = getObjCInterfaceType(LHS->getInterface()); 7513 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 7514 anyKindOf || LHS->isKindOfType()); 7515 return getObjCObjectPointerType(Result); 7516 } 7517 7518 return getObjCObjectPointerType(QualType(LHS, 0)); 7519 } 7520 7521 // Find the superclass. 7522 QualType LHSSuperType = LHS->getSuperClassType(); 7523 if (LHSSuperType.isNull()) 7524 break; 7525 7526 LHS = LHSSuperType->castAs<ObjCObjectType>(); 7527 } 7528 7529 // We didn't find anything by following the LHS to its root; now check 7530 // the RHS against the cached set of ancestors. 7531 while (true) { 7532 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 7533 if (KnownLHS != LHSAncestors.end()) { 7534 LHS = KnownLHS->second; 7535 7536 // Get the type arguments. 7537 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 7538 bool anyChanges = false; 7539 if (LHS->isSpecialized() && RHS->isSpecialized()) { 7540 // Both have type arguments, compare them. 7541 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 7542 LHS->getTypeArgs(), RHS->getTypeArgs(), 7543 /*stripKindOf=*/true)) 7544 return QualType(); 7545 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 7546 // If only one has type arguments, the result will not have type 7547 // arguments. 7548 RHSTypeArgs = { }; 7549 anyChanges = true; 7550 } 7551 7552 // Compute the intersection of protocols. 7553 SmallVector<ObjCProtocolDecl *, 8> Protocols; 7554 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 7555 Protocols); 7556 if (!Protocols.empty()) 7557 anyChanges = true; 7558 7559 // If we need to return a kindof type but RHS is not a kindof type, we 7560 // build a new result type. 7561 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 7562 QualType Result = getObjCInterfaceType(RHS->getInterface()); 7563 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 7564 anyKindOf || RHS->isKindOfType()); 7565 return getObjCObjectPointerType(Result); 7566 } 7567 7568 return getObjCObjectPointerType(QualType(RHS, 0)); 7569 } 7570 7571 // Find the superclass of the RHS. 7572 QualType RHSSuperType = RHS->getSuperClassType(); 7573 if (RHSSuperType.isNull()) 7574 break; 7575 7576 RHS = RHSSuperType->castAs<ObjCObjectType>(); 7577 } 7578 7579 return QualType(); 7580 } 7581 7582 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 7583 const ObjCObjectType *RHS) { 7584 assert(LHS->getInterface() && "LHS is not an interface type"); 7585 assert(RHS->getInterface() && "RHS is not an interface type"); 7586 7587 // Verify that the base decls are compatible: the RHS must be a subclass of 7588 // the LHS. 7589 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 7590 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 7591 if (!IsSuperClass) 7592 return false; 7593 7594 // If the LHS has protocol qualifiers, determine whether all of them are 7595 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 7596 // LHS). 7597 if (LHS->getNumProtocols() > 0) { 7598 // OK if conversion of LHS to SuperClass results in narrowing of types 7599 // ; i.e., SuperClass may implement at least one of the protocols 7600 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 7601 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 7602 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 7603 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 7604 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 7605 // qualifiers. 7606 for (auto *RHSPI : RHS->quals()) 7607 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 7608 // If there is no protocols associated with RHS, it is not a match. 7609 if (SuperClassInheritedProtocols.empty()) 7610 return false; 7611 7612 for (const auto *LHSProto : LHS->quals()) { 7613 bool SuperImplementsProtocol = false; 7614 for (auto *SuperClassProto : SuperClassInheritedProtocols) 7615 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 7616 SuperImplementsProtocol = true; 7617 break; 7618 } 7619 if (!SuperImplementsProtocol) 7620 return false; 7621 } 7622 } 7623 7624 // If the LHS is specialized, we may need to check type arguments. 7625 if (LHS->isSpecialized()) { 7626 // Follow the superclass chain until we've matched the LHS class in the 7627 // hierarchy. This substitutes type arguments through. 7628 const ObjCObjectType *RHSSuper = RHS; 7629 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 7630 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 7631 7632 // If the RHS is specializd, compare type arguments. 7633 if (RHSSuper->isSpecialized() && 7634 !sameObjCTypeArgs(*this, LHS->getInterface(), 7635 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 7636 /*stripKindOf=*/true)) { 7637 return false; 7638 } 7639 } 7640 7641 return true; 7642 } 7643 7644 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 7645 // get the "pointed to" types 7646 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 7647 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 7648 7649 if (!LHSOPT || !RHSOPT) 7650 return false; 7651 7652 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 7653 canAssignObjCInterfaces(RHSOPT, LHSOPT); 7654 } 7655 7656 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 7657 return canAssignObjCInterfaces( 7658 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 7659 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 7660 } 7661 7662 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 7663 /// both shall have the identically qualified version of a compatible type. 7664 /// C99 6.2.7p1: Two types have compatible types if their types are the 7665 /// same. See 6.7.[2,3,5] for additional rules. 7666 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 7667 bool CompareUnqualified) { 7668 if (getLangOpts().CPlusPlus) 7669 return hasSameType(LHS, RHS); 7670 7671 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 7672 } 7673 7674 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 7675 return typesAreCompatible(LHS, RHS); 7676 } 7677 7678 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 7679 return !mergeTypes(LHS, RHS, true).isNull(); 7680 } 7681 7682 /// mergeTransparentUnionType - if T is a transparent union type and a member 7683 /// of T is compatible with SubType, return the merged type, else return 7684 /// QualType() 7685 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 7686 bool OfBlockPointer, 7687 bool Unqualified) { 7688 if (const RecordType *UT = T->getAsUnionType()) { 7689 RecordDecl *UD = UT->getDecl(); 7690 if (UD->hasAttr<TransparentUnionAttr>()) { 7691 for (const auto *I : UD->fields()) { 7692 QualType ET = I->getType().getUnqualifiedType(); 7693 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 7694 if (!MT.isNull()) 7695 return MT; 7696 } 7697 } 7698 } 7699 7700 return QualType(); 7701 } 7702 7703 /// mergeFunctionParameterTypes - merge two types which appear as function 7704 /// parameter types 7705 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 7706 bool OfBlockPointer, 7707 bool Unqualified) { 7708 // GNU extension: two types are compatible if they appear as a function 7709 // argument, one of the types is a transparent union type and the other 7710 // type is compatible with a union member 7711 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 7712 Unqualified); 7713 if (!lmerge.isNull()) 7714 return lmerge; 7715 7716 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 7717 Unqualified); 7718 if (!rmerge.isNull()) 7719 return rmerge; 7720 7721 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 7722 } 7723 7724 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 7725 bool OfBlockPointer, 7726 bool Unqualified) { 7727 const FunctionType *lbase = lhs->getAs<FunctionType>(); 7728 const FunctionType *rbase = rhs->getAs<FunctionType>(); 7729 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 7730 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 7731 bool allLTypes = true; 7732 bool allRTypes = true; 7733 7734 // Check return type 7735 QualType retType; 7736 if (OfBlockPointer) { 7737 QualType RHS = rbase->getReturnType(); 7738 QualType LHS = lbase->getReturnType(); 7739 bool UnqualifiedResult = Unqualified; 7740 if (!UnqualifiedResult) 7741 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 7742 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 7743 } 7744 else 7745 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 7746 Unqualified); 7747 if (retType.isNull()) return QualType(); 7748 7749 if (Unqualified) 7750 retType = retType.getUnqualifiedType(); 7751 7752 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 7753 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 7754 if (Unqualified) { 7755 LRetType = LRetType.getUnqualifiedType(); 7756 RRetType = RRetType.getUnqualifiedType(); 7757 } 7758 7759 if (getCanonicalType(retType) != LRetType) 7760 allLTypes = false; 7761 if (getCanonicalType(retType) != RRetType) 7762 allRTypes = false; 7763 7764 // FIXME: double check this 7765 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 7766 // rbase->getRegParmAttr() != 0 && 7767 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 7768 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 7769 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 7770 7771 // Compatible functions must have compatible calling conventions 7772 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 7773 return QualType(); 7774 7775 // Regparm is part of the calling convention. 7776 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 7777 return QualType(); 7778 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 7779 return QualType(); 7780 7781 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 7782 return QualType(); 7783 7784 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 7785 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 7786 7787 if (lbaseInfo.getNoReturn() != NoReturn) 7788 allLTypes = false; 7789 if (rbaseInfo.getNoReturn() != NoReturn) 7790 allRTypes = false; 7791 7792 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 7793 7794 if (lproto && rproto) { // two C99 style function prototypes 7795 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 7796 "C++ shouldn't be here"); 7797 // Compatible functions must have the same number of parameters 7798 if (lproto->getNumParams() != rproto->getNumParams()) 7799 return QualType(); 7800 7801 // Variadic and non-variadic functions aren't compatible 7802 if (lproto->isVariadic() != rproto->isVariadic()) 7803 return QualType(); 7804 7805 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 7806 return QualType(); 7807 7808 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto)) 7809 return QualType(); 7810 7811 // Check parameter type compatibility 7812 SmallVector<QualType, 10> types; 7813 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 7814 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 7815 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 7816 QualType paramType = mergeFunctionParameterTypes( 7817 lParamType, rParamType, OfBlockPointer, Unqualified); 7818 if (paramType.isNull()) 7819 return QualType(); 7820 7821 if (Unqualified) 7822 paramType = paramType.getUnqualifiedType(); 7823 7824 types.push_back(paramType); 7825 if (Unqualified) { 7826 lParamType = lParamType.getUnqualifiedType(); 7827 rParamType = rParamType.getUnqualifiedType(); 7828 } 7829 7830 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 7831 allLTypes = false; 7832 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 7833 allRTypes = false; 7834 } 7835 7836 if (allLTypes) return lhs; 7837 if (allRTypes) return rhs; 7838 7839 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 7840 EPI.ExtInfo = einfo; 7841 return getFunctionType(retType, types, EPI); 7842 } 7843 7844 if (lproto) allRTypes = false; 7845 if (rproto) allLTypes = false; 7846 7847 const FunctionProtoType *proto = lproto ? lproto : rproto; 7848 if (proto) { 7849 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 7850 if (proto->isVariadic()) return QualType(); 7851 // Check that the types are compatible with the types that 7852 // would result from default argument promotions (C99 6.7.5.3p15). 7853 // The only types actually affected are promotable integer 7854 // types and floats, which would be passed as a different 7855 // type depending on whether the prototype is visible. 7856 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 7857 QualType paramTy = proto->getParamType(i); 7858 7859 // Look at the converted type of enum types, since that is the type used 7860 // to pass enum values. 7861 if (const EnumType *Enum = paramTy->getAs<EnumType>()) { 7862 paramTy = Enum->getDecl()->getIntegerType(); 7863 if (paramTy.isNull()) 7864 return QualType(); 7865 } 7866 7867 if (paramTy->isPromotableIntegerType() || 7868 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 7869 return QualType(); 7870 } 7871 7872 if (allLTypes) return lhs; 7873 if (allRTypes) return rhs; 7874 7875 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 7876 EPI.ExtInfo = einfo; 7877 return getFunctionType(retType, proto->getParamTypes(), EPI); 7878 } 7879 7880 if (allLTypes) return lhs; 7881 if (allRTypes) return rhs; 7882 return getFunctionNoProtoType(retType, einfo); 7883 } 7884 7885 /// Given that we have an enum type and a non-enum type, try to merge them. 7886 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 7887 QualType other, bool isBlockReturnType) { 7888 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 7889 // a signed integer type, or an unsigned integer type. 7890 // Compatibility is based on the underlying type, not the promotion 7891 // type. 7892 QualType underlyingType = ET->getDecl()->getIntegerType(); 7893 if (underlyingType.isNull()) return QualType(); 7894 if (Context.hasSameType(underlyingType, other)) 7895 return other; 7896 7897 // In block return types, we're more permissive and accept any 7898 // integral type of the same size. 7899 if (isBlockReturnType && other->isIntegerType() && 7900 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 7901 return other; 7902 7903 return QualType(); 7904 } 7905 7906 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 7907 bool OfBlockPointer, 7908 bool Unqualified, bool BlockReturnType) { 7909 // C++ [expr]: If an expression initially has the type "reference to T", the 7910 // type is adjusted to "T" prior to any further analysis, the expression 7911 // designates the object or function denoted by the reference, and the 7912 // expression is an lvalue unless the reference is an rvalue reference and 7913 // the expression is a function call (possibly inside parentheses). 7914 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 7915 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 7916 7917 if (Unqualified) { 7918 LHS = LHS.getUnqualifiedType(); 7919 RHS = RHS.getUnqualifiedType(); 7920 } 7921 7922 QualType LHSCan = getCanonicalType(LHS), 7923 RHSCan = getCanonicalType(RHS); 7924 7925 // If two types are identical, they are compatible. 7926 if (LHSCan == RHSCan) 7927 return LHS; 7928 7929 // If the qualifiers are different, the types aren't compatible... mostly. 7930 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7931 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7932 if (LQuals != RQuals) { 7933 if (getLangOpts().OpenCL) { 7934 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() || 7935 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers()) 7936 return QualType(); 7937 if (LQuals.isAddressSpaceSupersetOf(RQuals)) 7938 return LHS; 7939 if (RQuals.isAddressSpaceSupersetOf(LQuals)) 7940 return RHS; 7941 } 7942 // If any of these qualifiers are different, we have a type 7943 // mismatch. 7944 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7945 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 7946 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 7947 return QualType(); 7948 7949 // Exactly one GC qualifier difference is allowed: __strong is 7950 // okay if the other type has no GC qualifier but is an Objective 7951 // C object pointer (i.e. implicitly strong by default). We fix 7952 // this by pretending that the unqualified type was actually 7953 // qualified __strong. 7954 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7955 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7956 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7957 7958 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7959 return QualType(); 7960 7961 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 7962 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 7963 } 7964 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 7965 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 7966 } 7967 return QualType(); 7968 } 7969 7970 // Okay, qualifiers are equal. 7971 7972 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 7973 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 7974 7975 // We want to consider the two function types to be the same for these 7976 // comparisons, just force one to the other. 7977 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 7978 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 7979 7980 // Same as above for arrays 7981 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 7982 LHSClass = Type::ConstantArray; 7983 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 7984 RHSClass = Type::ConstantArray; 7985 7986 // ObjCInterfaces are just specialized ObjCObjects. 7987 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 7988 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 7989 7990 // Canonicalize ExtVector -> Vector. 7991 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 7992 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 7993 7994 // If the canonical type classes don't match. 7995 if (LHSClass != RHSClass) { 7996 // Note that we only have special rules for turning block enum 7997 // returns into block int returns, not vice-versa. 7998 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 7999 return mergeEnumWithInteger(*this, ETy, RHS, false); 8000 } 8001 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 8002 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 8003 } 8004 // allow block pointer type to match an 'id' type. 8005 if (OfBlockPointer && !BlockReturnType) { 8006 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 8007 return LHS; 8008 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 8009 return RHS; 8010 } 8011 8012 return QualType(); 8013 } 8014 8015 // The canonical type classes match. 8016 switch (LHSClass) { 8017 #define TYPE(Class, Base) 8018 #define ABSTRACT_TYPE(Class, Base) 8019 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 8020 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 8021 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 8022 #include "clang/AST/TypeNodes.def" 8023 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 8024 8025 case Type::Auto: 8026 case Type::LValueReference: 8027 case Type::RValueReference: 8028 case Type::MemberPointer: 8029 llvm_unreachable("C++ should never be in mergeTypes"); 8030 8031 case Type::ObjCInterface: 8032 case Type::IncompleteArray: 8033 case Type::VariableArray: 8034 case Type::FunctionProto: 8035 case Type::ExtVector: 8036 llvm_unreachable("Types are eliminated above"); 8037 8038 case Type::Pointer: 8039 { 8040 // Merge two pointer types, while trying to preserve typedef info 8041 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 8042 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 8043 if (Unqualified) { 8044 LHSPointee = LHSPointee.getUnqualifiedType(); 8045 RHSPointee = RHSPointee.getUnqualifiedType(); 8046 } 8047 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 8048 Unqualified); 8049 if (ResultType.isNull()) return QualType(); 8050 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8051 return LHS; 8052 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8053 return RHS; 8054 return getPointerType(ResultType); 8055 } 8056 case Type::BlockPointer: 8057 { 8058 // Merge two block pointer types, while trying to preserve typedef info 8059 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 8060 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 8061 if (Unqualified) { 8062 LHSPointee = LHSPointee.getUnqualifiedType(); 8063 RHSPointee = RHSPointee.getUnqualifiedType(); 8064 } 8065 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 8066 Unqualified); 8067 if (ResultType.isNull()) return QualType(); 8068 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8069 return LHS; 8070 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8071 return RHS; 8072 return getBlockPointerType(ResultType); 8073 } 8074 case Type::Atomic: 8075 { 8076 // Merge two pointer types, while trying to preserve typedef info 8077 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 8078 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 8079 if (Unqualified) { 8080 LHSValue = LHSValue.getUnqualifiedType(); 8081 RHSValue = RHSValue.getUnqualifiedType(); 8082 } 8083 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 8084 Unqualified); 8085 if (ResultType.isNull()) return QualType(); 8086 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 8087 return LHS; 8088 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 8089 return RHS; 8090 return getAtomicType(ResultType); 8091 } 8092 case Type::ConstantArray: 8093 { 8094 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 8095 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 8096 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 8097 return QualType(); 8098 8099 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 8100 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 8101 if (Unqualified) { 8102 LHSElem = LHSElem.getUnqualifiedType(); 8103 RHSElem = RHSElem.getUnqualifiedType(); 8104 } 8105 8106 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 8107 if (ResultType.isNull()) return QualType(); 8108 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8109 return LHS; 8110 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8111 return RHS; 8112 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 8113 ArrayType::ArraySizeModifier(), 0); 8114 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 8115 ArrayType::ArraySizeModifier(), 0); 8116 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 8117 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 8118 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8119 return LHS; 8120 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8121 return RHS; 8122 if (LVAT) { 8123 // FIXME: This isn't correct! But tricky to implement because 8124 // the array's size has to be the size of LHS, but the type 8125 // has to be different. 8126 return LHS; 8127 } 8128 if (RVAT) { 8129 // FIXME: This isn't correct! But tricky to implement because 8130 // the array's size has to be the size of RHS, but the type 8131 // has to be different. 8132 return RHS; 8133 } 8134 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 8135 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 8136 return getIncompleteArrayType(ResultType, 8137 ArrayType::ArraySizeModifier(), 0); 8138 } 8139 case Type::FunctionNoProto: 8140 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 8141 case Type::Record: 8142 case Type::Enum: 8143 return QualType(); 8144 case Type::Builtin: 8145 // Only exactly equal builtin types are compatible, which is tested above. 8146 return QualType(); 8147 case Type::Complex: 8148 // Distinct complex types are incompatible. 8149 return QualType(); 8150 case Type::Vector: 8151 // FIXME: The merged type should be an ExtVector! 8152 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 8153 RHSCan->getAs<VectorType>())) 8154 return LHS; 8155 return QualType(); 8156 case Type::ObjCObject: { 8157 // Check if the types are assignment compatible. 8158 // FIXME: This should be type compatibility, e.g. whether 8159 // "LHS x; RHS x;" at global scope is legal. 8160 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 8161 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 8162 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 8163 return LHS; 8164 8165 return QualType(); 8166 } 8167 case Type::ObjCObjectPointer: { 8168 if (OfBlockPointer) { 8169 if (canAssignObjCInterfacesInBlockPointer( 8170 LHS->getAs<ObjCObjectPointerType>(), 8171 RHS->getAs<ObjCObjectPointerType>(), 8172 BlockReturnType)) 8173 return LHS; 8174 return QualType(); 8175 } 8176 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 8177 RHS->getAs<ObjCObjectPointerType>())) 8178 return LHS; 8179 8180 return QualType(); 8181 } 8182 case Type::Pipe: 8183 { 8184 // Merge two pointer types, while trying to preserve typedef info 8185 QualType LHSValue = LHS->getAs<PipeType>()->getElementType(); 8186 QualType RHSValue = RHS->getAs<PipeType>()->getElementType(); 8187 if (Unqualified) { 8188 LHSValue = LHSValue.getUnqualifiedType(); 8189 RHSValue = RHSValue.getUnqualifiedType(); 8190 } 8191 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 8192 Unqualified); 8193 if (ResultType.isNull()) return QualType(); 8194 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 8195 return LHS; 8196 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 8197 return RHS; 8198 return getPipeType(ResultType); 8199 } 8200 } 8201 8202 llvm_unreachable("Invalid Type::Class!"); 8203 } 8204 8205 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos( 8206 const FunctionProtoType *firstFnType, 8207 const FunctionProtoType *secondFnType) { 8208 // Fast path: if the first type doesn't have ext parameter infos, 8209 // we match if and only if they second type also doesn't have them. 8210 if (!firstFnType->hasExtParameterInfos()) 8211 return !secondFnType->hasExtParameterInfos(); 8212 8213 // Otherwise, we can only match if the second type has them. 8214 if (!secondFnType->hasExtParameterInfos()) 8215 return false; 8216 8217 auto firstEPI = firstFnType->getExtParameterInfos(); 8218 auto secondEPI = secondFnType->getExtParameterInfos(); 8219 assert(firstEPI.size() == secondEPI.size()); 8220 8221 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) { 8222 if (firstEPI[i] != secondEPI[i]) 8223 return false; 8224 } 8225 return true; 8226 } 8227 8228 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 8229 ObjCLayouts[CD] = nullptr; 8230 } 8231 8232 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 8233 /// 'RHS' attributes and returns the merged version; including for function 8234 /// return types. 8235 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 8236 QualType LHSCan = getCanonicalType(LHS), 8237 RHSCan = getCanonicalType(RHS); 8238 // If two types are identical, they are compatible. 8239 if (LHSCan == RHSCan) 8240 return LHS; 8241 if (RHSCan->isFunctionType()) { 8242 if (!LHSCan->isFunctionType()) 8243 return QualType(); 8244 QualType OldReturnType = 8245 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 8246 QualType NewReturnType = 8247 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 8248 QualType ResReturnType = 8249 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 8250 if (ResReturnType.isNull()) 8251 return QualType(); 8252 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 8253 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 8254 // In either case, use OldReturnType to build the new function type. 8255 const FunctionType *F = LHS->getAs<FunctionType>(); 8256 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 8257 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8258 EPI.ExtInfo = getFunctionExtInfo(LHS); 8259 QualType ResultType = 8260 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 8261 return ResultType; 8262 } 8263 } 8264 return QualType(); 8265 } 8266 8267 // If the qualifiers are different, the types can still be merged. 8268 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 8269 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 8270 if (LQuals != RQuals) { 8271 // If any of these qualifiers are different, we have a type mismatch. 8272 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 8273 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 8274 return QualType(); 8275 8276 // Exactly one GC qualifier difference is allowed: __strong is 8277 // okay if the other type has no GC qualifier but is an Objective 8278 // C object pointer (i.e. implicitly strong by default). We fix 8279 // this by pretending that the unqualified type was actually 8280 // qualified __strong. 8281 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 8282 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 8283 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 8284 8285 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 8286 return QualType(); 8287 8288 if (GC_L == Qualifiers::Strong) 8289 return LHS; 8290 if (GC_R == Qualifiers::Strong) 8291 return RHS; 8292 return QualType(); 8293 } 8294 8295 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 8296 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 8297 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 8298 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 8299 if (ResQT == LHSBaseQT) 8300 return LHS; 8301 if (ResQT == RHSBaseQT) 8302 return RHS; 8303 } 8304 return QualType(); 8305 } 8306 8307 //===----------------------------------------------------------------------===// 8308 // Integer Predicates 8309 //===----------------------------------------------------------------------===// 8310 8311 unsigned ASTContext::getIntWidth(QualType T) const { 8312 if (const EnumType *ET = T->getAs<EnumType>()) 8313 T = ET->getDecl()->getIntegerType(); 8314 if (T->isBooleanType()) 8315 return 1; 8316 // For builtin types, just use the standard type sizing method 8317 return (unsigned)getTypeSize(T); 8318 } 8319 8320 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 8321 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 8322 8323 // Turn <4 x signed int> -> <4 x unsigned int> 8324 if (const VectorType *VTy = T->getAs<VectorType>()) 8325 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 8326 VTy->getNumElements(), VTy->getVectorKind()); 8327 8328 // For enums, we return the unsigned version of the base type. 8329 if (const EnumType *ETy = T->getAs<EnumType>()) 8330 T = ETy->getDecl()->getIntegerType(); 8331 8332 const BuiltinType *BTy = T->getAs<BuiltinType>(); 8333 assert(BTy && "Unexpected signed integer type"); 8334 switch (BTy->getKind()) { 8335 case BuiltinType::Char_S: 8336 case BuiltinType::SChar: 8337 return UnsignedCharTy; 8338 case BuiltinType::Short: 8339 return UnsignedShortTy; 8340 case BuiltinType::Int: 8341 return UnsignedIntTy; 8342 case BuiltinType::Long: 8343 return UnsignedLongTy; 8344 case BuiltinType::LongLong: 8345 return UnsignedLongLongTy; 8346 case BuiltinType::Int128: 8347 return UnsignedInt128Ty; 8348 default: 8349 llvm_unreachable("Unexpected signed integer type"); 8350 } 8351 } 8352 8353 ASTMutationListener::~ASTMutationListener() { } 8354 8355 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 8356 QualType ReturnType) {} 8357 8358 //===----------------------------------------------------------------------===// 8359 // Builtin Type Computation 8360 //===----------------------------------------------------------------------===// 8361 8362 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 8363 /// pointer over the consumed characters. This returns the resultant type. If 8364 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 8365 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 8366 /// a vector of "i*". 8367 /// 8368 /// RequiresICE is filled in on return to indicate whether the value is required 8369 /// to be an Integer Constant Expression. 8370 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 8371 ASTContext::GetBuiltinTypeError &Error, 8372 bool &RequiresICE, 8373 bool AllowTypeModifiers) { 8374 // Modifiers. 8375 int HowLong = 0; 8376 bool Signed = false, Unsigned = false; 8377 RequiresICE = false; 8378 8379 // Read the prefixed modifiers first. 8380 bool Done = false; 8381 while (!Done) { 8382 switch (*Str++) { 8383 default: Done = true; --Str; break; 8384 case 'I': 8385 RequiresICE = true; 8386 break; 8387 case 'S': 8388 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 8389 assert(!Signed && "Can't use 'S' modifier multiple times!"); 8390 Signed = true; 8391 break; 8392 case 'U': 8393 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 8394 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 8395 Unsigned = true; 8396 break; 8397 case 'L': 8398 assert(HowLong <= 2 && "Can't have LLLL modifier"); 8399 ++HowLong; 8400 break; 8401 case 'W': 8402 // This modifier represents int64 type. 8403 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 8404 switch (Context.getTargetInfo().getInt64Type()) { 8405 default: 8406 llvm_unreachable("Unexpected integer type"); 8407 case TargetInfo::SignedLong: 8408 HowLong = 1; 8409 break; 8410 case TargetInfo::SignedLongLong: 8411 HowLong = 2; 8412 break; 8413 } 8414 } 8415 } 8416 8417 QualType Type; 8418 8419 // Read the base type. 8420 switch (*Str++) { 8421 default: llvm_unreachable("Unknown builtin type letter!"); 8422 case 'v': 8423 assert(HowLong == 0 && !Signed && !Unsigned && 8424 "Bad modifiers used with 'v'!"); 8425 Type = Context.VoidTy; 8426 break; 8427 case 'h': 8428 assert(HowLong == 0 && !Signed && !Unsigned && 8429 "Bad modifiers used with 'h'!"); 8430 Type = Context.HalfTy; 8431 break; 8432 case 'f': 8433 assert(HowLong == 0 && !Signed && !Unsigned && 8434 "Bad modifiers used with 'f'!"); 8435 Type = Context.FloatTy; 8436 break; 8437 case 'd': 8438 assert(HowLong < 2 && !Signed && !Unsigned && 8439 "Bad modifiers used with 'd'!"); 8440 if (HowLong) 8441 Type = Context.LongDoubleTy; 8442 else 8443 Type = Context.DoubleTy; 8444 break; 8445 case 's': 8446 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 8447 if (Unsigned) 8448 Type = Context.UnsignedShortTy; 8449 else 8450 Type = Context.ShortTy; 8451 break; 8452 case 'i': 8453 if (HowLong == 3) 8454 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 8455 else if (HowLong == 2) 8456 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 8457 else if (HowLong == 1) 8458 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 8459 else 8460 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 8461 break; 8462 case 'c': 8463 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 8464 if (Signed) 8465 Type = Context.SignedCharTy; 8466 else if (Unsigned) 8467 Type = Context.UnsignedCharTy; 8468 else 8469 Type = Context.CharTy; 8470 break; 8471 case 'b': // boolean 8472 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 8473 Type = Context.BoolTy; 8474 break; 8475 case 'z': // size_t. 8476 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 8477 Type = Context.getSizeType(); 8478 break; 8479 case 'F': 8480 Type = Context.getCFConstantStringType(); 8481 break; 8482 case 'G': 8483 Type = Context.getObjCIdType(); 8484 break; 8485 case 'H': 8486 Type = Context.getObjCSelType(); 8487 break; 8488 case 'M': 8489 Type = Context.getObjCSuperType(); 8490 break; 8491 case 'a': 8492 Type = Context.getBuiltinVaListType(); 8493 assert(!Type.isNull() && "builtin va list type not initialized!"); 8494 break; 8495 case 'A': 8496 // This is a "reference" to a va_list; however, what exactly 8497 // this means depends on how va_list is defined. There are two 8498 // different kinds of va_list: ones passed by value, and ones 8499 // passed by reference. An example of a by-value va_list is 8500 // x86, where va_list is a char*. An example of by-ref va_list 8501 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 8502 // we want this argument to be a char*&; for x86-64, we want 8503 // it to be a __va_list_tag*. 8504 Type = Context.getBuiltinVaListType(); 8505 assert(!Type.isNull() && "builtin va list type not initialized!"); 8506 if (Type->isArrayType()) 8507 Type = Context.getArrayDecayedType(Type); 8508 else 8509 Type = Context.getLValueReferenceType(Type); 8510 break; 8511 case 'V': { 8512 char *End; 8513 unsigned NumElements = strtoul(Str, &End, 10); 8514 assert(End != Str && "Missing vector size"); 8515 Str = End; 8516 8517 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 8518 RequiresICE, false); 8519 assert(!RequiresICE && "Can't require vector ICE"); 8520 8521 // TODO: No way to make AltiVec vectors in builtins yet. 8522 Type = Context.getVectorType(ElementType, NumElements, 8523 VectorType::GenericVector); 8524 break; 8525 } 8526 case 'E': { 8527 char *End; 8528 8529 unsigned NumElements = strtoul(Str, &End, 10); 8530 assert(End != Str && "Missing vector size"); 8531 8532 Str = End; 8533 8534 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 8535 false); 8536 Type = Context.getExtVectorType(ElementType, NumElements); 8537 break; 8538 } 8539 case 'X': { 8540 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 8541 false); 8542 assert(!RequiresICE && "Can't require complex ICE"); 8543 Type = Context.getComplexType(ElementType); 8544 break; 8545 } 8546 case 'Y' : { 8547 Type = Context.getPointerDiffType(); 8548 break; 8549 } 8550 case 'P': 8551 Type = Context.getFILEType(); 8552 if (Type.isNull()) { 8553 Error = ASTContext::GE_Missing_stdio; 8554 return QualType(); 8555 } 8556 break; 8557 case 'J': 8558 if (Signed) 8559 Type = Context.getsigjmp_bufType(); 8560 else 8561 Type = Context.getjmp_bufType(); 8562 8563 if (Type.isNull()) { 8564 Error = ASTContext::GE_Missing_setjmp; 8565 return QualType(); 8566 } 8567 break; 8568 case 'K': 8569 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 8570 Type = Context.getucontext_tType(); 8571 8572 if (Type.isNull()) { 8573 Error = ASTContext::GE_Missing_ucontext; 8574 return QualType(); 8575 } 8576 break; 8577 case 'p': 8578 Type = Context.getProcessIDType(); 8579 break; 8580 } 8581 8582 // If there are modifiers and if we're allowed to parse them, go for it. 8583 Done = !AllowTypeModifiers; 8584 while (!Done) { 8585 switch (char c = *Str++) { 8586 default: Done = true; --Str; break; 8587 case '*': 8588 case '&': { 8589 // Both pointers and references can have their pointee types 8590 // qualified with an address space. 8591 char *End; 8592 unsigned AddrSpace = strtoul(Str, &End, 10); 8593 if (End != Str && AddrSpace != 0) { 8594 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 8595 Str = End; 8596 } 8597 if (c == '*') 8598 Type = Context.getPointerType(Type); 8599 else 8600 Type = Context.getLValueReferenceType(Type); 8601 break; 8602 } 8603 // FIXME: There's no way to have a built-in with an rvalue ref arg. 8604 case 'C': 8605 Type = Type.withConst(); 8606 break; 8607 case 'D': 8608 Type = Context.getVolatileType(Type); 8609 break; 8610 case 'R': 8611 Type = Type.withRestrict(); 8612 break; 8613 } 8614 } 8615 8616 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 8617 "Integer constant 'I' type must be an integer"); 8618 8619 return Type; 8620 } 8621 8622 /// GetBuiltinType - Return the type for the specified builtin. 8623 QualType ASTContext::GetBuiltinType(unsigned Id, 8624 GetBuiltinTypeError &Error, 8625 unsigned *IntegerConstantArgs) const { 8626 const char *TypeStr = BuiltinInfo.getTypeString(Id); 8627 8628 SmallVector<QualType, 8> ArgTypes; 8629 8630 bool RequiresICE = false; 8631 Error = GE_None; 8632 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 8633 RequiresICE, true); 8634 if (Error != GE_None) 8635 return QualType(); 8636 8637 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 8638 8639 while (TypeStr[0] && TypeStr[0] != '.') { 8640 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 8641 if (Error != GE_None) 8642 return QualType(); 8643 8644 // If this argument is required to be an IntegerConstantExpression and the 8645 // caller cares, fill in the bitmask we return. 8646 if (RequiresICE && IntegerConstantArgs) 8647 *IntegerConstantArgs |= 1 << ArgTypes.size(); 8648 8649 // Do array -> pointer decay. The builtin should use the decayed type. 8650 if (Ty->isArrayType()) 8651 Ty = getArrayDecayedType(Ty); 8652 8653 ArgTypes.push_back(Ty); 8654 } 8655 8656 if (Id == Builtin::BI__GetExceptionInfo) 8657 return QualType(); 8658 8659 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 8660 "'.' should only occur at end of builtin type list!"); 8661 8662 FunctionType::ExtInfo EI(CC_C); 8663 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 8664 8665 bool Variadic = (TypeStr[0] == '.'); 8666 8667 // We really shouldn't be making a no-proto type here, especially in C++. 8668 if (ArgTypes.empty() && Variadic) 8669 return getFunctionNoProtoType(ResType, EI); 8670 8671 FunctionProtoType::ExtProtoInfo EPI; 8672 EPI.ExtInfo = EI; 8673 EPI.Variadic = Variadic; 8674 8675 return getFunctionType(ResType, ArgTypes, EPI); 8676 } 8677 8678 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 8679 const FunctionDecl *FD) { 8680 if (!FD->isExternallyVisible()) 8681 return GVA_Internal; 8682 8683 GVALinkage External = GVA_StrongExternal; 8684 switch (FD->getTemplateSpecializationKind()) { 8685 case TSK_Undeclared: 8686 case TSK_ExplicitSpecialization: 8687 External = GVA_StrongExternal; 8688 break; 8689 8690 case TSK_ExplicitInstantiationDefinition: 8691 return GVA_StrongODR; 8692 8693 // C++11 [temp.explicit]p10: 8694 // [ Note: The intent is that an inline function that is the subject of 8695 // an explicit instantiation declaration will still be implicitly 8696 // instantiated when used so that the body can be considered for 8697 // inlining, but that no out-of-line copy of the inline function would be 8698 // generated in the translation unit. -- end note ] 8699 case TSK_ExplicitInstantiationDeclaration: 8700 return GVA_AvailableExternally; 8701 8702 case TSK_ImplicitInstantiation: 8703 External = GVA_DiscardableODR; 8704 break; 8705 } 8706 8707 if (!FD->isInlined()) 8708 return External; 8709 8710 if ((!Context.getLangOpts().CPlusPlus && 8711 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 8712 !FD->hasAttr<DLLExportAttr>()) || 8713 FD->hasAttr<GNUInlineAttr>()) { 8714 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 8715 8716 // GNU or C99 inline semantics. Determine whether this symbol should be 8717 // externally visible. 8718 if (FD->isInlineDefinitionExternallyVisible()) 8719 return External; 8720 8721 // C99 inline semantics, where the symbol is not externally visible. 8722 return GVA_AvailableExternally; 8723 } 8724 8725 // Functions specified with extern and inline in -fms-compatibility mode 8726 // forcibly get emitted. While the body of the function cannot be later 8727 // replaced, the function definition cannot be discarded. 8728 if (FD->isMSExternInline()) 8729 return GVA_StrongODR; 8730 8731 return GVA_DiscardableODR; 8732 } 8733 8734 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 8735 GVALinkage L, const Decl *D) { 8736 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 8737 // dllexport/dllimport on inline functions. 8738 if (D->hasAttr<DLLImportAttr>()) { 8739 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 8740 return GVA_AvailableExternally; 8741 } else if (D->hasAttr<DLLExportAttr>()) { 8742 if (L == GVA_DiscardableODR) 8743 return GVA_StrongODR; 8744 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && 8745 D->hasAttr<CUDAGlobalAttr>()) { 8746 // Device-side functions with __global__ attribute must always be 8747 // visible externally so they can be launched from host. 8748 if (L == GVA_DiscardableODR || L == GVA_Internal) 8749 return GVA_StrongODR; 8750 } 8751 return L; 8752 } 8753 8754 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 8755 return adjustGVALinkageForAttributes( 8756 *this, basicGVALinkageForFunction(*this, FD), FD); 8757 } 8758 8759 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 8760 const VarDecl *VD) { 8761 if (!VD->isExternallyVisible()) 8762 return GVA_Internal; 8763 8764 if (VD->isStaticLocal()) { 8765 GVALinkage StaticLocalLinkage = GVA_DiscardableODR; 8766 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 8767 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 8768 LexicalContext = LexicalContext->getLexicalParent(); 8769 8770 // Let the static local variable inherit its linkage from the nearest 8771 // enclosing function. 8772 if (LexicalContext) 8773 StaticLocalLinkage = 8774 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 8775 8776 // GVA_StrongODR function linkage is stronger than what we need, 8777 // downgrade to GVA_DiscardableODR. 8778 // This allows us to discard the variable if we never end up needing it. 8779 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR 8780 : StaticLocalLinkage; 8781 } 8782 8783 // MSVC treats in-class initialized static data members as definitions. 8784 // By giving them non-strong linkage, out-of-line definitions won't 8785 // cause link errors. 8786 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 8787 return GVA_DiscardableODR; 8788 8789 // Most non-template variables have strong linkage; inline variables are 8790 // linkonce_odr or (occasionally, for compatibility) weak_odr. 8791 GVALinkage StrongLinkage; 8792 switch (Context.getInlineVariableDefinitionKind(VD)) { 8793 case ASTContext::InlineVariableDefinitionKind::None: 8794 StrongLinkage = GVA_StrongExternal; 8795 break; 8796 case ASTContext::InlineVariableDefinitionKind::Weak: 8797 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 8798 StrongLinkage = GVA_DiscardableODR; 8799 break; 8800 case ASTContext::InlineVariableDefinitionKind::Strong: 8801 StrongLinkage = GVA_StrongODR; 8802 break; 8803 } 8804 8805 switch (VD->getTemplateSpecializationKind()) { 8806 case TSK_Undeclared: 8807 return StrongLinkage; 8808 8809 case TSK_ExplicitSpecialization: 8810 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 8811 VD->isStaticDataMember() 8812 ? GVA_StrongODR 8813 : StrongLinkage; 8814 8815 case TSK_ExplicitInstantiationDefinition: 8816 return GVA_StrongODR; 8817 8818 case TSK_ExplicitInstantiationDeclaration: 8819 return GVA_AvailableExternally; 8820 8821 case TSK_ImplicitInstantiation: 8822 return GVA_DiscardableODR; 8823 } 8824 8825 llvm_unreachable("Invalid Linkage!"); 8826 } 8827 8828 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 8829 return adjustGVALinkageForAttributes( 8830 *this, basicGVALinkageForVariable(*this, VD), VD); 8831 } 8832 8833 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 8834 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 8835 if (!VD->isFileVarDecl()) 8836 return false; 8837 // Global named register variables (GNU extension) are never emitted. 8838 if (VD->getStorageClass() == SC_Register) 8839 return false; 8840 if (VD->getDescribedVarTemplate() || 8841 isa<VarTemplatePartialSpecializationDecl>(VD)) 8842 return false; 8843 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8844 // We never need to emit an uninstantiated function template. 8845 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 8846 return false; 8847 } else if (isa<PragmaCommentDecl>(D)) 8848 return true; 8849 else if (isa<OMPThreadPrivateDecl>(D) || 8850 D->hasAttr<OMPDeclareTargetDeclAttr>()) 8851 return true; 8852 else if (isa<PragmaDetectMismatchDecl>(D)) 8853 return true; 8854 else if (isa<OMPThreadPrivateDecl>(D)) 8855 return !D->getDeclContext()->isDependentContext(); 8856 else if (isa<OMPDeclareReductionDecl>(D)) 8857 return !D->getDeclContext()->isDependentContext(); 8858 else if (isa<ImportDecl>(D)) 8859 return true; 8860 else 8861 return false; 8862 8863 // If this is a member of a class template, we do not need to emit it. 8864 if (D->getDeclContext()->isDependentContext()) 8865 return false; 8866 8867 // Weak references don't produce any output by themselves. 8868 if (D->hasAttr<WeakRefAttr>()) 8869 return false; 8870 8871 // Aliases and used decls are required. 8872 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 8873 return true; 8874 8875 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8876 // Forward declarations aren't required. 8877 if (!FD->doesThisDeclarationHaveABody()) 8878 return FD->doesDeclarationForceExternallyVisibleDefinition(); 8879 8880 // Constructors and destructors are required. 8881 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 8882 return true; 8883 8884 // The key function for a class is required. This rule only comes 8885 // into play when inline functions can be key functions, though. 8886 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 8887 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8888 const CXXRecordDecl *RD = MD->getParent(); 8889 if (MD->isOutOfLine() && RD->isDynamicClass()) { 8890 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 8891 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 8892 return true; 8893 } 8894 } 8895 } 8896 8897 // static, static inline, always_inline, and extern inline functions can 8898 // always be deferred. Normal inline functions can be deferred in C99/C++. 8899 // Implicit template instantiations can also be deferred in C++. 8900 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD)); 8901 } 8902 8903 const VarDecl *VD = cast<VarDecl>(D); 8904 assert(VD->isFileVarDecl() && "Expected file scoped var"); 8905 8906 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 8907 !isMSStaticDataMemberInlineDefinition(VD)) 8908 return false; 8909 8910 // Variables that can be needed in other TUs are required. 8911 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD))) 8912 return true; 8913 8914 // Variables that have destruction with side-effects are required. 8915 if (VD->getType().isDestructedType()) 8916 return true; 8917 8918 // Variables that have initialization with side-effects are required. 8919 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 8920 !VD->evaluateValue()) 8921 return true; 8922 8923 // Likewise, variables with tuple-like bindings are required if their 8924 // bindings have side-effects. 8925 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) 8926 for (auto *BD : DD->bindings()) 8927 if (auto *BindingVD = BD->getHoldingVar()) 8928 if (DeclMustBeEmitted(BindingVD)) 8929 return true; 8930 8931 return false; 8932 } 8933 8934 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 8935 bool IsCXXMethod) const { 8936 // Pass through to the C++ ABI object 8937 if (IsCXXMethod) 8938 return ABI->getDefaultMethodCallConv(IsVariadic); 8939 8940 switch (LangOpts.getDefaultCallingConv()) { 8941 case LangOptions::DCC_None: 8942 break; 8943 case LangOptions::DCC_CDecl: 8944 return CC_C; 8945 case LangOptions::DCC_FastCall: 8946 if (getTargetInfo().hasFeature("sse2")) 8947 return CC_X86FastCall; 8948 break; 8949 case LangOptions::DCC_StdCall: 8950 if (!IsVariadic) 8951 return CC_X86StdCall; 8952 break; 8953 case LangOptions::DCC_VectorCall: 8954 // __vectorcall cannot be applied to variadic functions. 8955 if (!IsVariadic) 8956 return CC_X86VectorCall; 8957 break; 8958 } 8959 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown); 8960 } 8961 8962 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 8963 // Pass through to the C++ ABI object 8964 return ABI->isNearlyEmpty(RD); 8965 } 8966 8967 VTableContextBase *ASTContext::getVTableContext() { 8968 if (!VTContext.get()) { 8969 if (Target->getCXXABI().isMicrosoft()) 8970 VTContext.reset(new MicrosoftVTableContext(*this)); 8971 else 8972 VTContext.reset(new ItaniumVTableContext(*this)); 8973 } 8974 return VTContext.get(); 8975 } 8976 8977 MangleContext *ASTContext::createMangleContext() { 8978 switch (Target->getCXXABI().getKind()) { 8979 case TargetCXXABI::GenericAArch64: 8980 case TargetCXXABI::GenericItanium: 8981 case TargetCXXABI::GenericARM: 8982 case TargetCXXABI::GenericMIPS: 8983 case TargetCXXABI::iOS: 8984 case TargetCXXABI::iOS64: 8985 case TargetCXXABI::WebAssembly: 8986 case TargetCXXABI::WatchOS: 8987 return ItaniumMangleContext::create(*this, getDiagnostics()); 8988 case TargetCXXABI::Microsoft: 8989 return MicrosoftMangleContext::create(*this, getDiagnostics()); 8990 } 8991 llvm_unreachable("Unsupported ABI"); 8992 } 8993 8994 CXXABI::~CXXABI() {} 8995 8996 size_t ASTContext::getSideTableAllocatedMemory() const { 8997 return ASTRecordLayouts.getMemorySize() + 8998 llvm::capacity_in_bytes(ObjCLayouts) + 8999 llvm::capacity_in_bytes(KeyFunctions) + 9000 llvm::capacity_in_bytes(ObjCImpls) + 9001 llvm::capacity_in_bytes(BlockVarCopyInits) + 9002 llvm::capacity_in_bytes(DeclAttrs) + 9003 llvm::capacity_in_bytes(TemplateOrInstantiation) + 9004 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 9005 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 9006 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 9007 llvm::capacity_in_bytes(OverriddenMethods) + 9008 llvm::capacity_in_bytes(Types) + 9009 llvm::capacity_in_bytes(VariableArrayTypes) + 9010 llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 9011 } 9012 9013 /// getIntTypeForBitwidth - 9014 /// sets integer QualTy according to specified details: 9015 /// bitwidth, signed/unsigned. 9016 /// Returns empty type if there is no appropriate target types. 9017 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 9018 unsigned Signed) const { 9019 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 9020 CanQualType QualTy = getFromTargetType(Ty); 9021 if (!QualTy && DestWidth == 128) 9022 return Signed ? Int128Ty : UnsignedInt128Ty; 9023 return QualTy; 9024 } 9025 9026 /// getRealTypeForBitwidth - 9027 /// sets floating point QualTy according to specified bitwidth. 9028 /// Returns empty type if there is no appropriate target types. 9029 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { 9030 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); 9031 switch (Ty) { 9032 case TargetInfo::Float: 9033 return FloatTy; 9034 case TargetInfo::Double: 9035 return DoubleTy; 9036 case TargetInfo::LongDouble: 9037 return LongDoubleTy; 9038 case TargetInfo::Float128: 9039 return Float128Ty; 9040 case TargetInfo::NoFloat: 9041 return QualType(); 9042 } 9043 9044 llvm_unreachable("Unhandled TargetInfo::RealType value"); 9045 } 9046 9047 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 9048 if (Number > 1) 9049 MangleNumbers[ND] = Number; 9050 } 9051 9052 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 9053 auto I = MangleNumbers.find(ND); 9054 return I != MangleNumbers.end() ? I->second : 1; 9055 } 9056 9057 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 9058 if (Number > 1) 9059 StaticLocalNumbers[VD] = Number; 9060 } 9061 9062 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 9063 auto I = StaticLocalNumbers.find(VD); 9064 return I != StaticLocalNumbers.end() ? I->second : 1; 9065 } 9066 9067 MangleNumberingContext & 9068 ASTContext::getManglingNumberContext(const DeclContext *DC) { 9069 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 9070 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 9071 if (!MCtx) 9072 MCtx = createMangleNumberingContext(); 9073 return *MCtx; 9074 } 9075 9076 std::unique_ptr<MangleNumberingContext> 9077 ASTContext::createMangleNumberingContext() const { 9078 return ABI->createMangleNumberingContext(); 9079 } 9080 9081 const CXXConstructorDecl * 9082 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 9083 return ABI->getCopyConstructorForExceptionObject( 9084 cast<CXXRecordDecl>(RD->getFirstDecl())); 9085 } 9086 9087 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 9088 CXXConstructorDecl *CD) { 9089 return ABI->addCopyConstructorForExceptionObject( 9090 cast<CXXRecordDecl>(RD->getFirstDecl()), 9091 cast<CXXConstructorDecl>(CD->getFirstDecl())); 9092 } 9093 9094 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD, 9095 unsigned ParmIdx, Expr *DAE) { 9096 ABI->addDefaultArgExprForConstructor( 9097 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE); 9098 } 9099 9100 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD, 9101 unsigned ParmIdx) { 9102 return ABI->getDefaultArgExprForConstructor( 9103 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx); 9104 } 9105 9106 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 9107 TypedefNameDecl *DD) { 9108 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 9109 } 9110 9111 TypedefNameDecl * 9112 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 9113 return ABI->getTypedefNameForUnnamedTagDecl(TD); 9114 } 9115 9116 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 9117 DeclaratorDecl *DD) { 9118 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 9119 } 9120 9121 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 9122 return ABI->getDeclaratorForUnnamedTagDecl(TD); 9123 } 9124 9125 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 9126 ParamIndices[D] = index; 9127 } 9128 9129 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 9130 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 9131 assert(I != ParamIndices.end() && 9132 "ParmIndices lacks entry set by ParmVarDecl"); 9133 return I->second; 9134 } 9135 9136 APValue * 9137 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, 9138 bool MayCreate) { 9139 assert(E && E->getStorageDuration() == SD_Static && 9140 "don't need to cache the computed value for this temporary"); 9141 if (MayCreate) { 9142 APValue *&MTVI = MaterializedTemporaryValues[E]; 9143 if (!MTVI) 9144 MTVI = new (*this) APValue; 9145 return MTVI; 9146 } 9147 9148 return MaterializedTemporaryValues.lookup(E); 9149 } 9150 9151 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 9152 const llvm::Triple &T = getTargetInfo().getTriple(); 9153 if (!T.isOSDarwin()) 9154 return false; 9155 9156 if (!(T.isiOS() && T.isOSVersionLT(7)) && 9157 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 9158 return false; 9159 9160 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 9161 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 9162 uint64_t Size = sizeChars.getQuantity(); 9163 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 9164 unsigned Align = alignChars.getQuantity(); 9165 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 9166 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 9167 } 9168 9169 namespace { 9170 9171 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap( 9172 ASTContext::ParentMapPointers::mapped_type U) { 9173 if (const auto *D = U.dyn_cast<const Decl *>()) 9174 return ast_type_traits::DynTypedNode::create(*D); 9175 if (const auto *S = U.dyn_cast<const Stmt *>()) 9176 return ast_type_traits::DynTypedNode::create(*S); 9177 return *U.get<ast_type_traits::DynTypedNode *>(); 9178 } 9179 9180 /// Template specializations to abstract away from pointers and TypeLocs. 9181 /// @{ 9182 template <typename T> 9183 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) { 9184 return ast_type_traits::DynTypedNode::create(*Node); 9185 } 9186 template <> 9187 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) { 9188 return ast_type_traits::DynTypedNode::create(Node); 9189 } 9190 template <> 9191 ast_type_traits::DynTypedNode 9192 createDynTypedNode(const NestedNameSpecifierLoc &Node) { 9193 return ast_type_traits::DynTypedNode::create(Node); 9194 } 9195 /// @} 9196 9197 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their 9198 /// parents as defined by the \c RecursiveASTVisitor. 9199 /// 9200 /// Note that the relationship described here is purely in terms of AST 9201 /// traversal - there are other relationships (for example declaration context) 9202 /// in the AST that are better modeled by special matchers. 9203 /// 9204 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. 9205 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> { 9206 public: 9207 /// \brief Builds and returns the translation unit's parent map. 9208 /// 9209 /// The caller takes ownership of the returned \c ParentMap. 9210 static std::pair<ASTContext::ParentMapPointers *, 9211 ASTContext::ParentMapOtherNodes *> 9212 buildMap(TranslationUnitDecl &TU) { 9213 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers, 9214 new ASTContext::ParentMapOtherNodes); 9215 Visitor.TraverseDecl(&TU); 9216 return std::make_pair(Visitor.Parents, Visitor.OtherParents); 9217 } 9218 9219 private: 9220 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase; 9221 9222 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents, 9223 ASTContext::ParentMapOtherNodes *OtherParents) 9224 : Parents(Parents), OtherParents(OtherParents) {} 9225 9226 bool shouldVisitTemplateInstantiations() const { 9227 return true; 9228 } 9229 bool shouldVisitImplicitCode() const { 9230 return true; 9231 } 9232 9233 template <typename T, typename MapNodeTy, typename BaseTraverseFn, 9234 typename MapTy> 9235 bool TraverseNode(T Node, MapNodeTy MapNode, 9236 BaseTraverseFn BaseTraverse, MapTy *Parents) { 9237 if (!Node) 9238 return true; 9239 if (ParentStack.size() > 0) { 9240 // FIXME: Currently we add the same parent multiple times, but only 9241 // when no memoization data is available for the type. 9242 // For example when we visit all subexpressions of template 9243 // instantiations; this is suboptimal, but benign: the only way to 9244 // visit those is with hasAncestor / hasParent, and those do not create 9245 // new matches. 9246 // The plan is to enable DynTypedNode to be storable in a map or hash 9247 // map. The main problem there is to implement hash functions / 9248 // comparison operators for all types that DynTypedNode supports that 9249 // do not have pointer identity. 9250 auto &NodeOrVector = (*Parents)[MapNode]; 9251 if (NodeOrVector.isNull()) { 9252 if (const auto *D = ParentStack.back().get<Decl>()) 9253 NodeOrVector = D; 9254 else if (const auto *S = ParentStack.back().get<Stmt>()) 9255 NodeOrVector = S; 9256 else 9257 NodeOrVector = 9258 new ast_type_traits::DynTypedNode(ParentStack.back()); 9259 } else { 9260 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) { 9261 auto *Vector = new ASTContext::ParentVector( 9262 1, getSingleDynTypedNodeFromParentMap(NodeOrVector)); 9263 if (auto *Node = 9264 NodeOrVector 9265 .template dyn_cast<ast_type_traits::DynTypedNode *>()) 9266 delete Node; 9267 NodeOrVector = Vector; 9268 } 9269 9270 auto *Vector = 9271 NodeOrVector.template get<ASTContext::ParentVector *>(); 9272 // Skip duplicates for types that have memoization data. 9273 // We must check that the type has memoization data before calling 9274 // std::find() because DynTypedNode::operator== can't compare all 9275 // types. 9276 bool Found = ParentStack.back().getMemoizationData() && 9277 std::find(Vector->begin(), Vector->end(), 9278 ParentStack.back()) != Vector->end(); 9279 if (!Found) 9280 Vector->push_back(ParentStack.back()); 9281 } 9282 } 9283 ParentStack.push_back(createDynTypedNode(Node)); 9284 bool Result = BaseTraverse(); 9285 ParentStack.pop_back(); 9286 return Result; 9287 } 9288 9289 bool TraverseDecl(Decl *DeclNode) { 9290 return TraverseNode(DeclNode, DeclNode, 9291 [&] { return VisitorBase::TraverseDecl(DeclNode); }, 9292 Parents); 9293 } 9294 9295 bool TraverseStmt(Stmt *StmtNode) { 9296 return TraverseNode(StmtNode, StmtNode, 9297 [&] { return VisitorBase::TraverseStmt(StmtNode); }, 9298 Parents); 9299 } 9300 9301 bool TraverseTypeLoc(TypeLoc TypeLocNode) { 9302 return TraverseNode( 9303 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode), 9304 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); }, 9305 OtherParents); 9306 } 9307 9308 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) { 9309 return TraverseNode( 9310 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode), 9311 [&] { 9312 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); 9313 }, 9314 OtherParents); 9315 } 9316 9317 ASTContext::ParentMapPointers *Parents; 9318 ASTContext::ParentMapOtherNodes *OtherParents; 9319 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; 9320 9321 friend class RecursiveASTVisitor<ParentMapASTVisitor>; 9322 }; 9323 9324 } // anonymous namespace 9325 9326 template <typename NodeTy, typename MapTy> 9327 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, 9328 const MapTy &Map) { 9329 auto I = Map.find(Node); 9330 if (I == Map.end()) { 9331 return llvm::ArrayRef<ast_type_traits::DynTypedNode>(); 9332 } 9333 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) { 9334 return llvm::makeArrayRef(*V); 9335 } 9336 return getSingleDynTypedNodeFromParentMap(I->second); 9337 } 9338 9339 ASTContext::DynTypedNodeList 9340 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { 9341 if (!PointerParents) { 9342 // We always need to run over the whole translation unit, as 9343 // hasAncestor can escape any subtree. 9344 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()); 9345 PointerParents.reset(Maps.first); 9346 OtherParents.reset(Maps.second); 9347 } 9348 if (Node.getNodeKind().hasPointerIdentity()) 9349 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents); 9350 return getDynNodeFromMap(Node, *OtherParents); 9351 } 9352 9353 bool 9354 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 9355 const ObjCMethodDecl *MethodImpl) { 9356 // No point trying to match an unavailable/deprecated mothod. 9357 if (MethodDecl->hasAttr<UnavailableAttr>() 9358 || MethodDecl->hasAttr<DeprecatedAttr>()) 9359 return false; 9360 if (MethodDecl->getObjCDeclQualifier() != 9361 MethodImpl->getObjCDeclQualifier()) 9362 return false; 9363 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 9364 return false; 9365 9366 if (MethodDecl->param_size() != MethodImpl->param_size()) 9367 return false; 9368 9369 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 9370 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 9371 EF = MethodDecl->param_end(); 9372 IM != EM && IF != EF; ++IM, ++IF) { 9373 const ParmVarDecl *DeclVar = (*IF); 9374 const ParmVarDecl *ImplVar = (*IM); 9375 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 9376 return false; 9377 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 9378 return false; 9379 } 9380 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 9381 9382 } 9383 9384 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 9385 // doesn't include ASTContext.h 9386 template 9387 clang::LazyGenerationalUpdatePtr< 9388 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 9389 clang::LazyGenerationalUpdatePtr< 9390 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 9391 const clang::ASTContext &Ctx, Decl *Value); 9392