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[] = {
709 2, // opencl_constant
715 return &FakeAddrSpaceMap;
717 return &T.getAddressSpaceMap();
721 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
728 case LangOptions::ASMM_Off:
731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
734 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
735 IdentifierTable &idents, SelectorTable &sels,
736 Builtin::Context &builtins)
737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
759 TUDecl = TranslationUnitDecl::Create(*this);
762 ASTContext::~ASTContext() {
763 ReleaseParentMapEntries();
765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
769 // Call all of the deallocation functions on all of their targets.
770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
792 A->second->~AttrVec();
794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
802 void ASTContext::ReleaseParentMapEntries() {
803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
811 for (const auto &Entry : *OtherParents) {
812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
814 } else if (Entry.second.is<ParentVector *>()) {
815 delete Entry.second.get<ParentVector *>();
820 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
821 Deallocations.push_back({Callback, Data});
825 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
826 ExternalSource = std::move(Source);
829 void ASTContext::PrintStats() const {
830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
833 unsigned counts[] = {
834 #define TYPE(Name, Parent) 0,
835 #define ABSTRACT_TYPE(Name, Parent)
836 #include "clang/AST/TypeNodes.def"
840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
842 counts[(unsigned)T->getTypeClass()]++;
846 unsigned TotalBytes = 0;
847 #define TYPE(Name, Parent) \
849 llvm::errs() << " " << counts[Idx] << " " << #Name \
851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
853 #define ABSTRACT_TYPE(Name, Parent)
854 #include "clang/AST/TypeNodes.def"
856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
858 // Implicit special member functions.
859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
865 if (getLangOpts().CPlusPlus)
866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
872 if (getLangOpts().CPlusPlus)
873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
880 if (ExternalSource) {
881 llvm::errs() << "\n";
882 ExternalSource->PrintStats();
885 BumpAlloc.PrintStats();
888 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
897 ND->setVisibleDespiteOwningModule();
900 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
905 auto &Merged = It->second;
906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
913 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source");
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
926 assert(LazyInitializers.empty() &&
927 "GetExternalDecl for lazy module initializer added more inits");
930 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
950 auto *&Inits = ModuleInitializers[M];
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
956 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
964 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
974 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
978 return ExternCContext;
981 BuiltinTemplateDecl *
982 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
988 return BuiltinTemplate;
991 BuiltinTemplateDecl *
992 ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
999 BuiltinTemplateDecl *
1000 ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1007 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
1010 RecordDecl *NewDecl;
1011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
1015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1017 NewDecl->setImplicit();
1018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1023 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1033 TypedefDecl *ASTContext::getInt128Decl() const {
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1039 TypedefDecl *ASTContext::getUInt128Decl() const {
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1045 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1048 Types.push_back(Ty);
1051 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
1053 assert((!this->Target || this->Target == &Target) &&
1054 "Incorrect target reinitialization");
1055 assert(VoidTy.isNull() && "Context reinitialized?");
1057 this->Target = &Target;
1058 this->AuxTarget = AuxTarget;
1060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1065 InitBuiltinType(VoidTy, BuiltinType::Void);
1068 InitBuiltinType(BoolTy, BuiltinType::Bool);
1070 if (LangOpts.CharIsSigned)
1071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
1075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1096 // GNU extension, 128-bit integers.
1097 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1101 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1103 else // -fshort-wchar makes wchar_t be unsigned.
1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1105 if (LangOpts.CPlusPlus && LangOpts.WChar)
1106 WideCharTy = WCharTy;
1108 // C99 (or C++ using -fno-wchar).
1109 WideCharTy = getFromTargetType(Target.getWCharType());
1112 WIntTy = getFromTargetType(Target.getWIntType());
1114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1115 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1117 Char16Ty = getFromTargetType(Target.getChar16Type());
1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1120 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1122 Char32Ty = getFromTargetType(Target.getChar32Type());
1124 // Placeholder type for type-dependent expressions whose type is
1125 // completely unknown. No code should ever check a type against
1126 // DependentTy and users should never see it; however, it is here to
1127 // help diagnose failures to properly check for type-dependent
1129 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1131 // Placeholder type for functions.
1132 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1134 // Placeholder type for bound members.
1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1137 // Placeholder type for pseudo-objects.
1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1140 // "any" type; useful for debugger-like clients.
1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1143 // Placeholder type for unbridged ARC casts.
1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1146 // Placeholder type for builtin functions.
1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1149 // Placeholder type for OMP array sections.
1150 if (LangOpts.OpenMP)
1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1154 FloatComplexTy = getComplexType(FloatTy);
1155 DoubleComplexTy = getComplexType(DoubleTy);
1156 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1157 Float128ComplexTy = getComplexType(Float128Ty);
1159 // Builtin types for 'id', 'Class', and 'SEL'.
1160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1164 if (LangOpts.OpenCL) {
1165 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1166 InitBuiltinType(SingletonId, BuiltinType::Id);
1167 #include "clang/Basic/OpenCLImageTypes.def"
1169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1176 // Builtin type for __objc_yes and __objc_no
1177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
1180 ObjCConstantStringType = QualType();
1182 ObjCSuperType = QualType();
1185 VoidPtrTy = getPointerType(VoidTy);
1187 // nullptr type (C++0x 2.14.7)
1188 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1190 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1191 InitBuiltinType(HalfTy, BuiltinType::Half);
1193 // Builtin type used to help define __builtin_va_list.
1194 VaListTagDecl = nullptr;
1197 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1198 return SourceMgr.getDiagnostics();
1201 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1202 AttrVec *&Result = DeclAttrs[D];
1204 void *Mem = Allocate(sizeof(AttrVec));
1205 Result = new (Mem) AttrVec;
1211 /// \brief Erase the attributes corresponding to the given declaration.
1212 void ASTContext::eraseDeclAttrs(const Decl *D) {
1213 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1214 if (Pos != DeclAttrs.end()) {
1215 Pos->second->~AttrVec();
1216 DeclAttrs.erase(Pos);
1221 MemberSpecializationInfo *
1222 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1223 assert(Var->isStaticDataMember() && "Not a static data member");
1224 return getTemplateOrSpecializationInfo(Var)
1225 .dyn_cast<MemberSpecializationInfo *>();
1228 ASTContext::TemplateOrSpecializationInfo
1229 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1230 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1231 TemplateOrInstantiation.find(Var);
1232 if (Pos == TemplateOrInstantiation.end())
1233 return TemplateOrSpecializationInfo();
1239 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1240 TemplateSpecializationKind TSK,
1241 SourceLocation PointOfInstantiation) {
1242 assert(Inst->isStaticDataMember() && "Not a static data member");
1243 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1244 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1245 Tmpl, TSK, PointOfInstantiation));
1249 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1250 TemplateOrSpecializationInfo TSI) {
1251 assert(!TemplateOrInstantiation[Inst] &&
1252 "Already noted what the variable was instantiated from");
1253 TemplateOrInstantiation[Inst] = TSI;
1256 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1257 const FunctionDecl *FD){
1258 assert(FD && "Specialization is 0");
1259 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1260 = ClassScopeSpecializationPattern.find(FD);
1261 if (Pos == ClassScopeSpecializationPattern.end())
1267 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1268 FunctionDecl *Pattern) {
1269 assert(FD && "Specialization is 0");
1270 assert(Pattern && "Class scope specialization pattern is 0");
1271 ClassScopeSpecializationPattern[FD] = Pattern;
1275 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1276 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1277 if (Pos == InstantiatedFromUsingDecl.end())
1284 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1285 assert((isa<UsingDecl>(Pattern) ||
1286 isa<UnresolvedUsingValueDecl>(Pattern) ||
1287 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1288 "pattern decl is not a using decl");
1289 assert((isa<UsingDecl>(Inst) ||
1290 isa<UnresolvedUsingValueDecl>(Inst) ||
1291 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1292 "instantiation did not produce a using decl");
1293 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1294 InstantiatedFromUsingDecl[Inst] = Pattern;
1298 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1299 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1300 = InstantiatedFromUsingShadowDecl.find(Inst);
1301 if (Pos == InstantiatedFromUsingShadowDecl.end())
1308 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1309 UsingShadowDecl *Pattern) {
1310 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1311 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1314 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1315 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1316 = InstantiatedFromUnnamedFieldDecl.find(Field);
1317 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1323 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1325 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1326 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1327 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1328 "Already noted what unnamed field was instantiated from");
1330 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1333 ASTContext::overridden_cxx_method_iterator
1334 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1335 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1336 OverriddenMethods.find(Method->getCanonicalDecl());
1337 if (Pos == OverriddenMethods.end())
1339 return Pos->second.begin();
1342 ASTContext::overridden_cxx_method_iterator
1343 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1344 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1345 OverriddenMethods.find(Method->getCanonicalDecl());
1346 if (Pos == OverriddenMethods.end())
1348 return Pos->second.end();
1352 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1354 OverriddenMethods.find(Method->getCanonicalDecl());
1355 if (Pos == OverriddenMethods.end())
1357 return Pos->second.size();
1360 ASTContext::overridden_method_range
1361 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1362 return overridden_method_range(overridden_methods_begin(Method),
1363 overridden_methods_end(Method));
1366 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1367 const CXXMethodDecl *Overridden) {
1368 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1369 OverriddenMethods[Method].push_back(Overridden);
1372 void ASTContext::getOverriddenMethods(
1374 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1377 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1378 Overridden.append(overridden_methods_begin(CXXMethod),
1379 overridden_methods_end(CXXMethod));
1383 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1387 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1388 Method->getOverriddenMethods(OverDecls);
1389 Overridden.append(OverDecls.begin(), OverDecls.end());
1392 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1393 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1394 assert(!Import->isFromASTFile() && "Non-local import declaration");
1395 if (!FirstLocalImport) {
1396 FirstLocalImport = Import;
1397 LastLocalImport = Import;
1401 LastLocalImport->NextLocalImport = Import;
1402 LastLocalImport = Import;
1405 //===----------------------------------------------------------------------===//
1406 // Type Sizing and Analysis
1407 //===----------------------------------------------------------------------===//
1409 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1410 /// scalar floating point type.
1411 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1412 const BuiltinType *BT = T->getAs<BuiltinType>();
1413 assert(BT && "Not a floating point type!");
1414 switch (BT->getKind()) {
1415 default: llvm_unreachable("Not a floating point type!");
1416 case BuiltinType::Half: return Target->getHalfFormat();
1417 case BuiltinType::Float: return Target->getFloatFormat();
1418 case BuiltinType::Double: return Target->getDoubleFormat();
1419 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1420 case BuiltinType::Float128: return Target->getFloat128Format();
1424 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1425 unsigned Align = Target->getCharWidth();
1427 bool UseAlignAttrOnly = false;
1428 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1429 Align = AlignFromAttr;
1431 // __attribute__((aligned)) can increase or decrease alignment
1432 // *except* on a struct or struct member, where it only increases
1433 // alignment unless 'packed' is also specified.
1435 // It is an error for alignas to decrease alignment, so we can
1436 // ignore that possibility; Sema should diagnose it.
1437 if (isa<FieldDecl>(D)) {
1438 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1439 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1441 UseAlignAttrOnly = true;
1444 else if (isa<FieldDecl>(D))
1446 D->hasAttr<PackedAttr>() ||
1447 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1449 // If we're using the align attribute only, just ignore everything
1450 // else about the declaration and its type.
1451 if (UseAlignAttrOnly) {
1454 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1455 QualType T = VD->getType();
1456 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1458 T = RT->getPointeeType();
1460 T = getPointerType(RT->getPointeeType());
1462 QualType BaseT = getBaseElementType(T);
1463 if (T->isFunctionType())
1464 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1465 else if (!BaseT->isIncompleteType()) {
1466 // Adjust alignments of declarations with array type by the
1467 // large-array alignment on the target.
1468 if (const ArrayType *arrayType = getAsArrayType(T)) {
1469 unsigned MinWidth = Target->getLargeArrayMinWidth();
1470 if (!ForAlignof && MinWidth) {
1471 if (isa<VariableArrayType>(arrayType))
1472 Align = std::max(Align, Target->getLargeArrayAlign());
1473 else if (isa<ConstantArrayType>(arrayType) &&
1474 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1475 Align = std::max(Align, Target->getLargeArrayAlign());
1478 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1479 if (BaseT.getQualifiers().hasUnaligned())
1480 Align = Target->getCharWidth();
1481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1482 if (VD->hasGlobalStorage() && !ForAlignof)
1483 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1487 // Fields can be subject to extra alignment constraints, like if
1488 // the field is packed, the struct is packed, or the struct has a
1489 // a max-field-alignment constraint (#pragma pack). So calculate
1490 // the actual alignment of the field within the struct, and then
1491 // (as we're expected to) constrain that by the alignment of the type.
1492 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1493 const RecordDecl *Parent = Field->getParent();
1494 // We can only produce a sensible answer if the record is valid.
1495 if (!Parent->isInvalidDecl()) {
1496 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1498 // Start with the record's overall alignment.
1499 unsigned FieldAlign = toBits(Layout.getAlignment());
1501 // Use the GCD of that and the offset within the record.
1502 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1504 // Alignment is always a power of 2, so the GCD will be a power of 2,
1505 // which means we get to do this crazy thing instead of Euclid's.
1506 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1507 if (LowBitOfOffset < FieldAlign)
1508 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1511 Align = std::min(Align, FieldAlign);
1516 return toCharUnitsFromBits(Align);
1519 // getTypeInfoDataSizeInChars - Return the size of a type, in
1520 // chars. If the type is a record, its data size is returned. This is
1521 // the size of the memcpy that's performed when assigning this type
1522 // using a trivial copy/move assignment operator.
1523 std::pair<CharUnits, CharUnits>
1524 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1525 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1527 // In C++, objects can sometimes be allocated into the tail padding
1528 // of a base-class subobject. We decide whether that's possible
1529 // during class layout, so here we can just trust the layout results.
1530 if (getLangOpts().CPlusPlus) {
1531 if (const RecordType *RT = T->getAs<RecordType>()) {
1532 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1533 sizeAndAlign.first = layout.getDataSize();
1537 return sizeAndAlign;
1540 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1541 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1542 std::pair<CharUnits, CharUnits>
1543 static getConstantArrayInfoInChars(const ASTContext &Context,
1544 const ConstantArrayType *CAT) {
1545 std::pair<CharUnits, CharUnits> EltInfo =
1546 Context.getTypeInfoInChars(CAT->getElementType());
1547 uint64_t Size = CAT->getSize().getZExtValue();
1548 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1549 (uint64_t)(-1)/Size) &&
1550 "Overflow in array type char size evaluation");
1551 uint64_t Width = EltInfo.first.getQuantity() * Size;
1552 unsigned Align = EltInfo.second.getQuantity();
1553 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1554 Context.getTargetInfo().getPointerWidth(0) == 64)
1555 Width = llvm::alignTo(Width, Align);
1556 return std::make_pair(CharUnits::fromQuantity(Width),
1557 CharUnits::fromQuantity(Align));
1560 std::pair<CharUnits, CharUnits>
1561 ASTContext::getTypeInfoInChars(const Type *T) const {
1562 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1563 return getConstantArrayInfoInChars(*this, CAT);
1564 TypeInfo Info = getTypeInfo(T);
1565 return std::make_pair(toCharUnitsFromBits(Info.Width),
1566 toCharUnitsFromBits(Info.Align));
1569 std::pair<CharUnits, CharUnits>
1570 ASTContext::getTypeInfoInChars(QualType T) const {
1571 return getTypeInfoInChars(T.getTypePtr());
1574 bool ASTContext::isAlignmentRequired(const Type *T) const {
1575 return getTypeInfo(T).AlignIsRequired;
1578 bool ASTContext::isAlignmentRequired(QualType T) const {
1579 return isAlignmentRequired(T.getTypePtr());
1582 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1583 // An alignment on a typedef overrides anything else.
1584 if (auto *TT = T->getAs<TypedefType>())
1585 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1588 // If we have an (array of) complete type, we're done.
1589 T = getBaseElementType(T);
1590 if (!T->isIncompleteType())
1591 return getTypeAlign(T);
1593 // If we had an array type, its element type might be a typedef
1594 // type with an alignment attribute.
1595 if (auto *TT = T->getAs<TypedefType>())
1596 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1599 // Otherwise, see if the declaration of the type had an attribute.
1600 if (auto *TT = T->getAs<TagType>())
1601 return TT->getDecl()->getMaxAlignment();
1606 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1607 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1608 if (I != MemoizedTypeInfo.end())
1611 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1612 TypeInfo TI = getTypeInfoImpl(T);
1613 MemoizedTypeInfo[T] = TI;
1617 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1618 /// method does not work on incomplete types.
1620 /// FIXME: Pointers into different addr spaces could have different sizes and
1621 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1622 /// should take a QualType, &c.
1623 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1626 bool AlignIsRequired = false;
1627 switch (T->getTypeClass()) {
1628 #define TYPE(Class, Base)
1629 #define ABSTRACT_TYPE(Class, Base)
1630 #define NON_CANONICAL_TYPE(Class, Base)
1631 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1632 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1634 assert(!T->isDependentType() && "should not see dependent types here"); \
1635 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1636 #include "clang/AST/TypeNodes.def"
1637 llvm_unreachable("Should not see dependent types");
1639 case Type::FunctionNoProto:
1640 case Type::FunctionProto:
1641 // GCC extension: alignof(function) = 32 bits
1646 case Type::IncompleteArray:
1647 case Type::VariableArray:
1649 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1652 case Type::ConstantArray: {
1653 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1655 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1656 uint64_t Size = CAT->getSize().getZExtValue();
1657 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1658 "Overflow in array type bit size evaluation");
1659 Width = EltInfo.Width * Size;
1660 Align = EltInfo.Align;
1661 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1662 getTargetInfo().getPointerWidth(0) == 64)
1663 Width = llvm::alignTo(Width, Align);
1666 case Type::ExtVector:
1667 case Type::Vector: {
1668 const VectorType *VT = cast<VectorType>(T);
1669 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1670 Width = EltInfo.Width * VT->getNumElements();
1672 // If the alignment is not a power of 2, round up to the next power of 2.
1673 // This happens for non-power-of-2 length vectors.
1674 if (Align & (Align-1)) {
1675 Align = llvm::NextPowerOf2(Align);
1676 Width = llvm::alignTo(Width, Align);
1678 // Adjust the alignment based on the target max.
1679 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1680 if (TargetVectorAlign && TargetVectorAlign < Align)
1681 Align = TargetVectorAlign;
1686 switch (cast<BuiltinType>(T)->getKind()) {
1687 default: llvm_unreachable("Unknown builtin type!");
1688 case BuiltinType::Void:
1689 // GCC extension: alignof(void) = 8 bits.
1694 case BuiltinType::Bool:
1695 Width = Target->getBoolWidth();
1696 Align = Target->getBoolAlign();
1698 case BuiltinType::Char_S:
1699 case BuiltinType::Char_U:
1700 case BuiltinType::UChar:
1701 case BuiltinType::SChar:
1702 Width = Target->getCharWidth();
1703 Align = Target->getCharAlign();
1705 case BuiltinType::WChar_S:
1706 case BuiltinType::WChar_U:
1707 Width = Target->getWCharWidth();
1708 Align = Target->getWCharAlign();
1710 case BuiltinType::Char16:
1711 Width = Target->getChar16Width();
1712 Align = Target->getChar16Align();
1714 case BuiltinType::Char32:
1715 Width = Target->getChar32Width();
1716 Align = Target->getChar32Align();
1718 case BuiltinType::UShort:
1719 case BuiltinType::Short:
1720 Width = Target->getShortWidth();
1721 Align = Target->getShortAlign();
1723 case BuiltinType::UInt:
1724 case BuiltinType::Int:
1725 Width = Target->getIntWidth();
1726 Align = Target->getIntAlign();
1728 case BuiltinType::ULong:
1729 case BuiltinType::Long:
1730 Width = Target->getLongWidth();
1731 Align = Target->getLongAlign();
1733 case BuiltinType::ULongLong:
1734 case BuiltinType::LongLong:
1735 Width = Target->getLongLongWidth();
1736 Align = Target->getLongLongAlign();
1738 case BuiltinType::Int128:
1739 case BuiltinType::UInt128:
1741 Align = 128; // int128_t is 128-bit aligned on all targets.
1743 case BuiltinType::Half:
1744 Width = Target->getHalfWidth();
1745 Align = Target->getHalfAlign();
1747 case BuiltinType::Float:
1748 Width = Target->getFloatWidth();
1749 Align = Target->getFloatAlign();
1751 case BuiltinType::Double:
1752 Width = Target->getDoubleWidth();
1753 Align = Target->getDoubleAlign();
1755 case BuiltinType::LongDouble:
1756 Width = Target->getLongDoubleWidth();
1757 Align = Target->getLongDoubleAlign();
1759 case BuiltinType::Float128:
1760 Width = Target->getFloat128Width();
1761 Align = Target->getFloat128Align();
1763 case BuiltinType::NullPtr:
1764 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1765 Align = Target->getPointerAlign(0); // == sizeof(void*)
1767 case BuiltinType::ObjCId:
1768 case BuiltinType::ObjCClass:
1769 case BuiltinType::ObjCSel:
1770 Width = Target->getPointerWidth(0);
1771 Align = Target->getPointerAlign(0);
1773 case BuiltinType::OCLSampler: {
1774 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1775 Width = Target->getPointerWidth(AS);
1776 Align = Target->getPointerAlign(AS);
1779 case BuiltinType::OCLEvent:
1780 case BuiltinType::OCLClkEvent:
1781 case BuiltinType::OCLQueue:
1782 case BuiltinType::OCLReserveID:
1783 // Currently these types are pointers to opaque types.
1784 Width = Target->getPointerWidth(0);
1785 Align = Target->getPointerAlign(0);
1787 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1788 case BuiltinType::Id:
1789 #include "clang/Basic/OpenCLImageTypes.def"
1791 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1792 Width = Target->getPointerWidth(AS);
1793 Align = Target->getPointerAlign(AS);
1797 case Type::ObjCObjectPointer:
1798 Width = Target->getPointerWidth(0);
1799 Align = Target->getPointerAlign(0);
1801 case Type::BlockPointer: {
1802 unsigned AS = getTargetAddressSpace(
1803 cast<BlockPointerType>(T)->getPointeeType());
1804 Width = Target->getPointerWidth(AS);
1805 Align = Target->getPointerAlign(AS);
1808 case Type::LValueReference:
1809 case Type::RValueReference: {
1810 // alignof and sizeof should never enter this code path here, so we go
1811 // the pointer route.
1812 unsigned AS = getTargetAddressSpace(
1813 cast<ReferenceType>(T)->getPointeeType());
1814 Width = Target->getPointerWidth(AS);
1815 Align = Target->getPointerAlign(AS);
1818 case Type::Pointer: {
1819 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1820 Width = Target->getPointerWidth(AS);
1821 Align = Target->getPointerAlign(AS);
1824 case Type::MemberPointer: {
1825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1826 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1829 case Type::Complex: {
1830 // Complex types have the same alignment as their elements, but twice the
1832 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1833 Width = EltInfo.Width * 2;
1834 Align = EltInfo.Align;
1837 case Type::ObjCObject:
1838 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1839 case Type::Adjusted:
1841 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1842 case Type::ObjCInterface: {
1843 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1844 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1845 Width = toBits(Layout.getSize());
1846 Align = toBits(Layout.getAlignment());
1851 const TagType *TT = cast<TagType>(T);
1853 if (TT->getDecl()->isInvalidDecl()) {
1859 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1860 const EnumDecl *ED = ET->getDecl();
1862 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1863 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1864 Info.Align = AttrAlign;
1865 Info.AlignIsRequired = true;
1870 const RecordType *RT = cast<RecordType>(TT);
1871 const RecordDecl *RD = RT->getDecl();
1872 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1873 Width = toBits(Layout.getSize());
1874 Align = toBits(Layout.getAlignment());
1875 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1879 case Type::SubstTemplateTypeParm:
1880 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1881 getReplacementType().getTypePtr());
1884 case Type::DeducedTemplateSpecialization: {
1885 const DeducedType *A = cast<DeducedType>(T);
1886 assert(!A->getDeducedType().isNull() &&
1887 "cannot request the size of an undeduced or dependent auto type");
1888 return getTypeInfo(A->getDeducedType().getTypePtr());
1892 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1894 case Type::ObjCTypeParam:
1895 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1897 case Type::Typedef: {
1898 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1899 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1900 // If the typedef has an aligned attribute on it, it overrides any computed
1901 // alignment we have. This violates the GCC documentation (which says that
1902 // attribute(aligned) can only round up) but matches its implementation.
1903 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1905 AlignIsRequired = true;
1908 AlignIsRequired = Info.AlignIsRequired;
1914 case Type::Elaborated:
1915 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1917 case Type::Attributed:
1919 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1921 case Type::Atomic: {
1922 // Start with the base type information.
1923 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1927 // If the size of the type doesn't exceed the platform's max
1928 // atomic promotion width, make the size and alignment more
1929 // favorable to atomic operations:
1930 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1931 // Round the size up to a power of 2.
1932 if (!llvm::isPowerOf2_64(Width))
1933 Width = llvm::NextPowerOf2(Width);
1935 // Set the alignment equal to the size.
1936 Align = static_cast<unsigned>(Width);
1942 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1943 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
1948 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1949 return TypeInfo(Width, Align, AlignIsRequired);
1952 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1953 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1954 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1955 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1956 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1957 getTargetInfo().getABI() == "elfv1-qpx" &&
1958 T->isSpecificBuiltinType(BuiltinType::Double))
1963 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1964 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1965 return CharUnits::fromQuantity(BitSize / getCharWidth());
1968 /// toBits - Convert a size in characters to a size in characters.
1969 int64_t ASTContext::toBits(CharUnits CharSize) const {
1970 return CharSize.getQuantity() * getCharWidth();
1973 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1974 /// This method does not work on incomplete types.
1975 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1976 return getTypeInfoInChars(T).first;
1978 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1979 return getTypeInfoInChars(T).first;
1982 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1983 /// characters. This method does not work on incomplete types.
1984 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1985 return toCharUnitsFromBits(getTypeAlign(T));
1987 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1988 return toCharUnitsFromBits(getTypeAlign(T));
1991 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1992 /// type for the current target in bits. This can be different than the ABI
1993 /// alignment in cases where it is beneficial for performance to overalign
1995 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1996 TypeInfo TI = getTypeInfo(T);
1997 unsigned ABIAlign = TI.Align;
1999 T = T->getBaseElementTypeUnsafe();
2001 // The preferred alignment of member pointers is that of a pointer.
2002 if (T->isMemberPointerType())
2003 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2005 if (!Target->allowsLargerPreferedTypeAlignment())
2008 // Double and long long should be naturally aligned if possible.
2009 if (const ComplexType *CT = T->getAs<ComplexType>())
2010 T = CT->getElementType().getTypePtr();
2011 if (const EnumType *ET = T->getAs<EnumType>())
2012 T = ET->getDecl()->getIntegerType().getTypePtr();
2013 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2014 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2015 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2016 // Don't increase the alignment if an alignment attribute was specified on a
2017 // typedef declaration.
2018 if (!TI.AlignIsRequired)
2019 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2024 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2025 /// for __attribute__((aligned)) on this target, to be used if no alignment
2026 /// value is specified.
2027 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2028 return getTargetInfo().getDefaultAlignForAttributeAligned();
2031 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2032 /// to a global variable of the specified type.
2033 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2034 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2037 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2038 /// should be given to a global variable of the specified type.
2039 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2040 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2043 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2044 CharUnits Offset = CharUnits::Zero();
2045 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2046 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2047 Offset += Layout->getBaseClassOffset(Base);
2048 Layout = &getASTRecordLayout(Base);
2053 /// DeepCollectObjCIvars -
2054 /// This routine first collects all declared, but not synthesized, ivars in
2055 /// super class and then collects all ivars, including those synthesized for
2056 /// current class. This routine is used for implementation of current class
2057 /// when all ivars, declared and synthesized are known.
2059 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2061 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2062 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2063 DeepCollectObjCIvars(SuperClass, false, Ivars);
2065 for (const auto *I : OI->ivars())
2068 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2069 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2070 Iv= Iv->getNextIvar())
2071 Ivars.push_back(Iv);
2075 /// CollectInheritedProtocols - Collect all protocols in current class and
2076 /// those inherited by it.
2077 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2078 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2079 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2080 // We can use protocol_iterator here instead of
2081 // all_referenced_protocol_iterator since we are walking all categories.
2082 for (auto *Proto : OI->all_referenced_protocols()) {
2083 CollectInheritedProtocols(Proto, Protocols);
2086 // Categories of this Interface.
2087 for (const auto *Cat : OI->visible_categories())
2088 CollectInheritedProtocols(Cat, Protocols);
2090 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2092 CollectInheritedProtocols(SD, Protocols);
2093 SD = SD->getSuperClass();
2095 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2096 for (auto *Proto : OC->protocols()) {
2097 CollectInheritedProtocols(Proto, Protocols);
2099 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2100 // Insert the protocol.
2101 if (!Protocols.insert(
2102 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2105 for (auto *Proto : OP->protocols())
2106 CollectInheritedProtocols(Proto, Protocols);
2110 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2112 // Count ivars declared in class extension.
2113 for (const auto *Ext : OI->known_extensions())
2114 count += Ext->ivar_size();
2116 // Count ivar defined in this class's implementation. This
2117 // includes synthesized ivars.
2118 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2119 count += ImplDecl->ivar_size();
2124 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2128 // nullptr_t is always treated as null.
2129 if (E->getType()->isNullPtrType()) return true;
2131 if (E->getType()->isAnyPointerType() &&
2132 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2133 Expr::NPC_ValueDependentIsNull))
2136 // Unfortunately, __null has type 'int'.
2137 if (isa<GNUNullExpr>(E)) return true;
2142 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2143 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2144 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2145 I = ObjCImpls.find(D);
2146 if (I != ObjCImpls.end())
2147 return cast<ObjCImplementationDecl>(I->second);
2150 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2151 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2152 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2153 I = ObjCImpls.find(D);
2154 if (I != ObjCImpls.end())
2155 return cast<ObjCCategoryImplDecl>(I->second);
2159 /// \brief Set the implementation of ObjCInterfaceDecl.
2160 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2161 ObjCImplementationDecl *ImplD) {
2162 assert(IFaceD && ImplD && "Passed null params");
2163 ObjCImpls[IFaceD] = ImplD;
2165 /// \brief Set the implementation of ObjCCategoryDecl.
2166 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2167 ObjCCategoryImplDecl *ImplD) {
2168 assert(CatD && ImplD && "Passed null params");
2169 ObjCImpls[CatD] = ImplD;
2172 const ObjCMethodDecl *
2173 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2174 return ObjCMethodRedecls.lookup(MD);
2177 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2178 const ObjCMethodDecl *Redecl) {
2179 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2180 ObjCMethodRedecls[MD] = Redecl;
2183 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2184 const NamedDecl *ND) const {
2185 if (const ObjCInterfaceDecl *ID =
2186 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2188 if (const ObjCCategoryDecl *CD =
2189 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2190 return CD->getClassInterface();
2191 if (const ObjCImplDecl *IMD =
2192 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2193 return IMD->getClassInterface();
2198 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2200 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2201 assert(VD && "Passed null params");
2202 assert(VD->hasAttr<BlocksAttr>() &&
2203 "getBlockVarCopyInits - not __block var");
2204 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2205 I = BlockVarCopyInits.find(VD);
2206 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2209 /// \brief Set the copy inialization expression of a block var decl.
2210 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2211 assert(VD && Init && "Passed null params");
2212 assert(VD->hasAttr<BlocksAttr>() &&
2213 "setBlockVarCopyInits - not __block var");
2214 BlockVarCopyInits[VD] = Init;
2217 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2218 unsigned DataSize) const {
2220 DataSize = TypeLoc::getFullDataSizeForType(T);
2222 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2223 "incorrect data size provided to CreateTypeSourceInfo!");
2225 TypeSourceInfo *TInfo =
2226 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2227 new (TInfo) TypeSourceInfo(T);
2231 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2232 SourceLocation L) const {
2233 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2234 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2238 const ASTRecordLayout &
2239 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2240 return getObjCLayout(D, nullptr);
2243 const ASTRecordLayout &
2244 ASTContext::getASTObjCImplementationLayout(
2245 const ObjCImplementationDecl *D) const {
2246 return getObjCLayout(D->getClassInterface(), D);
2249 //===----------------------------------------------------------------------===//
2250 // Type creation/memoization methods
2251 //===----------------------------------------------------------------------===//
2254 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2255 unsigned fastQuals = quals.getFastQualifiers();
2256 quals.removeFastQualifiers();
2258 // Check if we've already instantiated this type.
2259 llvm::FoldingSetNodeID ID;
2260 ExtQuals::Profile(ID, baseType, quals);
2261 void *insertPos = nullptr;
2262 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2263 assert(eq->getQualifiers() == quals);
2264 return QualType(eq, fastQuals);
2267 // If the base type is not canonical, make the appropriate canonical type.
2269 if (!baseType->isCanonicalUnqualified()) {
2270 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2271 canonSplit.Quals.addConsistentQualifiers(quals);
2272 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2274 // Re-find the insert position.
2275 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2278 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2279 ExtQualNodes.InsertNode(eq, insertPos);
2280 return QualType(eq, fastQuals);
2284 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2285 QualType CanT = getCanonicalType(T);
2286 if (CanT.getAddressSpace() == AddressSpace)
2289 // If we are composing extended qualifiers together, merge together
2290 // into one ExtQuals node.
2291 QualifierCollector Quals;
2292 const Type *TypeNode = Quals.strip(T);
2294 // If this type already has an address space specified, it cannot get
2296 assert(!Quals.hasAddressSpace() &&
2297 "Type cannot be in multiple addr spaces!");
2298 Quals.addAddressSpace(AddressSpace);
2300 return getExtQualType(TypeNode, Quals);
2303 QualType ASTContext::getObjCGCQualType(QualType T,
2304 Qualifiers::GC GCAttr) const {
2305 QualType CanT = getCanonicalType(T);
2306 if (CanT.getObjCGCAttr() == GCAttr)
2309 if (const PointerType *ptr = T->getAs<PointerType>()) {
2310 QualType Pointee = ptr->getPointeeType();
2311 if (Pointee->isAnyPointerType()) {
2312 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2313 return getPointerType(ResultType);
2317 // If we are composing extended qualifiers together, merge together
2318 // into one ExtQuals node.
2319 QualifierCollector Quals;
2320 const Type *TypeNode = Quals.strip(T);
2322 // If this type already has an ObjCGC specified, it cannot get
2324 assert(!Quals.hasObjCGCAttr() &&
2325 "Type cannot have multiple ObjCGCs!");
2326 Quals.addObjCGCAttr(GCAttr);
2328 return getExtQualType(TypeNode, Quals);
2331 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2332 FunctionType::ExtInfo Info) {
2333 if (T->getExtInfo() == Info)
2337 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2338 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2340 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2341 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2343 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2346 return cast<FunctionType>(Result.getTypePtr());
2349 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2350 QualType ResultType) {
2351 FD = FD->getMostRecentDecl();
2353 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2354 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2355 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2356 if (FunctionDecl *Next = FD->getPreviousDecl())
2361 if (ASTMutationListener *L = getASTMutationListener())
2362 L->DeducedReturnType(FD, ResultType);
2365 /// Get a function type and produce the equivalent function type with the
2366 /// specified exception specification. Type sugar that can be present on a
2367 /// declaration of a function with an exception specification is permitted
2368 /// and preserved. Other type sugar (for instance, typedefs) is not.
2369 static QualType getFunctionTypeWithExceptionSpec(
2370 ASTContext &Context, QualType Orig,
2371 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2372 // Might have some parens.
2373 if (auto *PT = dyn_cast<ParenType>(Orig))
2374 return Context.getParenType(
2375 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2377 // Might have a calling-convention attribute.
2378 if (auto *AT = dyn_cast<AttributedType>(Orig))
2379 return Context.getAttributedType(
2381 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2382 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2385 // Anything else must be a function type. Rebuild it with the new exception
2387 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2388 return Context.getFunctionType(
2389 Proto->getReturnType(), Proto->getParamTypes(),
2390 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2393 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2395 return hasSameType(T, U) ||
2396 (getLangOpts().CPlusPlus1z &&
2397 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2398 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2401 void ASTContext::adjustExceptionSpec(
2402 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2406 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2407 FD->setType(Updated);
2412 // Update the type in the type source information too.
2413 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2414 // If the type and the type-as-written differ, we may need to update
2415 // the type-as-written too.
2416 if (TSInfo->getType() != FD->getType())
2417 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2419 // FIXME: When we get proper type location information for exceptions,
2420 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2421 // up the TypeSourceInfo;
2422 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2423 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2424 "TypeLoc size mismatch from updating exception specification");
2425 TSInfo->overrideType(Updated);
2429 /// getComplexType - Return the uniqued reference to the type for a complex
2430 /// number with the specified element type.
2431 QualType ASTContext::getComplexType(QualType T) const {
2432 // Unique pointers, to guarantee there is only one pointer of a particular
2434 llvm::FoldingSetNodeID ID;
2435 ComplexType::Profile(ID, T);
2437 void *InsertPos = nullptr;
2438 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2439 return QualType(CT, 0);
2441 // If the pointee type isn't canonical, this won't be a canonical type either,
2442 // so fill in the canonical type field.
2444 if (!T.isCanonical()) {
2445 Canonical = getComplexType(getCanonicalType(T));
2447 // Get the new insert position for the node we care about.
2448 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2449 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2451 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2452 Types.push_back(New);
2453 ComplexTypes.InsertNode(New, InsertPos);
2454 return QualType(New, 0);
2457 /// getPointerType - Return the uniqued reference to the type for a pointer to
2458 /// the specified type.
2459 QualType ASTContext::getPointerType(QualType T) const {
2460 // Unique pointers, to guarantee there is only one pointer of a particular
2462 llvm::FoldingSetNodeID ID;
2463 PointerType::Profile(ID, T);
2465 void *InsertPos = nullptr;
2466 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2467 return QualType(PT, 0);
2469 // If the pointee type isn't canonical, this won't be a canonical type either,
2470 // so fill in the canonical type field.
2472 if (!T.isCanonical()) {
2473 Canonical = getPointerType(getCanonicalType(T));
2475 // Get the new insert position for the node we care about.
2476 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2477 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2479 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2480 Types.push_back(New);
2481 PointerTypes.InsertNode(New, InsertPos);
2482 return QualType(New, 0);
2485 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2486 llvm::FoldingSetNodeID ID;
2487 AdjustedType::Profile(ID, Orig, New);
2488 void *InsertPos = nullptr;
2489 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2491 return QualType(AT, 0);
2493 QualType Canonical = getCanonicalType(New);
2495 // Get the new insert position for the node we care about.
2496 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2497 assert(!AT && "Shouldn't be in the map!");
2499 AT = new (*this, TypeAlignment)
2500 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2501 Types.push_back(AT);
2502 AdjustedTypes.InsertNode(AT, InsertPos);
2503 return QualType(AT, 0);
2506 QualType ASTContext::getDecayedType(QualType T) const {
2507 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2512 // A declaration of a parameter as "array of type" shall be
2513 // adjusted to "qualified pointer to type", where the type
2514 // qualifiers (if any) are those specified within the [ and ] of
2515 // the array type derivation.
2516 if (T->isArrayType())
2517 Decayed = getArrayDecayedType(T);
2520 // A declaration of a parameter as "function returning type"
2521 // shall be adjusted to "pointer to function returning type", as
2523 if (T->isFunctionType())
2524 Decayed = getPointerType(T);
2526 llvm::FoldingSetNodeID ID;
2527 AdjustedType::Profile(ID, T, Decayed);
2528 void *InsertPos = nullptr;
2529 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 return QualType(AT, 0);
2533 QualType Canonical = getCanonicalType(Decayed);
2535 // Get the new insert position for the node we care about.
2536 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2537 assert(!AT && "Shouldn't be in the map!");
2539 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2540 Types.push_back(AT);
2541 AdjustedTypes.InsertNode(AT, InsertPos);
2542 return QualType(AT, 0);
2545 /// getBlockPointerType - Return the uniqued reference to the type for
2546 /// a pointer to the specified block.
2547 QualType ASTContext::getBlockPointerType(QualType T) const {
2548 assert(T->isFunctionType() && "block of function types only");
2549 // Unique pointers, to guarantee there is only one block of a particular
2551 llvm::FoldingSetNodeID ID;
2552 BlockPointerType::Profile(ID, T);
2554 void *InsertPos = nullptr;
2555 if (BlockPointerType *PT =
2556 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2557 return QualType(PT, 0);
2559 // If the block pointee type isn't canonical, this won't be a canonical
2560 // type either so fill in the canonical type field.
2562 if (!T.isCanonical()) {
2563 Canonical = getBlockPointerType(getCanonicalType(T));
2565 // Get the new insert position for the node we care about.
2566 BlockPointerType *NewIP =
2567 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2570 BlockPointerType *New
2571 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2572 Types.push_back(New);
2573 BlockPointerTypes.InsertNode(New, InsertPos);
2574 return QualType(New, 0);
2577 /// getLValueReferenceType - Return the uniqued reference to the type for an
2578 /// lvalue reference to the specified type.
2580 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2581 assert(getCanonicalType(T) != OverloadTy &&
2582 "Unresolved overloaded function type");
2584 // Unique pointers, to guarantee there is only one pointer of a particular
2586 llvm::FoldingSetNodeID ID;
2587 ReferenceType::Profile(ID, T, SpelledAsLValue);
2589 void *InsertPos = nullptr;
2590 if (LValueReferenceType *RT =
2591 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2592 return QualType(RT, 0);
2594 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2596 // If the referencee type isn't canonical, this won't be a canonical type
2597 // either, so fill in the canonical type field.
2599 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2600 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2601 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2603 // Get the new insert position for the node we care about.
2604 LValueReferenceType *NewIP =
2605 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2609 LValueReferenceType *New
2610 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2612 Types.push_back(New);
2613 LValueReferenceTypes.InsertNode(New, InsertPos);
2615 return QualType(New, 0);
2618 /// getRValueReferenceType - Return the uniqued reference to the type for an
2619 /// rvalue reference to the specified type.
2620 QualType ASTContext::getRValueReferenceType(QualType T) const {
2621 // Unique pointers, to guarantee there is only one pointer of a particular
2623 llvm::FoldingSetNodeID ID;
2624 ReferenceType::Profile(ID, T, false);
2626 void *InsertPos = nullptr;
2627 if (RValueReferenceType *RT =
2628 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2629 return QualType(RT, 0);
2631 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2633 // If the referencee type isn't canonical, this won't be a canonical type
2634 // either, so fill in the canonical type field.
2636 if (InnerRef || !T.isCanonical()) {
2637 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2638 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2640 // Get the new insert position for the node we care about.
2641 RValueReferenceType *NewIP =
2642 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2646 RValueReferenceType *New
2647 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2648 Types.push_back(New);
2649 RValueReferenceTypes.InsertNode(New, InsertPos);
2650 return QualType(New, 0);
2653 /// getMemberPointerType - Return the uniqued reference to the type for a
2654 /// member pointer to the specified type, in the specified class.
2655 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2656 // Unique pointers, to guarantee there is only one pointer of a particular
2658 llvm::FoldingSetNodeID ID;
2659 MemberPointerType::Profile(ID, T, Cls);
2661 void *InsertPos = nullptr;
2662 if (MemberPointerType *PT =
2663 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2664 return QualType(PT, 0);
2666 // If the pointee or class type isn't canonical, this won't be a canonical
2667 // type either, so fill in the canonical type field.
2669 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2670 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2672 // Get the new insert position for the node we care about.
2673 MemberPointerType *NewIP =
2674 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2675 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2677 MemberPointerType *New
2678 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2679 Types.push_back(New);
2680 MemberPointerTypes.InsertNode(New, InsertPos);
2681 return QualType(New, 0);
2684 /// getConstantArrayType - Return the unique reference to the type for an
2685 /// array of the specified element type.
2686 QualType ASTContext::getConstantArrayType(QualType EltTy,
2687 const llvm::APInt &ArySizeIn,
2688 ArrayType::ArraySizeModifier ASM,
2689 unsigned IndexTypeQuals) const {
2690 assert((EltTy->isDependentType() ||
2691 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2692 "Constant array of VLAs is illegal!");
2694 // Convert the array size into a canonical width matching the pointer size for
2696 llvm::APInt ArySize(ArySizeIn);
2697 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
2699 llvm::FoldingSetNodeID ID;
2700 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2702 void *InsertPos = nullptr;
2703 if (ConstantArrayType *ATP =
2704 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2705 return QualType(ATP, 0);
2707 // If the element type isn't canonical or has qualifiers, this won't
2708 // be a canonical type either, so fill in the canonical type field.
2710 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2711 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2712 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2713 ASM, IndexTypeQuals);
2714 Canon = getQualifiedType(Canon, canonSplit.Quals);
2716 // Get the new insert position for the node we care about.
2717 ConstantArrayType *NewIP =
2718 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2719 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2722 ConstantArrayType *New = new(*this,TypeAlignment)
2723 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2724 ConstantArrayTypes.InsertNode(New, InsertPos);
2725 Types.push_back(New);
2726 return QualType(New, 0);
2729 /// getVariableArrayDecayedType - Turns the given type, which may be
2730 /// variably-modified, into the corresponding type with all the known
2731 /// sizes replaced with [*].
2732 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2733 // Vastly most common case.
2734 if (!type->isVariablyModifiedType()) return type;
2738 SplitQualType split = type.getSplitDesugaredType();
2739 const Type *ty = split.Ty;
2740 switch (ty->getTypeClass()) {
2741 #define TYPE(Class, Base)
2742 #define ABSTRACT_TYPE(Class, Base)
2743 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2744 #include "clang/AST/TypeNodes.def"
2745 llvm_unreachable("didn't desugar past all non-canonical types?");
2747 // These types should never be variably-modified.
2751 case Type::ExtVector:
2752 case Type::DependentSizedExtVector:
2753 case Type::ObjCObject:
2754 case Type::ObjCInterface:
2755 case Type::ObjCObjectPointer:
2758 case Type::UnresolvedUsing:
2759 case Type::TypeOfExpr:
2761 case Type::Decltype:
2762 case Type::UnaryTransform:
2763 case Type::DependentName:
2764 case Type::InjectedClassName:
2765 case Type::TemplateSpecialization:
2766 case Type::DependentTemplateSpecialization:
2767 case Type::TemplateTypeParm:
2768 case Type::SubstTemplateTypeParmPack:
2770 case Type::DeducedTemplateSpecialization:
2771 case Type::PackExpansion:
2772 llvm_unreachable("type should never be variably-modified");
2774 // These types can be variably-modified but should never need to
2776 case Type::FunctionNoProto:
2777 case Type::FunctionProto:
2778 case Type::BlockPointer:
2779 case Type::MemberPointer:
2783 // These types can be variably-modified. All these modifications
2784 // preserve structure except as noted by comments.
2785 // TODO: if we ever care about optimizing VLAs, there are no-op
2786 // optimizations available here.
2788 result = getPointerType(getVariableArrayDecayedType(
2789 cast<PointerType>(ty)->getPointeeType()));
2792 case Type::LValueReference: {
2793 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2794 result = getLValueReferenceType(
2795 getVariableArrayDecayedType(lv->getPointeeType()),
2796 lv->isSpelledAsLValue());
2800 case Type::RValueReference: {
2801 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2802 result = getRValueReferenceType(
2803 getVariableArrayDecayedType(lv->getPointeeType()));
2807 case Type::Atomic: {
2808 const AtomicType *at = cast<AtomicType>(ty);
2809 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2813 case Type::ConstantArray: {
2814 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2815 result = getConstantArrayType(
2816 getVariableArrayDecayedType(cat->getElementType()),
2818 cat->getSizeModifier(),
2819 cat->getIndexTypeCVRQualifiers());
2823 case Type::DependentSizedArray: {
2824 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2825 result = getDependentSizedArrayType(
2826 getVariableArrayDecayedType(dat->getElementType()),
2828 dat->getSizeModifier(),
2829 dat->getIndexTypeCVRQualifiers(),
2830 dat->getBracketsRange());
2834 // Turn incomplete types into [*] types.
2835 case Type::IncompleteArray: {
2836 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2837 result = getVariableArrayType(
2838 getVariableArrayDecayedType(iat->getElementType()),
2841 iat->getIndexTypeCVRQualifiers(),
2846 // Turn VLA types into [*] types.
2847 case Type::VariableArray: {
2848 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2849 result = getVariableArrayType(
2850 getVariableArrayDecayedType(vat->getElementType()),
2853 vat->getIndexTypeCVRQualifiers(),
2854 vat->getBracketsRange());
2859 // Apply the top-level qualifiers from the original.
2860 return getQualifiedType(result, split.Quals);
2863 /// getVariableArrayType - Returns a non-unique reference to the type for a
2864 /// variable array of the specified element type.
2865 QualType ASTContext::getVariableArrayType(QualType EltTy,
2867 ArrayType::ArraySizeModifier ASM,
2868 unsigned IndexTypeQuals,
2869 SourceRange Brackets) const {
2870 // Since we don't unique expressions, it isn't possible to unique VLA's
2871 // that have an expression provided for their size.
2874 // Be sure to pull qualifiers off the element type.
2875 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2876 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2877 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2878 IndexTypeQuals, Brackets);
2879 Canon = getQualifiedType(Canon, canonSplit.Quals);
2882 VariableArrayType *New = new(*this, TypeAlignment)
2883 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2885 VariableArrayTypes.push_back(New);
2886 Types.push_back(New);
2887 return QualType(New, 0);
2890 /// getDependentSizedArrayType - Returns a non-unique reference to
2891 /// the type for a dependently-sized array of the specified element
2893 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2895 ArrayType::ArraySizeModifier ASM,
2896 unsigned elementTypeQuals,
2897 SourceRange brackets) const {
2898 assert((!numElements || numElements->isTypeDependent() ||
2899 numElements->isValueDependent()) &&
2900 "Size must be type- or value-dependent!");
2902 // Dependently-sized array types that do not have a specified number
2903 // of elements will have their sizes deduced from a dependent
2904 // initializer. We do no canonicalization here at all, which is okay
2905 // because they can't be used in most locations.
2907 DependentSizedArrayType *newType
2908 = new (*this, TypeAlignment)
2909 DependentSizedArrayType(*this, elementType, QualType(),
2910 numElements, ASM, elementTypeQuals,
2912 Types.push_back(newType);
2913 return QualType(newType, 0);
2916 // Otherwise, we actually build a new type every time, but we
2917 // also build a canonical type.
2919 SplitQualType canonElementType = getCanonicalType(elementType).split();
2921 void *insertPos = nullptr;
2922 llvm::FoldingSetNodeID ID;
2923 DependentSizedArrayType::Profile(ID, *this,
2924 QualType(canonElementType.Ty, 0),
2925 ASM, elementTypeQuals, numElements);
2927 // Look for an existing type with these properties.
2928 DependentSizedArrayType *canonTy =
2929 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2931 // If we don't have one, build one.
2933 canonTy = new (*this, TypeAlignment)
2934 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2935 QualType(), numElements, ASM, elementTypeQuals,
2937 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2938 Types.push_back(canonTy);
2941 // Apply qualifiers from the element type to the array.
2942 QualType canon = getQualifiedType(QualType(canonTy,0),
2943 canonElementType.Quals);
2945 // If we didn't need extra canonicalization for the element type or the size
2946 // expression, then just use that as our result.
2947 if (QualType(canonElementType.Ty, 0) == elementType &&
2948 canonTy->getSizeExpr() == numElements)
2951 // Otherwise, we need to build a type which follows the spelling
2952 // of the element type.
2953 DependentSizedArrayType *sugaredType
2954 = new (*this, TypeAlignment)
2955 DependentSizedArrayType(*this, elementType, canon, numElements,
2956 ASM, elementTypeQuals, brackets);
2957 Types.push_back(sugaredType);
2958 return QualType(sugaredType, 0);
2961 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2962 ArrayType::ArraySizeModifier ASM,
2963 unsigned elementTypeQuals) const {
2964 llvm::FoldingSetNodeID ID;
2965 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2967 void *insertPos = nullptr;
2968 if (IncompleteArrayType *iat =
2969 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2970 return QualType(iat, 0);
2972 // If the element type isn't canonical, this won't be a canonical type
2973 // either, so fill in the canonical type field. We also have to pull
2974 // qualifiers off the element type.
2977 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2978 SplitQualType canonSplit = getCanonicalType(elementType).split();
2979 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2980 ASM, elementTypeQuals);
2981 canon = getQualifiedType(canon, canonSplit.Quals);
2983 // Get the new insert position for the node we care about.
2984 IncompleteArrayType *existing =
2985 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2986 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2989 IncompleteArrayType *newType = new (*this, TypeAlignment)
2990 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2992 IncompleteArrayTypes.InsertNode(newType, insertPos);
2993 Types.push_back(newType);
2994 return QualType(newType, 0);
2997 /// getVectorType - Return the unique reference to a vector type of
2998 /// the specified element type and size. VectorType must be a built-in type.
2999 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3000 VectorType::VectorKind VecKind) const {
3001 assert(vecType->isBuiltinType());
3003 // Check if we've already instantiated a vector of this type.
3004 llvm::FoldingSetNodeID ID;
3005 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3007 void *InsertPos = nullptr;
3008 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(VTP, 0);
3011 // If the element type isn't canonical, this won't be a canonical type either,
3012 // so fill in the canonical type field.
3014 if (!vecType.isCanonical()) {
3015 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3017 // Get the new insert position for the node we care about.
3018 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3019 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3021 VectorType *New = new (*this, TypeAlignment)
3022 VectorType(vecType, NumElts, Canonical, VecKind);
3023 VectorTypes.InsertNode(New, InsertPos);
3024 Types.push_back(New);
3025 return QualType(New, 0);
3028 /// getExtVectorType - Return the unique reference to an extended vector type of
3029 /// the specified element type and size. VectorType must be a built-in type.
3031 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3032 assert(vecType->isBuiltinType() || vecType->isDependentType());
3034 // Check if we've already instantiated a vector of this type.
3035 llvm::FoldingSetNodeID ID;
3036 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3037 VectorType::GenericVector);
3038 void *InsertPos = nullptr;
3039 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(VTP, 0);
3042 // If the element type isn't canonical, this won't be a canonical type either,
3043 // so fill in the canonical type field.
3045 if (!vecType.isCanonical()) {
3046 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3048 // Get the new insert position for the node we care about.
3049 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3050 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3052 ExtVectorType *New = new (*this, TypeAlignment)
3053 ExtVectorType(vecType, NumElts, Canonical);
3054 VectorTypes.InsertNode(New, InsertPos);
3055 Types.push_back(New);
3056 return QualType(New, 0);
3060 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3062 SourceLocation AttrLoc) const {
3063 llvm::FoldingSetNodeID ID;
3064 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3067 void *InsertPos = nullptr;
3068 DependentSizedExtVectorType *Canon
3069 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3070 DependentSizedExtVectorType *New;
3072 // We already have a canonical version of this array type; use it as
3073 // the canonical type for a newly-built type.
3074 New = new (*this, TypeAlignment)
3075 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3078 QualType CanonVecTy = getCanonicalType(vecType);
3079 if (CanonVecTy == vecType) {
3080 New = new (*this, TypeAlignment)
3081 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3084 DependentSizedExtVectorType *CanonCheck
3085 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3086 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3088 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3090 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3092 New = new (*this, TypeAlignment)
3093 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3097 Types.push_back(New);
3098 return QualType(New, 0);
3101 /// \brief Determine whether \p T is canonical as the result type of a function.
3102 static bool isCanonicalResultType(QualType T) {
3103 return T.isCanonical() &&
3104 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3105 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3108 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3111 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3112 const FunctionType::ExtInfo &Info) const {
3113 // Unique functions, to guarantee there is only one function of a particular
3115 llvm::FoldingSetNodeID ID;
3116 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3118 void *InsertPos = nullptr;
3119 if (FunctionNoProtoType *FT =
3120 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3121 return QualType(FT, 0);
3124 if (!isCanonicalResultType(ResultTy)) {
3126 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3128 // Get the new insert position for the node we care about.
3129 FunctionNoProtoType *NewIP =
3130 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3131 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3134 FunctionNoProtoType *New = new (*this, TypeAlignment)
3135 FunctionNoProtoType(ResultTy, Canonical, Info);
3136 Types.push_back(New);
3137 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3138 return QualType(New, 0);
3142 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3143 CanQualType CanResultType = getCanonicalType(ResultType);
3145 // Canonical result types do not have ARC lifetime qualifiers.
3146 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3147 Qualifiers Qs = CanResultType.getQualifiers();
3148 Qs.removeObjCLifetime();
3149 return CanQualType::CreateUnsafe(
3150 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3153 return CanResultType;
3156 static bool isCanonicalExceptionSpecification(
3157 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3158 if (ESI.Type == EST_None)
3160 if (!NoexceptInType)
3163 // C++17 onwards: exception specification is part of the type, as a simple
3164 // boolean "can this function type throw".
3165 if (ESI.Type == EST_BasicNoexcept)
3168 // A dynamic exception specification is canonical if it only contains pack
3169 // expansions (so we can't tell whether it's non-throwing) and all its
3170 // contained types are canonical.
3171 if (ESI.Type == EST_Dynamic) {
3172 bool AnyPackExpansions = false;
3173 for (QualType ET : ESI.Exceptions) {
3174 if (!ET.isCanonical())
3176 if (ET->getAs<PackExpansionType>())
3177 AnyPackExpansions = true;
3179 return AnyPackExpansions;
3182 // A noexcept(expr) specification is (possibly) canonical if expr is
3184 if (ESI.Type == EST_ComputedNoexcept)
3185 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3190 QualType ASTContext::getFunctionTypeInternal(
3191 QualType ResultTy, ArrayRef<QualType> ArgArray,
3192 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3193 size_t NumArgs = ArgArray.size();
3195 // Unique functions, to guarantee there is only one function of a particular
3197 llvm::FoldingSetNodeID ID;
3198 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3202 bool Unique = false;
3204 void *InsertPos = nullptr;
3205 if (FunctionProtoType *FPT =
3206 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3207 QualType Existing = QualType(FPT, 0);
3209 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3210 // it so long as our exception specification doesn't contain a dependent
3211 // noexcept expression, or we're just looking for a canonical type.
3212 // Otherwise, we're going to need to create a type
3213 // sugar node to hold the concrete expression.
3214 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
3215 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3218 // We need a new type sugar node for this one, to hold the new noexcept
3219 // expression. We do no canonicalization here, but that's OK since we don't
3220 // expect to see the same noexcept expression much more than once.
3221 Canonical = getCanonicalType(Existing);
3225 bool NoexceptInType = getLangOpts().CPlusPlus1z;
3226 bool IsCanonicalExceptionSpec =
3227 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3229 // Determine whether the type being created is already canonical or not.
3230 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3231 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3232 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3233 if (!ArgArray[i].isCanonicalAsParam())
3234 isCanonical = false;
3236 if (OnlyWantCanonical)
3237 assert(isCanonical &&
3238 "given non-canonical parameters constructing canonical type");
3240 // If this type isn't canonical, get the canonical version of it if we don't
3241 // already have it. The exception spec is only partially part of the
3242 // canonical type, and only in C++17 onwards.
3243 if (!isCanonical && Canonical.isNull()) {
3244 SmallVector<QualType, 16> CanonicalArgs;
3245 CanonicalArgs.reserve(NumArgs);
3246 for (unsigned i = 0; i != NumArgs; ++i)
3247 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3249 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3250 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3251 CanonicalEPI.HasTrailingReturn = false;
3253 if (IsCanonicalExceptionSpec) {
3254 // Exception spec is already OK.
3255 } else if (NoexceptInType) {
3256 switch (EPI.ExceptionSpec.Type) {
3257 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3258 // We don't know yet. It shouldn't matter what we pick here; no-one
3259 // should ever look at this.
3261 case EST_None: case EST_MSAny:
3262 CanonicalEPI.ExceptionSpec.Type = EST_None;
3265 // A dynamic exception specification is almost always "not noexcept",
3266 // with the exception that a pack expansion might expand to no types.
3268 bool AnyPacks = false;
3269 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3270 if (ET->getAs<PackExpansionType>())
3272 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3275 CanonicalEPI.ExceptionSpec.Type = EST_None;
3277 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3278 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3283 case EST_DynamicNone: case EST_BasicNoexcept:
3284 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3287 case EST_ComputedNoexcept:
3288 llvm::APSInt Value(1);
3289 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3290 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3291 /*IsEvaluated*/false)) {
3292 // This noexcept specification is invalid.
3293 // FIXME: Should this be able to happen?
3294 CanonicalEPI.ExceptionSpec.Type = EST_None;
3298 CanonicalEPI.ExceptionSpec.Type =
3299 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3303 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3306 // Adjust the canonical function result type.
3307 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3309 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3311 // Get the new insert position for the node we care about.
3312 FunctionProtoType *NewIP =
3313 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3317 // FunctionProtoType objects are allocated with extra bytes after
3318 // them for three variable size arrays at the end:
3319 // - parameter types
3320 // - exception types
3321 // - extended parameter information
3322 // Instead of the exception types, there could be a noexcept
3323 // expression, or information used to resolve the exception
3325 size_t Size = sizeof(FunctionProtoType) +
3326 NumArgs * sizeof(QualType);
3328 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3329 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3330 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3331 Size += sizeof(Expr*);
3332 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3333 Size += 2 * sizeof(FunctionDecl*);
3334 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3335 Size += sizeof(FunctionDecl*);
3338 // Put the ExtParameterInfos last. If all were equal, it would make
3339 // more sense to put these before the exception specification, because
3340 // it's much easier to skip past them compared to the elaborate switch
3341 // required to skip the exception specification. However, all is not
3342 // equal; ExtParameterInfos are used to model very uncommon features,
3343 // and it's better not to burden the more common paths.
3344 if (EPI.ExtParameterInfos) {
3345 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3348 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3349 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3350 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3351 Types.push_back(FTP);
3353 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3354 return QualType(FTP, 0);
3357 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3358 llvm::FoldingSetNodeID ID;
3359 PipeType::Profile(ID, T, ReadOnly);
3361 void *InsertPos = 0;
3362 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3363 return QualType(PT, 0);
3365 // If the pipe element type isn't canonical, this won't be a canonical type
3366 // either, so fill in the canonical type field.
3368 if (!T.isCanonical()) {
3369 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3371 // Get the new insert position for the node we care about.
3372 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 assert(!NewIP && "Shouldn't be in the map!");
3376 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3377 Types.push_back(New);
3378 PipeTypes.InsertNode(New, InsertPos);
3379 return QualType(New, 0);
3382 QualType ASTContext::getReadPipeType(QualType T) const {
3383 return getPipeType(T, true);
3386 QualType ASTContext::getWritePipeType(QualType T) const {
3387 return getPipeType(T, false);
3391 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3392 if (!isa<CXXRecordDecl>(D)) return false;
3393 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3394 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3396 if (RD->getDescribedClassTemplate() &&
3397 !isa<ClassTemplateSpecializationDecl>(RD))
3403 /// getInjectedClassNameType - Return the unique reference to the
3404 /// injected class name type for the specified templated declaration.
3405 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3406 QualType TST) const {
3407 assert(NeedsInjectedClassNameType(Decl));
3408 if (Decl->TypeForDecl) {
3409 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3410 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3411 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3412 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3413 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3416 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3417 Decl->TypeForDecl = newType;
3418 Types.push_back(newType);
3420 return QualType(Decl->TypeForDecl, 0);
3423 /// getTypeDeclType - Return the unique reference to the type for the
3424 /// specified type declaration.
3425 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3426 assert(Decl && "Passed null for Decl param");
3427 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3429 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3430 return getTypedefType(Typedef);
3432 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3433 "Template type parameter types are always available.");
3435 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3436 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3437 assert(!NeedsInjectedClassNameType(Record));
3438 return getRecordType(Record);
3439 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3440 assert(Enum->isFirstDecl() && "enum has previous declaration");
3441 return getEnumType(Enum);
3442 } else if (const UnresolvedUsingTypenameDecl *Using =
3443 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3444 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3445 Decl->TypeForDecl = newType;
3446 Types.push_back(newType);
3448 llvm_unreachable("TypeDecl without a type?");
3450 return QualType(Decl->TypeForDecl, 0);
3453 /// getTypedefType - Return the unique reference to the type for the
3454 /// specified typedef name decl.
3456 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3457 QualType Canonical) const {
3458 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3460 if (Canonical.isNull())
3461 Canonical = getCanonicalType(Decl->getUnderlyingType());
3462 TypedefType *newType = new(*this, TypeAlignment)
3463 TypedefType(Type::Typedef, Decl, Canonical);
3464 Decl->TypeForDecl = newType;
3465 Types.push_back(newType);
3466 return QualType(newType, 0);
3469 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3470 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3472 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3473 if (PrevDecl->TypeForDecl)
3474 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3476 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3477 Decl->TypeForDecl = newType;
3478 Types.push_back(newType);
3479 return QualType(newType, 0);
3482 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3483 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3485 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3486 if (PrevDecl->TypeForDecl)
3487 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3489 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3490 Decl->TypeForDecl = newType;
3491 Types.push_back(newType);
3492 return QualType(newType, 0);
3495 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3496 QualType modifiedType,
3497 QualType equivalentType) {
3498 llvm::FoldingSetNodeID id;
3499 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3501 void *insertPos = nullptr;
3502 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3503 if (type) return QualType(type, 0);
3505 QualType canon = getCanonicalType(equivalentType);
3506 type = new (*this, TypeAlignment)
3507 AttributedType(canon, attrKind, modifiedType, equivalentType);
3509 Types.push_back(type);
3510 AttributedTypes.InsertNode(type, insertPos);
3512 return QualType(type, 0);
3515 /// \brief Retrieve a substitution-result type.
3517 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3518 QualType Replacement) const {
3519 assert(Replacement.isCanonical()
3520 && "replacement types must always be canonical");
3522 llvm::FoldingSetNodeID ID;
3523 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3524 void *InsertPos = nullptr;
3525 SubstTemplateTypeParmType *SubstParm
3526 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3529 SubstParm = new (*this, TypeAlignment)
3530 SubstTemplateTypeParmType(Parm, Replacement);
3531 Types.push_back(SubstParm);
3532 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3535 return QualType(SubstParm, 0);
3538 /// \brief Retrieve a
3539 QualType ASTContext::getSubstTemplateTypeParmPackType(
3540 const TemplateTypeParmType *Parm,
3541 const TemplateArgument &ArgPack) {
3543 for (const auto &P : ArgPack.pack_elements()) {
3544 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3545 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3549 llvm::FoldingSetNodeID ID;
3550 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3551 void *InsertPos = nullptr;
3552 if (SubstTemplateTypeParmPackType *SubstParm
3553 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3554 return QualType(SubstParm, 0);
3557 if (!Parm->isCanonicalUnqualified()) {
3558 Canon = getCanonicalType(QualType(Parm, 0));
3559 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3561 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3564 SubstTemplateTypeParmPackType *SubstParm
3565 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3567 Types.push_back(SubstParm);
3568 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
3569 return QualType(SubstParm, 0);
3572 /// \brief Retrieve the template type parameter type for a template
3573 /// parameter or parameter pack with the given depth, index, and (optionally)
3575 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3577 TemplateTypeParmDecl *TTPDecl) const {
3578 llvm::FoldingSetNodeID ID;
3579 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3580 void *InsertPos = nullptr;
3581 TemplateTypeParmType *TypeParm
3582 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3585 return QualType(TypeParm, 0);
3588 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3589 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3591 TemplateTypeParmType *TypeCheck
3592 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 assert(!TypeCheck && "Template type parameter canonical type broken");
3596 TypeParm = new (*this, TypeAlignment)
3597 TemplateTypeParmType(Depth, Index, ParameterPack);
3599 Types.push_back(TypeParm);
3600 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3602 return QualType(TypeParm, 0);
3606 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3607 SourceLocation NameLoc,
3608 const TemplateArgumentListInfo &Args,
3609 QualType Underlying) const {
3610 assert(!Name.getAsDependentTemplateName() &&
3611 "No dependent template names here!");
3612 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3614 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3615 TemplateSpecializationTypeLoc TL =
3616 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3617 TL.setTemplateKeywordLoc(SourceLocation());
3618 TL.setTemplateNameLoc(NameLoc);
3619 TL.setLAngleLoc(Args.getLAngleLoc());
3620 TL.setRAngleLoc(Args.getRAngleLoc());
3621 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3622 TL.setArgLocInfo(i, Args[i].getLocInfo());
3627 ASTContext::getTemplateSpecializationType(TemplateName Template,
3628 const TemplateArgumentListInfo &Args,
3629 QualType Underlying) const {
3630 assert(!Template.getAsDependentTemplateName() &&
3631 "No dependent template names here!");
3633 SmallVector<TemplateArgument, 4> ArgVec;
3634 ArgVec.reserve(Args.size());
3635 for (const TemplateArgumentLoc &Arg : Args.arguments())
3636 ArgVec.push_back(Arg.getArgument());
3638 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3642 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3643 for (const TemplateArgument &Arg : Args)
3644 if (Arg.isPackExpansion())
3652 ASTContext::getTemplateSpecializationType(TemplateName Template,
3653 ArrayRef<TemplateArgument> Args,
3654 QualType Underlying) const {
3655 assert(!Template.getAsDependentTemplateName() &&
3656 "No dependent template names here!");
3657 // Look through qualified template names.
3658 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3659 Template = TemplateName(QTN->getTemplateDecl());
3662 Template.getAsTemplateDecl() &&
3663 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3665 if (!Underlying.isNull())
3666 CanonType = getCanonicalType(Underlying);
3668 // We can get here with an alias template when the specialization contains
3669 // a pack expansion that does not match up with a parameter pack.
3670 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3671 "Caller must compute aliased type");
3672 IsTypeAlias = false;
3673 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3676 // Allocate the (non-canonical) template specialization type, but don't
3677 // try to unique it: these types typically have location information that
3678 // we don't unique and don't want to lose.
3679 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3680 sizeof(TemplateArgument) * Args.size() +
3681 (IsTypeAlias? sizeof(QualType) : 0),
3683 TemplateSpecializationType *Spec
3684 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3685 IsTypeAlias ? Underlying : QualType());
3687 Types.push_back(Spec);
3688 return QualType(Spec, 0);
3691 QualType ASTContext::getCanonicalTemplateSpecializationType(
3692 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3693 assert(!Template.getAsDependentTemplateName() &&
3694 "No dependent template names here!");
3696 // Look through qualified template names.
3697 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3698 Template = TemplateName(QTN->getTemplateDecl());
3700 // Build the canonical template specialization type.
3701 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3702 SmallVector<TemplateArgument, 4> CanonArgs;
3703 unsigned NumArgs = Args.size();
3704 CanonArgs.reserve(NumArgs);
3705 for (const TemplateArgument &Arg : Args)
3706 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3708 // Determine whether this canonical template specialization type already
3710 llvm::FoldingSetNodeID ID;
3711 TemplateSpecializationType::Profile(ID, CanonTemplate,
3714 void *InsertPos = nullptr;
3715 TemplateSpecializationType *Spec
3716 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3719 // Allocate a new canonical template specialization type.
3720 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3721 sizeof(TemplateArgument) * NumArgs),
3723 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3725 QualType(), QualType());
3726 Types.push_back(Spec);
3727 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3730 assert(Spec->isDependentType() &&
3731 "Non-dependent template-id type must have a canonical type");
3732 return QualType(Spec, 0);
3736 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3737 NestedNameSpecifier *NNS,
3738 QualType NamedType) const {
3739 llvm::FoldingSetNodeID ID;
3740 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3742 void *InsertPos = nullptr;
3743 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3745 return QualType(T, 0);
3747 QualType Canon = NamedType;
3748 if (!Canon.isCanonical()) {
3749 Canon = getCanonicalType(NamedType);
3750 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3751 assert(!CheckT && "Elaborated canonical type broken");
3755 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3757 ElaboratedTypes.InsertNode(T, InsertPos);
3758 return QualType(T, 0);
3762 ASTContext::getParenType(QualType InnerType) const {
3763 llvm::FoldingSetNodeID ID;
3764 ParenType::Profile(ID, InnerType);
3766 void *InsertPos = nullptr;
3767 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3769 return QualType(T, 0);
3771 QualType Canon = InnerType;
3772 if (!Canon.isCanonical()) {
3773 Canon = getCanonicalType(InnerType);
3774 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 assert(!CheckT && "Paren canonical type broken");
3779 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3781 ParenTypes.InsertNode(T, InsertPos);
3782 return QualType(T, 0);
3785 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3786 NestedNameSpecifier *NNS,
3787 const IdentifierInfo *Name,
3788 QualType Canon) const {
3789 if (Canon.isNull()) {
3790 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3791 if (CanonNNS != NNS)
3792 Canon = getDependentNameType(Keyword, CanonNNS, Name);
3795 llvm::FoldingSetNodeID ID;
3796 DependentNameType::Profile(ID, Keyword, NNS, Name);
3798 void *InsertPos = nullptr;
3799 DependentNameType *T
3800 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3802 return QualType(T, 0);
3804 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3806 DependentNameTypes.InsertNode(T, InsertPos);
3807 return QualType(T, 0);
3811 ASTContext::getDependentTemplateSpecializationType(
3812 ElaboratedTypeKeyword Keyword,
3813 NestedNameSpecifier *NNS,
3814 const IdentifierInfo *Name,
3815 const TemplateArgumentListInfo &Args) const {
3816 // TODO: avoid this copy
3817 SmallVector<TemplateArgument, 16> ArgCopy;
3818 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3819 ArgCopy.push_back(Args[I].getArgument());
3820 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3824 ASTContext::getDependentTemplateSpecializationType(
3825 ElaboratedTypeKeyword Keyword,
3826 NestedNameSpecifier *NNS,
3827 const IdentifierInfo *Name,
3828 ArrayRef<TemplateArgument> Args) const {
3829 assert((!NNS || NNS->isDependent()) &&
3830 "nested-name-specifier must be dependent");
3832 llvm::FoldingSetNodeID ID;
3833 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3836 void *InsertPos = nullptr;
3837 DependentTemplateSpecializationType *T
3838 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3840 return QualType(T, 0);
3842 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3844 ElaboratedTypeKeyword CanonKeyword = Keyword;
3845 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3847 bool AnyNonCanonArgs = false;
3848 unsigned NumArgs = Args.size();
3849 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3850 for (unsigned I = 0; I != NumArgs; ++I) {
3851 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3852 if (!CanonArgs[I].structurallyEquals(Args[I]))
3853 AnyNonCanonArgs = true;
3857 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3858 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3862 // Find the insert position again.
3863 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3866 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3867 sizeof(TemplateArgument) * NumArgs),
3869 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3872 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3873 return QualType(T, 0);
3876 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3877 TemplateArgument Arg;
3878 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3879 QualType ArgType = getTypeDeclType(TTP);
3880 if (TTP->isParameterPack())
3881 ArgType = getPackExpansionType(ArgType, None);
3883 Arg = TemplateArgument(ArgType);
3884 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3885 Expr *E = new (*this) DeclRefExpr(
3886 NTTP, /*enclosing*/false,
3887 NTTP->getType().getNonLValueExprType(*this),
3888 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3890 if (NTTP->isParameterPack())
3891 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3893 Arg = TemplateArgument(E);
3895 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3896 if (TTP->isParameterPack())
3897 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3899 Arg = TemplateArgument(TemplateName(TTP));
3902 if (Param->isTemplateParameterPack())
3903 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3909 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3910 SmallVectorImpl<TemplateArgument> &Args) {
3911 Args.reserve(Args.size() + Params->size());
3913 for (NamedDecl *Param : *Params)
3914 Args.push_back(getInjectedTemplateArg(Param));
3917 QualType ASTContext::getPackExpansionType(QualType Pattern,
3918 Optional<unsigned> NumExpansions) {
3919 llvm::FoldingSetNodeID ID;
3920 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3922 assert(Pattern->containsUnexpandedParameterPack() &&
3923 "Pack expansions must expand one or more parameter packs");
3924 void *InsertPos = nullptr;
3925 PackExpansionType *T
3926 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3928 return QualType(T, 0);
3931 if (!Pattern.isCanonical()) {
3932 Canon = getCanonicalType(Pattern);
3933 // The canonical type might not contain an unexpanded parameter pack, if it
3934 // contains an alias template specialization which ignores one of its
3936 if (Canon->containsUnexpandedParameterPack()) {
3937 Canon = getPackExpansionType(Canon, NumExpansions);
3939 // Find the insert position again, in case we inserted an element into
3940 // PackExpansionTypes and invalidated our insert position.
3941 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3945 T = new (*this, TypeAlignment)
3946 PackExpansionType(Pattern, Canon, NumExpansions);
3948 PackExpansionTypes.InsertNode(T, InsertPos);
3949 return QualType(T, 0);
3952 /// CmpProtocolNames - Comparison predicate for sorting protocols
3954 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3955 ObjCProtocolDecl *const *RHS) {
3956 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3959 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3960 if (Protocols.empty()) return true;
3962 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3965 for (unsigned i = 1; i != Protocols.size(); ++i)
3966 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3967 Protocols[i]->getCanonicalDecl() != Protocols[i])
3973 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3974 // Sort protocols, keyed by name.
3975 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3978 for (ObjCProtocolDecl *&P : Protocols)
3979 P = P->getCanonicalDecl();
3981 // Remove duplicates.
3982 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3983 Protocols.erase(ProtocolsEnd, Protocols.end());
3986 QualType ASTContext::getObjCObjectType(QualType BaseType,
3987 ObjCProtocolDecl * const *Protocols,
3988 unsigned NumProtocols) const {
3989 return getObjCObjectType(BaseType, { },
3990 llvm::makeArrayRef(Protocols, NumProtocols),
3991 /*isKindOf=*/false);
3994 QualType ASTContext::getObjCObjectType(
3996 ArrayRef<QualType> typeArgs,
3997 ArrayRef<ObjCProtocolDecl *> protocols,
3998 bool isKindOf) const {
3999 // If the base type is an interface and there aren't any protocols or
4000 // type arguments to add, then the interface type will do just fine.
4001 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4002 isa<ObjCInterfaceType>(baseType))
4005 // Look in the folding set for an existing type.
4006 llvm::FoldingSetNodeID ID;
4007 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4008 void *InsertPos = nullptr;
4009 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4010 return QualType(QT, 0);
4012 // Determine the type arguments to be used for canonicalization,
4013 // which may be explicitly specified here or written on the base
4015 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4016 if (effectiveTypeArgs.empty()) {
4017 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4018 effectiveTypeArgs = baseObject->getTypeArgs();
4021 // Build the canonical type, which has the canonical base type and a
4022 // sorted-and-uniqued list of protocols and the type arguments
4025 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4026 effectiveTypeArgs.end(),
4027 [&](QualType type) {
4028 return type.isCanonical();
4030 bool protocolsSorted = areSortedAndUniqued(protocols);
4031 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4032 // Determine the canonical type arguments.
4033 ArrayRef<QualType> canonTypeArgs;
4034 SmallVector<QualType, 4> canonTypeArgsVec;
4035 if (!typeArgsAreCanonical) {
4036 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4037 for (auto typeArg : effectiveTypeArgs)
4038 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4039 canonTypeArgs = canonTypeArgsVec;
4041 canonTypeArgs = effectiveTypeArgs;
4044 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4045 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4046 if (!protocolsSorted) {
4047 canonProtocolsVec.append(protocols.begin(), protocols.end());
4048 SortAndUniqueProtocols(canonProtocolsVec);
4049 canonProtocols = canonProtocolsVec;
4051 canonProtocols = protocols;
4054 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4055 canonProtocols, isKindOf);
4057 // Regenerate InsertPos.
4058 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4061 unsigned size = sizeof(ObjCObjectTypeImpl);
4062 size += typeArgs.size() * sizeof(QualType);
4063 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4064 void *mem = Allocate(size, TypeAlignment);
4065 ObjCObjectTypeImpl *T =
4066 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4070 ObjCObjectTypes.InsertNode(T, InsertPos);
4071 return QualType(T, 0);
4074 /// Apply Objective-C protocol qualifiers to the given type.
4075 /// If this is for the canonical type of a type parameter, we can apply
4076 /// protocol qualifiers on the ObjCObjectPointerType.
4078 ASTContext::applyObjCProtocolQualifiers(QualType type,
4079 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4080 bool allowOnPointerType) const {
4083 if (const ObjCTypeParamType *objT =
4084 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4085 return getObjCTypeParamType(objT->getDecl(), protocols);
4088 // Apply protocol qualifiers to ObjCObjectPointerType.
4089 if (allowOnPointerType) {
4090 if (const ObjCObjectPointerType *objPtr =
4091 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4092 const ObjCObjectType *objT = objPtr->getObjectType();
4093 // Merge protocol lists and construct ObjCObjectType.
4094 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4095 protocolsVec.append(objT->qual_begin(),
4097 protocolsVec.append(protocols.begin(), protocols.end());
4098 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4099 type = getObjCObjectType(
4100 objT->getBaseType(),
4101 objT->getTypeArgsAsWritten(),
4103 objT->isKindOfTypeAsWritten());
4104 return getObjCObjectPointerType(type);
4108 // Apply protocol qualifiers to ObjCObjectType.
4109 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4110 // FIXME: Check for protocols to which the class type is already
4111 // known to conform.
4113 return getObjCObjectType(objT->getBaseType(),
4114 objT->getTypeArgsAsWritten(),
4116 objT->isKindOfTypeAsWritten());
4119 // If the canonical type is ObjCObjectType, ...
4120 if (type->isObjCObjectType()) {
4121 // Silently overwrite any existing protocol qualifiers.
4122 // TODO: determine whether that's the right thing to do.
4124 // FIXME: Check for protocols to which the class type is already
4125 // known to conform.
4126 return getObjCObjectType(type, { }, protocols, false);
4129 // id<protocol-list>
4130 if (type->isObjCIdType()) {
4131 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4132 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4133 objPtr->isKindOfType());
4134 return getObjCObjectPointerType(type);
4137 // Class<protocol-list>
4138 if (type->isObjCClassType()) {
4139 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4140 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4141 objPtr->isKindOfType());
4142 return getObjCObjectPointerType(type);
4150 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4151 ArrayRef<ObjCProtocolDecl *> protocols,
4152 QualType Canonical) const {
4153 // Look in the folding set for an existing type.
4154 llvm::FoldingSetNodeID ID;
4155 ObjCTypeParamType::Profile(ID, Decl, protocols);
4156 void *InsertPos = nullptr;
4157 if (ObjCTypeParamType *TypeParam =
4158 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4159 return QualType(TypeParam, 0);
4161 if (Canonical.isNull()) {
4162 // We canonicalize to the underlying type.
4163 Canonical = getCanonicalType(Decl->getUnderlyingType());
4164 if (!protocols.empty()) {
4165 // Apply the protocol qualifers.
4167 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4168 true/*allowOnPointerType*/);
4169 assert(!hasError && "Error when apply protocol qualifier to bound type");
4173 unsigned size = sizeof(ObjCTypeParamType);
4174 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4175 void *mem = Allocate(size, TypeAlignment);
4176 ObjCTypeParamType *newType = new (mem)
4177 ObjCTypeParamType(Decl, Canonical, protocols);
4179 Types.push_back(newType);
4180 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4181 return QualType(newType, 0);
4184 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4185 /// protocol list adopt all protocols in QT's qualified-id protocol
4187 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4188 ObjCInterfaceDecl *IC) {
4189 if (!QT->isObjCQualifiedIdType())
4192 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4193 // If both the right and left sides have qualifiers.
4194 for (auto *Proto : OPT->quals()) {
4195 if (!IC->ClassImplementsProtocol(Proto, false))
4203 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4204 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4206 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4207 ObjCInterfaceDecl *IDecl) {
4208 if (!QT->isObjCQualifiedIdType())
4210 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4213 if (!IDecl->hasDefinition())
4215 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4216 CollectInheritedProtocols(IDecl, InheritedProtocols);
4217 if (InheritedProtocols.empty())
4219 // Check that if every protocol in list of id<plist> conforms to a protcol
4220 // of IDecl's, then bridge casting is ok.
4221 bool Conforms = false;
4222 for (auto *Proto : OPT->quals()) {
4224 for (auto *PI : InheritedProtocols) {
4225 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4236 for (auto *PI : InheritedProtocols) {
4237 // If both the right and left sides have qualifiers.
4238 bool Adopts = false;
4239 for (auto *Proto : OPT->quals()) {
4240 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4241 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4250 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4251 /// the given object type.
4252 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4253 llvm::FoldingSetNodeID ID;
4254 ObjCObjectPointerType::Profile(ID, ObjectT);
4256 void *InsertPos = nullptr;
4257 if (ObjCObjectPointerType *QT =
4258 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4259 return QualType(QT, 0);
4261 // Find the canonical object type.
4263 if (!ObjectT.isCanonical()) {
4264 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4266 // Regenerate InsertPos.
4267 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4271 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4272 ObjCObjectPointerType *QType =
4273 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4275 Types.push_back(QType);
4276 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4277 return QualType(QType, 0);
4280 /// getObjCInterfaceType - Return the unique reference to the type for the
4281 /// specified ObjC interface decl. The list of protocols is optional.
4282 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4283 ObjCInterfaceDecl *PrevDecl) const {
4284 if (Decl->TypeForDecl)
4285 return QualType(Decl->TypeForDecl, 0);
4288 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4289 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4290 return QualType(PrevDecl->TypeForDecl, 0);
4293 // Prefer the definition, if there is one.
4294 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4297 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4298 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4299 Decl->TypeForDecl = T;
4301 return QualType(T, 0);
4304 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4305 /// TypeOfExprType AST's (since expression's are never shared). For example,
4306 /// multiple declarations that refer to "typeof(x)" all contain different
4307 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4308 /// on canonical type's (which are always unique).
4309 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4310 TypeOfExprType *toe;
4311 if (tofExpr->isTypeDependent()) {
4312 llvm::FoldingSetNodeID ID;
4313 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4315 void *InsertPos = nullptr;
4316 DependentTypeOfExprType *Canon
4317 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4319 // We already have a "canonical" version of an identical, dependent
4320 // typeof(expr) type. Use that as our canonical type.
4321 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4322 QualType((TypeOfExprType*)Canon, 0));
4324 // Build a new, canonical typeof(expr) type.
4326 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4327 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4331 QualType Canonical = getCanonicalType(tofExpr->getType());
4332 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4334 Types.push_back(toe);
4335 return QualType(toe, 0);
4338 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4339 /// TypeOfType nodes. The only motivation to unique these nodes would be
4340 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4341 /// an issue. This doesn't affect the type checker, since it operates
4342 /// on canonical types (which are always unique).
4343 QualType ASTContext::getTypeOfType(QualType tofType) const {
4344 QualType Canonical = getCanonicalType(tofType);
4345 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4346 Types.push_back(tot);
4347 return QualType(tot, 0);
4350 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4351 /// nodes. This would never be helpful, since each such type has its own
4352 /// expression, and would not give a significant memory saving, since there
4353 /// is an Expr tree under each such type.
4354 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4357 // C++11 [temp.type]p2:
4358 // If an expression e involves a template parameter, decltype(e) denotes a
4359 // unique dependent type. Two such decltype-specifiers refer to the same
4360 // type only if their expressions are equivalent (14.5.6.1).
4361 if (e->isInstantiationDependent()) {
4362 llvm::FoldingSetNodeID ID;
4363 DependentDecltypeType::Profile(ID, *this, e);
4365 void *InsertPos = nullptr;
4366 DependentDecltypeType *Canon
4367 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4369 // Build a new, canonical decltype(expr) type.
4370 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4371 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4373 dt = new (*this, TypeAlignment)
4374 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4376 dt = new (*this, TypeAlignment)
4377 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4379 Types.push_back(dt);
4380 return QualType(dt, 0);
4383 /// getUnaryTransformationType - We don't unique these, since the memory
4384 /// savings are minimal and these are rare.
4385 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4386 QualType UnderlyingType,
4387 UnaryTransformType::UTTKind Kind)
4389 UnaryTransformType *ut = nullptr;
4391 if (BaseType->isDependentType()) {
4392 // Look in the folding set for an existing type.
4393 llvm::FoldingSetNodeID ID;
4394 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4396 void *InsertPos = nullptr;
4397 DependentUnaryTransformType *Canon
4398 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4401 // Build a new, canonical __underlying_type(type) type.
4402 Canon = new (*this, TypeAlignment)
4403 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4405 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4407 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4409 QualType(Canon, 0));
4411 QualType CanonType = getCanonicalType(UnderlyingType);
4412 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4413 UnderlyingType, Kind,
4416 Types.push_back(ut);
4417 return QualType(ut, 0);
4420 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4421 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4422 /// canonical deduced-but-dependent 'auto' type.
4423 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4424 bool IsDependent) const {
4425 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4426 return getAutoDeductType();
4428 // Look in the folding set for an existing type.
4429 void *InsertPos = nullptr;
4430 llvm::FoldingSetNodeID ID;
4431 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4432 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4433 return QualType(AT, 0);
4435 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4438 Types.push_back(AT);
4440 AutoTypes.InsertNode(AT, InsertPos);
4441 return QualType(AT, 0);
4444 /// Return the uniqued reference to the deduced template specialization type
4445 /// which has been deduced to the given type, or to the canonical undeduced
4446 /// such type, or the canonical deduced-but-dependent such type.
4447 QualType ASTContext::getDeducedTemplateSpecializationType(
4448 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4449 // Look in the folding set for an existing type.
4450 void *InsertPos = nullptr;
4451 llvm::FoldingSetNodeID ID;
4452 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4454 if (DeducedTemplateSpecializationType *DTST =
4455 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4456 return QualType(DTST, 0);
4458 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4459 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4460 Types.push_back(DTST);
4462 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4463 return QualType(DTST, 0);
4466 /// getAtomicType - Return the uniqued reference to the atomic type for
4467 /// the given value type.
4468 QualType ASTContext::getAtomicType(QualType T) const {
4469 // Unique pointers, to guarantee there is only one pointer of a particular
4471 llvm::FoldingSetNodeID ID;
4472 AtomicType::Profile(ID, T);
4474 void *InsertPos = nullptr;
4475 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4476 return QualType(AT, 0);
4478 // If the atomic value type isn't canonical, this won't be a canonical type
4479 // either, so fill in the canonical type field.
4481 if (!T.isCanonical()) {
4482 Canonical = getAtomicType(getCanonicalType(T));
4484 // Get the new insert position for the node we care about.
4485 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4486 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4488 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4489 Types.push_back(New);
4490 AtomicTypes.InsertNode(New, InsertPos);
4491 return QualType(New, 0);
4494 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4495 QualType ASTContext::getAutoDeductType() const {
4496 if (AutoDeductTy.isNull())
4497 AutoDeductTy = QualType(
4498 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4499 /*dependent*/false),
4501 return AutoDeductTy;
4504 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4505 QualType ASTContext::getAutoRRefDeductType() const {
4506 if (AutoRRefDeductTy.isNull())
4507 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4508 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4509 return AutoRRefDeductTy;
4512 /// getTagDeclType - Return the unique reference to the type for the
4513 /// specified TagDecl (struct/union/class/enum) decl.
4514 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4516 // FIXME: What is the design on getTagDeclType when it requires casting
4517 // away const? mutable?
4518 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4521 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4522 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4523 /// needs to agree with the definition in <stddef.h>.
4524 CanQualType ASTContext::getSizeType() const {
4525 return getFromTargetType(Target->getSizeType());
4528 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4529 CanQualType ASTContext::getIntMaxType() const {
4530 return getFromTargetType(Target->getIntMaxType());
4533 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4534 CanQualType ASTContext::getUIntMaxType() const {
4535 return getFromTargetType(Target->getUIntMaxType());
4538 /// getSignedWCharType - Return the type of "signed wchar_t".
4539 /// Used when in C++, as a GCC extension.
4540 QualType ASTContext::getSignedWCharType() const {
4541 // FIXME: derive from "Target" ?
4545 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4546 /// Used when in C++, as a GCC extension.
4547 QualType ASTContext::getUnsignedWCharType() const {
4548 // FIXME: derive from "Target" ?
4549 return UnsignedIntTy;
4552 QualType ASTContext::getIntPtrType() const {
4553 return getFromTargetType(Target->getIntPtrType());
4556 QualType ASTContext::getUIntPtrType() const {
4557 return getCorrespondingUnsignedType(getIntPtrType());
4560 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4561 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4562 QualType ASTContext::getPointerDiffType() const {
4563 return getFromTargetType(Target->getPtrDiffType(0));
4566 /// \brief Return the unique type for "pid_t" defined in
4567 /// <sys/types.h>. We need this to compute the correct type for vfork().
4568 QualType ASTContext::getProcessIDType() const {
4569 return getFromTargetType(Target->getProcessIDType());
4572 //===----------------------------------------------------------------------===//
4574 //===----------------------------------------------------------------------===//
4576 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4577 // Push qualifiers into arrays, and then discard any remaining
4579 T = getCanonicalType(T);
4580 T = getVariableArrayDecayedType(T);
4581 const Type *Ty = T.getTypePtr();
4583 if (isa<ArrayType>(Ty)) {
4584 Result = getArrayDecayedType(QualType(Ty,0));
4585 } else if (isa<FunctionType>(Ty)) {
4586 Result = getPointerType(QualType(Ty, 0));
4588 Result = QualType(Ty, 0);
4591 return CanQualType::CreateUnsafe(Result);
4594 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4595 Qualifiers &quals) {
4596 SplitQualType splitType = type.getSplitUnqualifiedType();
4598 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4599 // the unqualified desugared type and then drops it on the floor.
4600 // We then have to strip that sugar back off with
4601 // getUnqualifiedDesugaredType(), which is silly.
4602 const ArrayType *AT =
4603 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4605 // If we don't have an array, just use the results in splitType.
4607 quals = splitType.Quals;
4608 return QualType(splitType.Ty, 0);
4611 // Otherwise, recurse on the array's element type.
4612 QualType elementType = AT->getElementType();
4613 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4615 // If that didn't change the element type, AT has no qualifiers, so we
4616 // can just use the results in splitType.
4617 if (elementType == unqualElementType) {
4618 assert(quals.empty()); // from the recursive call
4619 quals = splitType.Quals;
4620 return QualType(splitType.Ty, 0);
4623 // Otherwise, add in the qualifiers from the outermost type, then
4624 // build the type back up.
4625 quals.addConsistentQualifiers(splitType.Quals);
4627 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4628 return getConstantArrayType(unqualElementType, CAT->getSize(),
4629 CAT->getSizeModifier(), 0);
4632 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4633 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4636 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4637 return getVariableArrayType(unqualElementType,
4639 VAT->getSizeModifier(),
4640 VAT->getIndexTypeCVRQualifiers(),
4641 VAT->getBracketsRange());
4644 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4645 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4646 DSAT->getSizeModifier(), 0,
4650 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4651 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4652 /// they point to and return true. If T1 and T2 aren't pointer types
4653 /// or pointer-to-member types, or if they are not similar at this
4654 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4655 /// qualifiers on T1 and T2 are ignored. This function will typically
4656 /// be called in a loop that successively "unwraps" pointer and
4657 /// pointer-to-member types to compare them at each level.
4658 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4659 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4660 *T2PtrType = T2->getAs<PointerType>();
4661 if (T1PtrType && T2PtrType) {
4662 T1 = T1PtrType->getPointeeType();
4663 T2 = T2PtrType->getPointeeType();
4667 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4668 *T2MPType = T2->getAs<MemberPointerType>();
4669 if (T1MPType && T2MPType &&
4670 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4671 QualType(T2MPType->getClass(), 0))) {
4672 T1 = T1MPType->getPointeeType();
4673 T2 = T2MPType->getPointeeType();
4677 if (getLangOpts().ObjC1) {
4678 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4679 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4680 if (T1OPType && T2OPType) {
4681 T1 = T1OPType->getPointeeType();
4682 T2 = T2OPType->getPointeeType();
4687 // FIXME: Block pointers, too?
4693 ASTContext::getNameForTemplate(TemplateName Name,
4694 SourceLocation NameLoc) const {
4695 switch (Name.getKind()) {
4696 case TemplateName::QualifiedTemplate:
4697 case TemplateName::Template:
4698 // DNInfo work in progress: CHECKME: what about DNLoc?
4699 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4702 case TemplateName::OverloadedTemplate: {
4703 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4704 // DNInfo work in progress: CHECKME: what about DNLoc?
4705 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4708 case TemplateName::DependentTemplate: {
4709 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4710 DeclarationName DName;
4711 if (DTN->isIdentifier()) {
4712 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4713 return DeclarationNameInfo(DName, NameLoc);
4715 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4716 // DNInfo work in progress: FIXME: source locations?
4717 DeclarationNameLoc DNLoc;
4718 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4719 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4720 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4724 case TemplateName::SubstTemplateTemplateParm: {
4725 SubstTemplateTemplateParmStorage *subst
4726 = Name.getAsSubstTemplateTemplateParm();
4727 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4731 case TemplateName::SubstTemplateTemplateParmPack: {
4732 SubstTemplateTemplateParmPackStorage *subst
4733 = Name.getAsSubstTemplateTemplateParmPack();
4734 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4739 llvm_unreachable("bad template name kind!");
4742 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4743 switch (Name.getKind()) {
4744 case TemplateName::QualifiedTemplate:
4745 case TemplateName::Template: {
4746 TemplateDecl *Template = Name.getAsTemplateDecl();
4747 if (TemplateTemplateParmDecl *TTP
4748 = dyn_cast<TemplateTemplateParmDecl>(Template))
4749 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4751 // The canonical template name is the canonical template declaration.
4752 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4755 case TemplateName::OverloadedTemplate:
4756 llvm_unreachable("cannot canonicalize overloaded template");
4758 case TemplateName::DependentTemplate: {
4759 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4760 assert(DTN && "Non-dependent template names must refer to template decls.");
4761 return DTN->CanonicalTemplateName;
4764 case TemplateName::SubstTemplateTemplateParm: {
4765 SubstTemplateTemplateParmStorage *subst
4766 = Name.getAsSubstTemplateTemplateParm();
4767 return getCanonicalTemplateName(subst->getReplacement());
4770 case TemplateName::SubstTemplateTemplateParmPack: {
4771 SubstTemplateTemplateParmPackStorage *subst
4772 = Name.getAsSubstTemplateTemplateParmPack();
4773 TemplateTemplateParmDecl *canonParameter
4774 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4775 TemplateArgument canonArgPack
4776 = getCanonicalTemplateArgument(subst->getArgumentPack());
4777 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4781 llvm_unreachable("bad template name!");
4784 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4785 X = getCanonicalTemplateName(X);
4786 Y = getCanonicalTemplateName(Y);
4787 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4791 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4792 switch (Arg.getKind()) {
4793 case TemplateArgument::Null:
4796 case TemplateArgument::Expression:
4799 case TemplateArgument::Declaration: {
4800 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4801 return TemplateArgument(D, Arg.getParamTypeForDecl());
4804 case TemplateArgument::NullPtr:
4805 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4808 case TemplateArgument::Template:
4809 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4811 case TemplateArgument::TemplateExpansion:
4812 return TemplateArgument(getCanonicalTemplateName(
4813 Arg.getAsTemplateOrTemplatePattern()),
4814 Arg.getNumTemplateExpansions());
4816 case TemplateArgument::Integral:
4817 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4819 case TemplateArgument::Type:
4820 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4822 case TemplateArgument::Pack: {
4823 if (Arg.pack_size() == 0)
4826 TemplateArgument *CanonArgs
4827 = new (*this) TemplateArgument[Arg.pack_size()];
4829 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4830 AEnd = Arg.pack_end();
4831 A != AEnd; (void)++A, ++Idx)
4832 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4834 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4838 // Silence GCC warning
4839 llvm_unreachable("Unhandled template argument kind");
4842 NestedNameSpecifier *
4843 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4847 switch (NNS->getKind()) {
4848 case NestedNameSpecifier::Identifier:
4849 // Canonicalize the prefix but keep the identifier the same.
4850 return NestedNameSpecifier::Create(*this,
4851 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4852 NNS->getAsIdentifier());
4854 case NestedNameSpecifier::Namespace:
4855 // A namespace is canonical; build a nested-name-specifier with
4856 // this namespace and no prefix.
4857 return NestedNameSpecifier::Create(*this, nullptr,
4858 NNS->getAsNamespace()->getOriginalNamespace());
4860 case NestedNameSpecifier::NamespaceAlias:
4861 // A namespace is canonical; build a nested-name-specifier with
4862 // this namespace and no prefix.
4863 return NestedNameSpecifier::Create(*this, nullptr,
4864 NNS->getAsNamespaceAlias()->getNamespace()
4865 ->getOriginalNamespace());
4867 case NestedNameSpecifier::TypeSpec:
4868 case NestedNameSpecifier::TypeSpecWithTemplate: {
4869 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4871 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4872 // break it apart into its prefix and identifier, then reconsititute those
4873 // as the canonical nested-name-specifier. This is required to canonicalize
4874 // a dependent nested-name-specifier involving typedefs of dependent-name
4876 // typedef typename T::type T1;
4877 // typedef typename T1::type T2;
4878 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4879 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4880 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4882 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4883 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4885 return NestedNameSpecifier::Create(*this, nullptr, false,
4886 const_cast<Type *>(T.getTypePtr()));
4889 case NestedNameSpecifier::Global:
4890 case NestedNameSpecifier::Super:
4891 // The global specifier and __super specifer are canonical and unique.
4895 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4898 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4899 // Handle the non-qualified case efficiently.
4900 if (!T.hasLocalQualifiers()) {
4901 // Handle the common positive case fast.
4902 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4906 // Handle the common negative case fast.
4907 if (!isa<ArrayType>(T.getCanonicalType()))
4910 // Apply any qualifiers from the array type to the element type. This
4911 // implements C99 6.7.3p8: "If the specification of an array type includes
4912 // any type qualifiers, the element type is so qualified, not the array type."
4914 // If we get here, we either have type qualifiers on the type, or we have
4915 // sugar such as a typedef in the way. If we have type qualifiers on the type
4916 // we must propagate them down into the element type.
4918 SplitQualType split = T.getSplitDesugaredType();
4919 Qualifiers qs = split.Quals;
4921 // If we have a simple case, just return now.
4922 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4923 if (!ATy || qs.empty())
4926 // Otherwise, we have an array and we have qualifiers on it. Push the
4927 // qualifiers into the array element type and return a new array type.
4928 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4930 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4931 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4932 CAT->getSizeModifier(),
4933 CAT->getIndexTypeCVRQualifiers()));
4934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4935 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4936 IAT->getSizeModifier(),
4937 IAT->getIndexTypeCVRQualifiers()));
4939 if (const DependentSizedArrayType *DSAT
4940 = dyn_cast<DependentSizedArrayType>(ATy))
4941 return cast<ArrayType>(
4942 getDependentSizedArrayType(NewEltTy,
4943 DSAT->getSizeExpr(),
4944 DSAT->getSizeModifier(),
4945 DSAT->getIndexTypeCVRQualifiers(),
4946 DSAT->getBracketsRange()));
4948 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4949 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4951 VAT->getSizeModifier(),
4952 VAT->getIndexTypeCVRQualifiers(),
4953 VAT->getBracketsRange()));
4956 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4957 if (T->isArrayType() || T->isFunctionType())
4958 return getDecayedType(T);
4962 QualType ASTContext::getSignatureParameterType(QualType T) const {
4963 T = getVariableArrayDecayedType(T);
4964 T = getAdjustedParameterType(T);
4965 return T.getUnqualifiedType();
4968 QualType ASTContext::getExceptionObjectType(QualType T) const {
4969 // C++ [except.throw]p3:
4970 // A throw-expression initializes a temporary object, called the exception
4971 // object, the type of which is determined by removing any top-level
4972 // cv-qualifiers from the static type of the operand of throw and adjusting
4973 // the type from "array of T" or "function returning T" to "pointer to T"
4974 // or "pointer to function returning T", [...]
4975 T = getVariableArrayDecayedType(T);
4976 if (T->isArrayType() || T->isFunctionType())
4977 T = getDecayedType(T);
4978 return T.getUnqualifiedType();
4981 /// getArrayDecayedType - Return the properly qualified result of decaying the
4982 /// specified array type to a pointer. This operation is non-trivial when
4983 /// handling typedefs etc. The canonical type of "T" must be an array type,
4984 /// this returns a pointer to a properly qualified element of the array.
4986 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4987 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4988 // Get the element type with 'getAsArrayType' so that we don't lose any
4989 // typedefs in the element type of the array. This also handles propagation
4990 // of type qualifiers from the array type into the element type if present
4992 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4993 assert(PrettyArrayType && "Not an array type!");
4995 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4997 // int x[restrict 4] -> int *restrict
4998 QualType Result = getQualifiedType(PtrTy,
4999 PrettyArrayType->getIndexTypeQualifiers());
5001 // int x[_Nullable] -> int * _Nullable
5002 if (auto Nullability = Ty->getNullability(*this)) {
5003 Result = const_cast<ASTContext *>(this)->getAttributedType(
5004 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5009 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5010 return getBaseElementType(array->getElementType());
5013 QualType ASTContext::getBaseElementType(QualType type) const {
5016 SplitQualType split = type.getSplitDesugaredType();
5017 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5020 type = array->getElementType();
5021 qs.addConsistentQualifiers(split.Quals);
5024 return getQualifiedType(type, qs);
5027 /// getConstantArrayElementCount - Returns number of constant array elements.
5029 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5030 uint64_t ElementCount = 1;
5032 ElementCount *= CA->getSize().getZExtValue();
5033 CA = dyn_cast_or_null<ConstantArrayType>(
5034 CA->getElementType()->getAsArrayTypeUnsafe());
5036 return ElementCount;
5039 /// getFloatingRank - Return a relative rank for floating point types.
5040 /// This routine will assert if passed a built-in type that isn't a float.
5041 static FloatingRank getFloatingRank(QualType T) {
5042 if (const ComplexType *CT = T->getAs<ComplexType>())
5043 return getFloatingRank(CT->getElementType());
5045 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5046 switch (T->getAs<BuiltinType>()->getKind()) {
5047 default: llvm_unreachable("getFloatingRank(): not a floating type");
5048 case BuiltinType::Half: return HalfRank;
5049 case BuiltinType::Float: return FloatRank;
5050 case BuiltinType::Double: return DoubleRank;
5051 case BuiltinType::LongDouble: return LongDoubleRank;
5052 case BuiltinType::Float128: return Float128Rank;
5056 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5057 /// point or a complex type (based on typeDomain/typeSize).
5058 /// 'typeDomain' is a real floating point or complex type.
5059 /// 'typeSize' is a real floating point or complex type.
5060 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5061 QualType Domain) const {
5062 FloatingRank EltRank = getFloatingRank(Size);
5063 if (Domain->isComplexType()) {
5065 case HalfRank: llvm_unreachable("Complex half is not supported");
5066 case FloatRank: return FloatComplexTy;
5067 case DoubleRank: return DoubleComplexTy;
5068 case LongDoubleRank: return LongDoubleComplexTy;
5069 case Float128Rank: return Float128ComplexTy;
5073 assert(Domain->isRealFloatingType() && "Unknown domain!");
5075 case HalfRank: return HalfTy;
5076 case FloatRank: return FloatTy;
5077 case DoubleRank: return DoubleTy;
5078 case LongDoubleRank: return LongDoubleTy;
5079 case Float128Rank: return Float128Ty;
5081 llvm_unreachable("getFloatingRank(): illegal value for rank");
5084 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5085 /// point types, ignoring the domain of the type (i.e. 'double' ==
5086 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5087 /// LHS < RHS, return -1.
5088 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5089 FloatingRank LHSR = getFloatingRank(LHS);
5090 FloatingRank RHSR = getFloatingRank(RHS);
5099 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5100 /// routine will assert if passed a built-in type that isn't an integer or enum,
5101 /// or if it is not canonicalized.
5102 unsigned ASTContext::getIntegerRank(const Type *T) const {
5103 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5105 switch (cast<BuiltinType>(T)->getKind()) {
5106 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5107 case BuiltinType::Bool:
5108 return 1 + (getIntWidth(BoolTy) << 3);
5109 case BuiltinType::Char_S:
5110 case BuiltinType::Char_U:
5111 case BuiltinType::SChar:
5112 case BuiltinType::UChar:
5113 return 2 + (getIntWidth(CharTy) << 3);
5114 case BuiltinType::Short:
5115 case BuiltinType::UShort:
5116 return 3 + (getIntWidth(ShortTy) << 3);
5117 case BuiltinType::Int:
5118 case BuiltinType::UInt:
5119 return 4 + (getIntWidth(IntTy) << 3);
5120 case BuiltinType::Long:
5121 case BuiltinType::ULong:
5122 return 5 + (getIntWidth(LongTy) << 3);
5123 case BuiltinType::LongLong:
5124 case BuiltinType::ULongLong:
5125 return 6 + (getIntWidth(LongLongTy) << 3);
5126 case BuiltinType::Int128:
5127 case BuiltinType::UInt128:
5128 return 7 + (getIntWidth(Int128Ty) << 3);
5132 /// \brief Whether this is a promotable bitfield reference according
5133 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5135 /// \returns the type this bit-field will promote to, or NULL if no
5136 /// promotion occurs.
5137 QualType ASTContext::isPromotableBitField(Expr *E) const {
5138 if (E->isTypeDependent() || E->isValueDependent())
5141 // FIXME: We should not do this unless E->refersToBitField() is true. This
5142 // matters in C where getSourceBitField() will find bit-fields for various
5143 // cases where the source expression is not a bit-field designator.
5145 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5149 QualType FT = Field->getType();
5151 uint64_t BitWidth = Field->getBitWidthValue(*this);
5152 uint64_t IntSize = getTypeSize(IntTy);
5153 // C++ [conv.prom]p5:
5154 // A prvalue for an integral bit-field can be converted to a prvalue of type
5155 // int if int can represent all the values of the bit-field; otherwise, it
5156 // can be converted to unsigned int if unsigned int can represent all the
5157 // values of the bit-field. If the bit-field is larger yet, no integral
5158 // promotion applies to it.
5160 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5161 // If an int can represent all values of the original type (as restricted by
5162 // the width, for a bit-field), the value is converted to an int; otherwise,
5163 // it is converted to an unsigned int.
5165 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5166 // We perform that promotion here to match GCC and C++.
5167 if (BitWidth < IntSize)
5170 if (BitWidth == IntSize)
5171 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5173 // Types bigger than int are not subject to promotions, and therefore act
5174 // like the base type. GCC has some weird bugs in this area that we
5175 // deliberately do not follow (GCC follows a pre-standard resolution to
5176 // C's DR315 which treats bit-width as being part of the type, and this leaks
5177 // into their semantics in some cases).
5181 /// getPromotedIntegerType - Returns the type that Promotable will
5182 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5184 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5185 assert(!Promotable.isNull());
5186 assert(Promotable->isPromotableIntegerType());
5187 if (const EnumType *ET = Promotable->getAs<EnumType>())
5188 return ET->getDecl()->getPromotionType();
5190 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5191 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5192 // (3.9.1) can be converted to a prvalue of the first of the following
5193 // types that can represent all the values of its underlying type:
5194 // int, unsigned int, long int, unsigned long int, long long int, or
5195 // unsigned long long int [...]
5196 // FIXME: Is there some better way to compute this?
5197 if (BT->getKind() == BuiltinType::WChar_S ||
5198 BT->getKind() == BuiltinType::WChar_U ||
5199 BT->getKind() == BuiltinType::Char16 ||
5200 BT->getKind() == BuiltinType::Char32) {
5201 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5202 uint64_t FromSize = getTypeSize(BT);
5203 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5204 LongLongTy, UnsignedLongLongTy };
5205 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5206 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5207 if (FromSize < ToSize ||
5208 (FromSize == ToSize &&
5209 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5210 return PromoteTypes[Idx];
5212 llvm_unreachable("char type should fit into long long");
5216 // At this point, we should have a signed or unsigned integer type.
5217 if (Promotable->isSignedIntegerType())
5219 uint64_t PromotableSize = getIntWidth(Promotable);
5220 uint64_t IntSize = getIntWidth(IntTy);
5221 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5222 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5225 /// \brief Recurses in pointer/array types until it finds an objc retainable
5226 /// type and returns its ownership.
5227 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5228 while (!T.isNull()) {
5229 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5230 return T.getObjCLifetime();
5231 if (T->isArrayType())
5232 T = getBaseElementType(T);
5233 else if (const PointerType *PT = T->getAs<PointerType>())
5234 T = PT->getPointeeType();
5235 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
5236 T = RT->getPointeeType();
5241 return Qualifiers::OCL_None;
5244 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5245 // Incomplete enum types are not treated as integer types.
5246 // FIXME: In C++, enum types are never integer types.
5247 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5248 return ET->getDecl()->getIntegerType().getTypePtr();
5252 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5253 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5254 /// LHS < RHS, return -1.
5255 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5256 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5257 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5259 // Unwrap enums to their underlying type.
5260 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5261 LHSC = getIntegerTypeForEnum(ET);
5262 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5263 RHSC = getIntegerTypeForEnum(ET);
5265 if (LHSC == RHSC) return 0;
5267 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5268 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5270 unsigned LHSRank = getIntegerRank(LHSC);
5271 unsigned RHSRank = getIntegerRank(RHSC);
5273 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5274 if (LHSRank == RHSRank) return 0;
5275 return LHSRank > RHSRank ? 1 : -1;
5278 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5280 // If the unsigned [LHS] type is larger, return it.
5281 if (LHSRank >= RHSRank)
5284 // If the signed type can represent all values of the unsigned type, it
5285 // wins. Because we are dealing with 2's complement and types that are
5286 // powers of two larger than each other, this is always safe.
5290 // If the unsigned [RHS] type is larger, return it.
5291 if (RHSRank >= LHSRank)
5294 // If the signed type can represent all values of the unsigned type, it
5295 // wins. Because we are dealing with 2's complement and types that are
5296 // powers of two larger than each other, this is always safe.
5300 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5301 if (!CFConstantStringTypeDecl) {
5302 assert(!CFConstantStringTagDecl &&
5303 "tag and typedef should be initialized together");
5304 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5305 CFConstantStringTagDecl->startDefinition();
5307 QualType FieldTypes[4];
5308 const char *FieldNames[4];
5311 FieldTypes[0] = getPointerType(IntTy.withConst());
5312 FieldNames[0] = "isa";
5314 FieldTypes[1] = IntTy;
5315 FieldNames[1] = "flags";
5317 FieldTypes[2] = getPointerType(CharTy.withConst());
5318 FieldNames[2] = "str";
5320 FieldTypes[3] = LongTy;
5321 FieldNames[3] = "length";
5324 for (unsigned i = 0; i < 4; ++i) {
5325 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5328 &Idents.get(FieldNames[i]),
5329 FieldTypes[i], /*TInfo=*/nullptr,
5330 /*BitWidth=*/nullptr,
5333 Field->setAccess(AS_public);
5334 CFConstantStringTagDecl->addDecl(Field);
5337 CFConstantStringTagDecl->completeDefinition();
5338 // This type is designed to be compatible with NSConstantString, but cannot
5339 // use the same name, since NSConstantString is an interface.
5340 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5341 CFConstantStringTypeDecl =
5342 buildImplicitTypedef(tagType, "__NSConstantString");
5345 return CFConstantStringTypeDecl;
5348 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5349 if (!CFConstantStringTagDecl)
5350 getCFConstantStringDecl(); // Build the tag and the typedef.
5351 return CFConstantStringTagDecl;
5354 // getCFConstantStringType - Return the type used for constant CFStrings.
5355 QualType ASTContext::getCFConstantStringType() const {
5356 return getTypedefType(getCFConstantStringDecl());
5359 QualType ASTContext::getObjCSuperType() const {
5360 if (ObjCSuperType.isNull()) {
5361 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5362 TUDecl->addDecl(ObjCSuperTypeDecl);
5363 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5365 return ObjCSuperType;
5368 void ASTContext::setCFConstantStringType(QualType T) {
5369 const TypedefType *TD = T->getAs<TypedefType>();
5370 assert(TD && "Invalid CFConstantStringType");
5371 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5373 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5374 assert(TagType && "Invalid CFConstantStringType");
5375 CFConstantStringTagDecl = TagType->getDecl();
5378 QualType ASTContext::getBlockDescriptorType() const {
5379 if (BlockDescriptorType)
5380 return getTagDeclType(BlockDescriptorType);
5383 // FIXME: Needs the FlagAppleBlock bit.
5384 RD = buildImplicitRecord("__block_descriptor");
5385 RD->startDefinition();
5387 QualType FieldTypes[] = {
5392 static const char *const FieldNames[] = {
5397 for (size_t i = 0; i < 2; ++i) {
5398 FieldDecl *Field = FieldDecl::Create(
5399 *this, RD, SourceLocation(), SourceLocation(),
5400 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5401 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5402 Field->setAccess(AS_public);
5406 RD->completeDefinition();
5408 BlockDescriptorType = RD;
5410 return getTagDeclType(BlockDescriptorType);
5413 QualType ASTContext::getBlockDescriptorExtendedType() const {
5414 if (BlockDescriptorExtendedType)
5415 return getTagDeclType(BlockDescriptorExtendedType);
5418 // FIXME: Needs the FlagAppleBlock bit.
5419 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5420 RD->startDefinition();
5422 QualType FieldTypes[] = {
5425 getPointerType(VoidPtrTy),
5426 getPointerType(VoidPtrTy)
5429 static const char *const FieldNames[] = {
5436 for (size_t i = 0; i < 4; ++i) {
5437 FieldDecl *Field = FieldDecl::Create(
5438 *this, RD, SourceLocation(), SourceLocation(),
5439 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5440 /*BitWidth=*/nullptr,
5441 /*Mutable=*/false, ICIS_NoInit);
5442 Field->setAccess(AS_public);
5446 RD->completeDefinition();
5448 BlockDescriptorExtendedType = RD;
5449 return getTagDeclType(BlockDescriptorExtendedType);
5452 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5453 /// requires copy/dispose. Note that this must match the logic
5454 /// in buildByrefHelpers.
5455 bool ASTContext::BlockRequiresCopying(QualType Ty,
5457 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5458 const Expr *copyExpr = getBlockVarCopyInits(D);
5459 if (!copyExpr && record->hasTrivialDestructor()) return false;
5464 if (!Ty->isObjCRetainableType()) return false;
5466 Qualifiers qs = Ty.getQualifiers();
5468 // If we have lifetime, that dominates.
5469 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5471 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5473 // These are just bits as far as the runtime is concerned.
5474 case Qualifiers::OCL_ExplicitNone:
5475 case Qualifiers::OCL_Autoreleasing:
5478 // Tell the runtime that this is ARC __weak, called by the
5480 case Qualifiers::OCL_Weak:
5481 // ARC __strong __block variables need to be retained.
5482 case Qualifiers::OCL_Strong:
5485 llvm_unreachable("fell out of lifetime switch!");
5487 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5488 Ty->isObjCObjectPointerType());
5491 bool ASTContext::getByrefLifetime(QualType Ty,
5492 Qualifiers::ObjCLifetime &LifeTime,
5493 bool &HasByrefExtendedLayout) const {
5495 if (!getLangOpts().ObjC1 ||
5496 getLangOpts().getGC() != LangOptions::NonGC)
5499 HasByrefExtendedLayout = false;
5500 if (Ty->isRecordType()) {
5501 HasByrefExtendedLayout = true;
5502 LifeTime = Qualifiers::OCL_None;
5503 } else if ((LifeTime = Ty.getObjCLifetime())) {
5504 // Honor the ARC qualifiers.
5505 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5507 LifeTime = Qualifiers::OCL_ExplicitNone;
5509 LifeTime = Qualifiers::OCL_None;
5514 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5515 if (!ObjCInstanceTypeDecl)
5516 ObjCInstanceTypeDecl =
5517 buildImplicitTypedef(getObjCIdType(), "instancetype");
5518 return ObjCInstanceTypeDecl;
5521 // This returns true if a type has been typedefed to BOOL:
5522 // typedef <type> BOOL;
5523 static bool isTypeTypedefedAsBOOL(QualType T) {
5524 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5525 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5526 return II->isStr("BOOL");
5531 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5533 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5534 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5535 return CharUnits::Zero();
5537 CharUnits sz = getTypeSizeInChars(type);
5539 // Make all integer and enum types at least as large as an int
5540 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5541 sz = std::max(sz, getTypeSizeInChars(IntTy));
5542 // Treat arrays as pointers, since that's how they're passed in.
5543 else if (type->isArrayType())
5544 sz = getTypeSizeInChars(VoidPtrTy);
5548 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5549 return getTargetInfo().getCXXABI().isMicrosoft() &&
5550 VD->isStaticDataMember() &&
5551 VD->getType()->isIntegralOrEnumerationType() &&
5552 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5555 ASTContext::InlineVariableDefinitionKind
5556 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5557 if (!VD->isInline())
5558 return InlineVariableDefinitionKind::None;
5560 // In almost all cases, it's a weak definition.
5561 auto *First = VD->getFirstDecl();
5562 if (!First->isConstexpr() || First->isInlineSpecified() ||
5563 !VD->isStaticDataMember())
5564 return InlineVariableDefinitionKind::Weak;
5566 // If there's a file-context declaration in this translation unit, it's a
5567 // non-discardable definition.
5568 for (auto *D : VD->redecls())
5569 if (D->getLexicalDeclContext()->isFileContext())
5570 return InlineVariableDefinitionKind::Strong;
5572 // If we've not seen one yet, we don't know.
5573 return InlineVariableDefinitionKind::WeakUnknown;
5577 std::string charUnitsToString(const CharUnits &CU) {
5578 return llvm::itostr(CU.getQuantity());
5581 /// getObjCEncodingForBlock - Return the encoded type for this block
5583 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5586 const BlockDecl *Decl = Expr->getBlockDecl();
5588 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5589 // Encode result type.
5590 if (getLangOpts().EncodeExtendedBlockSig)
5591 getObjCEncodingForMethodParameter(
5592 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5595 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5596 // Compute size of all parameters.
5597 // Start with computing size of a pointer in number of bytes.
5598 // FIXME: There might(should) be a better way of doing this computation!
5600 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5601 CharUnits ParmOffset = PtrSize;
5602 for (auto PI : Decl->parameters()) {
5603 QualType PType = PI->getType();
5604 CharUnits sz = getObjCEncodingTypeSize(PType);
5607 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5610 // Size of the argument frame
5611 S += charUnitsToString(ParmOffset);
5612 // Block pointer and offset.
5616 ParmOffset = PtrSize;
5617 for (auto PVDecl : Decl->parameters()) {
5618 QualType PType = PVDecl->getOriginalType();
5619 if (const ArrayType *AT =
5620 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5621 // Use array's original type only if it has known number of
5623 if (!isa<ConstantArrayType>(AT))
5624 PType = PVDecl->getType();
5625 } else if (PType->isFunctionType())
5626 PType = PVDecl->getType();
5627 if (getLangOpts().EncodeExtendedBlockSig)
5628 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5629 S, true /*Extended*/);
5631 getObjCEncodingForType(PType, S);
5632 S += charUnitsToString(ParmOffset);
5633 ParmOffset += getObjCEncodingTypeSize(PType);
5640 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5642 // Encode result type.
5643 getObjCEncodingForType(Decl->getReturnType(), S);
5644 CharUnits ParmOffset;
5645 // Compute size of all parameters.
5646 for (auto PI : Decl->parameters()) {
5647 QualType PType = PI->getType();
5648 CharUnits sz = getObjCEncodingTypeSize(PType);
5652 assert(sz.isPositive() &&
5653 "getObjCEncodingForFunctionDecl - Incomplete param type");
5656 S += charUnitsToString(ParmOffset);
5657 ParmOffset = CharUnits::Zero();
5660 for (auto PVDecl : Decl->parameters()) {
5661 QualType PType = PVDecl->getOriginalType();
5662 if (const ArrayType *AT =
5663 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5664 // Use array's original type only if it has known number of
5666 if (!isa<ConstantArrayType>(AT))
5667 PType = PVDecl->getType();
5668 } else if (PType->isFunctionType())
5669 PType = PVDecl->getType();
5670 getObjCEncodingForType(PType, S);
5671 S += charUnitsToString(ParmOffset);
5672 ParmOffset += getObjCEncodingTypeSize(PType);
5678 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5679 /// method parameter or return type. If Extended, include class names and
5680 /// block object types.
5681 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5682 QualType T, std::string& S,
5683 bool Extended) const {
5684 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5685 getObjCEncodingForTypeQualifier(QT, S);
5686 // Encode parameter type.
5687 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5688 true /*OutermostType*/,
5689 false /*EncodingProperty*/,
5690 false /*StructField*/,
5691 Extended /*EncodeBlockParameters*/,
5692 Extended /*EncodeClassNames*/);
5695 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5697 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5698 bool Extended) const {
5699 // FIXME: This is not very efficient.
5700 // Encode return type.
5702 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5703 Decl->getReturnType(), S, Extended);
5704 // Compute size of all parameters.
5705 // Start with computing size of a pointer in number of bytes.
5706 // FIXME: There might(should) be a better way of doing this computation!
5708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5709 // The first two arguments (self and _cmd) are pointers; account for
5711 CharUnits ParmOffset = 2 * PtrSize;
5712 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5713 E = Decl->sel_param_end(); PI != E; ++PI) {
5714 QualType PType = (*PI)->getType();
5715 CharUnits sz = getObjCEncodingTypeSize(PType);
5719 assert (sz.isPositive() &&
5720 "getObjCEncodingForMethodDecl - Incomplete param type");
5723 S += charUnitsToString(ParmOffset);
5725 S += charUnitsToString(PtrSize);
5728 ParmOffset = 2 * PtrSize;
5729 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5730 E = Decl->sel_param_end(); PI != E; ++PI) {
5731 const ParmVarDecl *PVDecl = *PI;
5732 QualType PType = PVDecl->getOriginalType();
5733 if (const ArrayType *AT =
5734 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5735 // Use array's original type only if it has known number of
5737 if (!isa<ConstantArrayType>(AT))
5738 PType = PVDecl->getType();
5739 } else if (PType->isFunctionType())
5740 PType = PVDecl->getType();
5741 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5742 PType, S, Extended);
5743 S += charUnitsToString(ParmOffset);
5744 ParmOffset += getObjCEncodingTypeSize(PType);
5750 ObjCPropertyImplDecl *
5751 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5752 const ObjCPropertyDecl *PD,
5753 const Decl *Container) const {
5756 if (const ObjCCategoryImplDecl *CID =
5757 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5758 for (auto *PID : CID->property_impls())
5759 if (PID->getPropertyDecl() == PD)
5762 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5763 for (auto *PID : OID->property_impls())
5764 if (PID->getPropertyDecl() == PD)
5770 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5771 /// property declaration. If non-NULL, Container must be either an
5772 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5773 /// NULL when getting encodings for protocol properties.
5774 /// Property attributes are stored as a comma-delimited C string. The simple
5775 /// attributes readonly and bycopy are encoded as single characters. The
5776 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5777 /// encoded as single characters, followed by an identifier. Property types
5778 /// are also encoded as a parametrized attribute. The characters used to encode
5779 /// these attributes are defined by the following enumeration:
5781 /// enum PropertyAttributes {
5782 /// kPropertyReadOnly = 'R', // property is read-only.
5783 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5784 /// kPropertyByref = '&', // property is a reference to the value last assigned
5785 /// kPropertyDynamic = 'D', // property is dynamic
5786 /// kPropertyGetter = 'G', // followed by getter selector name
5787 /// kPropertySetter = 'S', // followed by setter selector name
5788 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5789 /// kPropertyType = 'T' // followed by old-style type encoding.
5790 /// kPropertyWeak = 'W' // 'weak' property
5791 /// kPropertyStrong = 'P' // property GC'able
5792 /// kPropertyNonAtomic = 'N' // property non-atomic
5796 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5797 const Decl *Container) const {
5798 // Collect information from the property implementation decl(s).
5799 bool Dynamic = false;
5800 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5802 if (ObjCPropertyImplDecl *PropertyImpDecl =
5803 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5804 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5807 SynthesizePID = PropertyImpDecl;
5810 // FIXME: This is not very efficient.
5811 std::string S = "T";
5813 // Encode result type.
5814 // GCC has some special rules regarding encoding of properties which
5815 // closely resembles encoding of ivars.
5816 getObjCEncodingForPropertyType(PD->getType(), S);
5818 if (PD->isReadOnly()) {
5820 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5827 switch (PD->getSetterKind()) {
5828 case ObjCPropertyDecl::Assign: break;
5829 case ObjCPropertyDecl::Copy: S += ",C"; break;
5830 case ObjCPropertyDecl::Retain: S += ",&"; break;
5831 case ObjCPropertyDecl::Weak: S += ",W"; break;
5835 // It really isn't clear at all what this means, since properties
5836 // are "dynamic by default".
5840 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5843 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5845 S += PD->getGetterName().getAsString();
5848 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5850 S += PD->getSetterName().getAsString();
5853 if (SynthesizePID) {
5854 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5856 S += OID->getNameAsString();
5859 // FIXME: OBJCGC: weak & strong
5863 /// getLegacyIntegralTypeEncoding -
5864 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5865 /// 'l' or 'L' , but not always. For typedefs, we need to use
5866 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5868 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5869 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5870 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5871 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5872 PointeeTy = UnsignedIntTy;
5874 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5880 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5881 const FieldDecl *Field,
5882 QualType *NotEncodedT) const {
5883 // We follow the behavior of gcc, expanding structures which are
5884 // directly pointed to, and expanding embedded structures. Note that
5885 // these rules are sufficient to prevent recursive encoding of the
5887 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5888 true /* outermost type */, false, false,
5889 false, false, false, NotEncodedT);
5892 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5893 std::string& S) const {
5894 // Encode result type.
5895 // GCC has some special rules regarding encoding of properties which
5896 // closely resembles encoding of ivars.
5897 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5898 true /* outermost type */,
5899 true /* encoding property */);
5902 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5903 BuiltinType::Kind kind) {
5905 case BuiltinType::Void: return 'v';
5906 case BuiltinType::Bool: return 'B';
5907 case BuiltinType::Char_U:
5908 case BuiltinType::UChar: return 'C';
5909 case BuiltinType::Char16:
5910 case BuiltinType::UShort: return 'S';
5911 case BuiltinType::Char32:
5912 case BuiltinType::UInt: return 'I';
5913 case BuiltinType::ULong:
5914 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5915 case BuiltinType::UInt128: return 'T';
5916 case BuiltinType::ULongLong: return 'Q';
5917 case BuiltinType::Char_S:
5918 case BuiltinType::SChar: return 'c';
5919 case BuiltinType::Short: return 's';
5920 case BuiltinType::WChar_S:
5921 case BuiltinType::WChar_U:
5922 case BuiltinType::Int: return 'i';
5923 case BuiltinType::Long:
5924 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5925 case BuiltinType::LongLong: return 'q';
5926 case BuiltinType::Int128: return 't';
5927 case BuiltinType::Float: return 'f';
5928 case BuiltinType::Double: return 'd';
5929 case BuiltinType::LongDouble: return 'D';
5930 case BuiltinType::NullPtr: return '*'; // like char*
5932 case BuiltinType::Float128:
5933 case BuiltinType::Half:
5934 // FIXME: potentially need @encodes for these!
5937 case BuiltinType::ObjCId:
5938 case BuiltinType::ObjCClass:
5939 case BuiltinType::ObjCSel:
5940 llvm_unreachable("@encoding ObjC primitive type");
5942 // OpenCL and placeholder types don't need @encodings.
5943 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5944 case BuiltinType::Id:
5945 #include "clang/Basic/OpenCLImageTypes.def"
5946 case BuiltinType::OCLEvent:
5947 case BuiltinType::OCLClkEvent:
5948 case BuiltinType::OCLQueue:
5949 case BuiltinType::OCLReserveID:
5950 case BuiltinType::OCLSampler:
5951 case BuiltinType::Dependent:
5952 #define BUILTIN_TYPE(KIND, ID)
5953 #define PLACEHOLDER_TYPE(KIND, ID) \
5954 case BuiltinType::KIND:
5955 #include "clang/AST/BuiltinTypes.def"
5956 llvm_unreachable("invalid builtin type for @encode");
5958 llvm_unreachable("invalid BuiltinType::Kind value");
5961 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5962 EnumDecl *Enum = ET->getDecl();
5964 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5965 if (!Enum->isFixed())
5968 // The encoding of a fixed enum type matches its fixed underlying type.
5969 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5970 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5973 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5974 QualType T, const FieldDecl *FD) {
5975 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5977 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5978 // The GNU runtime requires more information; bitfields are encoded as b,
5979 // then the offset (in bits) of the first element, then the type of the
5980 // bitfield, then the size in bits. For example, in this structure:
5987 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5988 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5989 // information is not especially sensible, but we're stuck with it for
5990 // compatibility with GCC, although providing it breaks anything that
5991 // actually uses runtime introspection and wants to work on both runtimes...
5992 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5995 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
5996 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
5999 const RecordDecl *RD = FD->getParent();
6000 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6001 Offset = RL.getFieldOffset(FD->getFieldIndex());
6004 S += llvm::utostr(Offset);
6006 if (const EnumType *ET = T->getAs<EnumType>())
6007 S += ObjCEncodingForEnumType(Ctx, ET);
6009 const BuiltinType *BT = T->castAs<BuiltinType>();
6010 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6013 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6016 // FIXME: Use SmallString for accumulating string.
6017 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6018 bool ExpandPointedToStructures,
6019 bool ExpandStructures,
6020 const FieldDecl *FD,
6022 bool EncodingProperty,
6024 bool EncodeBlockParameters,
6025 bool EncodeClassNames,
6026 bool EncodePointerToObjCTypedef,
6027 QualType *NotEncodedT) const {
6028 CanQualType CT = getCanonicalType(T);
6029 switch (CT->getTypeClass()) {
6032 if (FD && FD->isBitField())
6033 return EncodeBitField(this, S, T, FD);
6034 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6035 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6037 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6040 case Type::Complex: {
6041 const ComplexType *CT = T->castAs<ComplexType>();
6043 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6047 case Type::Atomic: {
6048 const AtomicType *AT = T->castAs<AtomicType>();
6050 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6054 // encoding for pointer or reference types.
6056 case Type::LValueReference:
6057 case Type::RValueReference: {
6059 if (isa<PointerType>(CT)) {
6060 const PointerType *PT = T->castAs<PointerType>();
6061 if (PT->isObjCSelType()) {
6065 PointeeTy = PT->getPointeeType();
6067 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6070 bool isReadOnly = false;
6071 // For historical/compatibility reasons, the read-only qualifier of the
6072 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6073 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6074 // Also, do not emit the 'r' for anything but the outermost type!
6075 if (isa<TypedefType>(T.getTypePtr())) {
6076 if (OutermostType && T.isConstQualified()) {
6080 } else if (OutermostType) {
6081 QualType P = PointeeTy;
6082 while (P->getAs<PointerType>())
6083 P = P->getAs<PointerType>()->getPointeeType();
6084 if (P.isConstQualified()) {
6090 // Another legacy compatibility encoding. Some ObjC qualifier and type
6091 // combinations need to be rearranged.
6092 // Rewrite "in const" from "nr" to "rn"
6093 if (StringRef(S).endswith("nr"))
6094 S.replace(S.end()-2, S.end(), "rn");
6097 if (PointeeTy->isCharType()) {
6098 // char pointer types should be encoded as '*' unless it is a
6099 // type that has been typedef'd to 'BOOL'.
6100 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6104 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
6105 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6106 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6110 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6111 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6118 getLegacyIntegralTypeEncoding(PointeeTy);
6120 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6121 nullptr, false, false, false, false, false, false,
6126 case Type::ConstantArray:
6127 case Type::IncompleteArray:
6128 case Type::VariableArray: {
6129 const ArrayType *AT = cast<ArrayType>(CT);
6131 if (isa<IncompleteArrayType>(AT) && !StructField) {
6132 // Incomplete arrays are encoded as a pointer to the array element.
6135 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6136 false, ExpandStructures, FD);
6140 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6141 S += llvm::utostr(CAT->getSize().getZExtValue());
6143 //Variable length arrays are encoded as a regular array with 0 elements.
6144 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6145 "Unknown array type!");
6149 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6150 false, ExpandStructures, FD,
6151 false, false, false, false, false, false,
6158 case Type::FunctionNoProto:
6159 case Type::FunctionProto:
6163 case Type::Record: {
6164 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6165 S += RDecl->isUnion() ? '(' : '{';
6166 // Anonymous structures print as '?'
6167 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6169 if (ClassTemplateSpecializationDecl *Spec
6170 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6171 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6172 llvm::raw_string_ostream OS(S);
6173 TemplateSpecializationType::PrintTemplateArgumentList(OS,
6174 TemplateArgs.asArray(),
6175 (*this).getPrintingPolicy());
6180 if (ExpandStructures) {
6182 if (!RDecl->isUnion()) {
6183 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6185 for (const auto *Field : RDecl->fields()) {
6188 S += Field->getNameAsString();
6192 // Special case bit-fields.
6193 if (Field->isBitField()) {
6194 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6197 QualType qt = Field->getType();
6198 getLegacyIntegralTypeEncoding(qt);
6199 getObjCEncodingForTypeImpl(qt, S, false, true,
6200 FD, /*OutermostType*/false,
6201 /*EncodingProperty*/false,
6202 /*StructField*/true,
6203 false, false, false, NotEncodedT);
6208 S += RDecl->isUnion() ? ')' : '}';
6212 case Type::BlockPointer: {
6213 const BlockPointerType *BT = T->castAs<BlockPointerType>();
6214 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6215 if (EncodeBlockParameters) {
6216 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
6219 // Block return type
6220 getObjCEncodingForTypeImpl(
6221 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6222 FD, false /* OutermostType */, EncodingProperty,
6223 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6228 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
6229 for (const auto &I : FPT->param_types())
6230 getObjCEncodingForTypeImpl(
6231 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6232 false /* OutermostType */, EncodingProperty,
6233 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6234 false, NotEncodedT);
6241 case Type::ObjCObject: {
6242 // hack to match legacy encoding of *id and *Class
6243 QualType Ty = getObjCObjectPointerType(CT);
6244 if (Ty->isObjCIdType()) {
6245 S += "{objc_object=}";
6248 else if (Ty->isObjCClassType()) {
6249 S += "{objc_class=}";
6252 // TODO: Double check to make sure this intentially falls through.
6256 case Type::ObjCInterface: {
6257 // Ignore protocol qualifiers when mangling at this level.
6258 // @encode(class_name)
6259 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6261 S += OI->getObjCRuntimeNameAsString();
6262 if (ExpandStructures) {
6264 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6265 DeepCollectObjCIvars(OI, true, Ivars);
6266 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6267 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6268 if (Field->isBitField())
6269 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6271 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6272 false, false, false, false, false,
6273 EncodePointerToObjCTypedef,
6281 case Type::ObjCObjectPointer: {
6282 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
6283 if (OPT->isObjCIdType()) {
6288 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6289 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6290 // Since this is a binary compatibility issue, need to consult with runtime
6291 // folks. Fortunately, this is a *very* obsure construct.
6296 if (OPT->isObjCQualifiedIdType()) {
6297 getObjCEncodingForTypeImpl(getObjCIdType(), S,
6298 ExpandPointedToStructures,
6299 ExpandStructures, FD);
6300 if (FD || EncodingProperty || EncodeClassNames) {
6301 // Note that we do extended encoding of protocol qualifer list
6302 // Only when doing ivar or property encoding.
6304 for (const auto *I : OPT->quals()) {
6306 S += I->getObjCRuntimeNameAsString();
6314 QualType PointeeTy = OPT->getPointeeType();
6315 if (!EncodingProperty &&
6316 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6317 !EncodePointerToObjCTypedef) {
6318 // Another historical/compatibility reason.
6319 // We encode the underlying type which comes out as
6322 if (FD && OPT->getInterfaceDecl()) {
6323 // Prevent recursive encoding of fields in some rare cases.
6324 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6325 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6326 DeepCollectObjCIvars(OI, true, Ivars);
6327 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6328 if (cast<FieldDecl>(Ivars[i]) == FD) {
6330 S += OI->getObjCRuntimeNameAsString();
6336 getObjCEncodingForTypeImpl(PointeeTy, S,
6337 false, ExpandPointedToStructures,
6339 false, false, false, false, false,
6340 /*EncodePointerToObjCTypedef*/true);
6345 if (OPT->getInterfaceDecl() &&
6346 (FD || EncodingProperty || EncodeClassNames)) {
6348 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6349 for (const auto *I : OPT->quals()) {
6351 S += I->getObjCRuntimeNameAsString();
6359 // gcc just blithely ignores member pointers.
6360 // FIXME: we shoul do better than that. 'M' is available.
6361 case Type::MemberPointer:
6362 // This matches gcc's encoding, even though technically it is insufficient.
6363 //FIXME. We should do a better job than gcc.
6365 case Type::ExtVector:
6366 // Until we have a coherent encoding of these three types, issue warning.
6372 // We could see an undeduced auto type here during error recovery.
6375 case Type::DeducedTemplateSpecialization:
6379 #define ABSTRACT_TYPE(KIND, BASE)
6380 #define TYPE(KIND, BASE)
6381 #define DEPENDENT_TYPE(KIND, BASE) \
6383 #define NON_CANONICAL_TYPE(KIND, BASE) \
6385 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6387 #include "clang/AST/TypeNodes.def"
6388 llvm_unreachable("@encode for dependent type!");
6390 llvm_unreachable("bad type kind!");
6393 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6395 const FieldDecl *FD,
6397 QualType *NotEncodedT) const {
6398 assert(RDecl && "Expected non-null RecordDecl");
6399 assert(!RDecl->isUnion() && "Should not be called for unions");
6400 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6403 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6404 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6405 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6408 for (const auto &BI : CXXRec->bases()) {
6409 if (!BI.isVirtual()) {
6410 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6411 if (base->isEmpty())
6413 uint64_t offs = toBits(layout.getBaseClassOffset(base));
6414 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6415 std::make_pair(offs, base));
6421 for (auto *Field : RDecl->fields()) {
6422 uint64_t offs = layout.getFieldOffset(i);
6423 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6424 std::make_pair(offs, Field));
6428 if (CXXRec && includeVBases) {
6429 for (const auto &BI : CXXRec->vbases()) {
6430 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6431 if (base->isEmpty())
6433 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6434 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6435 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6436 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6437 std::make_pair(offs, base));
6443 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6445 size = layout.getSize();
6449 uint64_t CurOffs = 0;
6451 std::multimap<uint64_t, NamedDecl *>::iterator
6452 CurLayObj = FieldOrBaseOffsets.begin();
6454 if (CXXRec && CXXRec->isDynamicClass() &&
6455 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6458 std::string recname = CXXRec->getNameAsString();
6459 if (recname.empty()) recname = "?";
6465 CurOffs += getTypeSize(VoidPtrTy);
6469 if (!RDecl->hasFlexibleArrayMember()) {
6470 // Mark the end of the structure.
6471 uint64_t offs = toBits(size);
6472 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6473 std::make_pair(offs, nullptr));
6476 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6478 assert(CurOffs <= CurLayObj->first);
6479 if (CurOffs < CurLayObj->first) {
6480 uint64_t padding = CurLayObj->first - CurOffs;
6481 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6482 // packing/alignment of members is different that normal, in which case
6483 // the encoding will be out-of-sync with the real layout.
6484 // If the runtime switches to just consider the size of types without
6485 // taking into account alignment, we could make padding explicit in the
6486 // encoding (e.g. using arrays of chars). The encoding strings would be
6487 // longer then though.
6492 NamedDecl *dcl = CurLayObj->second;
6494 break; // reached end of structure.
6496 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6497 // We expand the bases without their virtual bases since those are going
6498 // in the initial structure. Note that this differs from gcc which
6499 // expands virtual bases each time one is encountered in the hierarchy,
6500 // making the encoding type bigger than it really is.
6501 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6503 assert(!base->isEmpty());
6505 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6508 FieldDecl *field = cast<FieldDecl>(dcl);
6511 S += field->getNameAsString();
6515 if (field->isBitField()) {
6516 EncodeBitField(this, S, field->getType(), field);
6518 CurOffs += field->getBitWidthValue(*this);
6521 QualType qt = field->getType();
6522 getLegacyIntegralTypeEncoding(qt);
6523 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6524 /*OutermostType*/false,
6525 /*EncodingProperty*/false,
6526 /*StructField*/true,
6527 false, false, false, NotEncodedT);
6529 CurOffs += getTypeSize(field->getType());
6536 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6537 std::string& S) const {
6538 if (QT & Decl::OBJC_TQ_In)
6540 if (QT & Decl::OBJC_TQ_Inout)
6542 if (QT & Decl::OBJC_TQ_Out)
6544 if (QT & Decl::OBJC_TQ_Bycopy)
6546 if (QT & Decl::OBJC_TQ_Byref)
6548 if (QT & Decl::OBJC_TQ_Oneway)
6552 TypedefDecl *ASTContext::getObjCIdDecl() const {
6554 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6555 T = getObjCObjectPointerType(T);
6556 ObjCIdDecl = buildImplicitTypedef(T, "id");
6561 TypedefDecl *ASTContext::getObjCSelDecl() const {
6563 QualType T = getPointerType(ObjCBuiltinSelTy);
6564 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6569 TypedefDecl *ASTContext::getObjCClassDecl() const {
6570 if (!ObjCClassDecl) {
6571 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6572 T = getObjCObjectPointerType(T);
6573 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6575 return ObjCClassDecl;
6578 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6579 if (!ObjCProtocolClassDecl) {
6580 ObjCProtocolClassDecl
6581 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6583 &Idents.get("Protocol"),
6584 /*typeParamList=*/nullptr,
6585 /*PrevDecl=*/nullptr,
6586 SourceLocation(), true);
6589 return ObjCProtocolClassDecl;
6592 //===----------------------------------------------------------------------===//
6593 // __builtin_va_list Construction Functions
6594 //===----------------------------------------------------------------------===//
6596 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6598 // typedef char* __builtin[_ms]_va_list;
6599 QualType T = Context->getPointerType(Context->CharTy);
6600 return Context->buildImplicitTypedef(T, Name);
6603 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6604 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6607 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6608 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6611 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6612 // typedef void* __builtin_va_list;
6613 QualType T = Context->getPointerType(Context->VoidTy);
6614 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6617 static TypedefDecl *
6618 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6620 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6621 if (Context->getLangOpts().CPlusPlus) {
6622 // namespace std { struct __va_list {
6624 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6625 Context->getTranslationUnitDecl(),
6626 /*Inline*/ false, SourceLocation(),
6627 SourceLocation(), &Context->Idents.get("std"),
6628 /*PrevDecl*/ nullptr);
6630 VaListTagDecl->setDeclContext(NS);
6633 VaListTagDecl->startDefinition();
6635 const size_t NumFields = 5;
6636 QualType FieldTypes[NumFields];
6637 const char *FieldNames[NumFields];
6640 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6641 FieldNames[0] = "__stack";
6644 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6645 FieldNames[1] = "__gr_top";
6648 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6649 FieldNames[2] = "__vr_top";
6652 FieldTypes[3] = Context->IntTy;
6653 FieldNames[3] = "__gr_offs";
6656 FieldTypes[4] = Context->IntTy;
6657 FieldNames[4] = "__vr_offs";
6660 for (unsigned i = 0; i < NumFields; ++i) {
6661 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6665 &Context->Idents.get(FieldNames[i]),
6666 FieldTypes[i], /*TInfo=*/nullptr,
6667 /*BitWidth=*/nullptr,
6670 Field->setAccess(AS_public);
6671 VaListTagDecl->addDecl(Field);
6673 VaListTagDecl->completeDefinition();
6674 Context->VaListTagDecl = VaListTagDecl;
6675 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6677 // } __builtin_va_list;
6678 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6681 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6682 // typedef struct __va_list_tag {
6683 RecordDecl *VaListTagDecl;
6685 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6686 VaListTagDecl->startDefinition();
6688 const size_t NumFields = 5;
6689 QualType FieldTypes[NumFields];
6690 const char *FieldNames[NumFields];
6692 // unsigned char gpr;
6693 FieldTypes[0] = Context->UnsignedCharTy;
6694 FieldNames[0] = "gpr";
6696 // unsigned char fpr;
6697 FieldTypes[1] = Context->UnsignedCharTy;
6698 FieldNames[1] = "fpr";
6700 // unsigned short reserved;
6701 FieldTypes[2] = Context->UnsignedShortTy;
6702 FieldNames[2] = "reserved";
6704 // void* overflow_arg_area;
6705 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6706 FieldNames[3] = "overflow_arg_area";
6708 // void* reg_save_area;
6709 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6710 FieldNames[4] = "reg_save_area";
6713 for (unsigned i = 0; i < NumFields; ++i) {
6714 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6717 &Context->Idents.get(FieldNames[i]),
6718 FieldTypes[i], /*TInfo=*/nullptr,
6719 /*BitWidth=*/nullptr,
6722 Field->setAccess(AS_public);
6723 VaListTagDecl->addDecl(Field);
6725 VaListTagDecl->completeDefinition();
6726 Context->VaListTagDecl = VaListTagDecl;
6727 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6730 TypedefDecl *VaListTagTypedefDecl =
6731 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6733 QualType VaListTagTypedefType =
6734 Context->getTypedefType(VaListTagTypedefDecl);
6736 // typedef __va_list_tag __builtin_va_list[1];
6737 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6738 QualType VaListTagArrayType
6739 = Context->getConstantArrayType(VaListTagTypedefType,
6740 Size, ArrayType::Normal, 0);
6741 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6744 static TypedefDecl *
6745 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6746 // struct __va_list_tag {
6747 RecordDecl *VaListTagDecl;
6748 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6749 VaListTagDecl->startDefinition();
6751 const size_t NumFields = 4;
6752 QualType FieldTypes[NumFields];
6753 const char *FieldNames[NumFields];
6755 // unsigned gp_offset;
6756 FieldTypes[0] = Context->UnsignedIntTy;
6757 FieldNames[0] = "gp_offset";
6759 // unsigned fp_offset;
6760 FieldTypes[1] = Context->UnsignedIntTy;
6761 FieldNames[1] = "fp_offset";
6763 // void* overflow_arg_area;
6764 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6765 FieldNames[2] = "overflow_arg_area";
6767 // void* reg_save_area;
6768 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6769 FieldNames[3] = "reg_save_area";
6772 for (unsigned i = 0; i < NumFields; ++i) {
6773 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6777 &Context->Idents.get(FieldNames[i]),
6778 FieldTypes[i], /*TInfo=*/nullptr,
6779 /*BitWidth=*/nullptr,
6782 Field->setAccess(AS_public);
6783 VaListTagDecl->addDecl(Field);
6785 VaListTagDecl->completeDefinition();
6786 Context->VaListTagDecl = VaListTagDecl;
6787 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6791 // typedef struct __va_list_tag __builtin_va_list[1];
6792 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6793 QualType VaListTagArrayType =
6794 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6795 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6798 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6799 // typedef int __builtin_va_list[4];
6800 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6801 QualType IntArrayType =
6802 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
6803 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6806 static TypedefDecl *
6807 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6809 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6810 if (Context->getLangOpts().CPlusPlus) {
6811 // namespace std { struct __va_list {
6813 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6814 Context->getTranslationUnitDecl(),
6815 /*Inline*/false, SourceLocation(),
6816 SourceLocation(), &Context->Idents.get("std"),
6817 /*PrevDecl*/ nullptr);
6819 VaListDecl->setDeclContext(NS);
6822 VaListDecl->startDefinition();
6825 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6829 &Context->Idents.get("__ap"),
6830 Context->getPointerType(Context->VoidTy),
6832 /*BitWidth=*/nullptr,
6835 Field->setAccess(AS_public);
6836 VaListDecl->addDecl(Field);
6839 VaListDecl->completeDefinition();
6840 Context->VaListTagDecl = VaListDecl;
6842 // typedef struct __va_list __builtin_va_list;
6843 QualType T = Context->getRecordType(VaListDecl);
6844 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6847 static TypedefDecl *
6848 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6849 // struct __va_list_tag {
6850 RecordDecl *VaListTagDecl;
6851 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6852 VaListTagDecl->startDefinition();
6854 const size_t NumFields = 4;
6855 QualType FieldTypes[NumFields];
6856 const char *FieldNames[NumFields];
6859 FieldTypes[0] = Context->LongTy;
6860 FieldNames[0] = "__gpr";
6863 FieldTypes[1] = Context->LongTy;
6864 FieldNames[1] = "__fpr";
6866 // void *__overflow_arg_area;
6867 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6868 FieldNames[2] = "__overflow_arg_area";
6870 // void *__reg_save_area;
6871 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6872 FieldNames[3] = "__reg_save_area";
6875 for (unsigned i = 0; i < NumFields; ++i) {
6876 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6880 &Context->Idents.get(FieldNames[i]),
6881 FieldTypes[i], /*TInfo=*/nullptr,
6882 /*BitWidth=*/nullptr,
6885 Field->setAccess(AS_public);
6886 VaListTagDecl->addDecl(Field);
6888 VaListTagDecl->completeDefinition();
6889 Context->VaListTagDecl = VaListTagDecl;
6890 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6894 // typedef __va_list_tag __builtin_va_list[1];
6895 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6896 QualType VaListTagArrayType =
6897 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6899 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6902 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6903 TargetInfo::BuiltinVaListKind Kind) {
6905 case TargetInfo::CharPtrBuiltinVaList:
6906 return CreateCharPtrBuiltinVaListDecl(Context);
6907 case TargetInfo::VoidPtrBuiltinVaList:
6908 return CreateVoidPtrBuiltinVaListDecl(Context);
6909 case TargetInfo::AArch64ABIBuiltinVaList:
6910 return CreateAArch64ABIBuiltinVaListDecl(Context);
6911 case TargetInfo::PowerABIBuiltinVaList:
6912 return CreatePowerABIBuiltinVaListDecl(Context);
6913 case TargetInfo::X86_64ABIBuiltinVaList:
6914 return CreateX86_64ABIBuiltinVaListDecl(Context);
6915 case TargetInfo::PNaClABIBuiltinVaList:
6916 return CreatePNaClABIBuiltinVaListDecl(Context);
6917 case TargetInfo::AAPCSABIBuiltinVaList:
6918 return CreateAAPCSABIBuiltinVaListDecl(Context);
6919 case TargetInfo::SystemZBuiltinVaList:
6920 return CreateSystemZBuiltinVaListDecl(Context);
6923 llvm_unreachable("Unhandled __builtin_va_list type kind");
6926 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6927 if (!BuiltinVaListDecl) {
6928 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6929 assert(BuiltinVaListDecl->isImplicit());
6932 return BuiltinVaListDecl;
6935 Decl *ASTContext::getVaListTagDecl() const {
6936 // Force the creation of VaListTagDecl by building the __builtin_va_list
6939 (void)getBuiltinVaListDecl();
6941 return VaListTagDecl;
6944 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6945 if (!BuiltinMSVaListDecl)
6946 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6948 return BuiltinMSVaListDecl;
6951 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6952 assert(ObjCConstantStringType.isNull() &&
6953 "'NSConstantString' type already set!");
6955 ObjCConstantStringType = getObjCInterfaceType(Decl);
6958 /// \brief Retrieve the template name that corresponds to a non-empty
6961 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6962 UnresolvedSetIterator End) const {
6963 unsigned size = End - Begin;
6964 assert(size > 1 && "set is not overloaded!");
6966 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6967 size * sizeof(FunctionTemplateDecl*));
6968 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6970 NamedDecl **Storage = OT->getStorage();
6971 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6973 assert(isa<FunctionTemplateDecl>(D) ||
6974 (isa<UsingShadowDecl>(D) &&
6975 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6979 return TemplateName(OT);
6982 /// \brief Retrieve the template name that represents a qualified
6983 /// template name such as \c std::vector.
6985 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6986 bool TemplateKeyword,
6987 TemplateDecl *Template) const {
6988 assert(NNS && "Missing nested-name-specifier in qualified template name");
6990 // FIXME: Canonicalization?
6991 llvm::FoldingSetNodeID ID;
6992 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6994 void *InsertPos = nullptr;
6995 QualifiedTemplateName *QTN =
6996 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6998 QTN = new (*this, alignof(QualifiedTemplateName))
6999 QualifiedTemplateName(NNS, TemplateKeyword, Template);
7000 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7003 return TemplateName(QTN);
7006 /// \brief Retrieve the template name that represents a dependent
7007 /// template name such as \c MetaFun::template apply.
7009 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7010 const IdentifierInfo *Name) const {
7011 assert((!NNS || NNS->isDependent()) &&
7012 "Nested name specifier must be dependent");
7014 llvm::FoldingSetNodeID ID;
7015 DependentTemplateName::Profile(ID, NNS, Name);
7017 void *InsertPos = nullptr;
7018 DependentTemplateName *QTN =
7019 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7022 return TemplateName(QTN);
7024 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7025 if (CanonNNS == NNS) {
7026 QTN = new (*this, alignof(DependentTemplateName))
7027 DependentTemplateName(NNS, Name);
7029 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7030 QTN = new (*this, alignof(DependentTemplateName))
7031 DependentTemplateName(NNS, Name, Canon);
7032 DependentTemplateName *CheckQTN =
7033 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7034 assert(!CheckQTN && "Dependent type name canonicalization broken");
7038 DependentTemplateNames.InsertNode(QTN, InsertPos);
7039 return TemplateName(QTN);
7042 /// \brief Retrieve the template name that represents a dependent
7043 /// template name such as \c MetaFun::template operator+.
7045 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7046 OverloadedOperatorKind Operator) const {
7047 assert((!NNS || NNS->isDependent()) &&
7048 "Nested name specifier must be dependent");
7050 llvm::FoldingSetNodeID ID;
7051 DependentTemplateName::Profile(ID, NNS, Operator);
7053 void *InsertPos = nullptr;
7054 DependentTemplateName *QTN
7055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7058 return TemplateName(QTN);
7060 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7061 if (CanonNNS == NNS) {
7062 QTN = new (*this, alignof(DependentTemplateName))
7063 DependentTemplateName(NNS, Operator);
7065 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7066 QTN = new (*this, alignof(DependentTemplateName))
7067 DependentTemplateName(NNS, Operator, Canon);
7069 DependentTemplateName *CheckQTN
7070 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7071 assert(!CheckQTN && "Dependent template name canonicalization broken");
7075 DependentTemplateNames.InsertNode(QTN, InsertPos);
7076 return TemplateName(QTN);
7080 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7081 TemplateName replacement) const {
7082 llvm::FoldingSetNodeID ID;
7083 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7085 void *insertPos = nullptr;
7086 SubstTemplateTemplateParmStorage *subst
7087 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7090 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7091 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7094 return TemplateName(subst);
7098 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7099 const TemplateArgument &ArgPack) const {
7100 ASTContext &Self = const_cast<ASTContext &>(*this);
7101 llvm::FoldingSetNodeID ID;
7102 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7104 void *InsertPos = nullptr;
7105 SubstTemplateTemplateParmPackStorage *Subst
7106 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7109 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7110 ArgPack.pack_size(),
7111 ArgPack.pack_begin());
7112 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7115 return TemplateName(Subst);
7118 /// getFromTargetType - Given one of the integer types provided by
7119 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7120 /// is actually a value of type @c TargetInfo::IntType.
7121 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7123 case TargetInfo::NoInt: return CanQualType();
7124 case TargetInfo::SignedChar: return SignedCharTy;
7125 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7126 case TargetInfo::SignedShort: return ShortTy;
7127 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7128 case TargetInfo::SignedInt: return IntTy;
7129 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7130 case TargetInfo::SignedLong: return LongTy;
7131 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7132 case TargetInfo::SignedLongLong: return LongLongTy;
7133 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7136 llvm_unreachable("Unhandled TargetInfo::IntType value");
7139 //===----------------------------------------------------------------------===//
7141 //===----------------------------------------------------------------------===//
7143 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7144 /// garbage collection attribute.
7146 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7147 if (getLangOpts().getGC() == LangOptions::NonGC)
7148 return Qualifiers::GCNone;
7150 assert(getLangOpts().ObjC1);
7151 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7153 // Default behaviour under objective-C's gc is for ObjC pointers
7154 // (or pointers to them) be treated as though they were declared
7156 if (GCAttrs == Qualifiers::GCNone) {
7157 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7158 return Qualifiers::Strong;
7159 else if (Ty->isPointerType())
7160 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7162 // It's not valid to set GC attributes on anything that isn't a
7165 QualType CT = Ty->getCanonicalTypeInternal();
7166 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7167 CT = AT->getElementType();
7168 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7174 //===----------------------------------------------------------------------===//
7175 // Type Compatibility Testing
7176 //===----------------------------------------------------------------------===//
7178 /// areCompatVectorTypes - Return true if the two specified vector types are
7180 static bool areCompatVectorTypes(const VectorType *LHS,
7181 const VectorType *RHS) {
7182 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7183 return LHS->getElementType() == RHS->getElementType() &&
7184 LHS->getNumElements() == RHS->getNumElements();
7187 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7188 QualType SecondVec) {
7189 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7190 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7192 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7195 // Treat Neon vector types and most AltiVec vector types as if they are the
7196 // equivalent GCC vector types.
7197 const VectorType *First = FirstVec->getAs<VectorType>();
7198 const VectorType *Second = SecondVec->getAs<VectorType>();
7199 if (First->getNumElements() == Second->getNumElements() &&
7200 hasSameType(First->getElementType(), Second->getElementType()) &&
7201 First->getVectorKind() != VectorType::AltiVecPixel &&
7202 First->getVectorKind() != VectorType::AltiVecBool &&
7203 Second->getVectorKind() != VectorType::AltiVecPixel &&
7204 Second->getVectorKind() != VectorType::AltiVecBool)
7210 //===----------------------------------------------------------------------===//
7211 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7212 //===----------------------------------------------------------------------===//
7214 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7215 /// inheritance hierarchy of 'rProto'.
7217 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7218 ObjCProtocolDecl *rProto) const {
7219 if (declaresSameEntity(lProto, rProto))
7221 for (auto *PI : rProto->protocols())
7222 if (ProtocolCompatibleWithProtocol(lProto, PI))
7227 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7228 /// Class<pr1, ...>.
7229 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7231 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7232 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7233 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7235 for (auto *lhsProto : lhsQID->quals()) {
7237 for (auto *rhsProto : rhsOPT->quals()) {
7238 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7249 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7250 /// ObjCQualifiedIDType.
7251 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7253 // Allow id<P..> and an 'id' or void* type in all cases.
7254 if (lhs->isVoidPointerType() ||
7255 lhs->isObjCIdType() || lhs->isObjCClassType())
7257 else if (rhs->isVoidPointerType() ||
7258 rhs->isObjCIdType() || rhs->isObjCClassType())
7261 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7262 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7264 if (!rhsOPT) return false;
7266 if (rhsOPT->qual_empty()) {
7267 // If the RHS is a unqualified interface pointer "NSString*",
7268 // make sure we check the class hierarchy.
7269 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7270 for (auto *I : lhsQID->quals()) {
7271 // when comparing an id<P> on lhs with a static type on rhs,
7272 // see if static class implements all of id's protocols, directly or
7273 // through its super class and categories.
7274 if (!rhsID->ClassImplementsProtocol(I, true))
7278 // If there are no qualifiers and no interface, we have an 'id'.
7281 // Both the right and left sides have qualifiers.
7282 for (auto *lhsProto : lhsQID->quals()) {
7285 // when comparing an id<P> on lhs with a static type on rhs,
7286 // see if static class implements all of id's protocols, directly or
7287 // through its super class and categories.
7288 for (auto *rhsProto : rhsOPT->quals()) {
7289 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7290 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7295 // If the RHS is a qualified interface pointer "NSString<P>*",
7296 // make sure we check the class hierarchy.
7297 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7298 for (auto *I : lhsQID->quals()) {
7299 // when comparing an id<P> on lhs with a static type on rhs,
7300 // see if static class implements all of id's protocols, directly or
7301 // through its super class and categories.
7302 if (rhsID->ClassImplementsProtocol(I, true)) {
7315 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7316 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7318 if (const ObjCObjectPointerType *lhsOPT =
7319 lhs->getAsObjCInterfacePointerType()) {
7320 // If both the right and left sides have qualifiers.
7321 for (auto *lhsProto : lhsOPT->quals()) {
7324 // when comparing an id<P> on rhs with a static type on lhs,
7325 // see if static class implements all of id's protocols, directly or
7326 // through its super class and categories.
7327 // First, lhs protocols in the qualifier list must be found, direct
7328 // or indirect in rhs's qualifier list or it is a mismatch.
7329 for (auto *rhsProto : rhsQID->quals()) {
7330 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7331 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7340 // Static class's protocols, or its super class or category protocols
7341 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7342 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7343 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7344 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7345 // This is rather dubious but matches gcc's behavior. If lhs has
7346 // no type qualifier and its class has no static protocol(s)
7347 // assume that it is mismatch.
7348 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7350 for (auto *lhsProto : LHSInheritedProtocols) {
7352 for (auto *rhsProto : rhsQID->quals()) {
7353 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7354 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7368 /// canAssignObjCInterfaces - Return true if the two interface types are
7369 /// compatible for assignment from RHS to LHS. This handles validation of any
7370 /// protocol qualifiers on the LHS or RHS.
7372 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7373 const ObjCObjectPointerType *RHSOPT) {
7374 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7375 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7377 // If either type represents the built-in 'id' or 'Class' types, return true.
7378 if (LHS->isObjCUnqualifiedIdOrClass() ||
7379 RHS->isObjCUnqualifiedIdOrClass())
7382 // Function object that propagates a successful result or handles
7384 auto finish = [&](bool succeeded) -> bool {
7388 if (!RHS->isKindOfType())
7391 // Strip off __kindof and protocol qualifiers, then check whether
7392 // we can assign the other way.
7393 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7394 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7397 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7398 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7403 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7404 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7405 QualType(RHSOPT,0)));
7408 // If we have 2 user-defined types, fall into that path.
7409 if (LHS->getInterface() && RHS->getInterface()) {
7410 return finish(canAssignObjCInterfaces(LHS, RHS));
7416 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7417 /// for providing type-safety for objective-c pointers used to pass/return
7418 /// arguments in block literals. When passed as arguments, passing 'A*' where
7419 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7420 /// not OK. For the return type, the opposite is not OK.
7421 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7422 const ObjCObjectPointerType *LHSOPT,
7423 const ObjCObjectPointerType *RHSOPT,
7424 bool BlockReturnType) {
7426 // Function object that propagates a successful result or handles
7428 auto finish = [&](bool succeeded) -> bool {
7432 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7433 if (!Expected->isKindOfType())
7436 // Strip off __kindof and protocol qualifiers, then check whether
7437 // we can assign the other way.
7438 return canAssignObjCInterfacesInBlockPointer(
7439 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7440 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7444 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7447 if (LHSOPT->isObjCBuiltinType()) {
7448 return finish(RHSOPT->isObjCBuiltinType() ||
7449 RHSOPT->isObjCQualifiedIdType());
7452 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7453 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7457 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7458 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7459 if (LHS && RHS) { // We have 2 user-defined types.
7461 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7462 return finish(BlockReturnType);
7463 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7464 return finish(!BlockReturnType);
7472 /// Comparison routine for Objective-C protocols to be used with
7473 /// llvm::array_pod_sort.
7474 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7475 ObjCProtocolDecl * const *rhs) {
7476 return (*lhs)->getName().compare((*rhs)->getName());
7480 /// getIntersectionOfProtocols - This routine finds the intersection of set
7481 /// of protocols inherited from two distinct objective-c pointer objects with
7482 /// the given common base.
7483 /// It is used to build composite qualifier list of the composite type of
7484 /// the conditional expression involving two objective-c pointer objects.
7486 void getIntersectionOfProtocols(ASTContext &Context,
7487 const ObjCInterfaceDecl *CommonBase,
7488 const ObjCObjectPointerType *LHSOPT,
7489 const ObjCObjectPointerType *RHSOPT,
7490 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7492 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7493 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7494 assert(LHS->getInterface() && "LHS must have an interface base");
7495 assert(RHS->getInterface() && "RHS must have an interface base");
7497 // Add all of the protocols for the LHS.
7498 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7500 // Start with the protocol qualifiers.
7501 for (auto proto : LHS->quals()) {
7502 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7505 // Also add the protocols associated with the LHS interface.
7506 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7508 // Add all of the protocls for the RHS.
7509 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7511 // Start with the protocol qualifiers.
7512 for (auto proto : RHS->quals()) {
7513 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7516 // Also add the protocols associated with the RHS interface.
7517 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7519 // Compute the intersection of the collected protocol sets.
7520 for (auto proto : LHSProtocolSet) {
7521 if (RHSProtocolSet.count(proto))
7522 IntersectionSet.push_back(proto);
7525 // Compute the set of protocols that is implied by either the common type or
7526 // the protocols within the intersection.
7527 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7528 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7530 // Remove any implied protocols from the list of inherited protocols.
7531 if (!ImpliedProtocols.empty()) {
7532 IntersectionSet.erase(
7533 std::remove_if(IntersectionSet.begin(),
7534 IntersectionSet.end(),
7535 [&](ObjCProtocolDecl *proto) -> bool {
7536 return ImpliedProtocols.count(proto) > 0;
7538 IntersectionSet.end());
7541 // Sort the remaining protocols by name.
7542 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7543 compareObjCProtocolsByName);
7546 /// Determine whether the first type is a subtype of the second.
7547 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7549 // Common case: two object pointers.
7550 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7551 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7552 if (lhsOPT && rhsOPT)
7553 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7555 // Two block pointers.
7556 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7557 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7558 if (lhsBlock && rhsBlock)
7559 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7561 // If either is an unqualified 'id' and the other is a block, it's
7563 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7564 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7570 // Check that the given Objective-C type argument lists are equivalent.
7571 static bool sameObjCTypeArgs(ASTContext &ctx,
7572 const ObjCInterfaceDecl *iface,
7573 ArrayRef<QualType> lhsArgs,
7574 ArrayRef<QualType> rhsArgs,
7576 if (lhsArgs.size() != rhsArgs.size())
7579 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7580 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7581 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7584 switch (typeParams->begin()[i]->getVariance()) {
7585 case ObjCTypeParamVariance::Invariant:
7587 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7588 rhsArgs[i].stripObjCKindOfType(ctx))) {
7593 case ObjCTypeParamVariance::Covariant:
7594 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7598 case ObjCTypeParamVariance::Contravariant:
7599 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7608 QualType ASTContext::areCommonBaseCompatible(
7609 const ObjCObjectPointerType *Lptr,
7610 const ObjCObjectPointerType *Rptr) {
7611 const ObjCObjectType *LHS = Lptr->getObjectType();
7612 const ObjCObjectType *RHS = Rptr->getObjectType();
7613 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7614 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7616 if (!LDecl || !RDecl)
7619 // When either LHS or RHS is a kindof type, we should return a kindof type.
7620 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7622 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7624 // Follow the left-hand side up the class hierarchy until we either hit a
7625 // root or find the RHS. Record the ancestors in case we don't find it.
7626 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7629 // Record this ancestor. We'll need this if the common type isn't in the
7630 // path from the LHS to the root.
7631 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7633 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7634 // Get the type arguments.
7635 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7636 bool anyChanges = false;
7637 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7638 // Both have type arguments, compare them.
7639 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7640 LHS->getTypeArgs(), RHS->getTypeArgs(),
7641 /*stripKindOf=*/true))
7643 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7644 // If only one has type arguments, the result will not have type
7650 // Compute the intersection of protocols.
7651 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7652 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7654 if (!Protocols.empty())
7657 // If anything in the LHS will have changed, build a new result type.
7658 // If we need to return a kindof type but LHS is not a kindof type, we
7659 // build a new result type.
7660 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7661 QualType Result = getObjCInterfaceType(LHS->getInterface());
7662 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7663 anyKindOf || LHS->isKindOfType());
7664 return getObjCObjectPointerType(Result);
7667 return getObjCObjectPointerType(QualType(LHS, 0));
7670 // Find the superclass.
7671 QualType LHSSuperType = LHS->getSuperClassType();
7672 if (LHSSuperType.isNull())
7675 LHS = LHSSuperType->castAs<ObjCObjectType>();
7678 // We didn't find anything by following the LHS to its root; now check
7679 // the RHS against the cached set of ancestors.
7681 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7682 if (KnownLHS != LHSAncestors.end()) {
7683 LHS = KnownLHS->second;
7685 // Get the type arguments.
7686 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7687 bool anyChanges = false;
7688 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7689 // Both have type arguments, compare them.
7690 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7691 LHS->getTypeArgs(), RHS->getTypeArgs(),
7692 /*stripKindOf=*/true))
7694 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7695 // If only one has type arguments, the result will not have type
7701 // Compute the intersection of protocols.
7702 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7703 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7705 if (!Protocols.empty())
7708 // If we need to return a kindof type but RHS is not a kindof type, we
7709 // build a new result type.
7710 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7711 QualType Result = getObjCInterfaceType(RHS->getInterface());
7712 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7713 anyKindOf || RHS->isKindOfType());
7714 return getObjCObjectPointerType(Result);
7717 return getObjCObjectPointerType(QualType(RHS, 0));
7720 // Find the superclass of the RHS.
7721 QualType RHSSuperType = RHS->getSuperClassType();
7722 if (RHSSuperType.isNull())
7725 RHS = RHSSuperType->castAs<ObjCObjectType>();
7731 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7732 const ObjCObjectType *RHS) {
7733 assert(LHS->getInterface() && "LHS is not an interface type");
7734 assert(RHS->getInterface() && "RHS is not an interface type");
7736 // Verify that the base decls are compatible: the RHS must be a subclass of
7738 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7739 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7743 // If the LHS has protocol qualifiers, determine whether all of them are
7744 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7746 if (LHS->getNumProtocols() > 0) {
7747 // OK if conversion of LHS to SuperClass results in narrowing of types
7748 // ; i.e., SuperClass may implement at least one of the protocols
7749 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7750 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7751 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7752 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7753 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7755 for (auto *RHSPI : RHS->quals())
7756 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7757 // If there is no protocols associated with RHS, it is not a match.
7758 if (SuperClassInheritedProtocols.empty())
7761 for (const auto *LHSProto : LHS->quals()) {
7762 bool SuperImplementsProtocol = false;
7763 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7764 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7765 SuperImplementsProtocol = true;
7768 if (!SuperImplementsProtocol)
7773 // If the LHS is specialized, we may need to check type arguments.
7774 if (LHS->isSpecialized()) {
7775 // Follow the superclass chain until we've matched the LHS class in the
7776 // hierarchy. This substitutes type arguments through.
7777 const ObjCObjectType *RHSSuper = RHS;
7778 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7779 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7781 // If the RHS is specializd, compare type arguments.
7782 if (RHSSuper->isSpecialized() &&
7783 !sameObjCTypeArgs(*this, LHS->getInterface(),
7784 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7785 /*stripKindOf=*/true)) {
7793 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7794 // get the "pointed to" types
7795 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7796 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7798 if (!LHSOPT || !RHSOPT)
7801 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7802 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7805 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7806 return canAssignObjCInterfaces(
7807 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7808 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7811 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7812 /// both shall have the identically qualified version of a compatible type.
7813 /// C99 6.2.7p1: Two types have compatible types if their types are the
7814 /// same. See 6.7.[2,3,5] for additional rules.
7815 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7816 bool CompareUnqualified) {
7817 if (getLangOpts().CPlusPlus)
7818 return hasSameType(LHS, RHS);
7820 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7823 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7824 return typesAreCompatible(LHS, RHS);
7827 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7828 return !mergeTypes(LHS, RHS, true).isNull();
7831 /// mergeTransparentUnionType - if T is a transparent union type and a member
7832 /// of T is compatible with SubType, return the merged type, else return
7834 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7835 bool OfBlockPointer,
7837 if (const RecordType *UT = T->getAsUnionType()) {
7838 RecordDecl *UD = UT->getDecl();
7839 if (UD->hasAttr<TransparentUnionAttr>()) {
7840 for (const auto *I : UD->fields()) {
7841 QualType ET = I->getType().getUnqualifiedType();
7842 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7852 /// mergeFunctionParameterTypes - merge two types which appear as function
7854 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7855 bool OfBlockPointer,
7857 // GNU extension: two types are compatible if they appear as a function
7858 // argument, one of the types is a transparent union type and the other
7859 // type is compatible with a union member
7860 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7862 if (!lmerge.isNull())
7865 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7867 if (!rmerge.isNull())
7870 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7873 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7874 bool OfBlockPointer,
7876 const FunctionType *lbase = lhs->getAs<FunctionType>();
7877 const FunctionType *rbase = rhs->getAs<FunctionType>();
7878 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7879 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7880 bool allLTypes = true;
7881 bool allRTypes = true;
7883 // Check return type
7885 if (OfBlockPointer) {
7886 QualType RHS = rbase->getReturnType();
7887 QualType LHS = lbase->getReturnType();
7888 bool UnqualifiedResult = Unqualified;
7889 if (!UnqualifiedResult)
7890 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7891 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7894 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7896 if (retType.isNull()) return QualType();
7899 retType = retType.getUnqualifiedType();
7901 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7902 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7904 LRetType = LRetType.getUnqualifiedType();
7905 RRetType = RRetType.getUnqualifiedType();
7908 if (getCanonicalType(retType) != LRetType)
7910 if (getCanonicalType(retType) != RRetType)
7913 // FIXME: double check this
7914 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7915 // rbase->getRegParmAttr() != 0 &&
7916 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7917 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7918 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7920 // Compatible functions must have compatible calling conventions
7921 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7924 // Regparm is part of the calling convention.
7925 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7927 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7930 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7932 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
7935 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7936 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7938 if (lbaseInfo.getNoReturn() != NoReturn)
7940 if (rbaseInfo.getNoReturn() != NoReturn)
7943 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7945 if (lproto && rproto) { // two C99 style function prototypes
7946 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7947 "C++ shouldn't be here");
7948 // Compatible functions must have the same number of parameters
7949 if (lproto->getNumParams() != rproto->getNumParams())
7952 // Variadic and non-variadic functions aren't compatible
7953 if (lproto->isVariadic() != rproto->isVariadic())
7956 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7959 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7962 // Check parameter type compatibility
7963 SmallVector<QualType, 10> types;
7964 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7965 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7966 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7967 QualType paramType = mergeFunctionParameterTypes(
7968 lParamType, rParamType, OfBlockPointer, Unqualified);
7969 if (paramType.isNull())
7973 paramType = paramType.getUnqualifiedType();
7975 types.push_back(paramType);
7977 lParamType = lParamType.getUnqualifiedType();
7978 rParamType = rParamType.getUnqualifiedType();
7981 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7983 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7987 if (allLTypes) return lhs;
7988 if (allRTypes) return rhs;
7990 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7991 EPI.ExtInfo = einfo;
7992 return getFunctionType(retType, types, EPI);
7995 if (lproto) allRTypes = false;
7996 if (rproto) allLTypes = false;
7998 const FunctionProtoType *proto = lproto ? lproto : rproto;
8000 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
8001 if (proto->isVariadic()) return QualType();
8002 // Check that the types are compatible with the types that
8003 // would result from default argument promotions (C99 6.7.5.3p15).
8004 // The only types actually affected are promotable integer
8005 // types and floats, which would be passed as a different
8006 // type depending on whether the prototype is visible.
8007 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8008 QualType paramTy = proto->getParamType(i);
8010 // Look at the converted type of enum types, since that is the type used
8011 // to pass enum values.
8012 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8013 paramTy = Enum->getDecl()->getIntegerType();
8014 if (paramTy.isNull())
8018 if (paramTy->isPromotableIntegerType() ||
8019 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
8023 if (allLTypes) return lhs;
8024 if (allRTypes) return rhs;
8026 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8027 EPI.ExtInfo = einfo;
8028 return getFunctionType(retType, proto->getParamTypes(), EPI);
8031 if (allLTypes) return lhs;
8032 if (allRTypes) return rhs;
8033 return getFunctionNoProtoType(retType, einfo);
8036 /// Given that we have an enum type and a non-enum type, try to merge them.
8037 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8038 QualType other, bool isBlockReturnType) {
8039 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8040 // a signed integer type, or an unsigned integer type.
8041 // Compatibility is based on the underlying type, not the promotion
8043 QualType underlyingType = ET->getDecl()->getIntegerType();
8044 if (underlyingType.isNull()) return QualType();
8045 if (Context.hasSameType(underlyingType, other))
8048 // In block return types, we're more permissive and accept any
8049 // integral type of the same size.
8050 if (isBlockReturnType && other->isIntegerType() &&
8051 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8057 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
8058 bool OfBlockPointer,
8059 bool Unqualified, bool BlockReturnType) {
8060 // C++ [expr]: If an expression initially has the type "reference to T", the
8061 // type is adjusted to "T" prior to any further analysis, the expression
8062 // designates the object or function denoted by the reference, and the
8063 // expression is an lvalue unless the reference is an rvalue reference and
8064 // the expression is a function call (possibly inside parentheses).
8065 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8066 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8069 LHS = LHS.getUnqualifiedType();
8070 RHS = RHS.getUnqualifiedType();
8073 QualType LHSCan = getCanonicalType(LHS),
8074 RHSCan = getCanonicalType(RHS);
8076 // If two types are identical, they are compatible.
8077 if (LHSCan == RHSCan)
8080 // If the qualifiers are different, the types aren't compatible... mostly.
8081 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8082 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8083 if (LQuals != RQuals) {
8084 // If any of these qualifiers are different, we have a type
8086 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8087 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8088 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8089 LQuals.hasUnaligned() != RQuals.hasUnaligned())
8092 // Exactly one GC qualifier difference is allowed: __strong is
8093 // okay if the other type has no GC qualifier but is an Objective
8094 // C object pointer (i.e. implicitly strong by default). We fix
8095 // this by pretending that the unqualified type was actually
8096 // qualified __strong.
8097 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8098 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8099 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8101 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8104 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8105 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8107 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8108 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8113 // Okay, qualifiers are equal.
8115 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8116 Type::TypeClass RHSClass = RHSCan->getTypeClass();
8118 // We want to consider the two function types to be the same for these
8119 // comparisons, just force one to the other.
8120 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8121 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8123 // Same as above for arrays
8124 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8125 LHSClass = Type::ConstantArray;
8126 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8127 RHSClass = Type::ConstantArray;
8129 // ObjCInterfaces are just specialized ObjCObjects.
8130 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8131 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8133 // Canonicalize ExtVector -> Vector.
8134 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8135 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8137 // If the canonical type classes don't match.
8138 if (LHSClass != RHSClass) {
8139 // Note that we only have special rules for turning block enum
8140 // returns into block int returns, not vice-versa.
8141 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
8142 return mergeEnumWithInteger(*this, ETy, RHS, false);
8144 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8145 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8147 // allow block pointer type to match an 'id' type.
8148 if (OfBlockPointer && !BlockReturnType) {
8149 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8151 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8158 // The canonical type classes match.
8160 #define TYPE(Class, Base)
8161 #define ABSTRACT_TYPE(Class, Base)
8162 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8163 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8164 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8165 #include "clang/AST/TypeNodes.def"
8166 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8169 case Type::DeducedTemplateSpecialization:
8170 case Type::LValueReference:
8171 case Type::RValueReference:
8172 case Type::MemberPointer:
8173 llvm_unreachable("C++ should never be in mergeTypes");
8175 case Type::ObjCInterface:
8176 case Type::IncompleteArray:
8177 case Type::VariableArray:
8178 case Type::FunctionProto:
8179 case Type::ExtVector:
8180 llvm_unreachable("Types are eliminated above");
8184 // Merge two pointer types, while trying to preserve typedef info
8185 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8186 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8188 LHSPointee = LHSPointee.getUnqualifiedType();
8189 RHSPointee = RHSPointee.getUnqualifiedType();
8191 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8193 if (ResultType.isNull()) return QualType();
8194 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8196 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8198 return getPointerType(ResultType);
8200 case Type::BlockPointer:
8202 // Merge two block pointer types, while trying to preserve typedef info
8203 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8204 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8206 LHSPointee = LHSPointee.getUnqualifiedType();
8207 RHSPointee = RHSPointee.getUnqualifiedType();
8209 if (getLangOpts().OpenCL) {
8210 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8211 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8212 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8213 // 6.12.5) thus the following check is asymmetric.
8214 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8216 LHSPteeQual.removeAddressSpace();
8217 RHSPteeQual.removeAddressSpace();
8219 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8221 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8223 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8225 if (ResultType.isNull()) return QualType();
8226 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8228 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8230 return getBlockPointerType(ResultType);
8234 // Merge two pointer types, while trying to preserve typedef info
8235 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8236 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8238 LHSValue = LHSValue.getUnqualifiedType();
8239 RHSValue = RHSValue.getUnqualifiedType();
8241 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8243 if (ResultType.isNull()) return QualType();
8244 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8246 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8248 return getAtomicType(ResultType);
8250 case Type::ConstantArray:
8252 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8253 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8254 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8257 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8258 QualType RHSElem = getAsArrayType(RHS)->getElementType();
8260 LHSElem = LHSElem.getUnqualifiedType();
8261 RHSElem = RHSElem.getUnqualifiedType();
8264 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8265 if (ResultType.isNull()) return QualType();
8266 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8268 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8270 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8271 ArrayType::ArraySizeModifier(), 0);
8272 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8273 ArrayType::ArraySizeModifier(), 0);
8274 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8275 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8276 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8278 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8281 // FIXME: This isn't correct! But tricky to implement because
8282 // the array's size has to be the size of LHS, but the type
8283 // has to be different.
8287 // FIXME: This isn't correct! But tricky to implement because
8288 // the array's size has to be the size of RHS, but the type
8289 // has to be different.
8292 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8293 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
8294 return getIncompleteArrayType(ResultType,
8295 ArrayType::ArraySizeModifier(), 0);
8297 case Type::FunctionNoProto:
8298 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
8303 // Only exactly equal builtin types are compatible, which is tested above.
8306 // Distinct complex types are incompatible.
8309 // FIXME: The merged type should be an ExtVector!
8310 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8311 RHSCan->getAs<VectorType>()))
8314 case Type::ObjCObject: {
8315 // Check if the types are assignment compatible.
8316 // FIXME: This should be type compatibility, e.g. whether
8317 // "LHS x; RHS x;" at global scope is legal.
8318 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8319 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8320 if (canAssignObjCInterfaces(LHSIface, RHSIface))
8325 case Type::ObjCObjectPointer: {
8326 if (OfBlockPointer) {
8327 if (canAssignObjCInterfacesInBlockPointer(
8328 LHS->getAs<ObjCObjectPointerType>(),
8329 RHS->getAs<ObjCObjectPointerType>(),
8334 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8335 RHS->getAs<ObjCObjectPointerType>()))
8342 assert(LHS != RHS &&
8343 "Equivalent pipe types should have already been handled!");
8348 llvm_unreachable("Invalid Type::Class!");
8351 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8352 const FunctionProtoType *firstFnType,
8353 const FunctionProtoType *secondFnType) {
8354 // Fast path: if the first type doesn't have ext parameter infos,
8355 // we match if and only if they second type also doesn't have them.
8356 if (!firstFnType->hasExtParameterInfos())
8357 return !secondFnType->hasExtParameterInfos();
8359 // Otherwise, we can only match if the second type has them.
8360 if (!secondFnType->hasExtParameterInfos())
8363 auto firstEPI = firstFnType->getExtParameterInfos();
8364 auto secondEPI = secondFnType->getExtParameterInfos();
8365 assert(firstEPI.size() == secondEPI.size());
8367 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8368 if (firstEPI[i] != secondEPI[i])
8374 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8375 ObjCLayouts[CD] = nullptr;
8378 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8379 /// 'RHS' attributes and returns the merged version; including for function
8381 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8382 QualType LHSCan = getCanonicalType(LHS),
8383 RHSCan = getCanonicalType(RHS);
8384 // If two types are identical, they are compatible.
8385 if (LHSCan == RHSCan)
8387 if (RHSCan->isFunctionType()) {
8388 if (!LHSCan->isFunctionType())
8390 QualType OldReturnType =
8391 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
8392 QualType NewReturnType =
8393 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
8394 QualType ResReturnType =
8395 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8396 if (ResReturnType.isNull())
8398 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8399 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8400 // In either case, use OldReturnType to build the new function type.
8401 const FunctionType *F = LHS->getAs<FunctionType>();
8402 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
8403 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8404 EPI.ExtInfo = getFunctionExtInfo(LHS);
8405 QualType ResultType =
8406 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
8413 // If the qualifiers are different, the types can still be merged.
8414 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8415 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8416 if (LQuals != RQuals) {
8417 // If any of these qualifiers are different, we have a type mismatch.
8418 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8419 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8422 // Exactly one GC qualifier difference is allowed: __strong is
8423 // okay if the other type has no GC qualifier but is an Objective
8424 // C object pointer (i.e. implicitly strong by default). We fix
8425 // this by pretending that the unqualified type was actually
8426 // qualified __strong.
8427 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8428 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8429 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8431 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8434 if (GC_L == Qualifiers::Strong)
8436 if (GC_R == Qualifiers::Strong)
8441 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8442 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8443 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8444 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8445 if (ResQT == LHSBaseQT)
8447 if (ResQT == RHSBaseQT)
8453 //===----------------------------------------------------------------------===//
8454 // Integer Predicates
8455 //===----------------------------------------------------------------------===//
8457 unsigned ASTContext::getIntWidth(QualType T) const {
8458 if (const EnumType *ET = T->getAs<EnumType>())
8459 T = ET->getDecl()->getIntegerType();
8460 if (T->isBooleanType())
8462 // For builtin types, just use the standard type sizing method
8463 return (unsigned)getTypeSize(T);
8466 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8467 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8469 // Turn <4 x signed int> -> <4 x unsigned int>
8470 if (const VectorType *VTy = T->getAs<VectorType>())
8471 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8472 VTy->getNumElements(), VTy->getVectorKind());
8474 // For enums, we return the unsigned version of the base type.
8475 if (const EnumType *ETy = T->getAs<EnumType>())
8476 T = ETy->getDecl()->getIntegerType();
8478 const BuiltinType *BTy = T->getAs<BuiltinType>();
8479 assert(BTy && "Unexpected signed integer type");
8480 switch (BTy->getKind()) {
8481 case BuiltinType::Char_S:
8482 case BuiltinType::SChar:
8483 return UnsignedCharTy;
8484 case BuiltinType::Short:
8485 return UnsignedShortTy;
8486 case BuiltinType::Int:
8487 return UnsignedIntTy;
8488 case BuiltinType::Long:
8489 return UnsignedLongTy;
8490 case BuiltinType::LongLong:
8491 return UnsignedLongLongTy;
8492 case BuiltinType::Int128:
8493 return UnsignedInt128Ty;
8495 llvm_unreachable("Unexpected signed integer type");
8499 ASTMutationListener::~ASTMutationListener() { }
8501 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8502 QualType ReturnType) {}
8504 //===----------------------------------------------------------------------===//
8505 // Builtin Type Computation
8506 //===----------------------------------------------------------------------===//
8508 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8509 /// pointer over the consumed characters. This returns the resultant type. If
8510 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8511 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8512 /// a vector of "i*".
8514 /// RequiresICE is filled in on return to indicate whether the value is required
8515 /// to be an Integer Constant Expression.
8516 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8517 ASTContext::GetBuiltinTypeError &Error,
8519 bool AllowTypeModifiers) {
8522 bool Signed = false, Unsigned = false;
8523 RequiresICE = false;
8525 // Read the prefixed modifiers first.
8528 bool IsSpecialLong = false;
8532 default: Done = true; --Str; break;
8537 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8538 assert(!Signed && "Can't use 'S' modifier multiple times!");
8542 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8543 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8547 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
8548 assert(HowLong <= 2 && "Can't have LLLL modifier");
8552 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8553 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8554 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
8556 IsSpecialLong = true;
8558 if (Context.getTargetInfo().getLongWidth() == 32)
8563 // This modifier represents int64 type.
8564 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8565 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8567 IsSpecialLong = true;
8569 switch (Context.getTargetInfo().getInt64Type()) {
8571 llvm_unreachable("Unexpected integer type");
8572 case TargetInfo::SignedLong:
8575 case TargetInfo::SignedLongLong:
8585 // Read the base type.
8587 default: llvm_unreachable("Unknown builtin type letter!");
8589 assert(HowLong == 0 && !Signed && !Unsigned &&
8590 "Bad modifiers used with 'v'!");
8591 Type = Context.VoidTy;
8594 assert(HowLong == 0 && !Signed && !Unsigned &&
8595 "Bad modifiers used with 'h'!");
8596 Type = Context.HalfTy;
8599 assert(HowLong == 0 && !Signed && !Unsigned &&
8600 "Bad modifiers used with 'f'!");
8601 Type = Context.FloatTy;
8604 assert(HowLong < 2 && !Signed && !Unsigned &&
8605 "Bad modifiers used with 'd'!");
8607 Type = Context.LongDoubleTy;
8609 Type = Context.DoubleTy;
8612 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8614 Type = Context.UnsignedShortTy;
8616 Type = Context.ShortTy;
8620 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8621 else if (HowLong == 2)
8622 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8623 else if (HowLong == 1)
8624 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8626 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8629 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8631 Type = Context.SignedCharTy;
8633 Type = Context.UnsignedCharTy;
8635 Type = Context.CharTy;
8637 case 'b': // boolean
8638 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8639 Type = Context.BoolTy;
8641 case 'z': // size_t.
8642 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8643 Type = Context.getSizeType();
8645 case 'w': // wchar_t.
8646 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8647 Type = Context.getWideCharType();
8650 Type = Context.getCFConstantStringType();
8653 Type = Context.getObjCIdType();
8656 Type = Context.getObjCSelType();
8659 Type = Context.getObjCSuperType();
8662 Type = Context.getBuiltinVaListType();
8663 assert(!Type.isNull() && "builtin va list type not initialized!");
8666 // This is a "reference" to a va_list; however, what exactly
8667 // this means depends on how va_list is defined. There are two
8668 // different kinds of va_list: ones passed by value, and ones
8669 // passed by reference. An example of a by-value va_list is
8670 // x86, where va_list is a char*. An example of by-ref va_list
8671 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8672 // we want this argument to be a char*&; for x86-64, we want
8673 // it to be a __va_list_tag*.
8674 Type = Context.getBuiltinVaListType();
8675 assert(!Type.isNull() && "builtin va list type not initialized!");
8676 if (Type->isArrayType())
8677 Type = Context.getArrayDecayedType(Type);
8679 Type = Context.getLValueReferenceType(Type);
8683 unsigned NumElements = strtoul(Str, &End, 10);
8684 assert(End != Str && "Missing vector size");
8687 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8688 RequiresICE, false);
8689 assert(!RequiresICE && "Can't require vector ICE");
8691 // TODO: No way to make AltiVec vectors in builtins yet.
8692 Type = Context.getVectorType(ElementType, NumElements,
8693 VectorType::GenericVector);
8699 unsigned NumElements = strtoul(Str, &End, 10);
8700 assert(End != Str && "Missing vector size");
8704 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8706 Type = Context.getExtVectorType(ElementType, NumElements);
8710 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8712 assert(!RequiresICE && "Can't require complex ICE");
8713 Type = Context.getComplexType(ElementType);
8717 Type = Context.getPointerDiffType();
8721 Type = Context.getFILEType();
8722 if (Type.isNull()) {
8723 Error = ASTContext::GE_Missing_stdio;
8729 Type = Context.getsigjmp_bufType();
8731 Type = Context.getjmp_bufType();
8733 if (Type.isNull()) {
8734 Error = ASTContext::GE_Missing_setjmp;
8739 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8740 Type = Context.getucontext_tType();
8742 if (Type.isNull()) {
8743 Error = ASTContext::GE_Missing_ucontext;
8748 Type = Context.getProcessIDType();
8752 // If there are modifiers and if we're allowed to parse them, go for it.
8753 Done = !AllowTypeModifiers;
8755 switch (char c = *Str++) {
8756 default: Done = true; --Str; break;
8759 // Both pointers and references can have their pointee types
8760 // qualified with an address space.
8762 unsigned AddrSpace = strtoul(Str, &End, 10);
8763 if (End != Str && AddrSpace != 0) {
8764 Type = Context.getAddrSpaceQualType(
8765 Type, AddrSpace + LangAS::FirstTargetAddressSpace);
8769 Type = Context.getPointerType(Type);
8771 Type = Context.getLValueReferenceType(Type);
8774 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8776 Type = Type.withConst();
8779 Type = Context.getVolatileType(Type);
8782 Type = Type.withRestrict();
8787 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8788 "Integer constant 'I' type must be an integer");
8793 /// GetBuiltinType - Return the type for the specified builtin.
8794 QualType ASTContext::GetBuiltinType(unsigned Id,
8795 GetBuiltinTypeError &Error,
8796 unsigned *IntegerConstantArgs) const {
8797 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8799 SmallVector<QualType, 8> ArgTypes;
8801 bool RequiresICE = false;
8803 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8805 if (Error != GE_None)
8808 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8810 while (TypeStr[0] && TypeStr[0] != '.') {
8811 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8812 if (Error != GE_None)
8815 // If this argument is required to be an IntegerConstantExpression and the
8816 // caller cares, fill in the bitmask we return.
8817 if (RequiresICE && IntegerConstantArgs)
8818 *IntegerConstantArgs |= 1 << ArgTypes.size();
8820 // Do array -> pointer decay. The builtin should use the decayed type.
8821 if (Ty->isArrayType())
8822 Ty = getArrayDecayedType(Ty);
8824 ArgTypes.push_back(Ty);
8827 if (Id == Builtin::BI__GetExceptionInfo)
8830 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8831 "'.' should only occur at end of builtin type list!");
8833 FunctionType::ExtInfo EI(CC_C);
8834 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8836 bool Variadic = (TypeStr[0] == '.');
8838 // We really shouldn't be making a no-proto type here.
8839 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
8840 return getFunctionNoProtoType(ResType, EI);
8842 FunctionProtoType::ExtProtoInfo EPI;
8844 EPI.Variadic = Variadic;
8845 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8846 EPI.ExceptionSpec.Type =
8847 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
8849 return getFunctionType(ResType, ArgTypes, EPI);
8852 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8853 const FunctionDecl *FD) {
8854 if (!FD->isExternallyVisible())
8855 return GVA_Internal;
8857 GVALinkage External;
8858 switch (FD->getTemplateSpecializationKind()) {
8859 case TSK_Undeclared:
8860 case TSK_ExplicitSpecialization:
8861 External = GVA_StrongExternal;
8864 case TSK_ExplicitInstantiationDefinition:
8865 return GVA_StrongODR;
8867 // C++11 [temp.explicit]p10:
8868 // [ Note: The intent is that an inline function that is the subject of
8869 // an explicit instantiation declaration will still be implicitly
8870 // instantiated when used so that the body can be considered for
8871 // inlining, but that no out-of-line copy of the inline function would be
8872 // generated in the translation unit. -- end note ]
8873 case TSK_ExplicitInstantiationDeclaration:
8874 return GVA_AvailableExternally;
8876 case TSK_ImplicitInstantiation:
8877 External = GVA_DiscardableODR;
8881 if (!FD->isInlined())
8884 if ((!Context.getLangOpts().CPlusPlus &&
8885 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8886 !FD->hasAttr<DLLExportAttr>()) ||
8887 FD->hasAttr<GNUInlineAttr>()) {
8888 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8890 // GNU or C99 inline semantics. Determine whether this symbol should be
8891 // externally visible.
8892 if (FD->isInlineDefinitionExternallyVisible())
8895 // C99 inline semantics, where the symbol is not externally visible.
8896 return GVA_AvailableExternally;
8899 // Functions specified with extern and inline in -fms-compatibility mode
8900 // forcibly get emitted. While the body of the function cannot be later
8901 // replaced, the function definition cannot be discarded.
8902 if (FD->isMSExternInline())
8903 return GVA_StrongODR;
8905 return GVA_DiscardableODR;
8908 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8909 GVALinkage L, const Decl *D) {
8910 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8911 // dllexport/dllimport on inline functions.
8912 if (D->hasAttr<DLLImportAttr>()) {
8913 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8914 return GVA_AvailableExternally;
8915 } else if (D->hasAttr<DLLExportAttr>()) {
8916 if (L == GVA_DiscardableODR)
8917 return GVA_StrongODR;
8918 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8919 D->hasAttr<CUDAGlobalAttr>()) {
8920 // Device-side functions with __global__ attribute must always be
8921 // visible externally so they can be launched from host.
8922 if (L == GVA_DiscardableODR || L == GVA_Internal)
8923 return GVA_StrongODR;
8928 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8929 auto L = adjustGVALinkageForAttributes(
8930 *this, basicGVALinkageForFunction(*this, FD), FD);
8931 auto EK = ExternalASTSource::EK_ReplyHazy;
8932 if (auto *Ext = getExternalSource())
8933 EK = Ext->hasExternalDefinitions(FD);
8935 case ExternalASTSource::EK_Never:
8936 if (L == GVA_DiscardableODR)
8937 return GVA_StrongODR;
8939 case ExternalASTSource::EK_Always:
8940 return GVA_AvailableExternally;
8941 case ExternalASTSource::EK_ReplyHazy:
8947 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8948 const VarDecl *VD) {
8949 if (!VD->isExternallyVisible())
8950 return GVA_Internal;
8952 if (VD->isStaticLocal()) {
8953 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8954 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8955 LexicalContext = LexicalContext->getLexicalParent();
8957 // ObjC Blocks can create local variables that don't have a FunctionDecl
8959 if (!LexicalContext)
8960 return GVA_DiscardableODR;
8962 // Otherwise, let the static local variable inherit its linkage from the
8963 // nearest enclosing function.
8964 auto StaticLocalLinkage =
8965 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8967 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8968 // be emitted in any object with references to the symbol for the object it
8969 // contains, whether inline or out-of-line."
8970 // Similar behavior is observed with MSVC. An alternative ABI could use
8971 // StrongODR/AvailableExternally to match the function, but none are
8972 // known/supported currently.
8973 if (StaticLocalLinkage == GVA_StrongODR ||
8974 StaticLocalLinkage == GVA_AvailableExternally)
8975 return GVA_DiscardableODR;
8976 return StaticLocalLinkage;
8979 // MSVC treats in-class initialized static data members as definitions.
8980 // By giving them non-strong linkage, out-of-line definitions won't
8981 // cause link errors.
8982 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8983 return GVA_DiscardableODR;
8985 // Most non-template variables have strong linkage; inline variables are
8986 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8987 GVALinkage StrongLinkage;
8988 switch (Context.getInlineVariableDefinitionKind(VD)) {
8989 case ASTContext::InlineVariableDefinitionKind::None:
8990 StrongLinkage = GVA_StrongExternal;
8992 case ASTContext::InlineVariableDefinitionKind::Weak:
8993 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8994 StrongLinkage = GVA_DiscardableODR;
8996 case ASTContext::InlineVariableDefinitionKind::Strong:
8997 StrongLinkage = GVA_StrongODR;
9001 switch (VD->getTemplateSpecializationKind()) {
9002 case TSK_Undeclared:
9003 return StrongLinkage;
9005 case TSK_ExplicitSpecialization:
9006 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9007 VD->isStaticDataMember()
9011 case TSK_ExplicitInstantiationDefinition:
9012 return GVA_StrongODR;
9014 case TSK_ExplicitInstantiationDeclaration:
9015 return GVA_AvailableExternally;
9017 case TSK_ImplicitInstantiation:
9018 return GVA_DiscardableODR;
9021 llvm_unreachable("Invalid Linkage!");
9024 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
9025 return adjustGVALinkageForAttributes(
9026 *this, basicGVALinkageForVariable(*this, VD), VD);
9029 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
9030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9031 if (!VD->isFileVarDecl())
9033 // Global named register variables (GNU extension) are never emitted.
9034 if (VD->getStorageClass() == SC_Register)
9036 if (VD->getDescribedVarTemplate() ||
9037 isa<VarTemplatePartialSpecializationDecl>(VD))
9039 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9040 // We never need to emit an uninstantiated function template.
9041 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9043 } else if (isa<PragmaCommentDecl>(D))
9045 else if (isa<OMPThreadPrivateDecl>(D) ||
9046 D->hasAttr<OMPDeclareTargetDeclAttr>())
9048 else if (isa<PragmaDetectMismatchDecl>(D))
9050 else if (isa<OMPThreadPrivateDecl>(D))
9051 return !D->getDeclContext()->isDependentContext();
9052 else if (isa<OMPDeclareReductionDecl>(D))
9053 return !D->getDeclContext()->isDependentContext();
9054 else if (isa<ImportDecl>(D))
9059 // If this is a member of a class template, we do not need to emit it.
9060 if (D->getDeclContext()->isDependentContext())
9063 // Weak references don't produce any output by themselves.
9064 if (D->hasAttr<WeakRefAttr>())
9067 // Aliases and used decls are required.
9068 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9071 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9072 // Forward declarations aren't required.
9073 if (!FD->doesThisDeclarationHaveABody())
9074 return FD->doesDeclarationForceExternallyVisibleDefinition();
9076 // Constructors and destructors are required.
9077 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9080 // The key function for a class is required. This rule only comes
9081 // into play when inline functions can be key functions, though.
9082 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9083 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9084 const CXXRecordDecl *RD = MD->getParent();
9085 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9086 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9087 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9093 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9095 // static, static inline, always_inline, and extern inline functions can
9096 // always be deferred. Normal inline functions can be deferred in C99/C++.
9097 // Implicit template instantiations can also be deferred in C++.
9098 return !isDiscardableGVALinkage(Linkage);
9101 const VarDecl *VD = cast<VarDecl>(D);
9102 assert(VD->isFileVarDecl() && "Expected file scoped var");
9104 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9105 !isMSStaticDataMemberInlineDefinition(VD))
9108 // Variables that can be needed in other TUs are required.
9109 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
9112 // Variables that have destruction with side-effects are required.
9113 if (VD->getType().isDestructedType())
9116 // Variables that have initialization with side-effects are required.
9117 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9118 // We can get a value-dependent initializer during error recovery.
9119 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9122 // Likewise, variables with tuple-like bindings are required if their
9123 // bindings have side-effects.
9124 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9125 for (auto *BD : DD->bindings())
9126 if (auto *BindingVD = BD->getHoldingVar())
9127 if (DeclMustBeEmitted(BindingVD))
9133 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9134 bool IsCXXMethod) const {
9135 // Pass through to the C++ ABI object
9137 return ABI->getDefaultMethodCallConv(IsVariadic);
9139 switch (LangOpts.getDefaultCallingConv()) {
9140 case LangOptions::DCC_None:
9142 case LangOptions::DCC_CDecl:
9144 case LangOptions::DCC_FastCall:
9145 if (getTargetInfo().hasFeature("sse2"))
9146 return CC_X86FastCall;
9148 case LangOptions::DCC_StdCall:
9150 return CC_X86StdCall;
9152 case LangOptions::DCC_VectorCall:
9153 // __vectorcall cannot be applied to variadic functions.
9155 return CC_X86VectorCall;
9158 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
9161 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
9162 // Pass through to the C++ ABI object
9163 return ABI->isNearlyEmpty(RD);
9166 VTableContextBase *ASTContext::getVTableContext() {
9167 if (!VTContext.get()) {
9168 if (Target->getCXXABI().isMicrosoft())
9169 VTContext.reset(new MicrosoftVTableContext(*this));
9171 VTContext.reset(new ItaniumVTableContext(*this));
9173 return VTContext.get();
9176 MangleContext *ASTContext::createMangleContext() {
9177 switch (Target->getCXXABI().getKind()) {
9178 case TargetCXXABI::GenericAArch64:
9179 case TargetCXXABI::GenericItanium:
9180 case TargetCXXABI::GenericARM:
9181 case TargetCXXABI::GenericMIPS:
9182 case TargetCXXABI::iOS:
9183 case TargetCXXABI::iOS64:
9184 case TargetCXXABI::WebAssembly:
9185 case TargetCXXABI::WatchOS:
9186 return ItaniumMangleContext::create(*this, getDiagnostics());
9187 case TargetCXXABI::Microsoft:
9188 return MicrosoftMangleContext::create(*this, getDiagnostics());
9190 llvm_unreachable("Unsupported ABI");
9193 CXXABI::~CXXABI() {}
9195 size_t ASTContext::getSideTableAllocatedMemory() const {
9196 return ASTRecordLayouts.getMemorySize() +
9197 llvm::capacity_in_bytes(ObjCLayouts) +
9198 llvm::capacity_in_bytes(KeyFunctions) +
9199 llvm::capacity_in_bytes(ObjCImpls) +
9200 llvm::capacity_in_bytes(BlockVarCopyInits) +
9201 llvm::capacity_in_bytes(DeclAttrs) +
9202 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9203 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9204 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9205 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9206 llvm::capacity_in_bytes(OverriddenMethods) +
9207 llvm::capacity_in_bytes(Types) +
9208 llvm::capacity_in_bytes(VariableArrayTypes) +
9209 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
9212 /// getIntTypeForBitwidth -
9213 /// sets integer QualTy according to specified details:
9214 /// bitwidth, signed/unsigned.
9215 /// Returns empty type if there is no appropriate target types.
9216 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9217 unsigned Signed) const {
9218 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9219 CanQualType QualTy = getFromTargetType(Ty);
9220 if (!QualTy && DestWidth == 128)
9221 return Signed ? Int128Ty : UnsignedInt128Ty;
9225 /// getRealTypeForBitwidth -
9226 /// sets floating point QualTy according to specified bitwidth.
9227 /// Returns empty type if there is no appropriate target types.
9228 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9229 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9231 case TargetInfo::Float:
9233 case TargetInfo::Double:
9235 case TargetInfo::LongDouble:
9236 return LongDoubleTy;
9237 case TargetInfo::Float128:
9239 case TargetInfo::NoFloat:
9243 llvm_unreachable("Unhandled TargetInfo::RealType value");
9246 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9248 MangleNumbers[ND] = Number;
9251 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
9252 auto I = MangleNumbers.find(ND);
9253 return I != MangleNumbers.end() ? I->second : 1;
9256 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9258 StaticLocalNumbers[VD] = Number;
9261 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
9262 auto I = StaticLocalNumbers.find(VD);
9263 return I != StaticLocalNumbers.end() ? I->second : 1;
9266 MangleNumberingContext &
9267 ASTContext::getManglingNumberContext(const DeclContext *DC) {
9268 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
9269 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
9271 MCtx = createMangleNumberingContext();
9275 std::unique_ptr<MangleNumberingContext>
9276 ASTContext::createMangleNumberingContext() const {
9277 return ABI->createMangleNumberingContext();
9280 const CXXConstructorDecl *
9281 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9282 return ABI->getCopyConstructorForExceptionObject(
9283 cast<CXXRecordDecl>(RD->getFirstDecl()));
9286 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9287 CXXConstructorDecl *CD) {
9288 return ABI->addCopyConstructorForExceptionObject(
9289 cast<CXXRecordDecl>(RD->getFirstDecl()),
9290 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9293 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9294 TypedefNameDecl *DD) {
9295 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9299 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9300 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9303 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9304 DeclaratorDecl *DD) {
9305 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9308 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9309 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9312 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9313 ParamIndices[D] = index;
9316 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9317 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9318 assert(I != ParamIndices.end() &&
9319 "ParmIndices lacks entry set by ParmVarDecl");
9324 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9326 assert(E && E->getStorageDuration() == SD_Static &&
9327 "don't need to cache the computed value for this temporary");
9329 APValue *&MTVI = MaterializedTemporaryValues[E];
9331 MTVI = new (*this) APValue;
9335 return MaterializedTemporaryValues.lookup(E);
9338 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9339 const llvm::Triple &T = getTargetInfo().getTriple();
9340 if (!T.isOSDarwin())
9343 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9344 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9347 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9348 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9349 uint64_t Size = sizeChars.getQuantity();
9350 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9351 unsigned Align = alignChars.getQuantity();
9352 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9353 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9358 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9359 ASTContext::ParentMapPointers::mapped_type U) {
9360 if (const auto *D = U.dyn_cast<const Decl *>())
9361 return ast_type_traits::DynTypedNode::create(*D);
9362 if (const auto *S = U.dyn_cast<const Stmt *>())
9363 return ast_type_traits::DynTypedNode::create(*S);
9364 return *U.get<ast_type_traits::DynTypedNode *>();
9367 /// Template specializations to abstract away from pointers and TypeLocs.
9369 template <typename T>
9370 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9371 return ast_type_traits::DynTypedNode::create(*Node);
9374 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9375 return ast_type_traits::DynTypedNode::create(Node);
9378 ast_type_traits::DynTypedNode
9379 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9380 return ast_type_traits::DynTypedNode::create(Node);
9384 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9385 /// parents as defined by the \c RecursiveASTVisitor.
9387 /// Note that the relationship described here is purely in terms of AST
9388 /// traversal - there are other relationships (for example declaration context)
9389 /// in the AST that are better modeled by special matchers.
9391 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
9392 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
9394 /// \brief Builds and returns the translation unit's parent map.
9396 /// The caller takes ownership of the returned \c ParentMap.
9397 static std::pair<ASTContext::ParentMapPointers *,
9398 ASTContext::ParentMapOtherNodes *>
9399 buildMap(TranslationUnitDecl &TU) {
9400 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9401 new ASTContext::ParentMapOtherNodes);
9402 Visitor.TraverseDecl(&TU);
9403 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
9407 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9409 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9410 ASTContext::ParentMapOtherNodes *OtherParents)
9411 : Parents(Parents), OtherParents(OtherParents) {}
9413 bool shouldVisitTemplateInstantiations() const {
9416 bool shouldVisitImplicitCode() const {
9420 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9422 bool TraverseNode(T Node, MapNodeTy MapNode,
9423 BaseTraverseFn BaseTraverse, MapTy *Parents) {
9426 if (ParentStack.size() > 0) {
9427 // FIXME: Currently we add the same parent multiple times, but only
9428 // when no memoization data is available for the type.
9429 // For example when we visit all subexpressions of template
9430 // instantiations; this is suboptimal, but benign: the only way to
9431 // visit those is with hasAncestor / hasParent, and those do not create
9433 // The plan is to enable DynTypedNode to be storable in a map or hash
9434 // map. The main problem there is to implement hash functions /
9435 // comparison operators for all types that DynTypedNode supports that
9436 // do not have pointer identity.
9437 auto &NodeOrVector = (*Parents)[MapNode];
9438 if (NodeOrVector.isNull()) {
9439 if (const auto *D = ParentStack.back().get<Decl>())
9441 else if (const auto *S = ParentStack.back().get<Stmt>())
9445 new ast_type_traits::DynTypedNode(ParentStack.back());
9447 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9448 auto *Vector = new ASTContext::ParentVector(
9449 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
9451 .template dyn_cast<ast_type_traits::DynTypedNode *>();
9452 NodeOrVector = Vector;
9456 NodeOrVector.template get<ASTContext::ParentVector *>();
9457 // Skip duplicates for types that have memoization data.
9458 // We must check that the type has memoization data before calling
9459 // std::find() because DynTypedNode::operator== can't compare all
9461 bool Found = ParentStack.back().getMemoizationData() &&
9462 std::find(Vector->begin(), Vector->end(),
9463 ParentStack.back()) != Vector->end();
9465 Vector->push_back(ParentStack.back());
9468 ParentStack.push_back(createDynTypedNode(Node));
9469 bool Result = BaseTraverse();
9470 ParentStack.pop_back();
9474 bool TraverseDecl(Decl *DeclNode) {
9475 return TraverseNode(DeclNode, DeclNode,
9476 [&] { return VisitorBase::TraverseDecl(DeclNode); },
9480 bool TraverseStmt(Stmt *StmtNode) {
9481 return TraverseNode(StmtNode, StmtNode,
9482 [&] { return VisitorBase::TraverseStmt(StmtNode); },
9486 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9487 return TraverseNode(
9488 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9489 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9493 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9494 return TraverseNode(
9495 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9497 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9502 ASTContext::ParentMapPointers *Parents;
9503 ASTContext::ParentMapOtherNodes *OtherParents;
9504 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9506 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9509 } // anonymous namespace
9511 template <typename NodeTy, typename MapTy>
9512 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9514 auto I = Map.find(Node);
9515 if (I == Map.end()) {
9516 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9518 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9519 return llvm::makeArrayRef(*V);
9521 return getSingleDynTypedNodeFromParentMap(I->second);
9524 ASTContext::DynTypedNodeList
9525 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9526 if (!PointerParents) {
9527 // We always need to run over the whole translation unit, as
9528 // hasAncestor can escape any subtree.
9529 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9530 PointerParents.reset(Maps.first);
9531 OtherParents.reset(Maps.second);
9533 if (Node.getNodeKind().hasPointerIdentity())
9534 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9535 return getDynNodeFromMap(Node, *OtherParents);
9539 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9540 const ObjCMethodDecl *MethodImpl) {
9541 // No point trying to match an unavailable/deprecated mothod.
9542 if (MethodDecl->hasAttr<UnavailableAttr>()
9543 || MethodDecl->hasAttr<DeprecatedAttr>())
9545 if (MethodDecl->getObjCDeclQualifier() !=
9546 MethodImpl->getObjCDeclQualifier())
9548 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9551 if (MethodDecl->param_size() != MethodImpl->param_size())
9554 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9555 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9556 EF = MethodDecl->param_end();
9557 IM != EM && IF != EF; ++IM, ++IF) {
9558 const ParmVarDecl *DeclVar = (*IF);
9559 const ParmVarDecl *ImplVar = (*IM);
9560 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9562 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9565 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9569 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9571 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9574 AS = QT->getPointeeType().getAddressSpace();
9576 return getTargetInfo().getNullPointerValue(AS);
9579 unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
9580 if (AS >= LangAS::FirstTargetAddressSpace)
9581 return AS - LangAS::FirstTargetAddressSpace;
9583 return (*AddrSpaceMap)[AS];
9586 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9587 // doesn't include ASTContext.h
9589 clang::LazyGenerationalUpdatePtr<
9590 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9591 clang::LazyGenerationalUpdatePtr<
9592 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9593 const clang::ASTContext &Ctx, Decl *Value);