1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.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"
44 using namespace clang;
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;
60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
73 CommentsLoaded = true;
78 // User can not attach documentation to implicit declarations.
82 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
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())
117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
121 // TODO: we could look up template parameter documentation in the template
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
128 ArrayRef<RawComment *> RawComments = Comments.getComments();
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
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
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();
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);
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())
172 // Find the comment that occurs just after this declaration.
173 ArrayRef<RawComment *>::iterator Comment;
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
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) {
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
200 // Decompose the location for the declaration and find the beginning of the
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
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)) {
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())
227 // Check that we actually have a non-member Doxygen comment.
228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
235 // If the comment and the declaration aren't in the same file, then they
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
253 if (Text.find_first_of(";{}#@") != StringRef::npos)
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())
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
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())
298 // Class is an implicit instantiation of a class template or partial
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
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 *>());
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
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())
327 // FIXME: Adjust alias templates?
330 } // anonymous namespace
332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl **OriginalDecl) const {
335 D = adjustDeclToTemplate(D);
337 // Check whether we have cached a comment for this declaration already.
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) {
345 *OriginalDecl = Raw.getOriginalDecl();
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) {
361 OriginalDeclForRC = Raw.getOriginalDecl();
365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
367 RawCommentAndCacheFlags Raw;
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);
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
386 *OriginalDecl = OriginalDeclForRC;
388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
392 Raw.setOriginalDecl(OriginalDeclForRC);
394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
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();
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);
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(),
435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
440 comments::FullComment *ASTContext::getCommentForDecl(
442 const Preprocessor *PP) const {
443 if (D->isInvalidDecl())
445 D = adjustDeclToTemplate(D);
447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
451 if (Pos != ParsedComments.end()) {
452 if (Canonical != D) {
453 comments::FullComment *FC = Pos->second;
454 comments::FullComment *CFC = cloneFullComment(FC, D);
460 const Decl *OriginalDecl;
462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
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);
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);
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);
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);
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);
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
502 // Check non-virtual bases.
503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
506 QualType Ty = I.getType();
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
517 // Check virtual bases.
518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
521 QualType Ty = I.getType();
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
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);
542 comments::FullComment *FC = RC->parse(*this, PP, D);
543 ParsedComments[Canonical] = FC;
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());
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddBoolean(TTP->isParameterPack());
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddBoolean(NTTP->isParameterPack());
568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
569 if (NTTP->isExpandedParameterPack()) {
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());
577 ID.AddBoolean(false);
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
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);
597 return Canonical->getParam();
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();
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
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()));
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
632 NTTP->getPosition(), nullptr,
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 NTTP->getPosition(), nullptr,
644 NTTP->isParameterPack(),
647 CanonParams.push_back(Param);
650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
656 Expr *const CanonRequiresClause = nullptr;
658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
662 TTP->isParameterPack(),
664 TemplateParameterList::Create(*this, SourceLocation(),
668 CanonRequiresClause));
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!");
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
681 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
682 if (!LangOpts.CPlusPlus) return nullptr;
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);
697 llvm_unreachable("Invalid CXXABI type!");
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[] = {
708 2, // opencl_constant
714 return &FakeAddrSpaceMap;
716 return &T.getAddressSpaceMap();
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:
727 case LangOptions::ASMM_Off:
730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
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);
759 ASTContext::~ASTContext() {
760 ReleaseParentMapEntries();
762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
766 // Call all of the deallocation functions on all of their targets.
767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
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))
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))
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
789 A->second->~AttrVec();
791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
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 *>();
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 *>();
817 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
818 Deallocations.push_back({Callback, Data});
822 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
823 ExternalSource = std::move(Source);
826 void ASTContext::PrintStats() const {
827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
830 unsigned counts[] = {
831 #define TYPE(Name, Parent) 0,
832 #define ABSTRACT_TYPE(Name, Parent)
833 #include "clang/AST/TypeNodes.def"
837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
839 counts[(unsigned)T->getTypeClass()]++;
843 unsigned TotalBytes = 0;
844 #define TYPE(Name, Parent) \
846 llvm::errs() << " " << counts[Idx] << " " << #Name \
848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
850 #define ABSTRACT_TYPE(Name, Parent)
851 #include "clang/AST/TypeNodes.def"
853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
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";
877 if (ExternalSource) {
878 llvm::errs() << "\n";
879 ExternalSource->PrintStats();
882 BumpAlloc.PrintStats();
885 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
894 ND->setHidden(false);
897 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
902 auto &Merged = It->second;
903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
910 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
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());
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
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))
947 auto *&Inits = ModuleInitializers[M];
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
953 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
961 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
971 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
975 return ExternCContext;
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);
985 return BuiltinTemplate;
988 BuiltinTemplateDecl *
989 ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
996 BuiltinTemplateDecl *
997 ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1004 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
1007 RecordDecl *NewDecl;
1008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
1012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1014 NewDecl->setImplicit();
1015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
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();
1030 TypedefDecl *ASTContext::getInt128Decl() const {
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1036 TypedefDecl *ASTContext::getUInt128Decl() const {
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
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);
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?");
1054 this->Target = &Target;
1055 this->AuxTarget = AuxTarget;
1057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1062 InitBuiltinType(VoidTy, BuiltinType::Void);
1065 InitBuiltinType(BoolTy, BuiltinType::Bool);
1067 if (LangOpts.CharIsSigned)
1068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
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);
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);
1086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
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;
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1109 WIntTy = getFromTargetType(Target.getWIntType());
1111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
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
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1154 Float128ComplexTy = getComplexType(Float128Ty);
1156 // Builtin types for 'id', 'Class', and 'SEL'.
1157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1161 if (LangOpts.OpenCL) {
1162 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
1164 #include "clang/Basic/OpenCLImageTypes.def"
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);
1174 // Builtin type for __objc_yes and __objc_no
1175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
1178 ObjCConstantStringType = QualType();
1180 ObjCSuperType = QualType();
1183 VoidPtrTy = getPointerType(VoidTy);
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
1191 // Builtin type used to help define __builtin_va_list.
1192 VaListTagDecl = nullptr;
1195 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1196 return SourceMgr.getDiagnostics();
1199 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
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);
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 *>();
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();
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));
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;
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())
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;
1273 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1274 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1275 if (Pos == InstantiatedFromUsingDecl.end())
1282 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1283 assert((isa<UsingDecl>(Pattern) ||
1284 isa<UnresolvedUsingValueDecl>(Pattern) ||
1285 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1286 "pattern decl is not a using decl");
1287 assert((isa<UsingDecl>(Inst) ||
1288 isa<UnresolvedUsingValueDecl>(Inst) ||
1289 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1290 "instantiation did not produce a using decl");
1291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1292 InstantiatedFromUsingDecl[Inst] = Pattern;
1296 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1298 = InstantiatedFromUsingShadowDecl.find(Inst);
1299 if (Pos == InstantiatedFromUsingShadowDecl.end())
1306 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1307 UsingShadowDecl *Pattern) {
1308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1312 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1314 = InstantiatedFromUnnamedFieldDecl.find(Field);
1315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1321 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1326 "Already noted what unnamed field was instantiated from");
1328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1331 ASTContext::overridden_cxx_method_iterator
1332 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
1335 if (Pos == OverriddenMethods.end())
1337 return Pos->second.begin();
1340 ASTContext::overridden_cxx_method_iterator
1341 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
1344 if (Pos == OverriddenMethods.end())
1346 return Pos->second.end();
1350 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
1353 if (Pos == OverriddenMethods.end())
1355 return Pos->second.size();
1358 ASTContext::overridden_method_range
1359 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1360 return overridden_method_range(overridden_methods_begin(Method),
1361 overridden_methods_end(Method));
1364 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1365 const CXXMethodDecl *Overridden) {
1366 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1367 OverriddenMethods[Method].push_back(Overridden);
1370 void ASTContext::getOverriddenMethods(
1372 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1375 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1376 Overridden.append(overridden_methods_begin(CXXMethod),
1377 overridden_methods_end(CXXMethod));
1381 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1385 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1386 Method->getOverriddenMethods(OverDecls);
1387 Overridden.append(OverDecls.begin(), OverDecls.end());
1390 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1391 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1392 assert(!Import->isFromASTFile() && "Non-local import declaration");
1393 if (!FirstLocalImport) {
1394 FirstLocalImport = Import;
1395 LastLocalImport = Import;
1399 LastLocalImport->NextLocalImport = Import;
1400 LastLocalImport = Import;
1403 //===----------------------------------------------------------------------===//
1404 // Type Sizing and Analysis
1405 //===----------------------------------------------------------------------===//
1407 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1408 /// scalar floating point type.
1409 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1410 const BuiltinType *BT = T->getAs<BuiltinType>();
1411 assert(BT && "Not a floating point type!");
1412 switch (BT->getKind()) {
1413 default: llvm_unreachable("Not a floating point type!");
1414 case BuiltinType::Half: return Target->getHalfFormat();
1415 case BuiltinType::Float: return Target->getFloatFormat();
1416 case BuiltinType::Double: return Target->getDoubleFormat();
1417 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1418 case BuiltinType::Float128: return Target->getFloat128Format();
1422 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1423 unsigned Align = Target->getCharWidth();
1425 bool UseAlignAttrOnly = false;
1426 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1427 Align = AlignFromAttr;
1429 // __attribute__((aligned)) can increase or decrease alignment
1430 // *except* on a struct or struct member, where it only increases
1431 // alignment unless 'packed' is also specified.
1433 // It is an error for alignas to decrease alignment, so we can
1434 // ignore that possibility; Sema should diagnose it.
1435 if (isa<FieldDecl>(D)) {
1436 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1437 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1439 UseAlignAttrOnly = true;
1442 else if (isa<FieldDecl>(D))
1444 D->hasAttr<PackedAttr>() ||
1445 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1447 // If we're using the align attribute only, just ignore everything
1448 // else about the declaration and its type.
1449 if (UseAlignAttrOnly) {
1452 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1453 QualType T = VD->getType();
1454 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1456 T = RT->getPointeeType();
1458 T = getPointerType(RT->getPointeeType());
1460 QualType BaseT = getBaseElementType(T);
1461 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1462 // Adjust alignments of declarations with array type by the
1463 // large-array alignment on the target.
1464 if (const ArrayType *arrayType = getAsArrayType(T)) {
1465 unsigned MinWidth = Target->getLargeArrayMinWidth();
1466 if (!ForAlignof && MinWidth) {
1467 if (isa<VariableArrayType>(arrayType))
1468 Align = std::max(Align, Target->getLargeArrayAlign());
1469 else if (isa<ConstantArrayType>(arrayType) &&
1470 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1471 Align = std::max(Align, Target->getLargeArrayAlign());
1474 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1475 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1476 if (VD->hasGlobalStorage() && !ForAlignof)
1477 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1481 // Fields can be subject to extra alignment constraints, like if
1482 // the field is packed, the struct is packed, or the struct has a
1483 // a max-field-alignment constraint (#pragma pack). So calculate
1484 // the actual alignment of the field within the struct, and then
1485 // (as we're expected to) constrain that by the alignment of the type.
1486 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1487 const RecordDecl *Parent = Field->getParent();
1488 // We can only produce a sensible answer if the record is valid.
1489 if (!Parent->isInvalidDecl()) {
1490 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1492 // Start with the record's overall alignment.
1493 unsigned FieldAlign = toBits(Layout.getAlignment());
1495 // Use the GCD of that and the offset within the record.
1496 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1498 // Alignment is always a power of 2, so the GCD will be a power of 2,
1499 // which means we get to do this crazy thing instead of Euclid's.
1500 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1501 if (LowBitOfOffset < FieldAlign)
1502 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1505 Align = std::min(Align, FieldAlign);
1510 return toCharUnitsFromBits(Align);
1513 // getTypeInfoDataSizeInChars - Return the size of a type, in
1514 // chars. If the type is a record, its data size is returned. This is
1515 // the size of the memcpy that's performed when assigning this type
1516 // using a trivial copy/move assignment operator.
1517 std::pair<CharUnits, CharUnits>
1518 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1519 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1521 // In C++, objects can sometimes be allocated into the tail padding
1522 // of a base-class subobject. We decide whether that's possible
1523 // during class layout, so here we can just trust the layout results.
1524 if (getLangOpts().CPlusPlus) {
1525 if (const RecordType *RT = T->getAs<RecordType>()) {
1526 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1527 sizeAndAlign.first = layout.getDataSize();
1531 return sizeAndAlign;
1534 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1535 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1536 std::pair<CharUnits, CharUnits>
1537 static getConstantArrayInfoInChars(const ASTContext &Context,
1538 const ConstantArrayType *CAT) {
1539 std::pair<CharUnits, CharUnits> EltInfo =
1540 Context.getTypeInfoInChars(CAT->getElementType());
1541 uint64_t Size = CAT->getSize().getZExtValue();
1542 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1543 (uint64_t)(-1)/Size) &&
1544 "Overflow in array type char size evaluation");
1545 uint64_t Width = EltInfo.first.getQuantity() * Size;
1546 unsigned Align = EltInfo.second.getQuantity();
1547 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1548 Context.getTargetInfo().getPointerWidth(0) == 64)
1549 Width = llvm::alignTo(Width, Align);
1550 return std::make_pair(CharUnits::fromQuantity(Width),
1551 CharUnits::fromQuantity(Align));
1554 std::pair<CharUnits, CharUnits>
1555 ASTContext::getTypeInfoInChars(const Type *T) const {
1556 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1557 return getConstantArrayInfoInChars(*this, CAT);
1558 TypeInfo Info = getTypeInfo(T);
1559 return std::make_pair(toCharUnitsFromBits(Info.Width),
1560 toCharUnitsFromBits(Info.Align));
1563 std::pair<CharUnits, CharUnits>
1564 ASTContext::getTypeInfoInChars(QualType T) const {
1565 return getTypeInfoInChars(T.getTypePtr());
1568 bool ASTContext::isAlignmentRequired(const Type *T) const {
1569 return getTypeInfo(T).AlignIsRequired;
1572 bool ASTContext::isAlignmentRequired(QualType T) const {
1573 return isAlignmentRequired(T.getTypePtr());
1576 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1577 // An alignment on a typedef overrides anything else.
1578 if (auto *TT = T->getAs<TypedefType>())
1579 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1582 // If we have an (array of) complete type, we're done.
1583 T = getBaseElementType(T);
1584 if (!T->isIncompleteType())
1585 return getTypeAlign(T);
1587 // If we had an array type, its element type might be a typedef
1588 // type with an alignment attribute.
1589 if (auto *TT = T->getAs<TypedefType>())
1590 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1593 // Otherwise, see if the declaration of the type had an attribute.
1594 if (auto *TT = T->getAs<TagType>())
1595 return TT->getDecl()->getMaxAlignment();
1600 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1601 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1602 if (I != MemoizedTypeInfo.end())
1605 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1606 TypeInfo TI = getTypeInfoImpl(T);
1607 MemoizedTypeInfo[T] = TI;
1611 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1612 /// method does not work on incomplete types.
1614 /// FIXME: Pointers into different addr spaces could have different sizes and
1615 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1616 /// should take a QualType, &c.
1617 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1620 bool AlignIsRequired = false;
1621 switch (T->getTypeClass()) {
1622 #define TYPE(Class, Base)
1623 #define ABSTRACT_TYPE(Class, Base)
1624 #define NON_CANONICAL_TYPE(Class, Base)
1625 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1626 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1628 assert(!T->isDependentType() && "should not see dependent types here"); \
1629 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1630 #include "clang/AST/TypeNodes.def"
1631 llvm_unreachable("Should not see dependent types");
1633 case Type::FunctionNoProto:
1634 case Type::FunctionProto:
1635 // GCC extension: alignof(function) = 32 bits
1640 case Type::IncompleteArray:
1641 case Type::VariableArray:
1643 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1646 case Type::ConstantArray: {
1647 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1649 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1650 uint64_t Size = CAT->getSize().getZExtValue();
1651 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1652 "Overflow in array type bit size evaluation");
1653 Width = EltInfo.Width * Size;
1654 Align = EltInfo.Align;
1655 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1656 getTargetInfo().getPointerWidth(0) == 64)
1657 Width = llvm::alignTo(Width, Align);
1660 case Type::ExtVector:
1661 case Type::Vector: {
1662 const VectorType *VT = cast<VectorType>(T);
1663 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1664 Width = EltInfo.Width * VT->getNumElements();
1666 // If the alignment is not a power of 2, round up to the next power of 2.
1667 // This happens for non-power-of-2 length vectors.
1668 if (Align & (Align-1)) {
1669 Align = llvm::NextPowerOf2(Align);
1670 Width = llvm::alignTo(Width, Align);
1672 // Adjust the alignment based on the target max.
1673 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1674 if (TargetVectorAlign && TargetVectorAlign < Align)
1675 Align = TargetVectorAlign;
1680 switch (cast<BuiltinType>(T)->getKind()) {
1681 default: llvm_unreachable("Unknown builtin type!");
1682 case BuiltinType::Void:
1683 // GCC extension: alignof(void) = 8 bits.
1688 case BuiltinType::Bool:
1689 Width = Target->getBoolWidth();
1690 Align = Target->getBoolAlign();
1692 case BuiltinType::Char_S:
1693 case BuiltinType::Char_U:
1694 case BuiltinType::UChar:
1695 case BuiltinType::SChar:
1696 Width = Target->getCharWidth();
1697 Align = Target->getCharAlign();
1699 case BuiltinType::WChar_S:
1700 case BuiltinType::WChar_U:
1701 Width = Target->getWCharWidth();
1702 Align = Target->getWCharAlign();
1704 case BuiltinType::Char16:
1705 Width = Target->getChar16Width();
1706 Align = Target->getChar16Align();
1708 case BuiltinType::Char32:
1709 Width = Target->getChar32Width();
1710 Align = Target->getChar32Align();
1712 case BuiltinType::UShort:
1713 case BuiltinType::Short:
1714 Width = Target->getShortWidth();
1715 Align = Target->getShortAlign();
1717 case BuiltinType::UInt:
1718 case BuiltinType::Int:
1719 Width = Target->getIntWidth();
1720 Align = Target->getIntAlign();
1722 case BuiltinType::ULong:
1723 case BuiltinType::Long:
1724 Width = Target->getLongWidth();
1725 Align = Target->getLongAlign();
1727 case BuiltinType::ULongLong:
1728 case BuiltinType::LongLong:
1729 Width = Target->getLongLongWidth();
1730 Align = Target->getLongLongAlign();
1732 case BuiltinType::Int128:
1733 case BuiltinType::UInt128:
1735 Align = 128; // int128_t is 128-bit aligned on all targets.
1737 case BuiltinType::Half:
1738 Width = Target->getHalfWidth();
1739 Align = Target->getHalfAlign();
1741 case BuiltinType::Float:
1742 Width = Target->getFloatWidth();
1743 Align = Target->getFloatAlign();
1745 case BuiltinType::Double:
1746 Width = Target->getDoubleWidth();
1747 Align = Target->getDoubleAlign();
1749 case BuiltinType::LongDouble:
1750 Width = Target->getLongDoubleWidth();
1751 Align = Target->getLongDoubleAlign();
1753 case BuiltinType::Float128:
1754 Width = Target->getFloat128Width();
1755 Align = Target->getFloat128Align();
1757 case BuiltinType::NullPtr:
1758 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1759 Align = Target->getPointerAlign(0); // == sizeof(void*)
1761 case BuiltinType::ObjCId:
1762 case BuiltinType::ObjCClass:
1763 case BuiltinType::ObjCSel:
1764 Width = Target->getPointerWidth(0);
1765 Align = Target->getPointerAlign(0);
1767 case BuiltinType::OCLSampler: {
1768 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1769 Width = Target->getPointerWidth(AS);
1770 Align = Target->getPointerAlign(AS);
1773 case BuiltinType::OCLEvent:
1774 case BuiltinType::OCLClkEvent:
1775 case BuiltinType::OCLQueue:
1776 case BuiltinType::OCLNDRange:
1777 case BuiltinType::OCLReserveID:
1778 // Currently these types are pointers to opaque types.
1779 Width = Target->getPointerWidth(0);
1780 Align = Target->getPointerAlign(0);
1782 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1783 case BuiltinType::Id:
1784 #include "clang/Basic/OpenCLImageTypes.def"
1786 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1787 Width = Target->getPointerWidth(AS);
1788 Align = Target->getPointerAlign(AS);
1792 case Type::ObjCObjectPointer:
1793 Width = Target->getPointerWidth(0);
1794 Align = Target->getPointerAlign(0);
1796 case Type::BlockPointer: {
1797 unsigned AS = getTargetAddressSpace(
1798 cast<BlockPointerType>(T)->getPointeeType());
1799 Width = Target->getPointerWidth(AS);
1800 Align = Target->getPointerAlign(AS);
1803 case Type::LValueReference:
1804 case Type::RValueReference: {
1805 // alignof and sizeof should never enter this code path here, so we go
1806 // the pointer route.
1807 unsigned AS = getTargetAddressSpace(
1808 cast<ReferenceType>(T)->getPointeeType());
1809 Width = Target->getPointerWidth(AS);
1810 Align = Target->getPointerAlign(AS);
1813 case Type::Pointer: {
1814 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1815 Width = Target->getPointerWidth(AS);
1816 Align = Target->getPointerAlign(AS);
1819 case Type::MemberPointer: {
1820 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1821 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1824 case Type::Complex: {
1825 // Complex types have the same alignment as their elements, but twice the
1827 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1828 Width = EltInfo.Width * 2;
1829 Align = EltInfo.Align;
1832 case Type::ObjCObject:
1833 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1834 case Type::Adjusted:
1836 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1837 case Type::ObjCInterface: {
1838 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1839 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1840 Width = toBits(Layout.getSize());
1841 Align = toBits(Layout.getAlignment());
1846 const TagType *TT = cast<TagType>(T);
1848 if (TT->getDecl()->isInvalidDecl()) {
1854 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1855 const EnumDecl *ED = ET->getDecl();
1857 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1858 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1859 Info.Align = AttrAlign;
1860 Info.AlignIsRequired = true;
1865 const RecordType *RT = cast<RecordType>(TT);
1866 const RecordDecl *RD = RT->getDecl();
1867 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1868 Width = toBits(Layout.getSize());
1869 Align = toBits(Layout.getAlignment());
1870 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1874 case Type::SubstTemplateTypeParm:
1875 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1876 getReplacementType().getTypePtr());
1879 const AutoType *A = cast<AutoType>(T);
1880 assert(!A->getDeducedType().isNull() &&
1881 "cannot request the size of an undeduced or dependent auto type");
1882 return getTypeInfo(A->getDeducedType().getTypePtr());
1886 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1888 case Type::ObjCTypeParam:
1889 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1891 case Type::Typedef: {
1892 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1893 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1894 // If the typedef has an aligned attribute on it, it overrides any computed
1895 // alignment we have. This violates the GCC documentation (which says that
1896 // attribute(aligned) can only round up) but matches its implementation.
1897 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1899 AlignIsRequired = true;
1902 AlignIsRequired = Info.AlignIsRequired;
1908 case Type::Elaborated:
1909 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1911 case Type::Attributed:
1913 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1915 case Type::Atomic: {
1916 // Start with the base type information.
1917 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1921 // If the size of the type doesn't exceed the platform's max
1922 // atomic promotion width, make the size and alignment more
1923 // favorable to atomic operations:
1924 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1925 // Round the size up to a power of 2.
1926 if (!llvm::isPowerOf2_64(Width))
1927 Width = llvm::NextPowerOf2(Width);
1929 // Set the alignment equal to the size.
1930 Align = static_cast<unsigned>(Width);
1936 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1943 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1944 return TypeInfo(Width, Align, AlignIsRequired);
1947 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1948 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1949 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1950 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1951 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1952 getTargetInfo().getABI() == "elfv1-qpx" &&
1953 T->isSpecificBuiltinType(BuiltinType::Double))
1958 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1959 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1960 return CharUnits::fromQuantity(BitSize / getCharWidth());
1963 /// toBits - Convert a size in characters to a size in characters.
1964 int64_t ASTContext::toBits(CharUnits CharSize) const {
1965 return CharSize.getQuantity() * getCharWidth();
1968 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1969 /// This method does not work on incomplete types.
1970 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1971 return getTypeInfoInChars(T).first;
1973 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1974 return getTypeInfoInChars(T).first;
1977 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1978 /// characters. This method does not work on incomplete types.
1979 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1980 return toCharUnitsFromBits(getTypeAlign(T));
1982 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1983 return toCharUnitsFromBits(getTypeAlign(T));
1986 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1987 /// type for the current target in bits. This can be different than the ABI
1988 /// alignment in cases where it is beneficial for performance to overalign
1990 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1991 TypeInfo TI = getTypeInfo(T);
1992 unsigned ABIAlign = TI.Align;
1994 T = T->getBaseElementTypeUnsafe();
1996 // The preferred alignment of member pointers is that of a pointer.
1997 if (T->isMemberPointerType())
1998 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2000 if (!Target->allowsLargerPreferedTypeAlignment())
2003 // Double and long long should be naturally aligned if possible.
2004 if (const ComplexType *CT = T->getAs<ComplexType>())
2005 T = CT->getElementType().getTypePtr();
2006 if (const EnumType *ET = T->getAs<EnumType>())
2007 T = ET->getDecl()->getIntegerType().getTypePtr();
2008 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2009 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2010 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2011 // Don't increase the alignment if an alignment attribute was specified on a
2012 // typedef declaration.
2013 if (!TI.AlignIsRequired)
2014 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2019 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2020 /// for __attribute__((aligned)) on this target, to be used if no alignment
2021 /// value is specified.
2022 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2023 return getTargetInfo().getDefaultAlignForAttributeAligned();
2026 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2027 /// to a global variable of the specified type.
2028 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2029 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2032 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2033 /// should be given to a global variable of the specified type.
2034 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2035 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2038 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2039 CharUnits Offset = CharUnits::Zero();
2040 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2041 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2042 Offset += Layout->getBaseClassOffset(Base);
2043 Layout = &getASTRecordLayout(Base);
2048 /// DeepCollectObjCIvars -
2049 /// This routine first collects all declared, but not synthesized, ivars in
2050 /// super class and then collects all ivars, including those synthesized for
2051 /// current class. This routine is used for implementation of current class
2052 /// when all ivars, declared and synthesized are known.
2054 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2056 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2057 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2058 DeepCollectObjCIvars(SuperClass, false, Ivars);
2060 for (const auto *I : OI->ivars())
2063 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2064 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2065 Iv= Iv->getNextIvar())
2066 Ivars.push_back(Iv);
2070 /// CollectInheritedProtocols - Collect all protocols in current class and
2071 /// those inherited by it.
2072 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2074 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2075 // We can use protocol_iterator here instead of
2076 // all_referenced_protocol_iterator since we are walking all categories.
2077 for (auto *Proto : OI->all_referenced_protocols()) {
2078 CollectInheritedProtocols(Proto, Protocols);
2081 // Categories of this Interface.
2082 for (const auto *Cat : OI->visible_categories())
2083 CollectInheritedProtocols(Cat, Protocols);
2085 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2087 CollectInheritedProtocols(SD, Protocols);
2088 SD = SD->getSuperClass();
2090 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2091 for (auto *Proto : OC->protocols()) {
2092 CollectInheritedProtocols(Proto, Protocols);
2094 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2095 // Insert the protocol.
2096 if (!Protocols.insert(
2097 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2100 for (auto *Proto : OP->protocols())
2101 CollectInheritedProtocols(Proto, Protocols);
2105 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2107 // Count ivars declared in class extension.
2108 for (const auto *Ext : OI->known_extensions())
2109 count += Ext->ivar_size();
2111 // Count ivar defined in this class's implementation. This
2112 // includes synthesized ivars.
2113 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2114 count += ImplDecl->ivar_size();
2119 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2123 // nullptr_t is always treated as null.
2124 if (E->getType()->isNullPtrType()) return true;
2126 if (E->getType()->isAnyPointerType() &&
2127 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2128 Expr::NPC_ValueDependentIsNull))
2131 // Unfortunately, __null has type 'int'.
2132 if (isa<GNUNullExpr>(E)) return true;
2137 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2138 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2139 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2140 I = ObjCImpls.find(D);
2141 if (I != ObjCImpls.end())
2142 return cast<ObjCImplementationDecl>(I->second);
2145 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2146 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2147 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2148 I = ObjCImpls.find(D);
2149 if (I != ObjCImpls.end())
2150 return cast<ObjCCategoryImplDecl>(I->second);
2154 /// \brief Set the implementation of ObjCInterfaceDecl.
2155 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2156 ObjCImplementationDecl *ImplD) {
2157 assert(IFaceD && ImplD && "Passed null params");
2158 ObjCImpls[IFaceD] = ImplD;
2160 /// \brief Set the implementation of ObjCCategoryDecl.
2161 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2162 ObjCCategoryImplDecl *ImplD) {
2163 assert(CatD && ImplD && "Passed null params");
2164 ObjCImpls[CatD] = ImplD;
2167 const ObjCMethodDecl *
2168 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2169 return ObjCMethodRedecls.lookup(MD);
2172 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2173 const ObjCMethodDecl *Redecl) {
2174 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2175 ObjCMethodRedecls[MD] = Redecl;
2178 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2179 const NamedDecl *ND) const {
2180 if (const ObjCInterfaceDecl *ID =
2181 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2183 if (const ObjCCategoryDecl *CD =
2184 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2185 return CD->getClassInterface();
2186 if (const ObjCImplDecl *IMD =
2187 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2188 return IMD->getClassInterface();
2193 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2195 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2196 assert(VD && "Passed null params");
2197 assert(VD->hasAttr<BlocksAttr>() &&
2198 "getBlockVarCopyInits - not __block var");
2199 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2200 I = BlockVarCopyInits.find(VD);
2201 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2204 /// \brief Set the copy inialization expression of a block var decl.
2205 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2206 assert(VD && Init && "Passed null params");
2207 assert(VD->hasAttr<BlocksAttr>() &&
2208 "setBlockVarCopyInits - not __block var");
2209 BlockVarCopyInits[VD] = Init;
2212 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2213 unsigned DataSize) const {
2215 DataSize = TypeLoc::getFullDataSizeForType(T);
2217 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2218 "incorrect data size provided to CreateTypeSourceInfo!");
2220 TypeSourceInfo *TInfo =
2221 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2222 new (TInfo) TypeSourceInfo(T);
2226 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2227 SourceLocation L) const {
2228 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2229 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2233 const ASTRecordLayout &
2234 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2235 return getObjCLayout(D, nullptr);
2238 const ASTRecordLayout &
2239 ASTContext::getASTObjCImplementationLayout(
2240 const ObjCImplementationDecl *D) const {
2241 return getObjCLayout(D->getClassInterface(), D);
2244 //===----------------------------------------------------------------------===//
2245 // Type creation/memoization methods
2246 //===----------------------------------------------------------------------===//
2249 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2250 unsigned fastQuals = quals.getFastQualifiers();
2251 quals.removeFastQualifiers();
2253 // Check if we've already instantiated this type.
2254 llvm::FoldingSetNodeID ID;
2255 ExtQuals::Profile(ID, baseType, quals);
2256 void *insertPos = nullptr;
2257 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2258 assert(eq->getQualifiers() == quals);
2259 return QualType(eq, fastQuals);
2262 // If the base type is not canonical, make the appropriate canonical type.
2264 if (!baseType->isCanonicalUnqualified()) {
2265 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2266 canonSplit.Quals.addConsistentQualifiers(quals);
2267 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2269 // Re-find the insert position.
2270 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2273 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2274 ExtQualNodes.InsertNode(eq, insertPos);
2275 return QualType(eq, fastQuals);
2279 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2280 QualType CanT = getCanonicalType(T);
2281 if (CanT.getAddressSpace() == AddressSpace)
2284 // If we are composing extended qualifiers together, merge together
2285 // into one ExtQuals node.
2286 QualifierCollector Quals;
2287 const Type *TypeNode = Quals.strip(T);
2289 // If this type already has an address space specified, it cannot get
2291 assert(!Quals.hasAddressSpace() &&
2292 "Type cannot be in multiple addr spaces!");
2293 Quals.addAddressSpace(AddressSpace);
2295 return getExtQualType(TypeNode, Quals);
2298 QualType ASTContext::getObjCGCQualType(QualType T,
2299 Qualifiers::GC GCAttr) const {
2300 QualType CanT = getCanonicalType(T);
2301 if (CanT.getObjCGCAttr() == GCAttr)
2304 if (const PointerType *ptr = T->getAs<PointerType>()) {
2305 QualType Pointee = ptr->getPointeeType();
2306 if (Pointee->isAnyPointerType()) {
2307 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2308 return getPointerType(ResultType);
2312 // If we are composing extended qualifiers together, merge together
2313 // into one ExtQuals node.
2314 QualifierCollector Quals;
2315 const Type *TypeNode = Quals.strip(T);
2317 // If this type already has an ObjCGC specified, it cannot get
2319 assert(!Quals.hasObjCGCAttr() &&
2320 "Type cannot have multiple ObjCGCs!");
2321 Quals.addObjCGCAttr(GCAttr);
2323 return getExtQualType(TypeNode, Quals);
2326 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2327 FunctionType::ExtInfo Info) {
2328 if (T->getExtInfo() == Info)
2332 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2333 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2335 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2336 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2338 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2341 return cast<FunctionType>(Result.getTypePtr());
2344 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2345 QualType ResultType) {
2346 FD = FD->getMostRecentDecl();
2348 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2349 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2350 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2351 if (FunctionDecl *Next = FD->getPreviousDecl())
2356 if (ASTMutationListener *L = getASTMutationListener())
2357 L->DeducedReturnType(FD, ResultType);
2360 /// Get a function type and produce the equivalent function type with the
2361 /// specified exception specification. Type sugar that can be present on a
2362 /// declaration of a function with an exception specification is permitted
2363 /// and preserved. Other type sugar (for instance, typedefs) is not.
2364 static QualType getFunctionTypeWithExceptionSpec(
2365 ASTContext &Context, QualType Orig,
2366 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2367 // Might have some parens.
2368 if (auto *PT = dyn_cast<ParenType>(Orig))
2369 return Context.getParenType(
2370 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2372 // Might have a calling-convention attribute.
2373 if (auto *AT = dyn_cast<AttributedType>(Orig))
2374 return Context.getAttributedType(
2376 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2377 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2380 // Anything else must be a function type. Rebuild it with the new exception
2382 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2383 return Context.getFunctionType(
2384 Proto->getReturnType(), Proto->getParamTypes(),
2385 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2388 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2390 return hasSameType(T, U) ||
2391 (getLangOpts().CPlusPlus1z &&
2392 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2393 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2396 void ASTContext::adjustExceptionSpec(
2397 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2401 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2402 FD->setType(Updated);
2407 // Update the type in the type source information too.
2408 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2409 // If the type and the type-as-written differ, we may need to update
2410 // the type-as-written too.
2411 if (TSInfo->getType() != FD->getType())
2412 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2414 // FIXME: When we get proper type location information for exceptions,
2415 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2416 // up the TypeSourceInfo;
2417 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2418 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2419 "TypeLoc size mismatch from updating exception specification");
2420 TSInfo->overrideType(Updated);
2424 /// getComplexType - Return the uniqued reference to the type for a complex
2425 /// number with the specified element type.
2426 QualType ASTContext::getComplexType(QualType T) const {
2427 // Unique pointers, to guarantee there is only one pointer of a particular
2429 llvm::FoldingSetNodeID ID;
2430 ComplexType::Profile(ID, T);
2432 void *InsertPos = nullptr;
2433 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2434 return QualType(CT, 0);
2436 // If the pointee type isn't canonical, this won't be a canonical type either,
2437 // so fill in the canonical type field.
2439 if (!T.isCanonical()) {
2440 Canonical = getComplexType(getCanonicalType(T));
2442 // Get the new insert position for the node we care about.
2443 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2444 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2446 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2447 Types.push_back(New);
2448 ComplexTypes.InsertNode(New, InsertPos);
2449 return QualType(New, 0);
2452 /// getPointerType - Return the uniqued reference to the type for a pointer to
2453 /// the specified type.
2454 QualType ASTContext::getPointerType(QualType T) const {
2455 // Unique pointers, to guarantee there is only one pointer of a particular
2457 llvm::FoldingSetNodeID ID;
2458 PointerType::Profile(ID, T);
2460 void *InsertPos = nullptr;
2461 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2462 return QualType(PT, 0);
2464 // If the pointee type isn't canonical, this won't be a canonical type either,
2465 // so fill in the canonical type field.
2467 if (!T.isCanonical()) {
2468 Canonical = getPointerType(getCanonicalType(T));
2470 // Get the new insert position for the node we care about.
2471 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2472 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2474 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2475 Types.push_back(New);
2476 PointerTypes.InsertNode(New, InsertPos);
2477 return QualType(New, 0);
2480 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2481 llvm::FoldingSetNodeID ID;
2482 AdjustedType::Profile(ID, Orig, New);
2483 void *InsertPos = nullptr;
2484 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2486 return QualType(AT, 0);
2488 QualType Canonical = getCanonicalType(New);
2490 // Get the new insert position for the node we care about.
2491 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 assert(!AT && "Shouldn't be in the map!");
2494 AT = new (*this, TypeAlignment)
2495 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2496 Types.push_back(AT);
2497 AdjustedTypes.InsertNode(AT, InsertPos);
2498 return QualType(AT, 0);
2501 QualType ASTContext::getDecayedType(QualType T) const {
2502 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2507 // A declaration of a parameter as "array of type" shall be
2508 // adjusted to "qualified pointer to type", where the type
2509 // qualifiers (if any) are those specified within the [ and ] of
2510 // the array type derivation.
2511 if (T->isArrayType())
2512 Decayed = getArrayDecayedType(T);
2515 // A declaration of a parameter as "function returning type"
2516 // shall be adjusted to "pointer to function returning type", as
2518 if (T->isFunctionType())
2519 Decayed = getPointerType(T);
2521 llvm::FoldingSetNodeID ID;
2522 AdjustedType::Profile(ID, T, Decayed);
2523 void *InsertPos = nullptr;
2524 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2526 return QualType(AT, 0);
2528 QualType Canonical = getCanonicalType(Decayed);
2530 // Get the new insert position for the node we care about.
2531 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 assert(!AT && "Shouldn't be in the map!");
2534 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2535 Types.push_back(AT);
2536 AdjustedTypes.InsertNode(AT, InsertPos);
2537 return QualType(AT, 0);
2540 /// getBlockPointerType - Return the uniqued reference to the type for
2541 /// a pointer to the specified block.
2542 QualType ASTContext::getBlockPointerType(QualType T) const {
2543 assert(T->isFunctionType() && "block of function types only");
2544 // Unique pointers, to guarantee there is only one block of a particular
2546 llvm::FoldingSetNodeID ID;
2547 BlockPointerType::Profile(ID, T);
2549 void *InsertPos = nullptr;
2550 if (BlockPointerType *PT =
2551 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2552 return QualType(PT, 0);
2554 // If the block pointee type isn't canonical, this won't be a canonical
2555 // type either so fill in the canonical type field.
2557 if (!T.isCanonical()) {
2558 Canonical = getBlockPointerType(getCanonicalType(T));
2560 // Get the new insert position for the node we care about.
2561 BlockPointerType *NewIP =
2562 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2563 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2565 BlockPointerType *New
2566 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2567 Types.push_back(New);
2568 BlockPointerTypes.InsertNode(New, InsertPos);
2569 return QualType(New, 0);
2572 /// getLValueReferenceType - Return the uniqued reference to the type for an
2573 /// lvalue reference to the specified type.
2575 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2576 assert(getCanonicalType(T) != OverloadTy &&
2577 "Unresolved overloaded function type");
2579 // Unique pointers, to guarantee there is only one pointer of a particular
2581 llvm::FoldingSetNodeID ID;
2582 ReferenceType::Profile(ID, T, SpelledAsLValue);
2584 void *InsertPos = nullptr;
2585 if (LValueReferenceType *RT =
2586 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2587 return QualType(RT, 0);
2589 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2591 // If the referencee type isn't canonical, this won't be a canonical type
2592 // either, so fill in the canonical type field.
2594 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2595 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2596 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2598 // Get the new insert position for the node we care about.
2599 LValueReferenceType *NewIP =
2600 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2601 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2604 LValueReferenceType *New
2605 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2607 Types.push_back(New);
2608 LValueReferenceTypes.InsertNode(New, InsertPos);
2610 return QualType(New, 0);
2613 /// getRValueReferenceType - Return the uniqued reference to the type for an
2614 /// rvalue reference to the specified type.
2615 QualType ASTContext::getRValueReferenceType(QualType T) const {
2616 // Unique pointers, to guarantee there is only one pointer of a particular
2618 llvm::FoldingSetNodeID ID;
2619 ReferenceType::Profile(ID, T, false);
2621 void *InsertPos = nullptr;
2622 if (RValueReferenceType *RT =
2623 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2624 return QualType(RT, 0);
2626 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2628 // If the referencee type isn't canonical, this won't be a canonical type
2629 // either, so fill in the canonical type field.
2631 if (InnerRef || !T.isCanonical()) {
2632 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2633 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2635 // Get the new insert position for the node we care about.
2636 RValueReferenceType *NewIP =
2637 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2638 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2641 RValueReferenceType *New
2642 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2643 Types.push_back(New);
2644 RValueReferenceTypes.InsertNode(New, InsertPos);
2645 return QualType(New, 0);
2648 /// getMemberPointerType - Return the uniqued reference to the type for a
2649 /// member pointer to the specified type, in the specified class.
2650 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2651 // Unique pointers, to guarantee there is only one pointer of a particular
2653 llvm::FoldingSetNodeID ID;
2654 MemberPointerType::Profile(ID, T, Cls);
2656 void *InsertPos = nullptr;
2657 if (MemberPointerType *PT =
2658 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2659 return QualType(PT, 0);
2661 // If the pointee or class type isn't canonical, this won't be a canonical
2662 // type either, so fill in the canonical type field.
2664 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2665 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2667 // Get the new insert position for the node we care about.
2668 MemberPointerType *NewIP =
2669 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2670 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2672 MemberPointerType *New
2673 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2674 Types.push_back(New);
2675 MemberPointerTypes.InsertNode(New, InsertPos);
2676 return QualType(New, 0);
2679 /// getConstantArrayType - Return the unique reference to the type for an
2680 /// array of the specified element type.
2681 QualType ASTContext::getConstantArrayType(QualType EltTy,
2682 const llvm::APInt &ArySizeIn,
2683 ArrayType::ArraySizeModifier ASM,
2684 unsigned IndexTypeQuals) const {
2685 assert((EltTy->isDependentType() ||
2686 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2687 "Constant array of VLAs is illegal!");
2689 // Convert the array size into a canonical width matching the pointer size for
2691 llvm::APInt ArySize(ArySizeIn);
2693 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2695 llvm::FoldingSetNodeID ID;
2696 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2698 void *InsertPos = nullptr;
2699 if (ConstantArrayType *ATP =
2700 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2701 return QualType(ATP, 0);
2703 // If the element type isn't canonical or has qualifiers, this won't
2704 // be a canonical type either, so fill in the canonical type field.
2706 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2707 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2708 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2709 ASM, IndexTypeQuals);
2710 Canon = getQualifiedType(Canon, canonSplit.Quals);
2712 // Get the new insert position for the node we care about.
2713 ConstantArrayType *NewIP =
2714 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2718 ConstantArrayType *New = new(*this,TypeAlignment)
2719 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2720 ConstantArrayTypes.InsertNode(New, InsertPos);
2721 Types.push_back(New);
2722 return QualType(New, 0);
2725 /// getVariableArrayDecayedType - Turns the given type, which may be
2726 /// variably-modified, into the corresponding type with all the known
2727 /// sizes replaced with [*].
2728 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2729 // Vastly most common case.
2730 if (!type->isVariablyModifiedType()) return type;
2734 SplitQualType split = type.getSplitDesugaredType();
2735 const Type *ty = split.Ty;
2736 switch (ty->getTypeClass()) {
2737 #define TYPE(Class, Base)
2738 #define ABSTRACT_TYPE(Class, Base)
2739 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2740 #include "clang/AST/TypeNodes.def"
2741 llvm_unreachable("didn't desugar past all non-canonical types?");
2743 // These types should never be variably-modified.
2747 case Type::ExtVector:
2748 case Type::DependentSizedExtVector:
2749 case Type::ObjCObject:
2750 case Type::ObjCInterface:
2751 case Type::ObjCObjectPointer:
2754 case Type::UnresolvedUsing:
2755 case Type::TypeOfExpr:
2757 case Type::Decltype:
2758 case Type::UnaryTransform:
2759 case Type::DependentName:
2760 case Type::InjectedClassName:
2761 case Type::TemplateSpecialization:
2762 case Type::DependentTemplateSpecialization:
2763 case Type::TemplateTypeParm:
2764 case Type::SubstTemplateTypeParmPack:
2766 case Type::PackExpansion:
2767 llvm_unreachable("type should never be variably-modified");
2769 // These types can be variably-modified but should never need to
2771 case Type::FunctionNoProto:
2772 case Type::FunctionProto:
2773 case Type::BlockPointer:
2774 case Type::MemberPointer:
2778 // These types can be variably-modified. All these modifications
2779 // preserve structure except as noted by comments.
2780 // TODO: if we ever care about optimizing VLAs, there are no-op
2781 // optimizations available here.
2783 result = getPointerType(getVariableArrayDecayedType(
2784 cast<PointerType>(ty)->getPointeeType()));
2787 case Type::LValueReference: {
2788 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2789 result = getLValueReferenceType(
2790 getVariableArrayDecayedType(lv->getPointeeType()),
2791 lv->isSpelledAsLValue());
2795 case Type::RValueReference: {
2796 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2797 result = getRValueReferenceType(
2798 getVariableArrayDecayedType(lv->getPointeeType()));
2802 case Type::Atomic: {
2803 const AtomicType *at = cast<AtomicType>(ty);
2804 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2808 case Type::ConstantArray: {
2809 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2810 result = getConstantArrayType(
2811 getVariableArrayDecayedType(cat->getElementType()),
2813 cat->getSizeModifier(),
2814 cat->getIndexTypeCVRQualifiers());
2818 case Type::DependentSizedArray: {
2819 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2820 result = getDependentSizedArrayType(
2821 getVariableArrayDecayedType(dat->getElementType()),
2823 dat->getSizeModifier(),
2824 dat->getIndexTypeCVRQualifiers(),
2825 dat->getBracketsRange());
2829 // Turn incomplete types into [*] types.
2830 case Type::IncompleteArray: {
2831 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2832 result = getVariableArrayType(
2833 getVariableArrayDecayedType(iat->getElementType()),
2836 iat->getIndexTypeCVRQualifiers(),
2841 // Turn VLA types into [*] types.
2842 case Type::VariableArray: {
2843 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2844 result = getVariableArrayType(
2845 getVariableArrayDecayedType(vat->getElementType()),
2848 vat->getIndexTypeCVRQualifiers(),
2849 vat->getBracketsRange());
2854 // Apply the top-level qualifiers from the original.
2855 return getQualifiedType(result, split.Quals);
2858 /// getVariableArrayType - Returns a non-unique reference to the type for a
2859 /// variable array of the specified element type.
2860 QualType ASTContext::getVariableArrayType(QualType EltTy,
2862 ArrayType::ArraySizeModifier ASM,
2863 unsigned IndexTypeQuals,
2864 SourceRange Brackets) const {
2865 // Since we don't unique expressions, it isn't possible to unique VLA's
2866 // that have an expression provided for their size.
2869 // Be sure to pull qualifiers off the element type.
2870 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2871 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2872 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2873 IndexTypeQuals, Brackets);
2874 Canon = getQualifiedType(Canon, canonSplit.Quals);
2877 VariableArrayType *New = new(*this, TypeAlignment)
2878 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2880 VariableArrayTypes.push_back(New);
2881 Types.push_back(New);
2882 return QualType(New, 0);
2885 /// getDependentSizedArrayType - Returns a non-unique reference to
2886 /// the type for a dependently-sized array of the specified element
2888 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2890 ArrayType::ArraySizeModifier ASM,
2891 unsigned elementTypeQuals,
2892 SourceRange brackets) const {
2893 assert((!numElements || numElements->isTypeDependent() ||
2894 numElements->isValueDependent()) &&
2895 "Size must be type- or value-dependent!");
2897 // Dependently-sized array types that do not have a specified number
2898 // of elements will have their sizes deduced from a dependent
2899 // initializer. We do no canonicalization here at all, which is okay
2900 // because they can't be used in most locations.
2902 DependentSizedArrayType *newType
2903 = new (*this, TypeAlignment)
2904 DependentSizedArrayType(*this, elementType, QualType(),
2905 numElements, ASM, elementTypeQuals,
2907 Types.push_back(newType);
2908 return QualType(newType, 0);
2911 // Otherwise, we actually build a new type every time, but we
2912 // also build a canonical type.
2914 SplitQualType canonElementType = getCanonicalType(elementType).split();
2916 void *insertPos = nullptr;
2917 llvm::FoldingSetNodeID ID;
2918 DependentSizedArrayType::Profile(ID, *this,
2919 QualType(canonElementType.Ty, 0),
2920 ASM, elementTypeQuals, numElements);
2922 // Look for an existing type with these properties.
2923 DependentSizedArrayType *canonTy =
2924 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2926 // If we don't have one, build one.
2928 canonTy = new (*this, TypeAlignment)
2929 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2930 QualType(), numElements, ASM, elementTypeQuals,
2932 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2933 Types.push_back(canonTy);
2936 // Apply qualifiers from the element type to the array.
2937 QualType canon = getQualifiedType(QualType(canonTy,0),
2938 canonElementType.Quals);
2940 // If we didn't need extra canonicalization for the element type or the size
2941 // expression, then just use that as our result.
2942 if (QualType(canonElementType.Ty, 0) == elementType &&
2943 canonTy->getSizeExpr() == numElements)
2946 // Otherwise, we need to build a type which follows the spelling
2947 // of the element type.
2948 DependentSizedArrayType *sugaredType
2949 = new (*this, TypeAlignment)
2950 DependentSizedArrayType(*this, elementType, canon, numElements,
2951 ASM, elementTypeQuals, brackets);
2952 Types.push_back(sugaredType);
2953 return QualType(sugaredType, 0);
2956 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2957 ArrayType::ArraySizeModifier ASM,
2958 unsigned elementTypeQuals) const {
2959 llvm::FoldingSetNodeID ID;
2960 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2962 void *insertPos = nullptr;
2963 if (IncompleteArrayType *iat =
2964 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2965 return QualType(iat, 0);
2967 // If the element type isn't canonical, this won't be a canonical type
2968 // either, so fill in the canonical type field. We also have to pull
2969 // qualifiers off the element type.
2972 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2973 SplitQualType canonSplit = getCanonicalType(elementType).split();
2974 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2975 ASM, elementTypeQuals);
2976 canon = getQualifiedType(canon, canonSplit.Quals);
2978 // Get the new insert position for the node we care about.
2979 IncompleteArrayType *existing =
2980 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2981 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2984 IncompleteArrayType *newType = new (*this, TypeAlignment)
2985 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2987 IncompleteArrayTypes.InsertNode(newType, insertPos);
2988 Types.push_back(newType);
2989 return QualType(newType, 0);
2992 /// getVectorType - Return the unique reference to a vector type of
2993 /// the specified element type and size. VectorType must be a built-in type.
2994 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2995 VectorType::VectorKind VecKind) const {
2996 assert(vecType->isBuiltinType());
2998 // Check if we've already instantiated a vector of this type.
2999 llvm::FoldingSetNodeID ID;
3000 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3002 void *InsertPos = nullptr;
3003 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3004 return QualType(VTP, 0);
3006 // If the element type isn't canonical, this won't be a canonical type either,
3007 // so fill in the canonical type field.
3009 if (!vecType.isCanonical()) {
3010 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3012 // Get the new insert position for the node we care about.
3013 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3014 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3016 VectorType *New = new (*this, TypeAlignment)
3017 VectorType(vecType, NumElts, Canonical, VecKind);
3018 VectorTypes.InsertNode(New, InsertPos);
3019 Types.push_back(New);
3020 return QualType(New, 0);
3023 /// getExtVectorType - Return the unique reference to an extended vector type of
3024 /// the specified element type and size. VectorType must be a built-in type.
3026 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3027 assert(vecType->isBuiltinType() || vecType->isDependentType());
3029 // Check if we've already instantiated a vector of this type.
3030 llvm::FoldingSetNodeID ID;
3031 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3032 VectorType::GenericVector);
3033 void *InsertPos = nullptr;
3034 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3035 return QualType(VTP, 0);
3037 // If the element type isn't canonical, this won't be a canonical type either,
3038 // so fill in the canonical type field.
3040 if (!vecType.isCanonical()) {
3041 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3043 // Get the new insert position for the node we care about.
3044 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3045 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3047 ExtVectorType *New = new (*this, TypeAlignment)
3048 ExtVectorType(vecType, NumElts, Canonical);
3049 VectorTypes.InsertNode(New, InsertPos);
3050 Types.push_back(New);
3051 return QualType(New, 0);
3055 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3057 SourceLocation AttrLoc) const {
3058 llvm::FoldingSetNodeID ID;
3059 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3062 void *InsertPos = nullptr;
3063 DependentSizedExtVectorType *Canon
3064 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3065 DependentSizedExtVectorType *New;
3067 // We already have a canonical version of this array type; use it as
3068 // the canonical type for a newly-built type.
3069 New = new (*this, TypeAlignment)
3070 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3073 QualType CanonVecTy = getCanonicalType(vecType);
3074 if (CanonVecTy == vecType) {
3075 New = new (*this, TypeAlignment)
3076 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3079 DependentSizedExtVectorType *CanonCheck
3080 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3083 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3085 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3087 New = new (*this, TypeAlignment)
3088 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3092 Types.push_back(New);
3093 return QualType(New, 0);
3096 /// \brief Determine whether \p T is canonical as the result type of a function.
3097 static bool isCanonicalResultType(QualType T) {
3098 return T.isCanonical() &&
3099 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3100 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3103 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3106 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3107 const FunctionType::ExtInfo &Info) const {
3108 // Unique functions, to guarantee there is only one function of a particular
3110 llvm::FoldingSetNodeID ID;
3111 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3113 void *InsertPos = nullptr;
3114 if (FunctionNoProtoType *FT =
3115 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3116 return QualType(FT, 0);
3119 if (!isCanonicalResultType(ResultTy)) {
3121 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3123 // Get the new insert position for the node we care about.
3124 FunctionNoProtoType *NewIP =
3125 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3126 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3129 FunctionNoProtoType *New = new (*this, TypeAlignment)
3130 FunctionNoProtoType(ResultTy, Canonical, Info);
3131 Types.push_back(New);
3132 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3133 return QualType(New, 0);
3137 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3138 CanQualType CanResultType = getCanonicalType(ResultType);
3140 // Canonical result types do not have ARC lifetime qualifiers.
3141 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3142 Qualifiers Qs = CanResultType.getQualifiers();
3143 Qs.removeObjCLifetime();
3144 return CanQualType::CreateUnsafe(
3145 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3148 return CanResultType;
3151 static bool isCanonicalExceptionSpecification(
3152 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3153 if (ESI.Type == EST_None)
3155 if (!NoexceptInType)
3158 // C++17 onwards: exception specification is part of the type, as a simple
3159 // boolean "can this function type throw".
3160 if (ESI.Type == EST_BasicNoexcept)
3163 // A dynamic exception specification is canonical if it only contains pack
3164 // expansions (so we can't tell whether it's non-throwing) and all its
3165 // contained types are canonical.
3166 if (ESI.Type == EST_Dynamic) {
3167 bool AnyPackExpansions = false;
3168 for (QualType ET : ESI.Exceptions) {
3169 if (!ET.isCanonical())
3171 if (ET->getAs<PackExpansionType>())
3172 AnyPackExpansions = true;
3174 return AnyPackExpansions;
3177 // A noexcept(expr) specification is (possibly) canonical if expr is
3179 if (ESI.Type == EST_ComputedNoexcept)
3180 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3185 QualType ASTContext::getFunctionTypeInternal(
3186 QualType ResultTy, ArrayRef<QualType> ArgArray,
3187 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3188 size_t NumArgs = ArgArray.size();
3190 // Unique functions, to guarantee there is only one function of a particular
3192 llvm::FoldingSetNodeID ID;
3193 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3197 bool Unique = false;
3199 void *InsertPos = nullptr;
3200 if (FunctionProtoType *FPT =
3201 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3202 QualType Existing = QualType(FPT, 0);
3204 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3205 // it so long as our exception specification doesn't contain a dependent
3206 // noexcept expression, or we're just looking for a canonical type.
3207 // Otherwise, we're going to need to create a type
3208 // sugar node to hold the concrete expression.
3209 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
3210 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3213 // We need a new type sugar node for this one, to hold the new noexcept
3214 // expression. We do no canonicalization here, but that's OK since we don't
3215 // expect to see the same noexcept expression much more than once.
3216 Canonical = getCanonicalType(Existing);
3220 bool NoexceptInType = getLangOpts().CPlusPlus1z;
3221 bool IsCanonicalExceptionSpec =
3222 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3224 // Determine whether the type being created is already canonical or not.
3225 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3226 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3227 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3228 if (!ArgArray[i].isCanonicalAsParam())
3229 isCanonical = false;
3231 if (OnlyWantCanonical)
3232 assert(isCanonical &&
3233 "given non-canonical parameters constructing canonical type");
3235 // If this type isn't canonical, get the canonical version of it if we don't
3236 // already have it. The exception spec is only partially part of the
3237 // canonical type, and only in C++17 onwards.
3238 if (!isCanonical && Canonical.isNull()) {
3239 SmallVector<QualType, 16> CanonicalArgs;
3240 CanonicalArgs.reserve(NumArgs);
3241 for (unsigned i = 0; i != NumArgs; ++i)
3242 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3244 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3245 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3246 CanonicalEPI.HasTrailingReturn = false;
3248 if (IsCanonicalExceptionSpec) {
3249 // Exception spec is already OK.
3250 } else if (NoexceptInType) {
3251 switch (EPI.ExceptionSpec.Type) {
3252 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3253 // We don't know yet. It shouldn't matter what we pick here; no-one
3254 // should ever look at this.
3256 case EST_None: case EST_MSAny:
3257 CanonicalEPI.ExceptionSpec.Type = EST_None;
3260 // A dynamic exception specification is almost always "not noexcept",
3261 // with the exception that a pack expansion might expand to no types.
3263 bool AnyPacks = false;
3264 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3265 if (ET->getAs<PackExpansionType>())
3267 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3270 CanonicalEPI.ExceptionSpec.Type = EST_None;
3272 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3273 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3278 case EST_DynamicNone: case EST_BasicNoexcept:
3279 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3282 case EST_ComputedNoexcept:
3283 llvm::APSInt Value(1);
3284 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3285 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3286 /*IsEvaluated*/false)) {
3287 // This noexcept specification is invalid.
3288 // FIXME: Should this be able to happen?
3289 CanonicalEPI.ExceptionSpec.Type = EST_None;
3293 CanonicalEPI.ExceptionSpec.Type =
3294 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3298 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3301 // Adjust the canonical function result type.
3302 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3304 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3306 // Get the new insert position for the node we care about.
3307 FunctionProtoType *NewIP =
3308 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3309 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3312 // FunctionProtoType objects are allocated with extra bytes after
3313 // them for three variable size arrays at the end:
3314 // - parameter types
3315 // - exception types
3316 // - extended parameter information
3317 // Instead of the exception types, there could be a noexcept
3318 // expression, or information used to resolve the exception
3320 size_t Size = sizeof(FunctionProtoType) +
3321 NumArgs * sizeof(QualType);
3323 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3324 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3325 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3326 Size += sizeof(Expr*);
3327 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3328 Size += 2 * sizeof(FunctionDecl*);
3329 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3330 Size += sizeof(FunctionDecl*);
3333 // Put the ExtParameterInfos last. If all were equal, it would make
3334 // more sense to put these before the exception specification, because
3335 // it's much easier to skip past them compared to the elaborate switch
3336 // required to skip the exception specification. However, all is not
3337 // equal; ExtParameterInfos are used to model very uncommon features,
3338 // and it's better not to burden the more common paths.
3339 if (EPI.ExtParameterInfos) {
3340 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3343 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3344 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3345 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3346 Types.push_back(FTP);
3348 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3349 return QualType(FTP, 0);
3352 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3353 llvm::FoldingSetNodeID ID;
3354 PipeType::Profile(ID, T, ReadOnly);
3356 void *InsertPos = 0;
3357 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3358 return QualType(PT, 0);
3360 // If the pipe element type isn't canonical, this won't be a canonical type
3361 // either, so fill in the canonical type field.
3363 if (!T.isCanonical()) {
3364 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3366 // Get the new insert position for the node we care about.
3367 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3368 assert(!NewIP && "Shouldn't be in the map!");
3371 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3372 Types.push_back(New);
3373 PipeTypes.InsertNode(New, InsertPos);
3374 return QualType(New, 0);
3377 QualType ASTContext::getReadPipeType(QualType T) const {
3378 return getPipeType(T, true);
3381 QualType ASTContext::getWritePipeType(QualType T) const {
3382 return getPipeType(T, false);
3386 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3387 if (!isa<CXXRecordDecl>(D)) return false;
3388 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3389 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3391 if (RD->getDescribedClassTemplate() &&
3392 !isa<ClassTemplateSpecializationDecl>(RD))
3398 /// getInjectedClassNameType - Return the unique reference to the
3399 /// injected class name type for the specified templated declaration.
3400 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3401 QualType TST) const {
3402 assert(NeedsInjectedClassNameType(Decl));
3403 if (Decl->TypeForDecl) {
3404 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3405 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3406 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3407 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3408 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3411 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3412 Decl->TypeForDecl = newType;
3413 Types.push_back(newType);
3415 return QualType(Decl->TypeForDecl, 0);
3418 /// getTypeDeclType - Return the unique reference to the type for the
3419 /// specified type declaration.
3420 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3421 assert(Decl && "Passed null for Decl param");
3422 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3424 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3425 return getTypedefType(Typedef);
3427 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3428 "Template type parameter types are always available.");
3430 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3431 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3432 assert(!NeedsInjectedClassNameType(Record));
3433 return getRecordType(Record);
3434 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3435 assert(Enum->isFirstDecl() && "enum has previous declaration");
3436 return getEnumType(Enum);
3437 } else if (const UnresolvedUsingTypenameDecl *Using =
3438 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3439 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3440 Decl->TypeForDecl = newType;
3441 Types.push_back(newType);
3443 llvm_unreachable("TypeDecl without a type?");
3445 return QualType(Decl->TypeForDecl, 0);
3448 /// getTypedefType - Return the unique reference to the type for the
3449 /// specified typedef name decl.
3451 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3452 QualType Canonical) const {
3453 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3455 if (Canonical.isNull())
3456 Canonical = getCanonicalType(Decl->getUnderlyingType());
3457 TypedefType *newType = new(*this, TypeAlignment)
3458 TypedefType(Type::Typedef, Decl, Canonical);
3459 Decl->TypeForDecl = newType;
3460 Types.push_back(newType);
3461 return QualType(newType, 0);
3464 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3465 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3467 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3468 if (PrevDecl->TypeForDecl)
3469 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3471 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3472 Decl->TypeForDecl = newType;
3473 Types.push_back(newType);
3474 return QualType(newType, 0);
3477 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3478 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3480 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3481 if (PrevDecl->TypeForDecl)
3482 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3484 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3485 Decl->TypeForDecl = newType;
3486 Types.push_back(newType);
3487 return QualType(newType, 0);
3490 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3491 QualType modifiedType,
3492 QualType equivalentType) {
3493 llvm::FoldingSetNodeID id;
3494 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3496 void *insertPos = nullptr;
3497 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3498 if (type) return QualType(type, 0);
3500 QualType canon = getCanonicalType(equivalentType);
3501 type = new (*this, TypeAlignment)
3502 AttributedType(canon, attrKind, modifiedType, equivalentType);
3504 Types.push_back(type);
3505 AttributedTypes.InsertNode(type, insertPos);
3507 return QualType(type, 0);
3510 /// \brief Retrieve a substitution-result type.
3512 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3513 QualType Replacement) const {
3514 assert(Replacement.isCanonical()
3515 && "replacement types must always be canonical");
3517 llvm::FoldingSetNodeID ID;
3518 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3519 void *InsertPos = nullptr;
3520 SubstTemplateTypeParmType *SubstParm
3521 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3524 SubstParm = new (*this, TypeAlignment)
3525 SubstTemplateTypeParmType(Parm, Replacement);
3526 Types.push_back(SubstParm);
3527 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3530 return QualType(SubstParm, 0);
3533 /// \brief Retrieve a
3534 QualType ASTContext::getSubstTemplateTypeParmPackType(
3535 const TemplateTypeParmType *Parm,
3536 const TemplateArgument &ArgPack) {
3538 for (const auto &P : ArgPack.pack_elements()) {
3539 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3540 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3544 llvm::FoldingSetNodeID ID;
3545 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3546 void *InsertPos = nullptr;
3547 if (SubstTemplateTypeParmPackType *SubstParm
3548 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3549 return QualType(SubstParm, 0);
3552 if (!Parm->isCanonicalUnqualified()) {
3553 Canon = getCanonicalType(QualType(Parm, 0));
3554 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3556 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3559 SubstTemplateTypeParmPackType *SubstParm
3560 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3562 Types.push_back(SubstParm);
3563 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3564 return QualType(SubstParm, 0);
3567 /// \brief Retrieve the template type parameter type for a template
3568 /// parameter or parameter pack with the given depth, index, and (optionally)
3570 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3572 TemplateTypeParmDecl *TTPDecl) const {
3573 llvm::FoldingSetNodeID ID;
3574 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3575 void *InsertPos = nullptr;
3576 TemplateTypeParmType *TypeParm
3577 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3580 return QualType(TypeParm, 0);
3583 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3584 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3586 TemplateTypeParmType *TypeCheck
3587 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3588 assert(!TypeCheck && "Template type parameter canonical type broken");
3591 TypeParm = new (*this, TypeAlignment)
3592 TemplateTypeParmType(Depth, Index, ParameterPack);
3594 Types.push_back(TypeParm);
3595 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3597 return QualType(TypeParm, 0);
3601 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3602 SourceLocation NameLoc,
3603 const TemplateArgumentListInfo &Args,
3604 QualType Underlying) const {
3605 assert(!Name.getAsDependentTemplateName() &&
3606 "No dependent template names here!");
3607 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3609 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3610 TemplateSpecializationTypeLoc TL =
3611 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3612 TL.setTemplateKeywordLoc(SourceLocation());
3613 TL.setTemplateNameLoc(NameLoc);
3614 TL.setLAngleLoc(Args.getLAngleLoc());
3615 TL.setRAngleLoc(Args.getRAngleLoc());
3616 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3617 TL.setArgLocInfo(i, Args[i].getLocInfo());
3622 ASTContext::getTemplateSpecializationType(TemplateName Template,
3623 const TemplateArgumentListInfo &Args,
3624 QualType Underlying) const {
3625 assert(!Template.getAsDependentTemplateName() &&
3626 "No dependent template names here!");
3628 SmallVector<TemplateArgument, 4> ArgVec;
3629 ArgVec.reserve(Args.size());
3630 for (const TemplateArgumentLoc &Arg : Args.arguments())
3631 ArgVec.push_back(Arg.getArgument());
3633 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3637 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3638 for (const TemplateArgument &Arg : Args)
3639 if (Arg.isPackExpansion())
3647 ASTContext::getTemplateSpecializationType(TemplateName Template,
3648 ArrayRef<TemplateArgument> Args,
3649 QualType Underlying) const {
3650 assert(!Template.getAsDependentTemplateName() &&
3651 "No dependent template names here!");
3652 // Look through qualified template names.
3653 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3654 Template = TemplateName(QTN->getTemplateDecl());
3657 Template.getAsTemplateDecl() &&
3658 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3660 if (!Underlying.isNull())
3661 CanonType = getCanonicalType(Underlying);
3663 // We can get here with an alias template when the specialization contains
3664 // a pack expansion that does not match up with a parameter pack.
3665 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3666 "Caller must compute aliased type");
3667 IsTypeAlias = false;
3668 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3671 // Allocate the (non-canonical) template specialization type, but don't
3672 // try to unique it: these types typically have location information that
3673 // we don't unique and don't want to lose.
3674 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3675 sizeof(TemplateArgument) * Args.size() +
3676 (IsTypeAlias? sizeof(QualType) : 0),
3678 TemplateSpecializationType *Spec
3679 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3680 IsTypeAlias ? Underlying : QualType());
3682 Types.push_back(Spec);
3683 return QualType(Spec, 0);
3686 QualType ASTContext::getCanonicalTemplateSpecializationType(
3687 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3688 assert(!Template.getAsDependentTemplateName() &&
3689 "No dependent template names here!");
3691 // Look through qualified template names.
3692 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3693 Template = TemplateName(QTN->getTemplateDecl());
3695 // Build the canonical template specialization type.
3696 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3697 SmallVector<TemplateArgument, 4> CanonArgs;
3698 unsigned NumArgs = Args.size();
3699 CanonArgs.reserve(NumArgs);
3700 for (const TemplateArgument &Arg : Args)
3701 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3703 // Determine whether this canonical template specialization type already
3705 llvm::FoldingSetNodeID ID;
3706 TemplateSpecializationType::Profile(ID, CanonTemplate,
3709 void *InsertPos = nullptr;
3710 TemplateSpecializationType *Spec
3711 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3714 // Allocate a new canonical template specialization type.
3715 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3716 sizeof(TemplateArgument) * NumArgs),
3718 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3720 QualType(), QualType());
3721 Types.push_back(Spec);
3722 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3725 assert(Spec->isDependentType() &&
3726 "Non-dependent template-id type must have a canonical type");
3727 return QualType(Spec, 0);
3731 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3732 NestedNameSpecifier *NNS,
3733 QualType NamedType) const {
3734 llvm::FoldingSetNodeID ID;
3735 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3737 void *InsertPos = nullptr;
3738 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3740 return QualType(T, 0);
3742 QualType Canon = NamedType;
3743 if (!Canon.isCanonical()) {
3744 Canon = getCanonicalType(NamedType);
3745 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3746 assert(!CheckT && "Elaborated canonical type broken");
3750 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3752 ElaboratedTypes.InsertNode(T, InsertPos);
3753 return QualType(T, 0);
3757 ASTContext::getParenType(QualType InnerType) const {
3758 llvm::FoldingSetNodeID ID;
3759 ParenType::Profile(ID, InnerType);
3761 void *InsertPos = nullptr;
3762 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3764 return QualType(T, 0);
3766 QualType Canon = InnerType;
3767 if (!Canon.isCanonical()) {
3768 Canon = getCanonicalType(InnerType);
3769 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3770 assert(!CheckT && "Paren canonical type broken");
3774 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3776 ParenTypes.InsertNode(T, InsertPos);
3777 return QualType(T, 0);
3780 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3781 NestedNameSpecifier *NNS,
3782 const IdentifierInfo *Name,
3783 QualType Canon) const {
3784 if (Canon.isNull()) {
3785 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3786 ElaboratedTypeKeyword CanonKeyword = Keyword;
3787 if (Keyword == ETK_None)
3788 CanonKeyword = ETK_Typename;
3790 if (CanonNNS != NNS || CanonKeyword != Keyword)
3791 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3794 llvm::FoldingSetNodeID ID;
3795 DependentNameType::Profile(ID, Keyword, NNS, Name);
3797 void *InsertPos = nullptr;
3798 DependentNameType *T
3799 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3801 return QualType(T, 0);
3803 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3805 DependentNameTypes.InsertNode(T, InsertPos);
3806 return QualType(T, 0);
3810 ASTContext::getDependentTemplateSpecializationType(
3811 ElaboratedTypeKeyword Keyword,
3812 NestedNameSpecifier *NNS,
3813 const IdentifierInfo *Name,
3814 const TemplateArgumentListInfo &Args) const {
3815 // TODO: avoid this copy
3816 SmallVector<TemplateArgument, 16> ArgCopy;
3817 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3818 ArgCopy.push_back(Args[I].getArgument());
3819 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3823 ASTContext::getDependentTemplateSpecializationType(
3824 ElaboratedTypeKeyword Keyword,
3825 NestedNameSpecifier *NNS,
3826 const IdentifierInfo *Name,
3827 ArrayRef<TemplateArgument> Args) const {
3828 assert((!NNS || NNS->isDependent()) &&
3829 "nested-name-specifier must be dependent");
3831 llvm::FoldingSetNodeID ID;
3832 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3835 void *InsertPos = nullptr;
3836 DependentTemplateSpecializationType *T
3837 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3839 return QualType(T, 0);
3841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3843 ElaboratedTypeKeyword CanonKeyword = Keyword;
3844 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3846 bool AnyNonCanonArgs = false;
3847 unsigned NumArgs = Args.size();
3848 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3849 for (unsigned I = 0; I != NumArgs; ++I) {
3850 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3851 if (!CanonArgs[I].structurallyEquals(Args[I]))
3852 AnyNonCanonArgs = true;
3856 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3857 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3861 // Find the insert position again.
3862 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3865 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3866 sizeof(TemplateArgument) * NumArgs),
3868 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3871 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3872 return QualType(T, 0);
3876 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3877 SmallVectorImpl<TemplateArgument> &Args) {
3878 Args.reserve(Args.size() + Params->size());
3880 for (NamedDecl *Param : *Params) {
3881 TemplateArgument Arg;
3882 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3883 QualType ArgType = getTypeDeclType(TTP);
3884 if (TTP->isParameterPack())
3885 ArgType = getPackExpansionType(ArgType, None);
3887 Arg = TemplateArgument(ArgType);
3888 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3889 Expr *E = new (*this) DeclRefExpr(
3890 NTTP, /*enclosing*/false,
3891 NTTP->getType().getNonLValueExprType(*this),
3892 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3894 if (NTTP->isParameterPack())
3895 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3897 Arg = TemplateArgument(E);
3899 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3900 if (TTP->isParameterPack())
3901 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3903 Arg = TemplateArgument(TemplateName(TTP));
3906 if (Param->isTemplateParameterPack())
3907 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3909 Args.push_back(Arg);
3913 QualType ASTContext::getPackExpansionType(QualType Pattern,
3914 Optional<unsigned> NumExpansions) {
3915 llvm::FoldingSetNodeID ID;
3916 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3918 assert(Pattern->containsUnexpandedParameterPack() &&
3919 "Pack expansions must expand one or more parameter packs");
3920 void *InsertPos = nullptr;
3921 PackExpansionType *T
3922 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3924 return QualType(T, 0);
3927 if (!Pattern.isCanonical()) {
3928 Canon = getCanonicalType(Pattern);
3929 // The canonical type might not contain an unexpanded parameter pack, if it
3930 // contains an alias template specialization which ignores one of its
3932 if (Canon->containsUnexpandedParameterPack()) {
3933 Canon = getPackExpansionType(Canon, NumExpansions);
3935 // Find the insert position again, in case we inserted an element into
3936 // PackExpansionTypes and invalidated our insert position.
3937 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3941 T = new (*this, TypeAlignment)
3942 PackExpansionType(Pattern, Canon, NumExpansions);
3944 PackExpansionTypes.InsertNode(T, InsertPos);
3945 return QualType(T, 0);
3948 /// CmpProtocolNames - Comparison predicate for sorting protocols
3950 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3951 ObjCProtocolDecl *const *RHS) {
3952 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3955 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3956 if (Protocols.empty()) return true;
3958 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3961 for (unsigned i = 1; i != Protocols.size(); ++i)
3962 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3963 Protocols[i]->getCanonicalDecl() != Protocols[i])
3969 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3970 // Sort protocols, keyed by name.
3971 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3974 for (ObjCProtocolDecl *&P : Protocols)
3975 P = P->getCanonicalDecl();
3977 // Remove duplicates.
3978 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3979 Protocols.erase(ProtocolsEnd, Protocols.end());
3982 QualType ASTContext::getObjCObjectType(QualType BaseType,
3983 ObjCProtocolDecl * const *Protocols,
3984 unsigned NumProtocols) const {
3985 return getObjCObjectType(BaseType, { },
3986 llvm::makeArrayRef(Protocols, NumProtocols),
3987 /*isKindOf=*/false);
3990 QualType ASTContext::getObjCObjectType(
3992 ArrayRef<QualType> typeArgs,
3993 ArrayRef<ObjCProtocolDecl *> protocols,
3994 bool isKindOf) const {
3995 // If the base type is an interface and there aren't any protocols or
3996 // type arguments to add, then the interface type will do just fine.
3997 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3998 isa<ObjCInterfaceType>(baseType))
4001 // Look in the folding set for an existing type.
4002 llvm::FoldingSetNodeID ID;
4003 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4004 void *InsertPos = nullptr;
4005 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4006 return QualType(QT, 0);
4008 // Determine the type arguments to be used for canonicalization,
4009 // which may be explicitly specified here or written on the base
4011 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4012 if (effectiveTypeArgs.empty()) {
4013 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4014 effectiveTypeArgs = baseObject->getTypeArgs();
4017 // Build the canonical type, which has the canonical base type and a
4018 // sorted-and-uniqued list of protocols and the type arguments
4021 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4022 effectiveTypeArgs.end(),
4023 [&](QualType type) {
4024 return type.isCanonical();
4026 bool protocolsSorted = areSortedAndUniqued(protocols);
4027 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4028 // Determine the canonical type arguments.
4029 ArrayRef<QualType> canonTypeArgs;
4030 SmallVector<QualType, 4> canonTypeArgsVec;
4031 if (!typeArgsAreCanonical) {
4032 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4033 for (auto typeArg : effectiveTypeArgs)
4034 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4035 canonTypeArgs = canonTypeArgsVec;
4037 canonTypeArgs = effectiveTypeArgs;
4040 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4041 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4042 if (!protocolsSorted) {
4043 canonProtocolsVec.append(protocols.begin(), protocols.end());
4044 SortAndUniqueProtocols(canonProtocolsVec);
4045 canonProtocols = canonProtocolsVec;
4047 canonProtocols = protocols;
4050 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4051 canonProtocols, isKindOf);
4053 // Regenerate InsertPos.
4054 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4057 unsigned size = sizeof(ObjCObjectTypeImpl);
4058 size += typeArgs.size() * sizeof(QualType);
4059 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4060 void *mem = Allocate(size, TypeAlignment);
4061 ObjCObjectTypeImpl *T =
4062 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4066 ObjCObjectTypes.InsertNode(T, InsertPos);
4067 return QualType(T, 0);
4070 /// Apply Objective-C protocol qualifiers to the given type.
4071 /// If this is for the canonical type of a type parameter, we can apply
4072 /// protocol qualifiers on the ObjCObjectPointerType.
4074 ASTContext::applyObjCProtocolQualifiers(QualType type,
4075 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4076 bool allowOnPointerType) const {
4079 if (const ObjCTypeParamType *objT =
4080 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4081 return getObjCTypeParamType(objT->getDecl(), protocols);
4084 // Apply protocol qualifiers to ObjCObjectPointerType.
4085 if (allowOnPointerType) {
4086 if (const ObjCObjectPointerType *objPtr =
4087 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4088 const ObjCObjectType *objT = objPtr->getObjectType();
4089 // Merge protocol lists and construct ObjCObjectType.
4090 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4091 protocolsVec.append(objT->qual_begin(),
4093 protocolsVec.append(protocols.begin(), protocols.end());
4094 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4095 type = getObjCObjectType(
4096 objT->getBaseType(),
4097 objT->getTypeArgsAsWritten(),
4099 objT->isKindOfTypeAsWritten());
4100 return getObjCObjectPointerType(type);
4104 // Apply protocol qualifiers to ObjCObjectType.
4105 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4106 // FIXME: Check for protocols to which the class type is already
4107 // known to conform.
4109 return getObjCObjectType(objT->getBaseType(),
4110 objT->getTypeArgsAsWritten(),
4112 objT->isKindOfTypeAsWritten());
4115 // If the canonical type is ObjCObjectType, ...
4116 if (type->isObjCObjectType()) {
4117 // Silently overwrite any existing protocol qualifiers.
4118 // TODO: determine whether that's the right thing to do.
4120 // FIXME: Check for protocols to which the class type is already
4121 // known to conform.
4122 return getObjCObjectType(type, { }, protocols, false);
4125 // id<protocol-list>
4126 if (type->isObjCIdType()) {
4127 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4128 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4129 objPtr->isKindOfType());
4130 return getObjCObjectPointerType(type);
4133 // Class<protocol-list>
4134 if (type->isObjCClassType()) {
4135 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4136 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4137 objPtr->isKindOfType());
4138 return getObjCObjectPointerType(type);
4146 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4147 ArrayRef<ObjCProtocolDecl *> protocols,
4148 QualType Canonical) const {
4149 // Look in the folding set for an existing type.
4150 llvm::FoldingSetNodeID ID;
4151 ObjCTypeParamType::Profile(ID, Decl, protocols);
4152 void *InsertPos = nullptr;
4153 if (ObjCTypeParamType *TypeParam =
4154 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4155 return QualType(TypeParam, 0);
4157 if (Canonical.isNull()) {
4158 // We canonicalize to the underlying type.
4159 Canonical = getCanonicalType(Decl->getUnderlyingType());
4160 if (!protocols.empty()) {
4161 // Apply the protocol qualifers.
4163 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4164 true/*allowOnPointerType*/);
4165 assert(!hasError && "Error when apply protocol qualifier to bound type");
4169 unsigned size = sizeof(ObjCTypeParamType);
4170 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4171 void *mem = Allocate(size, TypeAlignment);
4172 ObjCTypeParamType *newType = new (mem)
4173 ObjCTypeParamType(Decl, Canonical, protocols);
4175 Types.push_back(newType);
4176 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4177 return QualType(newType, 0);
4180 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4181 /// protocol list adopt all protocols in QT's qualified-id protocol
4183 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4184 ObjCInterfaceDecl *IC) {
4185 if (!QT->isObjCQualifiedIdType())
4188 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4189 // If both the right and left sides have qualifiers.
4190 for (auto *Proto : OPT->quals()) {
4191 if (!IC->ClassImplementsProtocol(Proto, false))
4199 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4200 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4202 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4203 ObjCInterfaceDecl *IDecl) {
4204 if (!QT->isObjCQualifiedIdType())
4206 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4209 if (!IDecl->hasDefinition())
4211 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4212 CollectInheritedProtocols(IDecl, InheritedProtocols);
4213 if (InheritedProtocols.empty())
4215 // Check that if every protocol in list of id<plist> conforms to a protcol
4216 // of IDecl's, then bridge casting is ok.
4217 bool Conforms = false;
4218 for (auto *Proto : OPT->quals()) {
4220 for (auto *PI : InheritedProtocols) {
4221 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4232 for (auto *PI : InheritedProtocols) {
4233 // If both the right and left sides have qualifiers.
4234 bool Adopts = false;
4235 for (auto *Proto : OPT->quals()) {
4236 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4237 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4246 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4247 /// the given object type.
4248 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4249 llvm::FoldingSetNodeID ID;
4250 ObjCObjectPointerType::Profile(ID, ObjectT);
4252 void *InsertPos = nullptr;
4253 if (ObjCObjectPointerType *QT =
4254 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4255 return QualType(QT, 0);
4257 // Find the canonical object type.
4259 if (!ObjectT.isCanonical()) {
4260 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4262 // Regenerate InsertPos.
4263 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4267 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4268 ObjCObjectPointerType *QType =
4269 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4271 Types.push_back(QType);
4272 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4273 return QualType(QType, 0);
4276 /// getObjCInterfaceType - Return the unique reference to the type for the
4277 /// specified ObjC interface decl. The list of protocols is optional.
4278 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4279 ObjCInterfaceDecl *PrevDecl) const {
4280 if (Decl->TypeForDecl)
4281 return QualType(Decl->TypeForDecl, 0);
4284 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4285 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4286 return QualType(PrevDecl->TypeForDecl, 0);
4289 // Prefer the definition, if there is one.
4290 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4293 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4294 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4295 Decl->TypeForDecl = T;
4297 return QualType(T, 0);
4300 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4301 /// TypeOfExprType AST's (since expression's are never shared). For example,
4302 /// multiple declarations that refer to "typeof(x)" all contain different
4303 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4304 /// on canonical type's (which are always unique).
4305 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4306 TypeOfExprType *toe;
4307 if (tofExpr->isTypeDependent()) {
4308 llvm::FoldingSetNodeID ID;
4309 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4311 void *InsertPos = nullptr;
4312 DependentTypeOfExprType *Canon
4313 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4315 // We already have a "canonical" version of an identical, dependent
4316 // typeof(expr) type. Use that as our canonical type.
4317 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4318 QualType((TypeOfExprType*)Canon, 0));
4320 // Build a new, canonical typeof(expr) type.
4322 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4323 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4327 QualType Canonical = getCanonicalType(tofExpr->getType());
4328 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4330 Types.push_back(toe);
4331 return QualType(toe, 0);
4334 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4335 /// TypeOfType nodes. The only motivation to unique these nodes would be
4336 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4337 /// an issue. This doesn't affect the type checker, since it operates
4338 /// on canonical types (which are always unique).
4339 QualType ASTContext::getTypeOfType(QualType tofType) const {
4340 QualType Canonical = getCanonicalType(tofType);
4341 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4342 Types.push_back(tot);
4343 return QualType(tot, 0);
4346 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4347 /// nodes. This would never be helpful, since each such type has its own
4348 /// expression, and would not give a significant memory saving, since there
4349 /// is an Expr tree under each such type.
4350 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4353 // C++11 [temp.type]p2:
4354 // If an expression e involves a template parameter, decltype(e) denotes a
4355 // unique dependent type. Two such decltype-specifiers refer to the same
4356 // type only if their expressions are equivalent (14.5.6.1).
4357 if (e->isInstantiationDependent()) {
4358 llvm::FoldingSetNodeID ID;
4359 DependentDecltypeType::Profile(ID, *this, e);
4361 void *InsertPos = nullptr;
4362 DependentDecltypeType *Canon
4363 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4365 // Build a new, canonical decltype(expr) type.
4366 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4367 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4369 dt = new (*this, TypeAlignment)
4370 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4372 dt = new (*this, TypeAlignment)
4373 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4375 Types.push_back(dt);
4376 return QualType(dt, 0);
4379 /// getUnaryTransformationType - We don't unique these, since the memory
4380 /// savings are minimal and these are rare.
4381 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4382 QualType UnderlyingType,
4383 UnaryTransformType::UTTKind Kind)
4385 UnaryTransformType *ut = nullptr;
4387 if (BaseType->isDependentType()) {
4388 // Look in the folding set for an existing type.
4389 llvm::FoldingSetNodeID ID;
4390 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4392 void *InsertPos = nullptr;
4393 DependentUnaryTransformType *Canon
4394 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4397 // Build a new, canonical __underlying_type(type) type.
4398 Canon = new (*this, TypeAlignment)
4399 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4401 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4403 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4405 QualType(Canon, 0));
4407 QualType CanonType = getCanonicalType(UnderlyingType);
4408 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4409 UnderlyingType, Kind,
4412 Types.push_back(ut);
4413 return QualType(ut, 0);
4416 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4417 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4418 /// canonical deduced-but-dependent 'auto' type.
4419 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4420 bool IsDependent) const {
4421 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4422 return getAutoDeductType();
4424 // Look in the folding set for an existing type.
4425 void *InsertPos = nullptr;
4426 llvm::FoldingSetNodeID ID;
4427 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4428 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4429 return QualType(AT, 0);
4431 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4434 Types.push_back(AT);
4436 AutoTypes.InsertNode(AT, InsertPos);
4437 return QualType(AT, 0);
4440 /// getAtomicType - Return the uniqued reference to the atomic type for
4441 /// the given value type.
4442 QualType ASTContext::getAtomicType(QualType T) const {
4443 // Unique pointers, to guarantee there is only one pointer of a particular
4445 llvm::FoldingSetNodeID ID;
4446 AtomicType::Profile(ID, T);
4448 void *InsertPos = nullptr;
4449 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4450 return QualType(AT, 0);
4452 // If the atomic value type isn't canonical, this won't be a canonical type
4453 // either, so fill in the canonical type field.
4455 if (!T.isCanonical()) {
4456 Canonical = getAtomicType(getCanonicalType(T));
4458 // Get the new insert position for the node we care about.
4459 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4460 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4462 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4463 Types.push_back(New);
4464 AtomicTypes.InsertNode(New, InsertPos);
4465 return QualType(New, 0);
4468 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4469 QualType ASTContext::getAutoDeductType() const {
4470 if (AutoDeductTy.isNull())
4471 AutoDeductTy = QualType(
4472 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4473 /*dependent*/false),
4475 return AutoDeductTy;
4478 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4479 QualType ASTContext::getAutoRRefDeductType() const {
4480 if (AutoRRefDeductTy.isNull())
4481 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4482 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4483 return AutoRRefDeductTy;
4486 /// getTagDeclType - Return the unique reference to the type for the
4487 /// specified TagDecl (struct/union/class/enum) decl.
4488 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4490 // FIXME: What is the design on getTagDeclType when it requires casting
4491 // away const? mutable?
4492 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4495 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4496 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4497 /// needs to agree with the definition in <stddef.h>.
4498 CanQualType ASTContext::getSizeType() const {
4499 return getFromTargetType(Target->getSizeType());
4502 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4503 CanQualType ASTContext::getIntMaxType() const {
4504 return getFromTargetType(Target->getIntMaxType());
4507 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4508 CanQualType ASTContext::getUIntMaxType() const {
4509 return getFromTargetType(Target->getUIntMaxType());
4512 /// getSignedWCharType - Return the type of "signed wchar_t".
4513 /// Used when in C++, as a GCC extension.
4514 QualType ASTContext::getSignedWCharType() const {
4515 // FIXME: derive from "Target" ?
4519 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4520 /// Used when in C++, as a GCC extension.
4521 QualType ASTContext::getUnsignedWCharType() const {
4522 // FIXME: derive from "Target" ?
4523 return UnsignedIntTy;
4526 QualType ASTContext::getIntPtrType() const {
4527 return getFromTargetType(Target->getIntPtrType());
4530 QualType ASTContext::getUIntPtrType() const {
4531 return getCorrespondingUnsignedType(getIntPtrType());
4534 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4535 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4536 QualType ASTContext::getPointerDiffType() const {
4537 return getFromTargetType(Target->getPtrDiffType(0));
4540 /// \brief Return the unique type for "pid_t" defined in
4541 /// <sys/types.h>. We need this to compute the correct type for vfork().
4542 QualType ASTContext::getProcessIDType() const {
4543 return getFromTargetType(Target->getProcessIDType());
4546 //===----------------------------------------------------------------------===//
4548 //===----------------------------------------------------------------------===//
4550 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4551 // Push qualifiers into arrays, and then discard any remaining
4553 T = getCanonicalType(T);
4554 T = getVariableArrayDecayedType(T);
4555 const Type *Ty = T.getTypePtr();
4557 if (isa<ArrayType>(Ty)) {
4558 Result = getArrayDecayedType(QualType(Ty,0));
4559 } else if (isa<FunctionType>(Ty)) {
4560 Result = getPointerType(QualType(Ty, 0));
4562 Result = QualType(Ty, 0);
4565 return CanQualType::CreateUnsafe(Result);
4568 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4569 Qualifiers &quals) {
4570 SplitQualType splitType = type.getSplitUnqualifiedType();
4572 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4573 // the unqualified desugared type and then drops it on the floor.
4574 // We then have to strip that sugar back off with
4575 // getUnqualifiedDesugaredType(), which is silly.
4576 const ArrayType *AT =
4577 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4579 // If we don't have an array, just use the results in splitType.
4581 quals = splitType.Quals;
4582 return QualType(splitType.Ty, 0);
4585 // Otherwise, recurse on the array's element type.
4586 QualType elementType = AT->getElementType();
4587 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4589 // If that didn't change the element type, AT has no qualifiers, so we
4590 // can just use the results in splitType.
4591 if (elementType == unqualElementType) {
4592 assert(quals.empty()); // from the recursive call
4593 quals = splitType.Quals;
4594 return QualType(splitType.Ty, 0);
4597 // Otherwise, add in the qualifiers from the outermost type, then
4598 // build the type back up.
4599 quals.addConsistentQualifiers(splitType.Quals);
4601 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4602 return getConstantArrayType(unqualElementType, CAT->getSize(),
4603 CAT->getSizeModifier(), 0);
4606 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4607 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4610 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4611 return getVariableArrayType(unqualElementType,
4613 VAT->getSizeModifier(),
4614 VAT->getIndexTypeCVRQualifiers(),
4615 VAT->getBracketsRange());
4618 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4619 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4620 DSAT->getSizeModifier(), 0,
4624 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4625 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4626 /// they point to and return true. If T1 and T2 aren't pointer types
4627 /// or pointer-to-member types, or if they are not similar at this
4628 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4629 /// qualifiers on T1 and T2 are ignored. This function will typically
4630 /// be called in a loop that successively "unwraps" pointer and
4631 /// pointer-to-member types to compare them at each level.
4632 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4633 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4634 *T2PtrType = T2->getAs<PointerType>();
4635 if (T1PtrType && T2PtrType) {
4636 T1 = T1PtrType->getPointeeType();
4637 T2 = T2PtrType->getPointeeType();
4641 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4642 *T2MPType = T2->getAs<MemberPointerType>();
4643 if (T1MPType && T2MPType &&
4644 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4645 QualType(T2MPType->getClass(), 0))) {
4646 T1 = T1MPType->getPointeeType();
4647 T2 = T2MPType->getPointeeType();
4651 if (getLangOpts().ObjC1) {
4652 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4653 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4654 if (T1OPType && T2OPType) {
4655 T1 = T1OPType->getPointeeType();
4656 T2 = T2OPType->getPointeeType();
4661 // FIXME: Block pointers, too?
4667 ASTContext::getNameForTemplate(TemplateName Name,
4668 SourceLocation NameLoc) const {
4669 switch (Name.getKind()) {
4670 case TemplateName::QualifiedTemplate:
4671 case TemplateName::Template:
4672 // DNInfo work in progress: CHECKME: what about DNLoc?
4673 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4676 case TemplateName::OverloadedTemplate: {
4677 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4678 // DNInfo work in progress: CHECKME: what about DNLoc?
4679 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4682 case TemplateName::DependentTemplate: {
4683 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4684 DeclarationName DName;
4685 if (DTN->isIdentifier()) {
4686 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4687 return DeclarationNameInfo(DName, NameLoc);
4689 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4690 // DNInfo work in progress: FIXME: source locations?
4691 DeclarationNameLoc DNLoc;
4692 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4693 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4694 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4698 case TemplateName::SubstTemplateTemplateParm: {
4699 SubstTemplateTemplateParmStorage *subst
4700 = Name.getAsSubstTemplateTemplateParm();
4701 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4705 case TemplateName::SubstTemplateTemplateParmPack: {
4706 SubstTemplateTemplateParmPackStorage *subst
4707 = Name.getAsSubstTemplateTemplateParmPack();
4708 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4713 llvm_unreachable("bad template name kind!");
4716 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4717 switch (Name.getKind()) {
4718 case TemplateName::QualifiedTemplate:
4719 case TemplateName::Template: {
4720 TemplateDecl *Template = Name.getAsTemplateDecl();
4721 if (TemplateTemplateParmDecl *TTP
4722 = dyn_cast<TemplateTemplateParmDecl>(Template))
4723 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4725 // The canonical template name is the canonical template declaration.
4726 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4729 case TemplateName::OverloadedTemplate:
4730 llvm_unreachable("cannot canonicalize overloaded template");
4732 case TemplateName::DependentTemplate: {
4733 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4734 assert(DTN && "Non-dependent template names must refer to template decls.");
4735 return DTN->CanonicalTemplateName;
4738 case TemplateName::SubstTemplateTemplateParm: {
4739 SubstTemplateTemplateParmStorage *subst
4740 = Name.getAsSubstTemplateTemplateParm();
4741 return getCanonicalTemplateName(subst->getReplacement());
4744 case TemplateName::SubstTemplateTemplateParmPack: {
4745 SubstTemplateTemplateParmPackStorage *subst
4746 = Name.getAsSubstTemplateTemplateParmPack();
4747 TemplateTemplateParmDecl *canonParameter
4748 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4749 TemplateArgument canonArgPack
4750 = getCanonicalTemplateArgument(subst->getArgumentPack());
4751 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4755 llvm_unreachable("bad template name!");
4758 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4759 X = getCanonicalTemplateName(X);
4760 Y = getCanonicalTemplateName(Y);
4761 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4765 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4766 switch (Arg.getKind()) {
4767 case TemplateArgument::Null:
4770 case TemplateArgument::Expression:
4773 case TemplateArgument::Declaration: {
4774 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4775 return TemplateArgument(D, Arg.getParamTypeForDecl());
4778 case TemplateArgument::NullPtr:
4779 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4782 case TemplateArgument::Template:
4783 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4785 case TemplateArgument::TemplateExpansion:
4786 return TemplateArgument(getCanonicalTemplateName(
4787 Arg.getAsTemplateOrTemplatePattern()),
4788 Arg.getNumTemplateExpansions());
4790 case TemplateArgument::Integral:
4791 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4793 case TemplateArgument::Type:
4794 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4796 case TemplateArgument::Pack: {
4797 if (Arg.pack_size() == 0)
4800 TemplateArgument *CanonArgs
4801 = new (*this) TemplateArgument[Arg.pack_size()];
4803 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4804 AEnd = Arg.pack_end();
4805 A != AEnd; (void)++A, ++Idx)
4806 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4808 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4812 // Silence GCC warning
4813 llvm_unreachable("Unhandled template argument kind");
4816 NestedNameSpecifier *
4817 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4821 switch (NNS->getKind()) {
4822 case NestedNameSpecifier::Identifier:
4823 // Canonicalize the prefix but keep the identifier the same.
4824 return NestedNameSpecifier::Create(*this,
4825 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4826 NNS->getAsIdentifier());
4828 case NestedNameSpecifier::Namespace:
4829 // A namespace is canonical; build a nested-name-specifier with
4830 // this namespace and no prefix.
4831 return NestedNameSpecifier::Create(*this, nullptr,
4832 NNS->getAsNamespace()->getOriginalNamespace());
4834 case NestedNameSpecifier::NamespaceAlias:
4835 // A namespace is canonical; build a nested-name-specifier with
4836 // this namespace and no prefix.
4837 return NestedNameSpecifier::Create(*this, nullptr,
4838 NNS->getAsNamespaceAlias()->getNamespace()
4839 ->getOriginalNamespace());
4841 case NestedNameSpecifier::TypeSpec:
4842 case NestedNameSpecifier::TypeSpecWithTemplate: {
4843 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4845 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4846 // break it apart into its prefix and identifier, then reconsititute those
4847 // as the canonical nested-name-specifier. This is required to canonicalize
4848 // a dependent nested-name-specifier involving typedefs of dependent-name
4850 // typedef typename T::type T1;
4851 // typedef typename T1::type T2;
4852 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4853 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4854 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4856 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4857 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4859 return NestedNameSpecifier::Create(*this, nullptr, false,
4860 const_cast<Type *>(T.getTypePtr()));
4863 case NestedNameSpecifier::Global:
4864 case NestedNameSpecifier::Super:
4865 // The global specifier and __super specifer are canonical and unique.
4869 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4872 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4873 // Handle the non-qualified case efficiently.
4874 if (!T.hasLocalQualifiers()) {
4875 // Handle the common positive case fast.
4876 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4880 // Handle the common negative case fast.
4881 if (!isa<ArrayType>(T.getCanonicalType()))
4884 // Apply any qualifiers from the array type to the element type. This
4885 // implements C99 6.7.3p8: "If the specification of an array type includes
4886 // any type qualifiers, the element type is so qualified, not the array type."
4888 // If we get here, we either have type qualifiers on the type, or we have
4889 // sugar such as a typedef in the way. If we have type qualifiers on the type
4890 // we must propagate them down into the element type.
4892 SplitQualType split = T.getSplitDesugaredType();
4893 Qualifiers qs = split.Quals;
4895 // If we have a simple case, just return now.
4896 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4897 if (!ATy || qs.empty())
4900 // Otherwise, we have an array and we have qualifiers on it. Push the
4901 // qualifiers into the array element type and return a new array type.
4902 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4904 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4905 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4906 CAT->getSizeModifier(),
4907 CAT->getIndexTypeCVRQualifiers()));
4908 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4909 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4910 IAT->getSizeModifier(),
4911 IAT->getIndexTypeCVRQualifiers()));
4913 if (const DependentSizedArrayType *DSAT
4914 = dyn_cast<DependentSizedArrayType>(ATy))
4915 return cast<ArrayType>(
4916 getDependentSizedArrayType(NewEltTy,
4917 DSAT->getSizeExpr(),
4918 DSAT->getSizeModifier(),
4919 DSAT->getIndexTypeCVRQualifiers(),
4920 DSAT->getBracketsRange()));
4922 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4923 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4925 VAT->getSizeModifier(),
4926 VAT->getIndexTypeCVRQualifiers(),
4927 VAT->getBracketsRange()));
4930 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4931 if (T->isArrayType() || T->isFunctionType())
4932 return getDecayedType(T);
4936 QualType ASTContext::getSignatureParameterType(QualType T) const {
4937 T = getVariableArrayDecayedType(T);
4938 T = getAdjustedParameterType(T);
4939 return T.getUnqualifiedType();
4942 QualType ASTContext::getExceptionObjectType(QualType T) const {
4943 // C++ [except.throw]p3:
4944 // A throw-expression initializes a temporary object, called the exception
4945 // object, the type of which is determined by removing any top-level
4946 // cv-qualifiers from the static type of the operand of throw and adjusting
4947 // the type from "array of T" or "function returning T" to "pointer to T"
4948 // or "pointer to function returning T", [...]
4949 T = getVariableArrayDecayedType(T);
4950 if (T->isArrayType() || T->isFunctionType())
4951 T = getDecayedType(T);
4952 return T.getUnqualifiedType();
4955 /// getArrayDecayedType - Return the properly qualified result of decaying the
4956 /// specified array type to a pointer. This operation is non-trivial when
4957 /// handling typedefs etc. The canonical type of "T" must be an array type,
4958 /// this returns a pointer to a properly qualified element of the array.
4960 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4961 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4962 // Get the element type with 'getAsArrayType' so that we don't lose any
4963 // typedefs in the element type of the array. This also handles propagation
4964 // of type qualifiers from the array type into the element type if present
4966 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4967 assert(PrettyArrayType && "Not an array type!");
4969 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4971 // int x[restrict 4] -> int *restrict
4972 QualType Result = getQualifiedType(PtrTy,
4973 PrettyArrayType->getIndexTypeQualifiers());
4975 // int x[_Nullable] -> int * _Nullable
4976 if (auto Nullability = Ty->getNullability(*this)) {
4977 Result = const_cast<ASTContext *>(this)->getAttributedType(
4978 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
4983 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4984 return getBaseElementType(array->getElementType());
4987 QualType ASTContext::getBaseElementType(QualType type) const {
4990 SplitQualType split = type.getSplitDesugaredType();
4991 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4994 type = array->getElementType();
4995 qs.addConsistentQualifiers(split.Quals);
4998 return getQualifiedType(type, qs);
5001 /// getConstantArrayElementCount - Returns number of constant array elements.
5003 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5004 uint64_t ElementCount = 1;
5006 ElementCount *= CA->getSize().getZExtValue();
5007 CA = dyn_cast_or_null<ConstantArrayType>(
5008 CA->getElementType()->getAsArrayTypeUnsafe());
5010 return ElementCount;
5013 /// getFloatingRank - Return a relative rank for floating point types.
5014 /// This routine will assert if passed a built-in type that isn't a float.
5015 static FloatingRank getFloatingRank(QualType T) {
5016 if (const ComplexType *CT = T->getAs<ComplexType>())
5017 return getFloatingRank(CT->getElementType());
5019 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5020 switch (T->getAs<BuiltinType>()->getKind()) {
5021 default: llvm_unreachable("getFloatingRank(): not a floating type");
5022 case BuiltinType::Half: return HalfRank;
5023 case BuiltinType::Float: return FloatRank;
5024 case BuiltinType::Double: return DoubleRank;
5025 case BuiltinType::LongDouble: return LongDoubleRank;
5026 case BuiltinType::Float128: return Float128Rank;
5030 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5031 /// point or a complex type (based on typeDomain/typeSize).
5032 /// 'typeDomain' is a real floating point or complex type.
5033 /// 'typeSize' is a real floating point or complex type.
5034 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5035 QualType Domain) const {
5036 FloatingRank EltRank = getFloatingRank(Size);
5037 if (Domain->isComplexType()) {
5039 case HalfRank: llvm_unreachable("Complex half is not supported");
5040 case FloatRank: return FloatComplexTy;
5041 case DoubleRank: return DoubleComplexTy;
5042 case LongDoubleRank: return LongDoubleComplexTy;
5043 case Float128Rank: return Float128ComplexTy;
5047 assert(Domain->isRealFloatingType() && "Unknown domain!");
5049 case HalfRank: return HalfTy;
5050 case FloatRank: return FloatTy;
5051 case DoubleRank: return DoubleTy;
5052 case LongDoubleRank: return LongDoubleTy;
5053 case Float128Rank: return Float128Ty;
5055 llvm_unreachable("getFloatingRank(): illegal value for rank");
5058 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5059 /// point types, ignoring the domain of the type (i.e. 'double' ==
5060 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5061 /// LHS < RHS, return -1.
5062 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5063 FloatingRank LHSR = getFloatingRank(LHS);
5064 FloatingRank RHSR = getFloatingRank(RHS);
5073 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5074 /// routine will assert if passed a built-in type that isn't an integer or enum,
5075 /// or if it is not canonicalized.
5076 unsigned ASTContext::getIntegerRank(const Type *T) const {
5077 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5079 switch (cast<BuiltinType>(T)->getKind()) {
5080 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5081 case BuiltinType::Bool:
5082 return 1 + (getIntWidth(BoolTy) << 3);
5083 case BuiltinType::Char_S:
5084 case BuiltinType::Char_U:
5085 case BuiltinType::SChar:
5086 case BuiltinType::UChar:
5087 return 2 + (getIntWidth(CharTy) << 3);
5088 case BuiltinType::Short:
5089 case BuiltinType::UShort:
5090 return 3 + (getIntWidth(ShortTy) << 3);
5091 case BuiltinType::Int:
5092 case BuiltinType::UInt:
5093 return 4 + (getIntWidth(IntTy) << 3);
5094 case BuiltinType::Long:
5095 case BuiltinType::ULong:
5096 return 5 + (getIntWidth(LongTy) << 3);
5097 case BuiltinType::LongLong:
5098 case BuiltinType::ULongLong:
5099 return 6 + (getIntWidth(LongLongTy) << 3);
5100 case BuiltinType::Int128:
5101 case BuiltinType::UInt128:
5102 return 7 + (getIntWidth(Int128Ty) << 3);
5106 /// \brief Whether this is a promotable bitfield reference according
5107 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5109 /// \returns the type this bit-field will promote to, or NULL if no
5110 /// promotion occurs.
5111 QualType ASTContext::isPromotableBitField(Expr *E) const {
5112 if (E->isTypeDependent() || E->isValueDependent())
5115 // FIXME: We should not do this unless E->refersToBitField() is true. This
5116 // matters in C where getSourceBitField() will find bit-fields for various
5117 // cases where the source expression is not a bit-field designator.
5119 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5123 QualType FT = Field->getType();
5125 uint64_t BitWidth = Field->getBitWidthValue(*this);
5126 uint64_t IntSize = getTypeSize(IntTy);
5127 // C++ [conv.prom]p5:
5128 // A prvalue for an integral bit-field can be converted to a prvalue of type
5129 // int if int can represent all the values of the bit-field; otherwise, it
5130 // can be converted to unsigned int if unsigned int can represent all the
5131 // values of the bit-field. If the bit-field is larger yet, no integral
5132 // promotion applies to it.
5134 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5135 // If an int can represent all values of the original type (as restricted by
5136 // the width, for a bit-field), the value is converted to an int; otherwise,
5137 // it is converted to an unsigned int.
5139 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5140 // We perform that promotion here to match GCC and C++.
5141 if (BitWidth < IntSize)
5144 if (BitWidth == IntSize)
5145 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5147 // Types bigger than int are not subject to promotions, and therefore act
5148 // like the base type. GCC has some weird bugs in this area that we
5149 // deliberately do not follow (GCC follows a pre-standard resolution to
5150 // C's DR315 which treats bit-width as being part of the type, and this leaks
5151 // into their semantics in some cases).
5155 /// getPromotedIntegerType - Returns the type that Promotable will
5156 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5158 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5159 assert(!Promotable.isNull());
5160 assert(Promotable->isPromotableIntegerType());
5161 if (const EnumType *ET = Promotable->getAs<EnumType>())
5162 return ET->getDecl()->getPromotionType();
5164 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5165 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5166 // (3.9.1) can be converted to a prvalue of the first of the following
5167 // types that can represent all the values of its underlying type:
5168 // int, unsigned int, long int, unsigned long int, long long int, or
5169 // unsigned long long int [...]
5170 // FIXME: Is there some better way to compute this?
5171 if (BT->getKind() == BuiltinType::WChar_S ||
5172 BT->getKind() == BuiltinType::WChar_U ||
5173 BT->getKind() == BuiltinType::Char16 ||
5174 BT->getKind() == BuiltinType::Char32) {
5175 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5176 uint64_t FromSize = getTypeSize(BT);
5177 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5178 LongLongTy, UnsignedLongLongTy };
5179 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5180 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5181 if (FromSize < ToSize ||
5182 (FromSize == ToSize &&
5183 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5184 return PromoteTypes[Idx];
5186 llvm_unreachable("char type should fit into long long");
5190 // At this point, we should have a signed or unsigned integer type.
5191 if (Promotable->isSignedIntegerType())
5193 uint64_t PromotableSize = getIntWidth(Promotable);
5194 uint64_t IntSize = getIntWidth(IntTy);
5195 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5196 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5199 /// \brief Recurses in pointer/array types until it finds an objc retainable
5200 /// type and returns its ownership.
5201 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5202 while (!T.isNull()) {
5203 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5204 return T.getObjCLifetime();
5205 if (T->isArrayType())
5206 T = getBaseElementType(T);
5207 else if (const PointerType *PT = T->getAs<PointerType>())
5208 T = PT->getPointeeType();
5209 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
5210 T = RT->getPointeeType();
5215 return Qualifiers::OCL_None;
5218 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5219 // Incomplete enum types are not treated as integer types.
5220 // FIXME: In C++, enum types are never integer types.
5221 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5222 return ET->getDecl()->getIntegerType().getTypePtr();
5226 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5227 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5228 /// LHS < RHS, return -1.
5229 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5230 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5231 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5233 // Unwrap enums to their underlying type.
5234 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5235 LHSC = getIntegerTypeForEnum(ET);
5236 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5237 RHSC = getIntegerTypeForEnum(ET);
5239 if (LHSC == RHSC) return 0;
5241 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5242 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5244 unsigned LHSRank = getIntegerRank(LHSC);
5245 unsigned RHSRank = getIntegerRank(RHSC);
5247 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5248 if (LHSRank == RHSRank) return 0;
5249 return LHSRank > RHSRank ? 1 : -1;
5252 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5254 // If the unsigned [LHS] type is larger, return it.
5255 if (LHSRank >= RHSRank)
5258 // If the signed type can represent all values of the unsigned type, it
5259 // wins. Because we are dealing with 2's complement and types that are
5260 // powers of two larger than each other, this is always safe.
5264 // If the unsigned [RHS] type is larger, return it.
5265 if (RHSRank >= LHSRank)
5268 // If the signed type can represent all values of the unsigned type, it
5269 // wins. Because we are dealing with 2's complement and types that are
5270 // powers of two larger than each other, this is always safe.
5274 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5275 if (!CFConstantStringTypeDecl) {
5276 assert(!CFConstantStringTagDecl &&
5277 "tag and typedef should be initialized together");
5278 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5279 CFConstantStringTagDecl->startDefinition();
5281 QualType FieldTypes[4];
5282 const char *FieldNames[4];
5285 FieldTypes[0] = getPointerType(IntTy.withConst());
5286 FieldNames[0] = "isa";
5288 FieldTypes[1] = IntTy;
5289 FieldNames[1] = "flags";
5291 FieldTypes[2] = getPointerType(CharTy.withConst());
5292 FieldNames[2] = "str";
5294 FieldTypes[3] = LongTy;
5295 FieldNames[3] = "length";
5298 for (unsigned i = 0; i < 4; ++i) {
5299 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5302 &Idents.get(FieldNames[i]),
5303 FieldTypes[i], /*TInfo=*/nullptr,
5304 /*BitWidth=*/nullptr,
5307 Field->setAccess(AS_public);
5308 CFConstantStringTagDecl->addDecl(Field);
5311 CFConstantStringTagDecl->completeDefinition();
5312 // This type is designed to be compatible with NSConstantString, but cannot
5313 // use the same name, since NSConstantString is an interface.
5314 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5315 CFConstantStringTypeDecl =
5316 buildImplicitTypedef(tagType, "__NSConstantString");
5319 return CFConstantStringTypeDecl;
5322 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5323 if (!CFConstantStringTagDecl)
5324 getCFConstantStringDecl(); // Build the tag and the typedef.
5325 return CFConstantStringTagDecl;
5328 // getCFConstantStringType - Return the type used for constant CFStrings.
5329 QualType ASTContext::getCFConstantStringType() const {
5330 return getTypedefType(getCFConstantStringDecl());
5333 QualType ASTContext::getObjCSuperType() const {
5334 if (ObjCSuperType.isNull()) {
5335 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5336 TUDecl->addDecl(ObjCSuperTypeDecl);
5337 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5339 return ObjCSuperType;
5342 void ASTContext::setCFConstantStringType(QualType T) {
5343 const TypedefType *TD = T->getAs<TypedefType>();
5344 assert(TD && "Invalid CFConstantStringType");
5345 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5347 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5348 assert(TagType && "Invalid CFConstantStringType");
5349 CFConstantStringTagDecl = TagType->getDecl();
5352 QualType ASTContext::getBlockDescriptorType() const {
5353 if (BlockDescriptorType)
5354 return getTagDeclType(BlockDescriptorType);
5357 // FIXME: Needs the FlagAppleBlock bit.
5358 RD = buildImplicitRecord("__block_descriptor");
5359 RD->startDefinition();
5361 QualType FieldTypes[] = {
5366 static const char *const FieldNames[] = {
5371 for (size_t i = 0; i < 2; ++i) {
5372 FieldDecl *Field = FieldDecl::Create(
5373 *this, RD, SourceLocation(), SourceLocation(),
5374 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5375 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5376 Field->setAccess(AS_public);
5380 RD->completeDefinition();
5382 BlockDescriptorType = RD;
5384 return getTagDeclType(BlockDescriptorType);
5387 QualType ASTContext::getBlockDescriptorExtendedType() const {
5388 if (BlockDescriptorExtendedType)
5389 return getTagDeclType(BlockDescriptorExtendedType);
5392 // FIXME: Needs the FlagAppleBlock bit.
5393 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5394 RD->startDefinition();
5396 QualType FieldTypes[] = {
5399 getPointerType(VoidPtrTy),
5400 getPointerType(VoidPtrTy)
5403 static const char *const FieldNames[] = {
5410 for (size_t i = 0; i < 4; ++i) {
5411 FieldDecl *Field = FieldDecl::Create(
5412 *this, RD, SourceLocation(), SourceLocation(),
5413 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5414 /*BitWidth=*/nullptr,
5415 /*Mutable=*/false, ICIS_NoInit);
5416 Field->setAccess(AS_public);
5420 RD->completeDefinition();
5422 BlockDescriptorExtendedType = RD;
5423 return getTagDeclType(BlockDescriptorExtendedType);
5426 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5427 /// requires copy/dispose. Note that this must match the logic
5428 /// in buildByrefHelpers.
5429 bool ASTContext::BlockRequiresCopying(QualType Ty,
5431 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5432 const Expr *copyExpr = getBlockVarCopyInits(D);
5433 if (!copyExpr && record->hasTrivialDestructor()) return false;
5438 if (!Ty->isObjCRetainableType()) return false;
5440 Qualifiers qs = Ty.getQualifiers();
5442 // If we have lifetime, that dominates.
5443 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5445 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5447 // These are just bits as far as the runtime is concerned.
5448 case Qualifiers::OCL_ExplicitNone:
5449 case Qualifiers::OCL_Autoreleasing:
5452 // Tell the runtime that this is ARC __weak, called by the
5454 case Qualifiers::OCL_Weak:
5455 // ARC __strong __block variables need to be retained.
5456 case Qualifiers::OCL_Strong:
5459 llvm_unreachable("fell out of lifetime switch!");
5461 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5462 Ty->isObjCObjectPointerType());
5465 bool ASTContext::getByrefLifetime(QualType Ty,
5466 Qualifiers::ObjCLifetime &LifeTime,
5467 bool &HasByrefExtendedLayout) const {
5469 if (!getLangOpts().ObjC1 ||
5470 getLangOpts().getGC() != LangOptions::NonGC)
5473 HasByrefExtendedLayout = false;
5474 if (Ty->isRecordType()) {
5475 HasByrefExtendedLayout = true;
5476 LifeTime = Qualifiers::OCL_None;
5477 } else if ((LifeTime = Ty.getObjCLifetime())) {
5478 // Honor the ARC qualifiers.
5479 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5481 LifeTime = Qualifiers::OCL_ExplicitNone;
5483 LifeTime = Qualifiers::OCL_None;
5488 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5489 if (!ObjCInstanceTypeDecl)
5490 ObjCInstanceTypeDecl =
5491 buildImplicitTypedef(getObjCIdType(), "instancetype");
5492 return ObjCInstanceTypeDecl;
5495 // This returns true if a type has been typedefed to BOOL:
5496 // typedef <type> BOOL;
5497 static bool isTypeTypedefedAsBOOL(QualType T) {
5498 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5499 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5500 return II->isStr("BOOL");
5505 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5507 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5508 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5509 return CharUnits::Zero();
5511 CharUnits sz = getTypeSizeInChars(type);
5513 // Make all integer and enum types at least as large as an int
5514 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5515 sz = std::max(sz, getTypeSizeInChars(IntTy));
5516 // Treat arrays as pointers, since that's how they're passed in.
5517 else if (type->isArrayType())
5518 sz = getTypeSizeInChars(VoidPtrTy);
5522 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5523 return getTargetInfo().getCXXABI().isMicrosoft() &&
5524 VD->isStaticDataMember() &&
5525 VD->getType()->isIntegralOrEnumerationType() &&
5526 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5529 ASTContext::InlineVariableDefinitionKind
5530 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5531 if (!VD->isInline())
5532 return InlineVariableDefinitionKind::None;
5534 // In almost all cases, it's a weak definition.
5535 auto *First = VD->getFirstDecl();
5536 if (!First->isConstexpr() || First->isInlineSpecified() ||
5537 !VD->isStaticDataMember())
5538 return InlineVariableDefinitionKind::Weak;
5540 // If there's a file-context declaration in this translation unit, it's a
5541 // non-discardable definition.
5542 for (auto *D : VD->redecls())
5543 if (D->getLexicalDeclContext()->isFileContext())
5544 return InlineVariableDefinitionKind::Strong;
5546 // If we've not seen one yet, we don't know.
5547 return InlineVariableDefinitionKind::WeakUnknown;
5551 std::string charUnitsToString(const CharUnits &CU) {
5552 return llvm::itostr(CU.getQuantity());
5555 /// getObjCEncodingForBlock - Return the encoded type for this block
5557 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5560 const BlockDecl *Decl = Expr->getBlockDecl();
5562 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5563 // Encode result type.
5564 if (getLangOpts().EncodeExtendedBlockSig)
5565 getObjCEncodingForMethodParameter(
5566 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5569 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5570 // Compute size of all parameters.
5571 // Start with computing size of a pointer in number of bytes.
5572 // FIXME: There might(should) be a better way of doing this computation!
5574 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5575 CharUnits ParmOffset = PtrSize;
5576 for (auto PI : Decl->parameters()) {
5577 QualType PType = PI->getType();
5578 CharUnits sz = getObjCEncodingTypeSize(PType);
5581 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5584 // Size of the argument frame
5585 S += charUnitsToString(ParmOffset);
5586 // Block pointer and offset.
5590 ParmOffset = PtrSize;
5591 for (auto PVDecl : Decl->parameters()) {
5592 QualType PType = PVDecl->getOriginalType();
5593 if (const ArrayType *AT =
5594 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5595 // Use array's original type only if it has known number of
5597 if (!isa<ConstantArrayType>(AT))
5598 PType = PVDecl->getType();
5599 } else if (PType->isFunctionType())
5600 PType = PVDecl->getType();
5601 if (getLangOpts().EncodeExtendedBlockSig)
5602 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5603 S, true /*Extended*/);
5605 getObjCEncodingForType(PType, S);
5606 S += charUnitsToString(ParmOffset);
5607 ParmOffset += getObjCEncodingTypeSize(PType);
5614 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5616 // Encode result type.
5617 getObjCEncodingForType(Decl->getReturnType(), S);
5618 CharUnits ParmOffset;
5619 // Compute size of all parameters.
5620 for (auto PI : Decl->parameters()) {
5621 QualType PType = PI->getType();
5622 CharUnits sz = getObjCEncodingTypeSize(PType);
5626 assert(sz.isPositive() &&
5627 "getObjCEncodingForFunctionDecl - Incomplete param type");
5630 S += charUnitsToString(ParmOffset);
5631 ParmOffset = CharUnits::Zero();
5634 for (auto PVDecl : Decl->parameters()) {
5635 QualType PType = PVDecl->getOriginalType();
5636 if (const ArrayType *AT =
5637 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5638 // Use array's original type only if it has known number of
5640 if (!isa<ConstantArrayType>(AT))
5641 PType = PVDecl->getType();
5642 } else if (PType->isFunctionType())
5643 PType = PVDecl->getType();
5644 getObjCEncodingForType(PType, S);
5645 S += charUnitsToString(ParmOffset);
5646 ParmOffset += getObjCEncodingTypeSize(PType);
5652 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5653 /// method parameter or return type. If Extended, include class names and
5654 /// block object types.
5655 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5656 QualType T, std::string& S,
5657 bool Extended) const {
5658 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5659 getObjCEncodingForTypeQualifier(QT, S);
5660 // Encode parameter type.
5661 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5662 true /*OutermostType*/,
5663 false /*EncodingProperty*/,
5664 false /*StructField*/,
5665 Extended /*EncodeBlockParameters*/,
5666 Extended /*EncodeClassNames*/);
5669 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5671 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5672 bool Extended) const {
5673 // FIXME: This is not very efficient.
5674 // Encode return type.
5676 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5677 Decl->getReturnType(), S, Extended);
5678 // Compute size of all parameters.
5679 // Start with computing size of a pointer in number of bytes.
5680 // FIXME: There might(should) be a better way of doing this computation!
5682 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5683 // The first two arguments (self and _cmd) are pointers; account for
5685 CharUnits ParmOffset = 2 * PtrSize;
5686 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5687 E = Decl->sel_param_end(); PI != E; ++PI) {
5688 QualType PType = (*PI)->getType();
5689 CharUnits sz = getObjCEncodingTypeSize(PType);
5693 assert (sz.isPositive() &&
5694 "getObjCEncodingForMethodDecl - Incomplete param type");
5697 S += charUnitsToString(ParmOffset);
5699 S += charUnitsToString(PtrSize);
5702 ParmOffset = 2 * PtrSize;
5703 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5704 E = Decl->sel_param_end(); PI != E; ++PI) {
5705 const ParmVarDecl *PVDecl = *PI;
5706 QualType PType = PVDecl->getOriginalType();
5707 if (const ArrayType *AT =
5708 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5709 // Use array's original type only if it has known number of
5711 if (!isa<ConstantArrayType>(AT))
5712 PType = PVDecl->getType();
5713 } else if (PType->isFunctionType())
5714 PType = PVDecl->getType();
5715 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5716 PType, S, Extended);
5717 S += charUnitsToString(ParmOffset);
5718 ParmOffset += getObjCEncodingTypeSize(PType);
5724 ObjCPropertyImplDecl *
5725 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5726 const ObjCPropertyDecl *PD,
5727 const Decl *Container) const {
5730 if (const ObjCCategoryImplDecl *CID =
5731 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5732 for (auto *PID : CID->property_impls())
5733 if (PID->getPropertyDecl() == PD)
5736 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5737 for (auto *PID : OID->property_impls())
5738 if (PID->getPropertyDecl() == PD)
5744 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5745 /// property declaration. If non-NULL, Container must be either an
5746 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5747 /// NULL when getting encodings for protocol properties.
5748 /// Property attributes are stored as a comma-delimited C string. The simple
5749 /// attributes readonly and bycopy are encoded as single characters. The
5750 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5751 /// encoded as single characters, followed by an identifier. Property types
5752 /// are also encoded as a parametrized attribute. The characters used to encode
5753 /// these attributes are defined by the following enumeration:
5755 /// enum PropertyAttributes {
5756 /// kPropertyReadOnly = 'R', // property is read-only.
5757 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5758 /// kPropertyByref = '&', // property is a reference to the value last assigned
5759 /// kPropertyDynamic = 'D', // property is dynamic
5760 /// kPropertyGetter = 'G', // followed by getter selector name
5761 /// kPropertySetter = 'S', // followed by setter selector name
5762 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5763 /// kPropertyType = 'T' // followed by old-style type encoding.
5764 /// kPropertyWeak = 'W' // 'weak' property
5765 /// kPropertyStrong = 'P' // property GC'able
5766 /// kPropertyNonAtomic = 'N' // property non-atomic
5770 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5771 const Decl *Container) const {
5772 // Collect information from the property implementation decl(s).
5773 bool Dynamic = false;
5774 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5776 if (ObjCPropertyImplDecl *PropertyImpDecl =
5777 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5778 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5781 SynthesizePID = PropertyImpDecl;
5784 // FIXME: This is not very efficient.
5785 std::string S = "T";
5787 // Encode result type.
5788 // GCC has some special rules regarding encoding of properties which
5789 // closely resembles encoding of ivars.
5790 getObjCEncodingForPropertyType(PD->getType(), S);
5792 if (PD->isReadOnly()) {
5794 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5798 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5801 switch (PD->getSetterKind()) {
5802 case ObjCPropertyDecl::Assign: break;
5803 case ObjCPropertyDecl::Copy: S += ",C"; break;
5804 case ObjCPropertyDecl::Retain: S += ",&"; break;
5805 case ObjCPropertyDecl::Weak: S += ",W"; break;
5809 // It really isn't clear at all what this means, since properties
5810 // are "dynamic by default".
5814 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5817 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5819 S += PD->getGetterName().getAsString();
5822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5824 S += PD->getSetterName().getAsString();
5827 if (SynthesizePID) {
5828 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5830 S += OID->getNameAsString();
5833 // FIXME: OBJCGC: weak & strong
5837 /// getLegacyIntegralTypeEncoding -
5838 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5839 /// 'l' or 'L' , but not always. For typedefs, we need to use
5840 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5842 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5843 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5844 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5845 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5846 PointeeTy = UnsignedIntTy;
5848 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5854 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5855 const FieldDecl *Field,
5856 QualType *NotEncodedT) const {
5857 // We follow the behavior of gcc, expanding structures which are
5858 // directly pointed to, and expanding embedded structures. Note that
5859 // these rules are sufficient to prevent recursive encoding of the
5861 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5862 true /* outermost type */, false, false,
5863 false, false, false, NotEncodedT);
5866 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5867 std::string& S) const {
5868 // Encode result type.
5869 // GCC has some special rules regarding encoding of properties which
5870 // closely resembles encoding of ivars.
5871 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5872 true /* outermost type */,
5873 true /* encoding property */);
5876 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5877 BuiltinType::Kind kind) {
5879 case BuiltinType::Void: return 'v';
5880 case BuiltinType::Bool: return 'B';
5881 case BuiltinType::Char_U:
5882 case BuiltinType::UChar: return 'C';
5883 case BuiltinType::Char16:
5884 case BuiltinType::UShort: return 'S';
5885 case BuiltinType::Char32:
5886 case BuiltinType::UInt: return 'I';
5887 case BuiltinType::ULong:
5888 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5889 case BuiltinType::UInt128: return 'T';
5890 case BuiltinType::ULongLong: return 'Q';
5891 case BuiltinType::Char_S:
5892 case BuiltinType::SChar: return 'c';
5893 case BuiltinType::Short: return 's';
5894 case BuiltinType::WChar_S:
5895 case BuiltinType::WChar_U:
5896 case BuiltinType::Int: return 'i';
5897 case BuiltinType::Long:
5898 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5899 case BuiltinType::LongLong: return 'q';
5900 case BuiltinType::Int128: return 't';
5901 case BuiltinType::Float: return 'f';
5902 case BuiltinType::Double: return 'd';
5903 case BuiltinType::LongDouble: return 'D';
5904 case BuiltinType::NullPtr: return '*'; // like char*
5906 case BuiltinType::Float128:
5907 case BuiltinType::Half:
5908 // FIXME: potentially need @encodes for these!
5911 case BuiltinType::ObjCId:
5912 case BuiltinType::ObjCClass:
5913 case BuiltinType::ObjCSel:
5914 llvm_unreachable("@encoding ObjC primitive type");
5916 // OpenCL and placeholder types don't need @encodings.
5917 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5918 case BuiltinType::Id:
5919 #include "clang/Basic/OpenCLImageTypes.def"
5920 case BuiltinType::OCLEvent:
5921 case BuiltinType::OCLClkEvent:
5922 case BuiltinType::OCLQueue:
5923 case BuiltinType::OCLNDRange:
5924 case BuiltinType::OCLReserveID:
5925 case BuiltinType::OCLSampler:
5926 case BuiltinType::Dependent:
5927 #define BUILTIN_TYPE(KIND, ID)
5928 #define PLACEHOLDER_TYPE(KIND, ID) \
5929 case BuiltinType::KIND:
5930 #include "clang/AST/BuiltinTypes.def"
5931 llvm_unreachable("invalid builtin type for @encode");
5933 llvm_unreachable("invalid BuiltinType::Kind value");
5936 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5937 EnumDecl *Enum = ET->getDecl();
5939 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5940 if (!Enum->isFixed())
5943 // The encoding of a fixed enum type matches its fixed underlying type.
5944 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5945 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5948 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5949 QualType T, const FieldDecl *FD) {
5950 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5952 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5953 // The GNU runtime requires more information; bitfields are encoded as b,
5954 // then the offset (in bits) of the first element, then the type of the
5955 // bitfield, then the size in bits. For example, in this structure:
5962 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5963 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5964 // information is not especially sensible, but we're stuck with it for
5965 // compatibility with GCC, although providing it breaks anything that
5966 // actually uses runtime introspection and wants to work on both runtimes...
5967 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5968 const RecordDecl *RD = FD->getParent();
5969 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5970 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5971 if (const EnumType *ET = T->getAs<EnumType>())
5972 S += ObjCEncodingForEnumType(Ctx, ET);
5974 const BuiltinType *BT = T->castAs<BuiltinType>();
5975 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5978 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5981 // FIXME: Use SmallString for accumulating string.
5982 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5983 bool ExpandPointedToStructures,
5984 bool ExpandStructures,
5985 const FieldDecl *FD,
5987 bool EncodingProperty,
5989 bool EncodeBlockParameters,
5990 bool EncodeClassNames,
5991 bool EncodePointerToObjCTypedef,
5992 QualType *NotEncodedT) const {
5993 CanQualType CT = getCanonicalType(T);
5994 switch (CT->getTypeClass()) {
5997 if (FD && FD->isBitField())
5998 return EncodeBitField(this, S, T, FD);
5999 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6000 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6002 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6005 case Type::Complex: {
6006 const ComplexType *CT = T->castAs<ComplexType>();
6008 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6012 case Type::Atomic: {
6013 const AtomicType *AT = T->castAs<AtomicType>();
6015 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6019 // encoding for pointer or reference types.
6021 case Type::LValueReference:
6022 case Type::RValueReference: {
6024 if (isa<PointerType>(CT)) {
6025 const PointerType *PT = T->castAs<PointerType>();
6026 if (PT->isObjCSelType()) {
6030 PointeeTy = PT->getPointeeType();
6032 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6035 bool isReadOnly = false;
6036 // For historical/compatibility reasons, the read-only qualifier of the
6037 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6038 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6039 // Also, do not emit the 'r' for anything but the outermost type!
6040 if (isa<TypedefType>(T.getTypePtr())) {
6041 if (OutermostType && T.isConstQualified()) {
6045 } else if (OutermostType) {
6046 QualType P = PointeeTy;
6047 while (P->getAs<PointerType>())
6048 P = P->getAs<PointerType>()->getPointeeType();
6049 if (P.isConstQualified()) {
6055 // Another legacy compatibility encoding. Some ObjC qualifier and type
6056 // combinations need to be rearranged.
6057 // Rewrite "in const" from "nr" to "rn"
6058 if (StringRef(S).endswith("nr"))
6059 S.replace(S.end()-2, S.end(), "rn");
6062 if (PointeeTy->isCharType()) {
6063 // char pointer types should be encoded as '*' unless it is a
6064 // type that has been typedef'd to 'BOOL'.
6065 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6069 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
6070 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6071 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6075 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6076 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6083 getLegacyIntegralTypeEncoding(PointeeTy);
6085 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6086 nullptr, false, false, false, false, false, false,
6091 case Type::ConstantArray:
6092 case Type::IncompleteArray:
6093 case Type::VariableArray: {
6094 const ArrayType *AT = cast<ArrayType>(CT);
6096 if (isa<IncompleteArrayType>(AT) && !StructField) {
6097 // Incomplete arrays are encoded as a pointer to the array element.
6100 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6101 false, ExpandStructures, FD);
6105 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6106 S += llvm::utostr(CAT->getSize().getZExtValue());
6108 //Variable length arrays are encoded as a regular array with 0 elements.
6109 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6110 "Unknown array type!");
6114 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6115 false, ExpandStructures, FD,
6116 false, false, false, false, false, false,
6123 case Type::FunctionNoProto:
6124 case Type::FunctionProto:
6128 case Type::Record: {
6129 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6130 S += RDecl->isUnion() ? '(' : '{';
6131 // Anonymous structures print as '?'
6132 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6134 if (ClassTemplateSpecializationDecl *Spec
6135 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6136 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6137 llvm::raw_string_ostream OS(S);
6138 TemplateSpecializationType::PrintTemplateArgumentList(OS,
6139 TemplateArgs.asArray(),
6140 (*this).getPrintingPolicy());
6145 if (ExpandStructures) {
6147 if (!RDecl->isUnion()) {
6148 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6150 for (const auto *Field : RDecl->fields()) {
6153 S += Field->getNameAsString();
6157 // Special case bit-fields.
6158 if (Field->isBitField()) {
6159 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6162 QualType qt = Field->getType();
6163 getLegacyIntegralTypeEncoding(qt);
6164 getObjCEncodingForTypeImpl(qt, S, false, true,
6165 FD, /*OutermostType*/false,
6166 /*EncodingProperty*/false,
6167 /*StructField*/true,
6168 false, false, false, NotEncodedT);
6173 S += RDecl->isUnion() ? ')' : '}';
6177 case Type::BlockPointer: {
6178 const BlockPointerType *BT = T->castAs<BlockPointerType>();
6179 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6180 if (EncodeBlockParameters) {
6181 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
6184 // Block return type
6185 getObjCEncodingForTypeImpl(
6186 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6187 FD, false /* OutermostType */, EncodingProperty,
6188 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6193 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
6194 for (const auto &I : FPT->param_types())
6195 getObjCEncodingForTypeImpl(
6196 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6197 false /* OutermostType */, EncodingProperty,
6198 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6199 false, NotEncodedT);
6206 case Type::ObjCObject: {
6207 // hack to match legacy encoding of *id and *Class
6208 QualType Ty = getObjCObjectPointerType(CT);
6209 if (Ty->isObjCIdType()) {
6210 S += "{objc_object=}";
6213 else if (Ty->isObjCClassType()) {
6214 S += "{objc_class=}";
6219 case Type::ObjCInterface: {
6220 // Ignore protocol qualifiers when mangling at this level.
6221 // @encode(class_name)
6222 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6224 S += OI->getObjCRuntimeNameAsString();
6225 if (ExpandStructures) {
6227 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6228 DeepCollectObjCIvars(OI, true, Ivars);
6229 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6230 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6231 if (Field->isBitField())
6232 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6234 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6235 false, false, false, false, false,
6236 EncodePointerToObjCTypedef,
6244 case Type::ObjCObjectPointer: {
6245 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
6246 if (OPT->isObjCIdType()) {
6251 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6252 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6253 // Since this is a binary compatibility issue, need to consult with runtime
6254 // folks. Fortunately, this is a *very* obsure construct.
6259 if (OPT->isObjCQualifiedIdType()) {
6260 getObjCEncodingForTypeImpl(getObjCIdType(), S,
6261 ExpandPointedToStructures,
6262 ExpandStructures, FD);
6263 if (FD || EncodingProperty || EncodeClassNames) {
6264 // Note that we do extended encoding of protocol qualifer list
6265 // Only when doing ivar or property encoding.
6267 for (const auto *I : OPT->quals()) {
6269 S += I->getObjCRuntimeNameAsString();
6277 QualType PointeeTy = OPT->getPointeeType();
6278 if (!EncodingProperty &&
6279 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6280 !EncodePointerToObjCTypedef) {
6281 // Another historical/compatibility reason.
6282 // We encode the underlying type which comes out as
6285 if (FD && OPT->getInterfaceDecl()) {
6286 // Prevent recursive encoding of fields in some rare cases.
6287 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6288 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6289 DeepCollectObjCIvars(OI, true, Ivars);
6290 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6291 if (cast<FieldDecl>(Ivars[i]) == FD) {
6293 S += OI->getObjCRuntimeNameAsString();
6299 getObjCEncodingForTypeImpl(PointeeTy, S,
6300 false, ExpandPointedToStructures,
6302 false, false, false, false, false,
6303 /*EncodePointerToObjCTypedef*/true);
6308 if (OPT->getInterfaceDecl() &&
6309 (FD || EncodingProperty || EncodeClassNames)) {
6311 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6312 for (const auto *I : OPT->quals()) {
6314 S += I->getObjCRuntimeNameAsString();
6322 // gcc just blithely ignores member pointers.
6323 // FIXME: we shoul do better than that. 'M' is available.
6324 case Type::MemberPointer:
6325 // This matches gcc's encoding, even though technically it is insufficient.
6326 //FIXME. We should do a better job than gcc.
6328 case Type::ExtVector:
6329 // Until we have a coherent encoding of these three types, issue warning.
6335 // We could see an undeduced auto type here during error recovery.
6341 #define ABSTRACT_TYPE(KIND, BASE)
6342 #define TYPE(KIND, BASE)
6343 #define DEPENDENT_TYPE(KIND, BASE) \
6345 #define NON_CANONICAL_TYPE(KIND, BASE) \
6347 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6349 #include "clang/AST/TypeNodes.def"
6350 llvm_unreachable("@encode for dependent type!");
6352 llvm_unreachable("bad type kind!");
6355 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6357 const FieldDecl *FD,
6359 QualType *NotEncodedT) const {
6360 assert(RDecl && "Expected non-null RecordDecl");
6361 assert(!RDecl->isUnion() && "Should not be called for unions");
6362 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6365 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6366 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6367 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6370 for (const auto &BI : CXXRec->bases()) {
6371 if (!BI.isVirtual()) {
6372 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6373 if (base->isEmpty())
6375 uint64_t offs = toBits(layout.getBaseClassOffset(base));
6376 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6377 std::make_pair(offs, base));
6383 for (auto *Field : RDecl->fields()) {
6384 uint64_t offs = layout.getFieldOffset(i);
6385 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6386 std::make_pair(offs, Field));
6390 if (CXXRec && includeVBases) {
6391 for (const auto &BI : CXXRec->vbases()) {
6392 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6393 if (base->isEmpty())
6395 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6396 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6397 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6398 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6399 std::make_pair(offs, base));
6405 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6407 size = layout.getSize();
6411 uint64_t CurOffs = 0;
6413 std::multimap<uint64_t, NamedDecl *>::iterator
6414 CurLayObj = FieldOrBaseOffsets.begin();
6416 if (CXXRec && CXXRec->isDynamicClass() &&
6417 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6420 std::string recname = CXXRec->getNameAsString();
6421 if (recname.empty()) recname = "?";
6427 CurOffs += getTypeSize(VoidPtrTy);
6431 if (!RDecl->hasFlexibleArrayMember()) {
6432 // Mark the end of the structure.
6433 uint64_t offs = toBits(size);
6434 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6435 std::make_pair(offs, nullptr));
6438 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6440 assert(CurOffs <= CurLayObj->first);
6441 if (CurOffs < CurLayObj->first) {
6442 uint64_t padding = CurLayObj->first - CurOffs;
6443 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6444 // packing/alignment of members is different that normal, in which case
6445 // the encoding will be out-of-sync with the real layout.
6446 // If the runtime switches to just consider the size of types without
6447 // taking into account alignment, we could make padding explicit in the
6448 // encoding (e.g. using arrays of chars). The encoding strings would be
6449 // longer then though.
6454 NamedDecl *dcl = CurLayObj->second;
6456 break; // reached end of structure.
6458 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6459 // We expand the bases without their virtual bases since those are going
6460 // in the initial structure. Note that this differs from gcc which
6461 // expands virtual bases each time one is encountered in the hierarchy,
6462 // making the encoding type bigger than it really is.
6463 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6465 assert(!base->isEmpty());
6467 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6470 FieldDecl *field = cast<FieldDecl>(dcl);
6473 S += field->getNameAsString();
6477 if (field->isBitField()) {
6478 EncodeBitField(this, S, field->getType(), field);
6480 CurOffs += field->getBitWidthValue(*this);
6483 QualType qt = field->getType();
6484 getLegacyIntegralTypeEncoding(qt);
6485 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6486 /*OutermostType*/false,
6487 /*EncodingProperty*/false,
6488 /*StructField*/true,
6489 false, false, false, NotEncodedT);
6491 CurOffs += getTypeSize(field->getType());
6498 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6499 std::string& S) const {
6500 if (QT & Decl::OBJC_TQ_In)
6502 if (QT & Decl::OBJC_TQ_Inout)
6504 if (QT & Decl::OBJC_TQ_Out)
6506 if (QT & Decl::OBJC_TQ_Bycopy)
6508 if (QT & Decl::OBJC_TQ_Byref)
6510 if (QT & Decl::OBJC_TQ_Oneway)
6514 TypedefDecl *ASTContext::getObjCIdDecl() const {
6516 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6517 T = getObjCObjectPointerType(T);
6518 ObjCIdDecl = buildImplicitTypedef(T, "id");
6523 TypedefDecl *ASTContext::getObjCSelDecl() const {
6525 QualType T = getPointerType(ObjCBuiltinSelTy);
6526 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6531 TypedefDecl *ASTContext::getObjCClassDecl() const {
6532 if (!ObjCClassDecl) {
6533 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6534 T = getObjCObjectPointerType(T);
6535 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6537 return ObjCClassDecl;
6540 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6541 if (!ObjCProtocolClassDecl) {
6542 ObjCProtocolClassDecl
6543 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6545 &Idents.get("Protocol"),
6546 /*typeParamList=*/nullptr,
6547 /*PrevDecl=*/nullptr,
6548 SourceLocation(), true);
6551 return ObjCProtocolClassDecl;
6554 //===----------------------------------------------------------------------===//
6555 // __builtin_va_list Construction Functions
6556 //===----------------------------------------------------------------------===//
6558 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6560 // typedef char* __builtin[_ms]_va_list;
6561 QualType T = Context->getPointerType(Context->CharTy);
6562 return Context->buildImplicitTypedef(T, Name);
6565 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6566 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6569 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6570 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6573 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6574 // typedef void* __builtin_va_list;
6575 QualType T = Context->getPointerType(Context->VoidTy);
6576 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6579 static TypedefDecl *
6580 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6582 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6583 if (Context->getLangOpts().CPlusPlus) {
6584 // namespace std { struct __va_list {
6586 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6587 Context->getTranslationUnitDecl(),
6588 /*Inline*/ false, SourceLocation(),
6589 SourceLocation(), &Context->Idents.get("std"),
6590 /*PrevDecl*/ nullptr);
6592 VaListTagDecl->setDeclContext(NS);
6595 VaListTagDecl->startDefinition();
6597 const size_t NumFields = 5;
6598 QualType FieldTypes[NumFields];
6599 const char *FieldNames[NumFields];
6602 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6603 FieldNames[0] = "__stack";
6606 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6607 FieldNames[1] = "__gr_top";
6610 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6611 FieldNames[2] = "__vr_top";
6614 FieldTypes[3] = Context->IntTy;
6615 FieldNames[3] = "__gr_offs";
6618 FieldTypes[4] = Context->IntTy;
6619 FieldNames[4] = "__vr_offs";
6622 for (unsigned i = 0; i < NumFields; ++i) {
6623 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6627 &Context->Idents.get(FieldNames[i]),
6628 FieldTypes[i], /*TInfo=*/nullptr,
6629 /*BitWidth=*/nullptr,
6632 Field->setAccess(AS_public);
6633 VaListTagDecl->addDecl(Field);
6635 VaListTagDecl->completeDefinition();
6636 Context->VaListTagDecl = VaListTagDecl;
6637 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6639 // } __builtin_va_list;
6640 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6643 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6644 // typedef struct __va_list_tag {
6645 RecordDecl *VaListTagDecl;
6647 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6648 VaListTagDecl->startDefinition();
6650 const size_t NumFields = 5;
6651 QualType FieldTypes[NumFields];
6652 const char *FieldNames[NumFields];
6654 // unsigned char gpr;
6655 FieldTypes[0] = Context->UnsignedCharTy;
6656 FieldNames[0] = "gpr";
6658 // unsigned char fpr;
6659 FieldTypes[1] = Context->UnsignedCharTy;
6660 FieldNames[1] = "fpr";
6662 // unsigned short reserved;
6663 FieldTypes[2] = Context->UnsignedShortTy;
6664 FieldNames[2] = "reserved";
6666 // void* overflow_arg_area;
6667 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6668 FieldNames[3] = "overflow_arg_area";
6670 // void* reg_save_area;
6671 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6672 FieldNames[4] = "reg_save_area";
6675 for (unsigned i = 0; i < NumFields; ++i) {
6676 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6679 &Context->Idents.get(FieldNames[i]),
6680 FieldTypes[i], /*TInfo=*/nullptr,
6681 /*BitWidth=*/nullptr,
6684 Field->setAccess(AS_public);
6685 VaListTagDecl->addDecl(Field);
6687 VaListTagDecl->completeDefinition();
6688 Context->VaListTagDecl = VaListTagDecl;
6689 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6692 TypedefDecl *VaListTagTypedefDecl =
6693 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6695 QualType VaListTagTypedefType =
6696 Context->getTypedefType(VaListTagTypedefDecl);
6698 // typedef __va_list_tag __builtin_va_list[1];
6699 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6700 QualType VaListTagArrayType
6701 = Context->getConstantArrayType(VaListTagTypedefType,
6702 Size, ArrayType::Normal, 0);
6703 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6706 static TypedefDecl *
6707 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6708 // struct __va_list_tag {
6709 RecordDecl *VaListTagDecl;
6710 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6711 VaListTagDecl->startDefinition();
6713 const size_t NumFields = 4;
6714 QualType FieldTypes[NumFields];
6715 const char *FieldNames[NumFields];
6717 // unsigned gp_offset;
6718 FieldTypes[0] = Context->UnsignedIntTy;
6719 FieldNames[0] = "gp_offset";
6721 // unsigned fp_offset;
6722 FieldTypes[1] = Context->UnsignedIntTy;
6723 FieldNames[1] = "fp_offset";
6725 // void* overflow_arg_area;
6726 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6727 FieldNames[2] = "overflow_arg_area";
6729 // void* reg_save_area;
6730 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6731 FieldNames[3] = "reg_save_area";
6734 for (unsigned i = 0; i < NumFields; ++i) {
6735 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6739 &Context->Idents.get(FieldNames[i]),
6740 FieldTypes[i], /*TInfo=*/nullptr,
6741 /*BitWidth=*/nullptr,
6744 Field->setAccess(AS_public);
6745 VaListTagDecl->addDecl(Field);
6747 VaListTagDecl->completeDefinition();
6748 Context->VaListTagDecl = VaListTagDecl;
6749 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6753 // typedef struct __va_list_tag __builtin_va_list[1];
6754 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6755 QualType VaListTagArrayType =
6756 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6757 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6760 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6761 // typedef int __builtin_va_list[4];
6762 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6763 QualType IntArrayType =
6764 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
6765 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6768 static TypedefDecl *
6769 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6771 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6772 if (Context->getLangOpts().CPlusPlus) {
6773 // namespace std { struct __va_list {
6775 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6776 Context->getTranslationUnitDecl(),
6777 /*Inline*/false, SourceLocation(),
6778 SourceLocation(), &Context->Idents.get("std"),
6779 /*PrevDecl*/ nullptr);
6781 VaListDecl->setDeclContext(NS);
6784 VaListDecl->startDefinition();
6787 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6791 &Context->Idents.get("__ap"),
6792 Context->getPointerType(Context->VoidTy),
6794 /*BitWidth=*/nullptr,
6797 Field->setAccess(AS_public);
6798 VaListDecl->addDecl(Field);
6801 VaListDecl->completeDefinition();
6802 Context->VaListTagDecl = VaListDecl;
6804 // typedef struct __va_list __builtin_va_list;
6805 QualType T = Context->getRecordType(VaListDecl);
6806 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6809 static TypedefDecl *
6810 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6811 // struct __va_list_tag {
6812 RecordDecl *VaListTagDecl;
6813 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6814 VaListTagDecl->startDefinition();
6816 const size_t NumFields = 4;
6817 QualType FieldTypes[NumFields];
6818 const char *FieldNames[NumFields];
6821 FieldTypes[0] = Context->LongTy;
6822 FieldNames[0] = "__gpr";
6825 FieldTypes[1] = Context->LongTy;
6826 FieldNames[1] = "__fpr";
6828 // void *__overflow_arg_area;
6829 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6830 FieldNames[2] = "__overflow_arg_area";
6832 // void *__reg_save_area;
6833 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6834 FieldNames[3] = "__reg_save_area";
6837 for (unsigned i = 0; i < NumFields; ++i) {
6838 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6842 &Context->Idents.get(FieldNames[i]),
6843 FieldTypes[i], /*TInfo=*/nullptr,
6844 /*BitWidth=*/nullptr,
6847 Field->setAccess(AS_public);
6848 VaListTagDecl->addDecl(Field);
6850 VaListTagDecl->completeDefinition();
6851 Context->VaListTagDecl = VaListTagDecl;
6852 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6856 // typedef __va_list_tag __builtin_va_list[1];
6857 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6858 QualType VaListTagArrayType =
6859 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6861 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6864 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6865 TargetInfo::BuiltinVaListKind Kind) {
6867 case TargetInfo::CharPtrBuiltinVaList:
6868 return CreateCharPtrBuiltinVaListDecl(Context);
6869 case TargetInfo::VoidPtrBuiltinVaList:
6870 return CreateVoidPtrBuiltinVaListDecl(Context);
6871 case TargetInfo::AArch64ABIBuiltinVaList:
6872 return CreateAArch64ABIBuiltinVaListDecl(Context);
6873 case TargetInfo::PowerABIBuiltinVaList:
6874 return CreatePowerABIBuiltinVaListDecl(Context);
6875 case TargetInfo::X86_64ABIBuiltinVaList:
6876 return CreateX86_64ABIBuiltinVaListDecl(Context);
6877 case TargetInfo::PNaClABIBuiltinVaList:
6878 return CreatePNaClABIBuiltinVaListDecl(Context);
6879 case TargetInfo::AAPCSABIBuiltinVaList:
6880 return CreateAAPCSABIBuiltinVaListDecl(Context);
6881 case TargetInfo::SystemZBuiltinVaList:
6882 return CreateSystemZBuiltinVaListDecl(Context);
6885 llvm_unreachable("Unhandled __builtin_va_list type kind");
6888 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6889 if (!BuiltinVaListDecl) {
6890 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6891 assert(BuiltinVaListDecl->isImplicit());
6894 return BuiltinVaListDecl;
6897 Decl *ASTContext::getVaListTagDecl() const {
6898 // Force the creation of VaListTagDecl by building the __builtin_va_list
6901 (void)getBuiltinVaListDecl();
6903 return VaListTagDecl;
6906 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6907 if (!BuiltinMSVaListDecl)
6908 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6910 return BuiltinMSVaListDecl;
6913 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6914 assert(ObjCConstantStringType.isNull() &&
6915 "'NSConstantString' type already set!");
6917 ObjCConstantStringType = getObjCInterfaceType(Decl);
6920 /// \brief Retrieve the template name that corresponds to a non-empty
6923 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6924 UnresolvedSetIterator End) const {
6925 unsigned size = End - Begin;
6926 assert(size > 1 && "set is not overloaded!");
6928 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6929 size * sizeof(FunctionTemplateDecl*));
6930 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6932 NamedDecl **Storage = OT->getStorage();
6933 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6935 assert(isa<FunctionTemplateDecl>(D) ||
6936 (isa<UsingShadowDecl>(D) &&
6937 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6941 return TemplateName(OT);
6944 /// \brief Retrieve the template name that represents a qualified
6945 /// template name such as \c std::vector.
6947 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6948 bool TemplateKeyword,
6949 TemplateDecl *Template) const {
6950 assert(NNS && "Missing nested-name-specifier in qualified template name");
6952 // FIXME: Canonicalization?
6953 llvm::FoldingSetNodeID ID;
6954 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6956 void *InsertPos = nullptr;
6957 QualifiedTemplateName *QTN =
6958 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6960 QTN = new (*this, alignof(QualifiedTemplateName))
6961 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6962 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6965 return TemplateName(QTN);
6968 /// \brief Retrieve the template name that represents a dependent
6969 /// template name such as \c MetaFun::template apply.
6971 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6972 const IdentifierInfo *Name) const {
6973 assert((!NNS || NNS->isDependent()) &&
6974 "Nested name specifier must be dependent");
6976 llvm::FoldingSetNodeID ID;
6977 DependentTemplateName::Profile(ID, NNS, Name);
6979 void *InsertPos = nullptr;
6980 DependentTemplateName *QTN =
6981 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6984 return TemplateName(QTN);
6986 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6987 if (CanonNNS == NNS) {
6988 QTN = new (*this, alignof(DependentTemplateName))
6989 DependentTemplateName(NNS, Name);
6991 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6992 QTN = new (*this, alignof(DependentTemplateName))
6993 DependentTemplateName(NNS, Name, Canon);
6994 DependentTemplateName *CheckQTN =
6995 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6996 assert(!CheckQTN && "Dependent type name canonicalization broken");
7000 DependentTemplateNames.InsertNode(QTN, InsertPos);
7001 return TemplateName(QTN);
7004 /// \brief Retrieve the template name that represents a dependent
7005 /// template name such as \c MetaFun::template operator+.
7007 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7008 OverloadedOperatorKind Operator) const {
7009 assert((!NNS || NNS->isDependent()) &&
7010 "Nested name specifier must be dependent");
7012 llvm::FoldingSetNodeID ID;
7013 DependentTemplateName::Profile(ID, NNS, Operator);
7015 void *InsertPos = nullptr;
7016 DependentTemplateName *QTN
7017 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7020 return TemplateName(QTN);
7022 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7023 if (CanonNNS == NNS) {
7024 QTN = new (*this, alignof(DependentTemplateName))
7025 DependentTemplateName(NNS, Operator);
7027 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7028 QTN = new (*this, alignof(DependentTemplateName))
7029 DependentTemplateName(NNS, Operator, Canon);
7031 DependentTemplateName *CheckQTN
7032 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7033 assert(!CheckQTN && "Dependent template name canonicalization broken");
7037 DependentTemplateNames.InsertNode(QTN, InsertPos);
7038 return TemplateName(QTN);
7042 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7043 TemplateName replacement) const {
7044 llvm::FoldingSetNodeID ID;
7045 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7047 void *insertPos = nullptr;
7048 SubstTemplateTemplateParmStorage *subst
7049 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7052 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7053 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7056 return TemplateName(subst);
7060 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7061 const TemplateArgument &ArgPack) const {
7062 ASTContext &Self = const_cast<ASTContext &>(*this);
7063 llvm::FoldingSetNodeID ID;
7064 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7066 void *InsertPos = nullptr;
7067 SubstTemplateTemplateParmPackStorage *Subst
7068 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7071 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7072 ArgPack.pack_size(),
7073 ArgPack.pack_begin());
7074 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7077 return TemplateName(Subst);
7080 /// getFromTargetType - Given one of the integer types provided by
7081 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7082 /// is actually a value of type @c TargetInfo::IntType.
7083 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7085 case TargetInfo::NoInt: return CanQualType();
7086 case TargetInfo::SignedChar: return SignedCharTy;
7087 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7088 case TargetInfo::SignedShort: return ShortTy;
7089 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7090 case TargetInfo::SignedInt: return IntTy;
7091 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7092 case TargetInfo::SignedLong: return LongTy;
7093 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7094 case TargetInfo::SignedLongLong: return LongLongTy;
7095 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7098 llvm_unreachable("Unhandled TargetInfo::IntType value");
7101 //===----------------------------------------------------------------------===//
7103 //===----------------------------------------------------------------------===//
7105 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7106 /// garbage collection attribute.
7108 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7109 if (getLangOpts().getGC() == LangOptions::NonGC)
7110 return Qualifiers::GCNone;
7112 assert(getLangOpts().ObjC1);
7113 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7115 // Default behaviour under objective-C's gc is for ObjC pointers
7116 // (or pointers to them) be treated as though they were declared
7118 if (GCAttrs == Qualifiers::GCNone) {
7119 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7120 return Qualifiers::Strong;
7121 else if (Ty->isPointerType())
7122 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7124 // It's not valid to set GC attributes on anything that isn't a
7127 QualType CT = Ty->getCanonicalTypeInternal();
7128 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7129 CT = AT->getElementType();
7130 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7136 //===----------------------------------------------------------------------===//
7137 // Type Compatibility Testing
7138 //===----------------------------------------------------------------------===//
7140 /// areCompatVectorTypes - Return true if the two specified vector types are
7142 static bool areCompatVectorTypes(const VectorType *LHS,
7143 const VectorType *RHS) {
7144 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7145 return LHS->getElementType() == RHS->getElementType() &&
7146 LHS->getNumElements() == RHS->getNumElements();
7149 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7150 QualType SecondVec) {
7151 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7152 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7154 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7157 // Treat Neon vector types and most AltiVec vector types as if they are the
7158 // equivalent GCC vector types.
7159 const VectorType *First = FirstVec->getAs<VectorType>();
7160 const VectorType *Second = SecondVec->getAs<VectorType>();
7161 if (First->getNumElements() == Second->getNumElements() &&
7162 hasSameType(First->getElementType(), Second->getElementType()) &&
7163 First->getVectorKind() != VectorType::AltiVecPixel &&
7164 First->getVectorKind() != VectorType::AltiVecBool &&
7165 Second->getVectorKind() != VectorType::AltiVecPixel &&
7166 Second->getVectorKind() != VectorType::AltiVecBool)
7172 //===----------------------------------------------------------------------===//
7173 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7174 //===----------------------------------------------------------------------===//
7176 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7177 /// inheritance hierarchy of 'rProto'.
7179 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7180 ObjCProtocolDecl *rProto) const {
7181 if (declaresSameEntity(lProto, rProto))
7183 for (auto *PI : rProto->protocols())
7184 if (ProtocolCompatibleWithProtocol(lProto, PI))
7189 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7190 /// Class<pr1, ...>.
7191 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7193 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7194 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7195 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7197 for (auto *lhsProto : lhsQID->quals()) {
7199 for (auto *rhsProto : rhsOPT->quals()) {
7200 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7211 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7212 /// ObjCQualifiedIDType.
7213 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7215 // Allow id<P..> and an 'id' or void* type in all cases.
7216 if (lhs->isVoidPointerType() ||
7217 lhs->isObjCIdType() || lhs->isObjCClassType())
7219 else if (rhs->isVoidPointerType() ||
7220 rhs->isObjCIdType() || rhs->isObjCClassType())
7223 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7224 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7226 if (!rhsOPT) return false;
7228 if (rhsOPT->qual_empty()) {
7229 // If the RHS is a unqualified interface pointer "NSString*",
7230 // make sure we check the class hierarchy.
7231 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7232 for (auto *I : lhsQID->quals()) {
7233 // when comparing an id<P> on lhs with a static type on rhs,
7234 // see if static class implements all of id's protocols, directly or
7235 // through its super class and categories.
7236 if (!rhsID->ClassImplementsProtocol(I, true))
7240 // If there are no qualifiers and no interface, we have an 'id'.
7243 // Both the right and left sides have qualifiers.
7244 for (auto *lhsProto : lhsQID->quals()) {
7247 // when comparing an id<P> on lhs with a static type on rhs,
7248 // see if static class implements all of id's protocols, directly or
7249 // through its super class and categories.
7250 for (auto *rhsProto : rhsOPT->quals()) {
7251 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7252 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7257 // If the RHS is a qualified interface pointer "NSString<P>*",
7258 // make sure we check the class hierarchy.
7259 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7260 for (auto *I : lhsQID->quals()) {
7261 // when comparing an id<P> on lhs with a static type on rhs,
7262 // see if static class implements all of id's protocols, directly or
7263 // through its super class and categories.
7264 if (rhsID->ClassImplementsProtocol(I, true)) {
7277 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7278 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7280 if (const ObjCObjectPointerType *lhsOPT =
7281 lhs->getAsObjCInterfacePointerType()) {
7282 // If both the right and left sides have qualifiers.
7283 for (auto *lhsProto : lhsOPT->quals()) {
7286 // when comparing an id<P> on rhs with a static type on lhs,
7287 // see if static class implements all of id's protocols, directly or
7288 // through its super class and categories.
7289 // First, lhs protocols in the qualifier list must be found, direct
7290 // or indirect in rhs's qualifier list or it is a mismatch.
7291 for (auto *rhsProto : rhsQID->quals()) {
7292 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7293 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7302 // Static class's protocols, or its super class or category protocols
7303 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7304 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7305 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7306 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7307 // This is rather dubious but matches gcc's behavior. If lhs has
7308 // no type qualifier and its class has no static protocol(s)
7309 // assume that it is mismatch.
7310 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7312 for (auto *lhsProto : LHSInheritedProtocols) {
7314 for (auto *rhsProto : rhsQID->quals()) {
7315 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7316 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7330 /// canAssignObjCInterfaces - Return true if the two interface types are
7331 /// compatible for assignment from RHS to LHS. This handles validation of any
7332 /// protocol qualifiers on the LHS or RHS.
7334 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7335 const ObjCObjectPointerType *RHSOPT) {
7336 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7337 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7339 // If either type represents the built-in 'id' or 'Class' types, return true.
7340 if (LHS->isObjCUnqualifiedIdOrClass() ||
7341 RHS->isObjCUnqualifiedIdOrClass())
7344 // Function object that propagates a successful result or handles
7346 auto finish = [&](bool succeeded) -> bool {
7350 if (!RHS->isKindOfType())
7353 // Strip off __kindof and protocol qualifiers, then check whether
7354 // we can assign the other way.
7355 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7356 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7359 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7360 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7365 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7366 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7367 QualType(RHSOPT,0)));
7370 // If we have 2 user-defined types, fall into that path.
7371 if (LHS->getInterface() && RHS->getInterface()) {
7372 return finish(canAssignObjCInterfaces(LHS, RHS));
7378 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7379 /// for providing type-safety for objective-c pointers used to pass/return
7380 /// arguments in block literals. When passed as arguments, passing 'A*' where
7381 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7382 /// not OK. For the return type, the opposite is not OK.
7383 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7384 const ObjCObjectPointerType *LHSOPT,
7385 const ObjCObjectPointerType *RHSOPT,
7386 bool BlockReturnType) {
7388 // Function object that propagates a successful result or handles
7390 auto finish = [&](bool succeeded) -> bool {
7394 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7395 if (!Expected->isKindOfType())
7398 // Strip off __kindof and protocol qualifiers, then check whether
7399 // we can assign the other way.
7400 return canAssignObjCInterfacesInBlockPointer(
7401 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7402 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7406 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7409 if (LHSOPT->isObjCBuiltinType()) {
7410 return finish(RHSOPT->isObjCBuiltinType() ||
7411 RHSOPT->isObjCQualifiedIdType());
7414 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7415 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7419 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7420 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7421 if (LHS && RHS) { // We have 2 user-defined types.
7423 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7424 return finish(BlockReturnType);
7425 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7426 return finish(!BlockReturnType);
7434 /// Comparison routine for Objective-C protocols to be used with
7435 /// llvm::array_pod_sort.
7436 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7437 ObjCProtocolDecl * const *rhs) {
7438 return (*lhs)->getName().compare((*rhs)->getName());
7442 /// getIntersectionOfProtocols - This routine finds the intersection of set
7443 /// of protocols inherited from two distinct objective-c pointer objects with
7444 /// the given common base.
7445 /// It is used to build composite qualifier list of the composite type of
7446 /// the conditional expression involving two objective-c pointer objects.
7448 void getIntersectionOfProtocols(ASTContext &Context,
7449 const ObjCInterfaceDecl *CommonBase,
7450 const ObjCObjectPointerType *LHSOPT,
7451 const ObjCObjectPointerType *RHSOPT,
7452 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7454 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7455 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7456 assert(LHS->getInterface() && "LHS must have an interface base");
7457 assert(RHS->getInterface() && "RHS must have an interface base");
7459 // Add all of the protocols for the LHS.
7460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7462 // Start with the protocol qualifiers.
7463 for (auto proto : LHS->quals()) {
7464 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7467 // Also add the protocols associated with the LHS interface.
7468 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7470 // Add all of the protocls for the RHS.
7471 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7473 // Start with the protocol qualifiers.
7474 for (auto proto : RHS->quals()) {
7475 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7478 // Also add the protocols associated with the RHS interface.
7479 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7481 // Compute the intersection of the collected protocol sets.
7482 for (auto proto : LHSProtocolSet) {
7483 if (RHSProtocolSet.count(proto))
7484 IntersectionSet.push_back(proto);
7487 // Compute the set of protocols that is implied by either the common type or
7488 // the protocols within the intersection.
7489 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7490 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7492 // Remove any implied protocols from the list of inherited protocols.
7493 if (!ImpliedProtocols.empty()) {
7494 IntersectionSet.erase(
7495 std::remove_if(IntersectionSet.begin(),
7496 IntersectionSet.end(),
7497 [&](ObjCProtocolDecl *proto) -> bool {
7498 return ImpliedProtocols.count(proto) > 0;
7500 IntersectionSet.end());
7503 // Sort the remaining protocols by name.
7504 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7505 compareObjCProtocolsByName);
7508 /// Determine whether the first type is a subtype of the second.
7509 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7511 // Common case: two object pointers.
7512 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7513 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7514 if (lhsOPT && rhsOPT)
7515 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7517 // Two block pointers.
7518 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7519 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7520 if (lhsBlock && rhsBlock)
7521 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7523 // If either is an unqualified 'id' and the other is a block, it's
7525 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7526 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7532 // Check that the given Objective-C type argument lists are equivalent.
7533 static bool sameObjCTypeArgs(ASTContext &ctx,
7534 const ObjCInterfaceDecl *iface,
7535 ArrayRef<QualType> lhsArgs,
7536 ArrayRef<QualType> rhsArgs,
7538 if (lhsArgs.size() != rhsArgs.size())
7541 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7542 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7543 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7546 switch (typeParams->begin()[i]->getVariance()) {
7547 case ObjCTypeParamVariance::Invariant:
7549 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7550 rhsArgs[i].stripObjCKindOfType(ctx))) {
7555 case ObjCTypeParamVariance::Covariant:
7556 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7560 case ObjCTypeParamVariance::Contravariant:
7561 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7570 QualType ASTContext::areCommonBaseCompatible(
7571 const ObjCObjectPointerType *Lptr,
7572 const ObjCObjectPointerType *Rptr) {
7573 const ObjCObjectType *LHS = Lptr->getObjectType();
7574 const ObjCObjectType *RHS = Rptr->getObjectType();
7575 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7576 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7578 if (!LDecl || !RDecl)
7581 // When either LHS or RHS is a kindof type, we should return a kindof type.
7582 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7584 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7586 // Follow the left-hand side up the class hierarchy until we either hit a
7587 // root or find the RHS. Record the ancestors in case we don't find it.
7588 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7591 // Record this ancestor. We'll need this if the common type isn't in the
7592 // path from the LHS to the root.
7593 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7595 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7596 // Get the type arguments.
7597 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7598 bool anyChanges = false;
7599 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7600 // Both have type arguments, compare them.
7601 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7602 LHS->getTypeArgs(), RHS->getTypeArgs(),
7603 /*stripKindOf=*/true))
7605 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7606 // If only one has type arguments, the result will not have type
7612 // Compute the intersection of protocols.
7613 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7614 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7616 if (!Protocols.empty())
7619 // If anything in the LHS will have changed, build a new result type.
7620 // If we need to return a kindof type but LHS is not a kindof type, we
7621 // build a new result type.
7622 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7623 QualType Result = getObjCInterfaceType(LHS->getInterface());
7624 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7625 anyKindOf || LHS->isKindOfType());
7626 return getObjCObjectPointerType(Result);
7629 return getObjCObjectPointerType(QualType(LHS, 0));
7632 // Find the superclass.
7633 QualType LHSSuperType = LHS->getSuperClassType();
7634 if (LHSSuperType.isNull())
7637 LHS = LHSSuperType->castAs<ObjCObjectType>();
7640 // We didn't find anything by following the LHS to its root; now check
7641 // the RHS against the cached set of ancestors.
7643 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7644 if (KnownLHS != LHSAncestors.end()) {
7645 LHS = KnownLHS->second;
7647 // Get the type arguments.
7648 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7649 bool anyChanges = false;
7650 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7651 // Both have type arguments, compare them.
7652 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7653 LHS->getTypeArgs(), RHS->getTypeArgs(),
7654 /*stripKindOf=*/true))
7656 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7657 // If only one has type arguments, the result will not have type
7663 // Compute the intersection of protocols.
7664 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7665 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7667 if (!Protocols.empty())
7670 // If we need to return a kindof type but RHS is not a kindof type, we
7671 // build a new result type.
7672 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7673 QualType Result = getObjCInterfaceType(RHS->getInterface());
7674 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7675 anyKindOf || RHS->isKindOfType());
7676 return getObjCObjectPointerType(Result);
7679 return getObjCObjectPointerType(QualType(RHS, 0));
7682 // Find the superclass of the RHS.
7683 QualType RHSSuperType = RHS->getSuperClassType();
7684 if (RHSSuperType.isNull())
7687 RHS = RHSSuperType->castAs<ObjCObjectType>();
7693 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7694 const ObjCObjectType *RHS) {
7695 assert(LHS->getInterface() && "LHS is not an interface type");
7696 assert(RHS->getInterface() && "RHS is not an interface type");
7698 // Verify that the base decls are compatible: the RHS must be a subclass of
7700 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7701 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7705 // If the LHS has protocol qualifiers, determine whether all of them are
7706 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7708 if (LHS->getNumProtocols() > 0) {
7709 // OK if conversion of LHS to SuperClass results in narrowing of types
7710 // ; i.e., SuperClass may implement at least one of the protocols
7711 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7712 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7713 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7714 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7715 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7717 for (auto *RHSPI : RHS->quals())
7718 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7719 // If there is no protocols associated with RHS, it is not a match.
7720 if (SuperClassInheritedProtocols.empty())
7723 for (const auto *LHSProto : LHS->quals()) {
7724 bool SuperImplementsProtocol = false;
7725 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7726 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7727 SuperImplementsProtocol = true;
7730 if (!SuperImplementsProtocol)
7735 // If the LHS is specialized, we may need to check type arguments.
7736 if (LHS->isSpecialized()) {
7737 // Follow the superclass chain until we've matched the LHS class in the
7738 // hierarchy. This substitutes type arguments through.
7739 const ObjCObjectType *RHSSuper = RHS;
7740 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7741 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7743 // If the RHS is specializd, compare type arguments.
7744 if (RHSSuper->isSpecialized() &&
7745 !sameObjCTypeArgs(*this, LHS->getInterface(),
7746 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7747 /*stripKindOf=*/true)) {
7755 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7756 // get the "pointed to" types
7757 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7758 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7760 if (!LHSOPT || !RHSOPT)
7763 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7764 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7767 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7768 return canAssignObjCInterfaces(
7769 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7770 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7773 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7774 /// both shall have the identically qualified version of a compatible type.
7775 /// C99 6.2.7p1: Two types have compatible types if their types are the
7776 /// same. See 6.7.[2,3,5] for additional rules.
7777 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7778 bool CompareUnqualified) {
7779 if (getLangOpts().CPlusPlus)
7780 return hasSameType(LHS, RHS);
7782 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7785 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7786 return typesAreCompatible(LHS, RHS);
7789 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7790 return !mergeTypes(LHS, RHS, true).isNull();
7793 /// mergeTransparentUnionType - if T is a transparent union type and a member
7794 /// of T is compatible with SubType, return the merged type, else return
7796 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7797 bool OfBlockPointer,
7799 if (const RecordType *UT = T->getAsUnionType()) {
7800 RecordDecl *UD = UT->getDecl();
7801 if (UD->hasAttr<TransparentUnionAttr>()) {
7802 for (const auto *I : UD->fields()) {
7803 QualType ET = I->getType().getUnqualifiedType();
7804 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7814 /// mergeFunctionParameterTypes - merge two types which appear as function
7816 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7817 bool OfBlockPointer,
7819 // GNU extension: two types are compatible if they appear as a function
7820 // argument, one of the types is a transparent union type and the other
7821 // type is compatible with a union member
7822 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7824 if (!lmerge.isNull())
7827 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7829 if (!rmerge.isNull())
7832 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7835 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7836 bool OfBlockPointer,
7838 const FunctionType *lbase = lhs->getAs<FunctionType>();
7839 const FunctionType *rbase = rhs->getAs<FunctionType>();
7840 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7841 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7842 bool allLTypes = true;
7843 bool allRTypes = true;
7845 // Check return type
7847 if (OfBlockPointer) {
7848 QualType RHS = rbase->getReturnType();
7849 QualType LHS = lbase->getReturnType();
7850 bool UnqualifiedResult = Unqualified;
7851 if (!UnqualifiedResult)
7852 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7853 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7856 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7858 if (retType.isNull()) return QualType();
7861 retType = retType.getUnqualifiedType();
7863 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7864 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7866 LRetType = LRetType.getUnqualifiedType();
7867 RRetType = RRetType.getUnqualifiedType();
7870 if (getCanonicalType(retType) != LRetType)
7872 if (getCanonicalType(retType) != RRetType)
7875 // FIXME: double check this
7876 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7877 // rbase->getRegParmAttr() != 0 &&
7878 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7879 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7880 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7882 // Compatible functions must have compatible calling conventions
7883 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7886 // Regparm is part of the calling convention.
7887 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7889 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7892 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7895 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7896 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7898 if (lbaseInfo.getNoReturn() != NoReturn)
7900 if (rbaseInfo.getNoReturn() != NoReturn)
7903 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7905 if (lproto && rproto) { // two C99 style function prototypes
7906 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7907 "C++ shouldn't be here");
7908 // Compatible functions must have the same number of parameters
7909 if (lproto->getNumParams() != rproto->getNumParams())
7912 // Variadic and non-variadic functions aren't compatible
7913 if (lproto->isVariadic() != rproto->isVariadic())
7916 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7919 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7922 // Check parameter type compatibility
7923 SmallVector<QualType, 10> types;
7924 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7925 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7926 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7927 QualType paramType = mergeFunctionParameterTypes(
7928 lParamType, rParamType, OfBlockPointer, Unqualified);
7929 if (paramType.isNull())
7933 paramType = paramType.getUnqualifiedType();
7935 types.push_back(paramType);
7937 lParamType = lParamType.getUnqualifiedType();
7938 rParamType = rParamType.getUnqualifiedType();
7941 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7943 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7947 if (allLTypes) return lhs;
7948 if (allRTypes) return rhs;
7950 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7951 EPI.ExtInfo = einfo;
7952 return getFunctionType(retType, types, EPI);
7955 if (lproto) allRTypes = false;
7956 if (rproto) allLTypes = false;
7958 const FunctionProtoType *proto = lproto ? lproto : rproto;
7960 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7961 if (proto->isVariadic()) return QualType();
7962 // Check that the types are compatible with the types that
7963 // would result from default argument promotions (C99 6.7.5.3p15).
7964 // The only types actually affected are promotable integer
7965 // types and floats, which would be passed as a different
7966 // type depending on whether the prototype is visible.
7967 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7968 QualType paramTy = proto->getParamType(i);
7970 // Look at the converted type of enum types, since that is the type used
7971 // to pass enum values.
7972 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7973 paramTy = Enum->getDecl()->getIntegerType();
7974 if (paramTy.isNull())
7978 if (paramTy->isPromotableIntegerType() ||
7979 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7983 if (allLTypes) return lhs;
7984 if (allRTypes) return rhs;
7986 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7987 EPI.ExtInfo = einfo;
7988 return getFunctionType(retType, proto->getParamTypes(), EPI);
7991 if (allLTypes) return lhs;
7992 if (allRTypes) return rhs;
7993 return getFunctionNoProtoType(retType, einfo);
7996 /// Given that we have an enum type and a non-enum type, try to merge them.
7997 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7998 QualType other, bool isBlockReturnType) {
7999 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8000 // a signed integer type, or an unsigned integer type.
8001 // Compatibility is based on the underlying type, not the promotion
8003 QualType underlyingType = ET->getDecl()->getIntegerType();
8004 if (underlyingType.isNull()) return QualType();
8005 if (Context.hasSameType(underlyingType, other))
8008 // In block return types, we're more permissive and accept any
8009 // integral type of the same size.
8010 if (isBlockReturnType && other->isIntegerType() &&
8011 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8017 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
8018 bool OfBlockPointer,
8019 bool Unqualified, bool BlockReturnType) {
8020 // C++ [expr]: If an expression initially has the type "reference to T", the
8021 // type is adjusted to "T" prior to any further analysis, the expression
8022 // designates the object or function denoted by the reference, and the
8023 // expression is an lvalue unless the reference is an rvalue reference and
8024 // the expression is a function call (possibly inside parentheses).
8025 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8026 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8029 LHS = LHS.getUnqualifiedType();
8030 RHS = RHS.getUnqualifiedType();
8033 QualType LHSCan = getCanonicalType(LHS),
8034 RHSCan = getCanonicalType(RHS);
8036 // If two types are identical, they are compatible.
8037 if (LHSCan == RHSCan)
8040 // If the qualifiers are different, the types aren't compatible... mostly.
8041 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8042 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8043 if (LQuals != RQuals) {
8044 if (getLangOpts().OpenCL) {
8045 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
8046 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
8048 if (LQuals.isAddressSpaceSupersetOf(RQuals))
8050 if (RQuals.isAddressSpaceSupersetOf(LQuals))
8053 // If any of these qualifiers are different, we have a type
8055 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8056 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8057 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
8060 // Exactly one GC qualifier difference is allowed: __strong is
8061 // okay if the other type has no GC qualifier but is an Objective
8062 // C object pointer (i.e. implicitly strong by default). We fix
8063 // this by pretending that the unqualified type was actually
8064 // qualified __strong.
8065 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8066 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8067 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8069 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8072 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8073 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8075 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8076 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8081 // Okay, qualifiers are equal.
8083 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8084 Type::TypeClass RHSClass = RHSCan->getTypeClass();
8086 // We want to consider the two function types to be the same for these
8087 // comparisons, just force one to the other.
8088 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8089 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8091 // Same as above for arrays
8092 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8093 LHSClass = Type::ConstantArray;
8094 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8095 RHSClass = Type::ConstantArray;
8097 // ObjCInterfaces are just specialized ObjCObjects.
8098 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8099 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8101 // Canonicalize ExtVector -> Vector.
8102 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8103 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8105 // If the canonical type classes don't match.
8106 if (LHSClass != RHSClass) {
8107 // Note that we only have special rules for turning block enum
8108 // returns into block int returns, not vice-versa.
8109 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
8110 return mergeEnumWithInteger(*this, ETy, RHS, false);
8112 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8113 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8115 // allow block pointer type to match an 'id' type.
8116 if (OfBlockPointer && !BlockReturnType) {
8117 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8119 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8126 // The canonical type classes match.
8128 #define TYPE(Class, Base)
8129 #define ABSTRACT_TYPE(Class, Base)
8130 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8131 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8132 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8133 #include "clang/AST/TypeNodes.def"
8134 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8137 case Type::LValueReference:
8138 case Type::RValueReference:
8139 case Type::MemberPointer:
8140 llvm_unreachable("C++ should never be in mergeTypes");
8142 case Type::ObjCInterface:
8143 case Type::IncompleteArray:
8144 case Type::VariableArray:
8145 case Type::FunctionProto:
8146 case Type::ExtVector:
8147 llvm_unreachable("Types are eliminated above");
8151 // Merge two pointer types, while trying to preserve typedef info
8152 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8153 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8155 LHSPointee = LHSPointee.getUnqualifiedType();
8156 RHSPointee = RHSPointee.getUnqualifiedType();
8158 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8160 if (ResultType.isNull()) return QualType();
8161 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8163 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8165 return getPointerType(ResultType);
8167 case Type::BlockPointer:
8169 // Merge two block pointer types, while trying to preserve typedef info
8170 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8171 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8173 LHSPointee = LHSPointee.getUnqualifiedType();
8174 RHSPointee = RHSPointee.getUnqualifiedType();
8176 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8178 if (ResultType.isNull()) return QualType();
8179 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8181 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8183 return getBlockPointerType(ResultType);
8187 // Merge two pointer types, while trying to preserve typedef info
8188 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8189 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8191 LHSValue = LHSValue.getUnqualifiedType();
8192 RHSValue = RHSValue.getUnqualifiedType();
8194 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8196 if (ResultType.isNull()) return QualType();
8197 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8199 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8201 return getAtomicType(ResultType);
8203 case Type::ConstantArray:
8205 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8206 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8207 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8210 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8211 QualType RHSElem = getAsArrayType(RHS)->getElementType();
8213 LHSElem = LHSElem.getUnqualifiedType();
8214 RHSElem = RHSElem.getUnqualifiedType();
8217 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8218 if (ResultType.isNull()) return QualType();
8219 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8221 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8223 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8224 ArrayType::ArraySizeModifier(), 0);
8225 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8226 ArrayType::ArraySizeModifier(), 0);
8227 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8228 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8229 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8231 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8234 // FIXME: This isn't correct! But tricky to implement because
8235 // the array's size has to be the size of LHS, but the type
8236 // has to be different.
8240 // FIXME: This isn't correct! But tricky to implement because
8241 // the array's size has to be the size of RHS, but the type
8242 // has to be different.
8245 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8246 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
8247 return getIncompleteArrayType(ResultType,
8248 ArrayType::ArraySizeModifier(), 0);
8250 case Type::FunctionNoProto:
8251 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
8256 // Only exactly equal builtin types are compatible, which is tested above.
8259 // Distinct complex types are incompatible.
8262 // FIXME: The merged type should be an ExtVector!
8263 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8264 RHSCan->getAs<VectorType>()))
8267 case Type::ObjCObject: {
8268 // Check if the types are assignment compatible.
8269 // FIXME: This should be type compatibility, e.g. whether
8270 // "LHS x; RHS x;" at global scope is legal.
8271 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8272 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8273 if (canAssignObjCInterfaces(LHSIface, RHSIface))
8278 case Type::ObjCObjectPointer: {
8279 if (OfBlockPointer) {
8280 if (canAssignObjCInterfacesInBlockPointer(
8281 LHS->getAs<ObjCObjectPointerType>(),
8282 RHS->getAs<ObjCObjectPointerType>(),
8287 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8288 RHS->getAs<ObjCObjectPointerType>()))
8295 assert(LHS != RHS &&
8296 "Equivalent pipe types should have already been handled!");
8301 llvm_unreachable("Invalid Type::Class!");
8304 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8305 const FunctionProtoType *firstFnType,
8306 const FunctionProtoType *secondFnType) {
8307 // Fast path: if the first type doesn't have ext parameter infos,
8308 // we match if and only if they second type also doesn't have them.
8309 if (!firstFnType->hasExtParameterInfos())
8310 return !secondFnType->hasExtParameterInfos();
8312 // Otherwise, we can only match if the second type has them.
8313 if (!secondFnType->hasExtParameterInfos())
8316 auto firstEPI = firstFnType->getExtParameterInfos();
8317 auto secondEPI = secondFnType->getExtParameterInfos();
8318 assert(firstEPI.size() == secondEPI.size());
8320 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8321 if (firstEPI[i] != secondEPI[i])
8327 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8328 ObjCLayouts[CD] = nullptr;
8331 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8332 /// 'RHS' attributes and returns the merged version; including for function
8334 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8335 QualType LHSCan = getCanonicalType(LHS),
8336 RHSCan = getCanonicalType(RHS);
8337 // If two types are identical, they are compatible.
8338 if (LHSCan == RHSCan)
8340 if (RHSCan->isFunctionType()) {
8341 if (!LHSCan->isFunctionType())
8343 QualType OldReturnType =
8344 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
8345 QualType NewReturnType =
8346 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
8347 QualType ResReturnType =
8348 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8349 if (ResReturnType.isNull())
8351 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8352 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8353 // In either case, use OldReturnType to build the new function type.
8354 const FunctionType *F = LHS->getAs<FunctionType>();
8355 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
8356 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8357 EPI.ExtInfo = getFunctionExtInfo(LHS);
8358 QualType ResultType =
8359 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
8366 // If the qualifiers are different, the types can still be merged.
8367 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8368 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8369 if (LQuals != RQuals) {
8370 // If any of these qualifiers are different, we have a type mismatch.
8371 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8372 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8375 // Exactly one GC qualifier difference is allowed: __strong is
8376 // okay if the other type has no GC qualifier but is an Objective
8377 // C object pointer (i.e. implicitly strong by default). We fix
8378 // this by pretending that the unqualified type was actually
8379 // qualified __strong.
8380 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8381 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8382 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8384 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8387 if (GC_L == Qualifiers::Strong)
8389 if (GC_R == Qualifiers::Strong)
8394 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8395 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8396 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8397 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8398 if (ResQT == LHSBaseQT)
8400 if (ResQT == RHSBaseQT)
8406 //===----------------------------------------------------------------------===//
8407 // Integer Predicates
8408 //===----------------------------------------------------------------------===//
8410 unsigned ASTContext::getIntWidth(QualType T) const {
8411 if (const EnumType *ET = T->getAs<EnumType>())
8412 T = ET->getDecl()->getIntegerType();
8413 if (T->isBooleanType())
8415 // For builtin types, just use the standard type sizing method
8416 return (unsigned)getTypeSize(T);
8419 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8420 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8422 // Turn <4 x signed int> -> <4 x unsigned int>
8423 if (const VectorType *VTy = T->getAs<VectorType>())
8424 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8425 VTy->getNumElements(), VTy->getVectorKind());
8427 // For enums, we return the unsigned version of the base type.
8428 if (const EnumType *ETy = T->getAs<EnumType>())
8429 T = ETy->getDecl()->getIntegerType();
8431 const BuiltinType *BTy = T->getAs<BuiltinType>();
8432 assert(BTy && "Unexpected signed integer type");
8433 switch (BTy->getKind()) {
8434 case BuiltinType::Char_S:
8435 case BuiltinType::SChar:
8436 return UnsignedCharTy;
8437 case BuiltinType::Short:
8438 return UnsignedShortTy;
8439 case BuiltinType::Int:
8440 return UnsignedIntTy;
8441 case BuiltinType::Long:
8442 return UnsignedLongTy;
8443 case BuiltinType::LongLong:
8444 return UnsignedLongLongTy;
8445 case BuiltinType::Int128:
8446 return UnsignedInt128Ty;
8448 llvm_unreachable("Unexpected signed integer type");
8452 ASTMutationListener::~ASTMutationListener() { }
8454 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8455 QualType ReturnType) {}
8457 //===----------------------------------------------------------------------===//
8458 // Builtin Type Computation
8459 //===----------------------------------------------------------------------===//
8461 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8462 /// pointer over the consumed characters. This returns the resultant type. If
8463 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8464 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8465 /// a vector of "i*".
8467 /// RequiresICE is filled in on return to indicate whether the value is required
8468 /// to be an Integer Constant Expression.
8469 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8470 ASTContext::GetBuiltinTypeError &Error,
8472 bool AllowTypeModifiers) {
8475 bool Signed = false, Unsigned = false;
8476 RequiresICE = false;
8478 // Read the prefixed modifiers first.
8482 default: Done = true; --Str; break;
8487 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8488 assert(!Signed && "Can't use 'S' modifier multiple times!");
8492 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8493 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8497 assert(HowLong <= 2 && "Can't have LLLL modifier");
8501 // This modifier represents int64 type.
8502 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8503 switch (Context.getTargetInfo().getInt64Type()) {
8505 llvm_unreachable("Unexpected integer type");
8506 case TargetInfo::SignedLong:
8509 case TargetInfo::SignedLongLong:
8518 // Read the base type.
8520 default: llvm_unreachable("Unknown builtin type letter!");
8522 assert(HowLong == 0 && !Signed && !Unsigned &&
8523 "Bad modifiers used with 'v'!");
8524 Type = Context.VoidTy;
8527 assert(HowLong == 0 && !Signed && !Unsigned &&
8528 "Bad modifiers used with 'h'!");
8529 Type = Context.HalfTy;
8532 assert(HowLong == 0 && !Signed && !Unsigned &&
8533 "Bad modifiers used with 'f'!");
8534 Type = Context.FloatTy;
8537 assert(HowLong < 2 && !Signed && !Unsigned &&
8538 "Bad modifiers used with 'd'!");
8540 Type = Context.LongDoubleTy;
8542 Type = Context.DoubleTy;
8545 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8547 Type = Context.UnsignedShortTy;
8549 Type = Context.ShortTy;
8553 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8554 else if (HowLong == 2)
8555 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8556 else if (HowLong == 1)
8557 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8559 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8562 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8564 Type = Context.SignedCharTy;
8566 Type = Context.UnsignedCharTy;
8568 Type = Context.CharTy;
8570 case 'b': // boolean
8571 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8572 Type = Context.BoolTy;
8574 case 'z': // size_t.
8575 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8576 Type = Context.getSizeType();
8578 case 'w': // wchar_t.
8579 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8580 Type = Context.getWideCharType();
8583 Type = Context.getCFConstantStringType();
8586 Type = Context.getObjCIdType();
8589 Type = Context.getObjCSelType();
8592 Type = Context.getObjCSuperType();
8595 Type = Context.getBuiltinVaListType();
8596 assert(!Type.isNull() && "builtin va list type not initialized!");
8599 // This is a "reference" to a va_list; however, what exactly
8600 // this means depends on how va_list is defined. There are two
8601 // different kinds of va_list: ones passed by value, and ones
8602 // passed by reference. An example of a by-value va_list is
8603 // x86, where va_list is a char*. An example of by-ref va_list
8604 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8605 // we want this argument to be a char*&; for x86-64, we want
8606 // it to be a __va_list_tag*.
8607 Type = Context.getBuiltinVaListType();
8608 assert(!Type.isNull() && "builtin va list type not initialized!");
8609 if (Type->isArrayType())
8610 Type = Context.getArrayDecayedType(Type);
8612 Type = Context.getLValueReferenceType(Type);
8616 unsigned NumElements = strtoul(Str, &End, 10);
8617 assert(End != Str && "Missing vector size");
8620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8621 RequiresICE, false);
8622 assert(!RequiresICE && "Can't require vector ICE");
8624 // TODO: No way to make AltiVec vectors in builtins yet.
8625 Type = Context.getVectorType(ElementType, NumElements,
8626 VectorType::GenericVector);
8632 unsigned NumElements = strtoul(Str, &End, 10);
8633 assert(End != Str && "Missing vector size");
8637 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8639 Type = Context.getExtVectorType(ElementType, NumElements);
8643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8645 assert(!RequiresICE && "Can't require complex ICE");
8646 Type = Context.getComplexType(ElementType);
8650 Type = Context.getPointerDiffType();
8654 Type = Context.getFILEType();
8655 if (Type.isNull()) {
8656 Error = ASTContext::GE_Missing_stdio;
8662 Type = Context.getsigjmp_bufType();
8664 Type = Context.getjmp_bufType();
8666 if (Type.isNull()) {
8667 Error = ASTContext::GE_Missing_setjmp;
8672 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8673 Type = Context.getucontext_tType();
8675 if (Type.isNull()) {
8676 Error = ASTContext::GE_Missing_ucontext;
8681 Type = Context.getProcessIDType();
8685 // If there are modifiers and if we're allowed to parse them, go for it.
8686 Done = !AllowTypeModifiers;
8688 switch (char c = *Str++) {
8689 default: Done = true; --Str; break;
8692 // Both pointers and references can have their pointee types
8693 // qualified with an address space.
8695 unsigned AddrSpace = strtoul(Str, &End, 10);
8696 if (End != Str && AddrSpace != 0) {
8697 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8701 Type = Context.getPointerType(Type);
8703 Type = Context.getLValueReferenceType(Type);
8706 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8708 Type = Type.withConst();
8711 Type = Context.getVolatileType(Type);
8714 Type = Type.withRestrict();
8719 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8720 "Integer constant 'I' type must be an integer");
8725 /// GetBuiltinType - Return the type for the specified builtin.
8726 QualType ASTContext::GetBuiltinType(unsigned Id,
8727 GetBuiltinTypeError &Error,
8728 unsigned *IntegerConstantArgs) const {
8729 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8731 SmallVector<QualType, 8> ArgTypes;
8733 bool RequiresICE = false;
8735 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8737 if (Error != GE_None)
8740 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8742 while (TypeStr[0] && TypeStr[0] != '.') {
8743 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8744 if (Error != GE_None)
8747 // If this argument is required to be an IntegerConstantExpression and the
8748 // caller cares, fill in the bitmask we return.
8749 if (RequiresICE && IntegerConstantArgs)
8750 *IntegerConstantArgs |= 1 << ArgTypes.size();
8752 // Do array -> pointer decay. The builtin should use the decayed type.
8753 if (Ty->isArrayType())
8754 Ty = getArrayDecayedType(Ty);
8756 ArgTypes.push_back(Ty);
8759 if (Id == Builtin::BI__GetExceptionInfo)
8762 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8763 "'.' should only occur at end of builtin type list!");
8765 FunctionType::ExtInfo EI(CC_C);
8766 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8768 bool Variadic = (TypeStr[0] == '.');
8770 // We really shouldn't be making a no-proto type here.
8771 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
8772 return getFunctionNoProtoType(ResType, EI);
8774 FunctionProtoType::ExtProtoInfo EPI;
8776 EPI.Variadic = Variadic;
8777 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8778 EPI.ExceptionSpec.Type =
8779 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
8781 return getFunctionType(ResType, ArgTypes, EPI);
8784 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8785 const FunctionDecl *FD) {
8786 if (!FD->isExternallyVisible())
8787 return GVA_Internal;
8789 GVALinkage External = GVA_StrongExternal;
8790 switch (FD->getTemplateSpecializationKind()) {
8791 case TSK_Undeclared:
8792 case TSK_ExplicitSpecialization:
8793 External = GVA_StrongExternal;
8796 case TSK_ExplicitInstantiationDefinition:
8797 return GVA_StrongODR;
8799 // C++11 [temp.explicit]p10:
8800 // [ Note: The intent is that an inline function that is the subject of
8801 // an explicit instantiation declaration will still be implicitly
8802 // instantiated when used so that the body can be considered for
8803 // inlining, but that no out-of-line copy of the inline function would be
8804 // generated in the translation unit. -- end note ]
8805 case TSK_ExplicitInstantiationDeclaration:
8806 return GVA_AvailableExternally;
8808 case TSK_ImplicitInstantiation:
8809 External = GVA_DiscardableODR;
8813 if (!FD->isInlined())
8816 if ((!Context.getLangOpts().CPlusPlus &&
8817 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8818 !FD->hasAttr<DLLExportAttr>()) ||
8819 FD->hasAttr<GNUInlineAttr>()) {
8820 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8822 // GNU or C99 inline semantics. Determine whether this symbol should be
8823 // externally visible.
8824 if (FD->isInlineDefinitionExternallyVisible())
8827 // C99 inline semantics, where the symbol is not externally visible.
8828 return GVA_AvailableExternally;
8831 // Functions specified with extern and inline in -fms-compatibility mode
8832 // forcibly get emitted. While the body of the function cannot be later
8833 // replaced, the function definition cannot be discarded.
8834 if (FD->isMSExternInline())
8835 return GVA_StrongODR;
8837 return GVA_DiscardableODR;
8840 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8841 GVALinkage L, const Decl *D) {
8842 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8843 // dllexport/dllimport on inline functions.
8844 if (D->hasAttr<DLLImportAttr>()) {
8845 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8846 return GVA_AvailableExternally;
8847 } else if (D->hasAttr<DLLExportAttr>()) {
8848 if (L == GVA_DiscardableODR)
8849 return GVA_StrongODR;
8850 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8851 D->hasAttr<CUDAGlobalAttr>()) {
8852 // Device-side functions with __global__ attribute must always be
8853 // visible externally so they can be launched from host.
8854 if (L == GVA_DiscardableODR || L == GVA_Internal)
8855 return GVA_StrongODR;
8860 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8861 return adjustGVALinkageForAttributes(
8862 *this, basicGVALinkageForFunction(*this, FD), FD);
8865 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8866 const VarDecl *VD) {
8867 if (!VD->isExternallyVisible())
8868 return GVA_Internal;
8870 if (VD->isStaticLocal()) {
8871 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8872 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8873 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8874 LexicalContext = LexicalContext->getLexicalParent();
8876 // Let the static local variable inherit its linkage from the nearest
8877 // enclosing function.
8879 StaticLocalLinkage =
8880 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8882 // GVA_StrongODR function linkage is stronger than what we need,
8883 // downgrade to GVA_DiscardableODR.
8884 // This allows us to discard the variable if we never end up needing it.
8885 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8886 : StaticLocalLinkage;
8889 // MSVC treats in-class initialized static data members as definitions.
8890 // By giving them non-strong linkage, out-of-line definitions won't
8891 // cause link errors.
8892 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8893 return GVA_DiscardableODR;
8895 // Most non-template variables have strong linkage; inline variables are
8896 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8897 GVALinkage StrongLinkage;
8898 switch (Context.getInlineVariableDefinitionKind(VD)) {
8899 case ASTContext::InlineVariableDefinitionKind::None:
8900 StrongLinkage = GVA_StrongExternal;
8902 case ASTContext::InlineVariableDefinitionKind::Weak:
8903 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8904 StrongLinkage = GVA_DiscardableODR;
8906 case ASTContext::InlineVariableDefinitionKind::Strong:
8907 StrongLinkage = GVA_StrongODR;
8911 switch (VD->getTemplateSpecializationKind()) {
8912 case TSK_Undeclared:
8913 return StrongLinkage;
8915 case TSK_ExplicitSpecialization:
8916 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8917 VD->isStaticDataMember()
8921 case TSK_ExplicitInstantiationDefinition:
8922 return GVA_StrongODR;
8924 case TSK_ExplicitInstantiationDeclaration:
8925 return GVA_AvailableExternally;
8927 case TSK_ImplicitInstantiation:
8928 return GVA_DiscardableODR;
8931 llvm_unreachable("Invalid Linkage!");
8934 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8935 return adjustGVALinkageForAttributes(
8936 *this, basicGVALinkageForVariable(*this, VD), VD);
8939 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8940 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8941 if (!VD->isFileVarDecl())
8943 // Global named register variables (GNU extension) are never emitted.
8944 if (VD->getStorageClass() == SC_Register)
8946 if (VD->getDescribedVarTemplate() ||
8947 isa<VarTemplatePartialSpecializationDecl>(VD))
8949 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8950 // We never need to emit an uninstantiated function template.
8951 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8953 } else if (isa<PragmaCommentDecl>(D))
8955 else if (isa<OMPThreadPrivateDecl>(D) ||
8956 D->hasAttr<OMPDeclareTargetDeclAttr>())
8958 else if (isa<PragmaDetectMismatchDecl>(D))
8960 else if (isa<OMPThreadPrivateDecl>(D))
8961 return !D->getDeclContext()->isDependentContext();
8962 else if (isa<OMPDeclareReductionDecl>(D))
8963 return !D->getDeclContext()->isDependentContext();
8964 else if (isa<ImportDecl>(D))
8969 // If this is a member of a class template, we do not need to emit it.
8970 if (D->getDeclContext()->isDependentContext())
8973 // Weak references don't produce any output by themselves.
8974 if (D->hasAttr<WeakRefAttr>())
8977 // Aliases and used decls are required.
8978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8982 // Forward declarations aren't required.
8983 if (!FD->doesThisDeclarationHaveABody())
8984 return FD->doesDeclarationForceExternallyVisibleDefinition();
8986 // Constructors and destructors are required.
8987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8990 // The key function for a class is required. This rule only comes
8991 // into play when inline functions can be key functions, though.
8992 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8993 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8994 const CXXRecordDecl *RD = MD->getParent();
8995 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8996 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8997 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9003 // static, static inline, always_inline, and extern inline functions can
9004 // always be deferred. Normal inline functions can be deferred in C99/C++.
9005 // Implicit template instantiations can also be deferred in C++.
9006 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
9009 const VarDecl *VD = cast<VarDecl>(D);
9010 assert(VD->isFileVarDecl() && "Expected file scoped var");
9012 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9013 !isMSStaticDataMemberInlineDefinition(VD))
9016 // Variables that can be needed in other TUs are required.
9017 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
9020 // Variables that have destruction with side-effects are required.
9021 if (VD->getType().isDestructedType())
9024 // Variables that have initialization with side-effects are required.
9025 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9026 !VD->evaluateValue())
9029 // Likewise, variables with tuple-like bindings are required if their
9030 // bindings have side-effects.
9031 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9032 for (auto *BD : DD->bindings())
9033 if (auto *BindingVD = BD->getHoldingVar())
9034 if (DeclMustBeEmitted(BindingVD))
9040 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9041 bool IsCXXMethod) const {
9042 // Pass through to the C++ ABI object
9044 return ABI->getDefaultMethodCallConv(IsVariadic);
9046 switch (LangOpts.getDefaultCallingConv()) {
9047 case LangOptions::DCC_None:
9049 case LangOptions::DCC_CDecl:
9051 case LangOptions::DCC_FastCall:
9052 if (getTargetInfo().hasFeature("sse2"))
9053 return CC_X86FastCall;
9055 case LangOptions::DCC_StdCall:
9057 return CC_X86StdCall;
9059 case LangOptions::DCC_VectorCall:
9060 // __vectorcall cannot be applied to variadic functions.
9062 return CC_X86VectorCall;
9065 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
9068 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
9069 // Pass through to the C++ ABI object
9070 return ABI->isNearlyEmpty(RD);
9073 VTableContextBase *ASTContext::getVTableContext() {
9074 if (!VTContext.get()) {
9075 if (Target->getCXXABI().isMicrosoft())
9076 VTContext.reset(new MicrosoftVTableContext(*this));
9078 VTContext.reset(new ItaniumVTableContext(*this));
9080 return VTContext.get();
9083 MangleContext *ASTContext::createMangleContext() {
9084 switch (Target->getCXXABI().getKind()) {
9085 case TargetCXXABI::GenericAArch64:
9086 case TargetCXXABI::GenericItanium:
9087 case TargetCXXABI::GenericARM:
9088 case TargetCXXABI::GenericMIPS:
9089 case TargetCXXABI::iOS:
9090 case TargetCXXABI::iOS64:
9091 case TargetCXXABI::WebAssembly:
9092 case TargetCXXABI::WatchOS:
9093 return ItaniumMangleContext::create(*this, getDiagnostics());
9094 case TargetCXXABI::Microsoft:
9095 return MicrosoftMangleContext::create(*this, getDiagnostics());
9097 llvm_unreachable("Unsupported ABI");
9100 CXXABI::~CXXABI() {}
9102 size_t ASTContext::getSideTableAllocatedMemory() const {
9103 return ASTRecordLayouts.getMemorySize() +
9104 llvm::capacity_in_bytes(ObjCLayouts) +
9105 llvm::capacity_in_bytes(KeyFunctions) +
9106 llvm::capacity_in_bytes(ObjCImpls) +
9107 llvm::capacity_in_bytes(BlockVarCopyInits) +
9108 llvm::capacity_in_bytes(DeclAttrs) +
9109 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9110 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9111 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9112 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9113 llvm::capacity_in_bytes(OverriddenMethods) +
9114 llvm::capacity_in_bytes(Types) +
9115 llvm::capacity_in_bytes(VariableArrayTypes) +
9116 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
9119 /// getIntTypeForBitwidth -
9120 /// sets integer QualTy according to specified details:
9121 /// bitwidth, signed/unsigned.
9122 /// Returns empty type if there is no appropriate target types.
9123 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9124 unsigned Signed) const {
9125 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9126 CanQualType QualTy = getFromTargetType(Ty);
9127 if (!QualTy && DestWidth == 128)
9128 return Signed ? Int128Ty : UnsignedInt128Ty;
9132 /// getRealTypeForBitwidth -
9133 /// sets floating point QualTy according to specified bitwidth.
9134 /// Returns empty type if there is no appropriate target types.
9135 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9136 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9138 case TargetInfo::Float:
9140 case TargetInfo::Double:
9142 case TargetInfo::LongDouble:
9143 return LongDoubleTy;
9144 case TargetInfo::Float128:
9146 case TargetInfo::NoFloat:
9150 llvm_unreachable("Unhandled TargetInfo::RealType value");
9153 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9155 MangleNumbers[ND] = Number;
9158 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
9159 auto I = MangleNumbers.find(ND);
9160 return I != MangleNumbers.end() ? I->second : 1;
9163 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9165 StaticLocalNumbers[VD] = Number;
9168 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
9169 auto I = StaticLocalNumbers.find(VD);
9170 return I != StaticLocalNumbers.end() ? I->second : 1;
9173 MangleNumberingContext &
9174 ASTContext::getManglingNumberContext(const DeclContext *DC) {
9175 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
9176 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
9178 MCtx = createMangleNumberingContext();
9182 std::unique_ptr<MangleNumberingContext>
9183 ASTContext::createMangleNumberingContext() const {
9184 return ABI->createMangleNumberingContext();
9187 const CXXConstructorDecl *
9188 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9189 return ABI->getCopyConstructorForExceptionObject(
9190 cast<CXXRecordDecl>(RD->getFirstDecl()));
9193 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9194 CXXConstructorDecl *CD) {
9195 return ABI->addCopyConstructorForExceptionObject(
9196 cast<CXXRecordDecl>(RD->getFirstDecl()),
9197 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9200 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9201 TypedefNameDecl *DD) {
9202 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9206 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9207 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9210 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9211 DeclaratorDecl *DD) {
9212 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9215 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9216 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9219 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9220 ParamIndices[D] = index;
9223 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9224 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9225 assert(I != ParamIndices.end() &&
9226 "ParmIndices lacks entry set by ParmVarDecl");
9231 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9233 assert(E && E->getStorageDuration() == SD_Static &&
9234 "don't need to cache the computed value for this temporary");
9236 APValue *&MTVI = MaterializedTemporaryValues[E];
9238 MTVI = new (*this) APValue;
9242 return MaterializedTemporaryValues.lookup(E);
9245 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9246 const llvm::Triple &T = getTargetInfo().getTriple();
9247 if (!T.isOSDarwin())
9250 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9251 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9254 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9255 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9256 uint64_t Size = sizeChars.getQuantity();
9257 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9258 unsigned Align = alignChars.getQuantity();
9259 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9260 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9265 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9266 ASTContext::ParentMapPointers::mapped_type U) {
9267 if (const auto *D = U.dyn_cast<const Decl *>())
9268 return ast_type_traits::DynTypedNode::create(*D);
9269 if (const auto *S = U.dyn_cast<const Stmt *>())
9270 return ast_type_traits::DynTypedNode::create(*S);
9271 return *U.get<ast_type_traits::DynTypedNode *>();
9274 /// Template specializations to abstract away from pointers and TypeLocs.
9276 template <typename T>
9277 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9278 return ast_type_traits::DynTypedNode::create(*Node);
9281 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9282 return ast_type_traits::DynTypedNode::create(Node);
9285 ast_type_traits::DynTypedNode
9286 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9287 return ast_type_traits::DynTypedNode::create(Node);
9291 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9292 /// parents as defined by the \c RecursiveASTVisitor.
9294 /// Note that the relationship described here is purely in terms of AST
9295 /// traversal - there are other relationships (for example declaration context)
9296 /// in the AST that are better modeled by special matchers.
9298 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
9299 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
9301 /// \brief Builds and returns the translation unit's parent map.
9303 /// The caller takes ownership of the returned \c ParentMap.
9304 static std::pair<ASTContext::ParentMapPointers *,
9305 ASTContext::ParentMapOtherNodes *>
9306 buildMap(TranslationUnitDecl &TU) {
9307 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9308 new ASTContext::ParentMapOtherNodes);
9309 Visitor.TraverseDecl(&TU);
9310 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
9314 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9316 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9317 ASTContext::ParentMapOtherNodes *OtherParents)
9318 : Parents(Parents), OtherParents(OtherParents) {}
9320 bool shouldVisitTemplateInstantiations() const {
9323 bool shouldVisitImplicitCode() const {
9327 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9329 bool TraverseNode(T Node, MapNodeTy MapNode,
9330 BaseTraverseFn BaseTraverse, MapTy *Parents) {
9333 if (ParentStack.size() > 0) {
9334 // FIXME: Currently we add the same parent multiple times, but only
9335 // when no memoization data is available for the type.
9336 // For example when we visit all subexpressions of template
9337 // instantiations; this is suboptimal, but benign: the only way to
9338 // visit those is with hasAncestor / hasParent, and those do not create
9340 // The plan is to enable DynTypedNode to be storable in a map or hash
9341 // map. The main problem there is to implement hash functions /
9342 // comparison operators for all types that DynTypedNode supports that
9343 // do not have pointer identity.
9344 auto &NodeOrVector = (*Parents)[MapNode];
9345 if (NodeOrVector.isNull()) {
9346 if (const auto *D = ParentStack.back().get<Decl>())
9348 else if (const auto *S = ParentStack.back().get<Stmt>())
9352 new ast_type_traits::DynTypedNode(ParentStack.back());
9354 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9355 auto *Vector = new ASTContext::ParentVector(
9356 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
9359 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9361 NodeOrVector = Vector;
9365 NodeOrVector.template get<ASTContext::ParentVector *>();
9366 // Skip duplicates for types that have memoization data.
9367 // We must check that the type has memoization data before calling
9368 // std::find() because DynTypedNode::operator== can't compare all
9370 bool Found = ParentStack.back().getMemoizationData() &&
9371 std::find(Vector->begin(), Vector->end(),
9372 ParentStack.back()) != Vector->end();
9374 Vector->push_back(ParentStack.back());
9377 ParentStack.push_back(createDynTypedNode(Node));
9378 bool Result = BaseTraverse();
9379 ParentStack.pop_back();
9383 bool TraverseDecl(Decl *DeclNode) {
9384 return TraverseNode(DeclNode, DeclNode,
9385 [&] { return VisitorBase::TraverseDecl(DeclNode); },
9389 bool TraverseStmt(Stmt *StmtNode) {
9390 return TraverseNode(StmtNode, StmtNode,
9391 [&] { return VisitorBase::TraverseStmt(StmtNode); },
9395 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9396 return TraverseNode(
9397 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9398 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9402 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9403 return TraverseNode(
9404 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9406 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9411 ASTContext::ParentMapPointers *Parents;
9412 ASTContext::ParentMapOtherNodes *OtherParents;
9413 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9415 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9418 } // anonymous namespace
9420 template <typename NodeTy, typename MapTy>
9421 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9423 auto I = Map.find(Node);
9424 if (I == Map.end()) {
9425 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9427 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9428 return llvm::makeArrayRef(*V);
9430 return getSingleDynTypedNodeFromParentMap(I->second);
9433 ASTContext::DynTypedNodeList
9434 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9435 if (!PointerParents) {
9436 // We always need to run over the whole translation unit, as
9437 // hasAncestor can escape any subtree.
9438 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9439 PointerParents.reset(Maps.first);
9440 OtherParents.reset(Maps.second);
9442 if (Node.getNodeKind().hasPointerIdentity())
9443 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9444 return getDynNodeFromMap(Node, *OtherParents);
9448 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9449 const ObjCMethodDecl *MethodImpl) {
9450 // No point trying to match an unavailable/deprecated mothod.
9451 if (MethodDecl->hasAttr<UnavailableAttr>()
9452 || MethodDecl->hasAttr<DeprecatedAttr>())
9454 if (MethodDecl->getObjCDeclQualifier() !=
9455 MethodImpl->getObjCDeclQualifier())
9457 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9460 if (MethodDecl->param_size() != MethodImpl->param_size())
9463 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9464 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9465 EF = MethodDecl->param_end();
9466 IM != EM && IF != EF; ++IM, ++IF) {
9467 const ParmVarDecl *DeclVar = (*IF);
9468 const ParmVarDecl *ImplVar = (*IM);
9469 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9471 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9474 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9478 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9480 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9483 AS = QT->getPointeeType().getAddressSpace();
9485 return getTargetInfo().getNullPointerValue(AS);
9488 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9489 // doesn't include ASTContext.h
9491 clang::LazyGenerationalUpdatePtr<
9492 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9493 clang::LazyGenerationalUpdatePtr<
9494 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9495 const clang::ASTContext &Ctx, Decl *Value);