xref: /aosp_15_r20/external/clang/lib/AST/ASTContext.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements the ASTContext interface.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/AST/ASTContext.h"
15*67e74705SXin Li #include "CXXABI.h"
16*67e74705SXin Li #include "clang/AST/ASTMutationListener.h"
17*67e74705SXin Li #include "clang/AST/Attr.h"
18*67e74705SXin Li #include "clang/AST/CharUnits.h"
19*67e74705SXin Li #include "clang/AST/Comment.h"
20*67e74705SXin Li #include "clang/AST/CommentCommandTraits.h"
21*67e74705SXin Li #include "clang/AST/DeclCXX.h"
22*67e74705SXin Li #include "clang/AST/DeclContextInternals.h"
23*67e74705SXin Li #include "clang/AST/DeclObjC.h"
24*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
25*67e74705SXin Li #include "clang/AST/Expr.h"
26*67e74705SXin Li #include "clang/AST/ExprCXX.h"
27*67e74705SXin Li #include "clang/AST/ExternalASTSource.h"
28*67e74705SXin Li #include "clang/AST/Mangle.h"
29*67e74705SXin Li #include "clang/AST/MangleNumberingContext.h"
30*67e74705SXin Li #include "clang/AST/RecordLayout.h"
31*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
32*67e74705SXin Li #include "clang/AST/TypeLoc.h"
33*67e74705SXin Li #include "clang/AST/VTableBuilder.h"
34*67e74705SXin Li #include "clang/Basic/Builtins.h"
35*67e74705SXin Li #include "clang/Basic/SourceManager.h"
36*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
37*67e74705SXin Li #include "llvm/ADT/SmallString.h"
38*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
39*67e74705SXin Li #include "llvm/ADT/Triple.h"
40*67e74705SXin Li #include "llvm/Support/Capacity.h"
41*67e74705SXin Li #include "llvm/Support/MathExtras.h"
42*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
43*67e74705SXin Li #include <map>
44*67e74705SXin Li 
45*67e74705SXin Li using namespace clang;
46*67e74705SXin Li 
47*67e74705SXin Li unsigned ASTContext::NumImplicitDefaultConstructors;
48*67e74705SXin Li unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
49*67e74705SXin Li unsigned ASTContext::NumImplicitCopyConstructors;
50*67e74705SXin Li unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
51*67e74705SXin Li unsigned ASTContext::NumImplicitMoveConstructors;
52*67e74705SXin Li unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
53*67e74705SXin Li unsigned ASTContext::NumImplicitCopyAssignmentOperators;
54*67e74705SXin Li unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
55*67e74705SXin Li unsigned ASTContext::NumImplicitMoveAssignmentOperators;
56*67e74705SXin Li unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
57*67e74705SXin Li unsigned ASTContext::NumImplicitDestructors;
58*67e74705SXin Li unsigned ASTContext::NumImplicitDestructorsDeclared;
59*67e74705SXin Li 
60*67e74705SXin Li enum FloatingRank {
61*67e74705SXin Li   HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
62*67e74705SXin Li };
63*67e74705SXin Li 
getRawCommentForDeclNoCache(const Decl * D) const64*67e74705SXin Li RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
65*67e74705SXin Li   if (!CommentsLoaded && ExternalSource) {
66*67e74705SXin Li     ExternalSource->ReadComments();
67*67e74705SXin Li 
68*67e74705SXin Li #ifndef NDEBUG
69*67e74705SXin Li     ArrayRef<RawComment *> RawComments = Comments.getComments();
70*67e74705SXin Li     assert(std::is_sorted(RawComments.begin(), RawComments.end(),
71*67e74705SXin Li                           BeforeThanCompare<RawComment>(SourceMgr)));
72*67e74705SXin Li #endif
73*67e74705SXin Li 
74*67e74705SXin Li     CommentsLoaded = true;
75*67e74705SXin Li   }
76*67e74705SXin Li 
77*67e74705SXin Li   assert(D);
78*67e74705SXin Li 
79*67e74705SXin Li   // User can not attach documentation to implicit declarations.
80*67e74705SXin Li   if (D->isImplicit())
81*67e74705SXin Li     return nullptr;
82*67e74705SXin Li 
83*67e74705SXin Li   // User can not attach documentation to implicit instantiations.
84*67e74705SXin Li   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85*67e74705SXin Li     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86*67e74705SXin Li       return nullptr;
87*67e74705SXin Li   }
88*67e74705SXin Li 
89*67e74705SXin Li   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
90*67e74705SXin Li     if (VD->isStaticDataMember() &&
91*67e74705SXin Li         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
92*67e74705SXin Li       return nullptr;
93*67e74705SXin Li   }
94*67e74705SXin Li 
95*67e74705SXin Li   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
96*67e74705SXin Li     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
97*67e74705SXin Li       return nullptr;
98*67e74705SXin Li   }
99*67e74705SXin Li 
100*67e74705SXin Li   if (const ClassTemplateSpecializationDecl *CTSD =
101*67e74705SXin Li           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
102*67e74705SXin Li     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
103*67e74705SXin Li     if (TSK == TSK_ImplicitInstantiation ||
104*67e74705SXin Li         TSK == TSK_Undeclared)
105*67e74705SXin Li       return nullptr;
106*67e74705SXin Li   }
107*67e74705SXin Li 
108*67e74705SXin Li   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
109*67e74705SXin Li     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
110*67e74705SXin Li       return nullptr;
111*67e74705SXin Li   }
112*67e74705SXin Li   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
113*67e74705SXin Li     // When tag declaration (but not definition!) is part of the
114*67e74705SXin Li     // decl-specifier-seq of some other declaration, it doesn't get comment
115*67e74705SXin Li     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
116*67e74705SXin Li       return nullptr;
117*67e74705SXin Li   }
118*67e74705SXin Li   // TODO: handle comments for function parameters properly.
119*67e74705SXin Li   if (isa<ParmVarDecl>(D))
120*67e74705SXin Li     return nullptr;
121*67e74705SXin Li 
122*67e74705SXin Li   // TODO: we could look up template parameter documentation in the template
123*67e74705SXin Li   // documentation.
124*67e74705SXin Li   if (isa<TemplateTypeParmDecl>(D) ||
125*67e74705SXin Li       isa<NonTypeTemplateParmDecl>(D) ||
126*67e74705SXin Li       isa<TemplateTemplateParmDecl>(D))
127*67e74705SXin Li     return nullptr;
128*67e74705SXin Li 
129*67e74705SXin Li   ArrayRef<RawComment *> RawComments = Comments.getComments();
130*67e74705SXin Li 
131*67e74705SXin Li   // If there are no comments anywhere, we won't find anything.
132*67e74705SXin Li   if (RawComments.empty())
133*67e74705SXin Li     return nullptr;
134*67e74705SXin Li 
135*67e74705SXin Li   // Find declaration location.
136*67e74705SXin Li   // For Objective-C declarations we generally don't expect to have multiple
137*67e74705SXin Li   // declarators, thus use declaration starting location as the "declaration
138*67e74705SXin Li   // location".
139*67e74705SXin Li   // For all other declarations multiple declarators are used quite frequently,
140*67e74705SXin Li   // so we use the location of the identifier as the "declaration location".
141*67e74705SXin Li   SourceLocation DeclLoc;
142*67e74705SXin Li   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
143*67e74705SXin Li       isa<ObjCPropertyDecl>(D) ||
144*67e74705SXin Li       isa<RedeclarableTemplateDecl>(D) ||
145*67e74705SXin Li       isa<ClassTemplateSpecializationDecl>(D))
146*67e74705SXin Li     DeclLoc = D->getLocStart();
147*67e74705SXin Li   else {
148*67e74705SXin Li     DeclLoc = D->getLocation();
149*67e74705SXin Li     if (DeclLoc.isMacroID()) {
150*67e74705SXin Li       if (isa<TypedefDecl>(D)) {
151*67e74705SXin Li         // If location of the typedef name is in a macro, it is because being
152*67e74705SXin Li         // declared via a macro. Try using declaration's starting location as
153*67e74705SXin Li         // the "declaration location".
154*67e74705SXin Li         DeclLoc = D->getLocStart();
155*67e74705SXin Li       } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
156*67e74705SXin Li         // If location of the tag decl is inside a macro, but the spelling of
157*67e74705SXin Li         // the tag name comes from a macro argument, it looks like a special
158*67e74705SXin Li         // macro like NS_ENUM is being used to define the tag decl.  In that
159*67e74705SXin Li         // case, adjust the source location to the expansion loc so that we can
160*67e74705SXin Li         // attach the comment to the tag decl.
161*67e74705SXin Li         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
162*67e74705SXin Li             TD->isCompleteDefinition())
163*67e74705SXin Li           DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
164*67e74705SXin Li       }
165*67e74705SXin Li     }
166*67e74705SXin Li   }
167*67e74705SXin Li 
168*67e74705SXin Li   // If the declaration doesn't map directly to a location in a file, we
169*67e74705SXin Li   // can't find the comment.
170*67e74705SXin Li   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
171*67e74705SXin Li     return nullptr;
172*67e74705SXin Li 
173*67e74705SXin Li   // Find the comment that occurs just after this declaration.
174*67e74705SXin Li   ArrayRef<RawComment *>::iterator Comment;
175*67e74705SXin Li   {
176*67e74705SXin Li     // When searching for comments during parsing, the comment we are looking
177*67e74705SXin Li     // for is usually among the last two comments we parsed -- check them
178*67e74705SXin Li     // first.
179*67e74705SXin Li     RawComment CommentAtDeclLoc(
180*67e74705SXin Li         SourceMgr, SourceRange(DeclLoc), false,
181*67e74705SXin Li         LangOpts.CommentOpts.ParseAllComments);
182*67e74705SXin Li     BeforeThanCompare<RawComment> Compare(SourceMgr);
183*67e74705SXin Li     ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
184*67e74705SXin Li     bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
185*67e74705SXin Li     if (!Found && RawComments.size() >= 2) {
186*67e74705SXin Li       MaybeBeforeDecl--;
187*67e74705SXin Li       Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
188*67e74705SXin Li     }
189*67e74705SXin Li 
190*67e74705SXin Li     if (Found) {
191*67e74705SXin Li       Comment = MaybeBeforeDecl + 1;
192*67e74705SXin Li       assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
193*67e74705SXin Li                                          &CommentAtDeclLoc, Compare));
194*67e74705SXin Li     } else {
195*67e74705SXin Li       // Slow path.
196*67e74705SXin Li       Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
197*67e74705SXin Li                                  &CommentAtDeclLoc, Compare);
198*67e74705SXin Li     }
199*67e74705SXin Li   }
200*67e74705SXin Li 
201*67e74705SXin Li   // Decompose the location for the declaration and find the beginning of the
202*67e74705SXin Li   // file buffer.
203*67e74705SXin Li   std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204*67e74705SXin Li 
205*67e74705SXin Li   // First check whether we have a trailing comment.
206*67e74705SXin Li   if (Comment != RawComments.end() &&
207*67e74705SXin Li       (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
208*67e74705SXin Li       (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
209*67e74705SXin Li        isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
210*67e74705SXin Li     std::pair<FileID, unsigned> CommentBeginDecomp
211*67e74705SXin Li       = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
212*67e74705SXin Li     // Check that Doxygen trailing comment comes after the declaration, starts
213*67e74705SXin Li     // on the same line and in the same file as the declaration.
214*67e74705SXin Li     if (DeclLocDecomp.first == CommentBeginDecomp.first &&
215*67e74705SXin Li         SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
216*67e74705SXin Li           == SourceMgr.getLineNumber(CommentBeginDecomp.first,
217*67e74705SXin Li                                      CommentBeginDecomp.second)) {
218*67e74705SXin Li       return *Comment;
219*67e74705SXin Li     }
220*67e74705SXin Li   }
221*67e74705SXin Li 
222*67e74705SXin Li   // The comment just after the declaration was not a trailing comment.
223*67e74705SXin Li   // Let's look at the previous comment.
224*67e74705SXin Li   if (Comment == RawComments.begin())
225*67e74705SXin Li     return nullptr;
226*67e74705SXin Li   --Comment;
227*67e74705SXin Li 
228*67e74705SXin Li   // Check that we actually have a non-member Doxygen comment.
229*67e74705SXin Li   if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
230*67e74705SXin Li     return nullptr;
231*67e74705SXin Li 
232*67e74705SXin Li   // Decompose the end of the comment.
233*67e74705SXin Li   std::pair<FileID, unsigned> CommentEndDecomp
234*67e74705SXin Li     = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
235*67e74705SXin Li 
236*67e74705SXin Li   // If the comment and the declaration aren't in the same file, then they
237*67e74705SXin Li   // aren't related.
238*67e74705SXin Li   if (DeclLocDecomp.first != CommentEndDecomp.first)
239*67e74705SXin Li     return nullptr;
240*67e74705SXin Li 
241*67e74705SXin Li   // Get the corresponding buffer.
242*67e74705SXin Li   bool Invalid = false;
243*67e74705SXin Li   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
244*67e74705SXin Li                                                &Invalid).data();
245*67e74705SXin Li   if (Invalid)
246*67e74705SXin Li     return nullptr;
247*67e74705SXin Li 
248*67e74705SXin Li   // Extract text between the comment and declaration.
249*67e74705SXin Li   StringRef Text(Buffer + CommentEndDecomp.second,
250*67e74705SXin Li                  DeclLocDecomp.second - CommentEndDecomp.second);
251*67e74705SXin Li 
252*67e74705SXin Li   // There should be no other declarations or preprocessor directives between
253*67e74705SXin Li   // comment and declaration.
254*67e74705SXin Li   if (Text.find_first_of(";{}#@") != StringRef::npos)
255*67e74705SXin Li     return nullptr;
256*67e74705SXin Li 
257*67e74705SXin Li   return *Comment;
258*67e74705SXin Li }
259*67e74705SXin Li 
260*67e74705SXin Li namespace {
261*67e74705SXin Li /// If we have a 'templated' declaration for a template, adjust 'D' to
262*67e74705SXin Li /// refer to the actual template.
263*67e74705SXin Li /// If we have an implicit instantiation, adjust 'D' to refer to template.
adjustDeclToTemplate(const Decl * D)264*67e74705SXin Li const Decl *adjustDeclToTemplate(const Decl *D) {
265*67e74705SXin Li   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266*67e74705SXin Li     // Is this function declaration part of a function template?
267*67e74705SXin Li     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
268*67e74705SXin Li       return FTD;
269*67e74705SXin Li 
270*67e74705SXin Li     // Nothing to do if function is not an implicit instantiation.
271*67e74705SXin Li     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
272*67e74705SXin Li       return D;
273*67e74705SXin Li 
274*67e74705SXin Li     // Function is an implicit instantiation of a function template?
275*67e74705SXin Li     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
276*67e74705SXin Li       return FTD;
277*67e74705SXin Li 
278*67e74705SXin Li     // Function is instantiated from a member definition of a class template?
279*67e74705SXin Li     if (const FunctionDecl *MemberDecl =
280*67e74705SXin Li             FD->getInstantiatedFromMemberFunction())
281*67e74705SXin Li       return MemberDecl;
282*67e74705SXin Li 
283*67e74705SXin Li     return D;
284*67e74705SXin Li   }
285*67e74705SXin Li   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
286*67e74705SXin Li     // Static data member is instantiated from a member definition of a class
287*67e74705SXin Li     // template?
288*67e74705SXin Li     if (VD->isStaticDataMember())
289*67e74705SXin Li       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
290*67e74705SXin Li         return MemberDecl;
291*67e74705SXin Li 
292*67e74705SXin Li     return D;
293*67e74705SXin Li   }
294*67e74705SXin Li   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
295*67e74705SXin Li     // Is this class declaration part of a class template?
296*67e74705SXin Li     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
297*67e74705SXin Li       return CTD;
298*67e74705SXin Li 
299*67e74705SXin Li     // Class is an implicit instantiation of a class template or partial
300*67e74705SXin Li     // specialization?
301*67e74705SXin Li     if (const ClassTemplateSpecializationDecl *CTSD =
302*67e74705SXin Li             dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
303*67e74705SXin Li       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304*67e74705SXin Li         return D;
305*67e74705SXin Li       llvm::PointerUnion<ClassTemplateDecl *,
306*67e74705SXin Li                          ClassTemplatePartialSpecializationDecl *>
307*67e74705SXin Li           PU = CTSD->getSpecializedTemplateOrPartial();
308*67e74705SXin Li       return PU.is<ClassTemplateDecl*>() ?
309*67e74705SXin Li           static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
310*67e74705SXin Li           static_cast<const Decl*>(
311*67e74705SXin Li               PU.get<ClassTemplatePartialSpecializationDecl *>());
312*67e74705SXin Li     }
313*67e74705SXin Li 
314*67e74705SXin Li     // Class is instantiated from a member definition of a class template?
315*67e74705SXin Li     if (const MemberSpecializationInfo *Info =
316*67e74705SXin Li                    CRD->getMemberSpecializationInfo())
317*67e74705SXin Li       return Info->getInstantiatedFrom();
318*67e74705SXin Li 
319*67e74705SXin Li     return D;
320*67e74705SXin Li   }
321*67e74705SXin Li   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
322*67e74705SXin Li     // Enum is instantiated from a member definition of a class template?
323*67e74705SXin Li     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
324*67e74705SXin Li       return MemberDecl;
325*67e74705SXin Li 
326*67e74705SXin Li     return D;
327*67e74705SXin Li   }
328*67e74705SXin Li   // FIXME: Adjust alias templates?
329*67e74705SXin Li   return D;
330*67e74705SXin Li }
331*67e74705SXin Li } // anonymous namespace
332*67e74705SXin Li 
getRawCommentForAnyRedecl(const Decl * D,const Decl ** OriginalDecl) const333*67e74705SXin Li const RawComment *ASTContext::getRawCommentForAnyRedecl(
334*67e74705SXin Li                                                 const Decl *D,
335*67e74705SXin Li                                                 const Decl **OriginalDecl) const {
336*67e74705SXin Li   D = adjustDeclToTemplate(D);
337*67e74705SXin Li 
338*67e74705SXin Li   // Check whether we have cached a comment for this declaration already.
339*67e74705SXin Li   {
340*67e74705SXin Li     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
341*67e74705SXin Li         RedeclComments.find(D);
342*67e74705SXin Li     if (Pos != RedeclComments.end()) {
343*67e74705SXin Li       const RawCommentAndCacheFlags &Raw = Pos->second;
344*67e74705SXin Li       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345*67e74705SXin Li         if (OriginalDecl)
346*67e74705SXin Li           *OriginalDecl = Raw.getOriginalDecl();
347*67e74705SXin Li         return Raw.getRaw();
348*67e74705SXin Li       }
349*67e74705SXin Li     }
350*67e74705SXin Li   }
351*67e74705SXin Li 
352*67e74705SXin Li   // Search for comments attached to declarations in the redeclaration chain.
353*67e74705SXin Li   const RawComment *RC = nullptr;
354*67e74705SXin Li   const Decl *OriginalDeclForRC = nullptr;
355*67e74705SXin Li   for (auto I : D->redecls()) {
356*67e74705SXin Li     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
357*67e74705SXin Li         RedeclComments.find(I);
358*67e74705SXin Li     if (Pos != RedeclComments.end()) {
359*67e74705SXin Li       const RawCommentAndCacheFlags &Raw = Pos->second;
360*67e74705SXin Li       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361*67e74705SXin Li         RC = Raw.getRaw();
362*67e74705SXin Li         OriginalDeclForRC = Raw.getOriginalDecl();
363*67e74705SXin Li         break;
364*67e74705SXin Li       }
365*67e74705SXin Li     } else {
366*67e74705SXin Li       RC = getRawCommentForDeclNoCache(I);
367*67e74705SXin Li       OriginalDeclForRC = I;
368*67e74705SXin Li       RawCommentAndCacheFlags Raw;
369*67e74705SXin Li       if (RC) {
370*67e74705SXin Li         // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
371*67e74705SXin Li         // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
372*67e74705SXin Li         Raw.setKind(RawCommentAndCacheFlags::FromDecl);
373*67e74705SXin Li         Raw.setRaw(RC);
374*67e74705SXin Li       } else
375*67e74705SXin Li         Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
376*67e74705SXin Li       Raw.setOriginalDecl(I);
377*67e74705SXin Li       RedeclComments[I] = Raw;
378*67e74705SXin Li       if (RC)
379*67e74705SXin Li         break;
380*67e74705SXin Li     }
381*67e74705SXin Li   }
382*67e74705SXin Li 
383*67e74705SXin Li   // If we found a comment, it should be a documentation comment.
384*67e74705SXin Li   assert(!RC || RC->isDocumentation());
385*67e74705SXin Li 
386*67e74705SXin Li   if (OriginalDecl)
387*67e74705SXin Li     *OriginalDecl = OriginalDeclForRC;
388*67e74705SXin Li 
389*67e74705SXin Li   // Update cache for every declaration in the redeclaration chain.
390*67e74705SXin Li   RawCommentAndCacheFlags Raw;
391*67e74705SXin Li   Raw.setRaw(RC);
392*67e74705SXin Li   Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
393*67e74705SXin Li   Raw.setOriginalDecl(OriginalDeclForRC);
394*67e74705SXin Li 
395*67e74705SXin Li   for (auto I : D->redecls()) {
396*67e74705SXin Li     RawCommentAndCacheFlags &R = RedeclComments[I];
397*67e74705SXin Li     if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
398*67e74705SXin Li       R = Raw;
399*67e74705SXin Li   }
400*67e74705SXin Li 
401*67e74705SXin Li   return RC;
402*67e74705SXin Li }
403*67e74705SXin Li 
addRedeclaredMethods(const ObjCMethodDecl * ObjCMethod,SmallVectorImpl<const NamedDecl * > & Redeclared)404*67e74705SXin Li static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
405*67e74705SXin Li                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
406*67e74705SXin Li   const DeclContext *DC = ObjCMethod->getDeclContext();
407*67e74705SXin Li   if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
408*67e74705SXin Li     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
409*67e74705SXin Li     if (!ID)
410*67e74705SXin Li       return;
411*67e74705SXin Li     // Add redeclared method here.
412*67e74705SXin Li     for (const auto *Ext : ID->known_extensions()) {
413*67e74705SXin Li       if (ObjCMethodDecl *RedeclaredMethod =
414*67e74705SXin Li             Ext->getMethod(ObjCMethod->getSelector(),
415*67e74705SXin Li                                   ObjCMethod->isInstanceMethod()))
416*67e74705SXin Li         Redeclared.push_back(RedeclaredMethod);
417*67e74705SXin Li     }
418*67e74705SXin Li   }
419*67e74705SXin Li }
420*67e74705SXin Li 
cloneFullComment(comments::FullComment * FC,const Decl * D) const421*67e74705SXin Li comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
422*67e74705SXin Li                                                     const Decl *D) const {
423*67e74705SXin Li   comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
424*67e74705SXin Li   ThisDeclInfo->CommentDecl = D;
425*67e74705SXin Li   ThisDeclInfo->IsFilled = false;
426*67e74705SXin Li   ThisDeclInfo->fill();
427*67e74705SXin Li   ThisDeclInfo->CommentDecl = FC->getDecl();
428*67e74705SXin Li   if (!ThisDeclInfo->TemplateParameters)
429*67e74705SXin Li     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
430*67e74705SXin Li   comments::FullComment *CFC =
431*67e74705SXin Li     new (*this) comments::FullComment(FC->getBlocks(),
432*67e74705SXin Li                                       ThisDeclInfo);
433*67e74705SXin Li   return CFC;
434*67e74705SXin Li }
435*67e74705SXin Li 
getLocalCommentForDeclUncached(const Decl * D) const436*67e74705SXin Li comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437*67e74705SXin Li   const RawComment *RC = getRawCommentForDeclNoCache(D);
438*67e74705SXin Li   return RC ? RC->parse(*this, nullptr, D) : nullptr;
439*67e74705SXin Li }
440*67e74705SXin Li 
getCommentForDecl(const Decl * D,const Preprocessor * PP) const441*67e74705SXin Li comments::FullComment *ASTContext::getCommentForDecl(
442*67e74705SXin Li                                               const Decl *D,
443*67e74705SXin Li                                               const Preprocessor *PP) const {
444*67e74705SXin Li   if (D->isInvalidDecl())
445*67e74705SXin Li     return nullptr;
446*67e74705SXin Li   D = adjustDeclToTemplate(D);
447*67e74705SXin Li 
448*67e74705SXin Li   const Decl *Canonical = D->getCanonicalDecl();
449*67e74705SXin Li   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450*67e74705SXin Li       ParsedComments.find(Canonical);
451*67e74705SXin Li 
452*67e74705SXin Li   if (Pos != ParsedComments.end()) {
453*67e74705SXin Li     if (Canonical != D) {
454*67e74705SXin Li       comments::FullComment *FC = Pos->second;
455*67e74705SXin Li       comments::FullComment *CFC = cloneFullComment(FC, D);
456*67e74705SXin Li       return CFC;
457*67e74705SXin Li     }
458*67e74705SXin Li     return Pos->second;
459*67e74705SXin Li   }
460*67e74705SXin Li 
461*67e74705SXin Li   const Decl *OriginalDecl;
462*67e74705SXin Li 
463*67e74705SXin Li   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
464*67e74705SXin Li   if (!RC) {
465*67e74705SXin Li     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
466*67e74705SXin Li       SmallVector<const NamedDecl*, 8> Overridden;
467*67e74705SXin Li       const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
468*67e74705SXin Li       if (OMD && OMD->isPropertyAccessor())
469*67e74705SXin Li         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470*67e74705SXin Li           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471*67e74705SXin Li             return cloneFullComment(FC, D);
472*67e74705SXin Li       if (OMD)
473*67e74705SXin Li         addRedeclaredMethods(OMD, Overridden);
474*67e74705SXin Li       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
475*67e74705SXin Li       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476*67e74705SXin Li         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477*67e74705SXin Li           return cloneFullComment(FC, D);
478*67e74705SXin Li     }
479*67e74705SXin Li     else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
480*67e74705SXin Li       // Attach any tag type's documentation to its typedef if latter
481*67e74705SXin Li       // does not have one of its own.
482*67e74705SXin Li       QualType QT = TD->getUnderlyingType();
483*67e74705SXin Li       if (const TagType *TT = QT->getAs<TagType>())
484*67e74705SXin Li         if (const Decl *TD = TT->getDecl())
485*67e74705SXin Li           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
486*67e74705SXin Li             return cloneFullComment(FC, D);
487*67e74705SXin Li     }
488*67e74705SXin Li     else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489*67e74705SXin Li       while (IC->getSuperClass()) {
490*67e74705SXin Li         IC = IC->getSuperClass();
491*67e74705SXin Li         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492*67e74705SXin Li           return cloneFullComment(FC, D);
493*67e74705SXin Li       }
494*67e74705SXin Li     }
495*67e74705SXin Li     else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496*67e74705SXin Li       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497*67e74705SXin Li         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498*67e74705SXin Li           return cloneFullComment(FC, D);
499*67e74705SXin Li     }
500*67e74705SXin Li     else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501*67e74705SXin Li       if (!(RD = RD->getDefinition()))
502*67e74705SXin Li         return nullptr;
503*67e74705SXin Li       // Check non-virtual bases.
504*67e74705SXin Li       for (const auto &I : RD->bases()) {
505*67e74705SXin Li         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
506*67e74705SXin Li           continue;
507*67e74705SXin Li         QualType Ty = I.getType();
508*67e74705SXin Li         if (Ty.isNull())
509*67e74705SXin Li           continue;
510*67e74705SXin Li         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511*67e74705SXin Li           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512*67e74705SXin Li             continue;
513*67e74705SXin Li 
514*67e74705SXin Li           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515*67e74705SXin Li             return cloneFullComment(FC, D);
516*67e74705SXin Li         }
517*67e74705SXin Li       }
518*67e74705SXin Li       // Check virtual bases.
519*67e74705SXin Li       for (const auto &I : RD->vbases()) {
520*67e74705SXin Li         if (I.getAccessSpecifier() != AS_public)
521*67e74705SXin Li           continue;
522*67e74705SXin Li         QualType Ty = I.getType();
523*67e74705SXin Li         if (Ty.isNull())
524*67e74705SXin Li           continue;
525*67e74705SXin Li         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526*67e74705SXin Li           if (!(VirtualBase= VirtualBase->getDefinition()))
527*67e74705SXin Li             continue;
528*67e74705SXin Li           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529*67e74705SXin Li             return cloneFullComment(FC, D);
530*67e74705SXin Li         }
531*67e74705SXin Li       }
532*67e74705SXin Li     }
533*67e74705SXin Li     return nullptr;
534*67e74705SXin Li   }
535*67e74705SXin Li 
536*67e74705SXin Li   // If the RawComment was attached to other redeclaration of this Decl, we
537*67e74705SXin Li   // should parse the comment in context of that other Decl.  This is important
538*67e74705SXin Li   // because comments can contain references to parameter names which can be
539*67e74705SXin Li   // different across redeclarations.
540*67e74705SXin Li   if (D != OriginalDecl)
541*67e74705SXin Li     return getCommentForDecl(OriginalDecl, PP);
542*67e74705SXin Li 
543*67e74705SXin Li   comments::FullComment *FC = RC->parse(*this, PP, D);
544*67e74705SXin Li   ParsedComments[Canonical] = FC;
545*67e74705SXin Li   return FC;
546*67e74705SXin Li }
547*67e74705SXin Li 
548*67e74705SXin Li void
Profile(llvm::FoldingSetNodeID & ID,TemplateTemplateParmDecl * Parm)549*67e74705SXin Li ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550*67e74705SXin Li                                                TemplateTemplateParmDecl *Parm) {
551*67e74705SXin Li   ID.AddInteger(Parm->getDepth());
552*67e74705SXin Li   ID.AddInteger(Parm->getPosition());
553*67e74705SXin Li   ID.AddBoolean(Parm->isParameterPack());
554*67e74705SXin Li 
555*67e74705SXin Li   TemplateParameterList *Params = Parm->getTemplateParameters();
556*67e74705SXin Li   ID.AddInteger(Params->size());
557*67e74705SXin Li   for (TemplateParameterList::const_iterator P = Params->begin(),
558*67e74705SXin Li                                           PEnd = Params->end();
559*67e74705SXin Li        P != PEnd; ++P) {
560*67e74705SXin Li     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561*67e74705SXin Li       ID.AddInteger(0);
562*67e74705SXin Li       ID.AddBoolean(TTP->isParameterPack());
563*67e74705SXin Li       continue;
564*67e74705SXin Li     }
565*67e74705SXin Li 
566*67e74705SXin Li     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567*67e74705SXin Li       ID.AddInteger(1);
568*67e74705SXin Li       ID.AddBoolean(NTTP->isParameterPack());
569*67e74705SXin Li       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
570*67e74705SXin Li       if (NTTP->isExpandedParameterPack()) {
571*67e74705SXin Li         ID.AddBoolean(true);
572*67e74705SXin Li         ID.AddInteger(NTTP->getNumExpansionTypes());
573*67e74705SXin Li         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574*67e74705SXin Li           QualType T = NTTP->getExpansionType(I);
575*67e74705SXin Li           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576*67e74705SXin Li         }
577*67e74705SXin Li       } else
578*67e74705SXin Li         ID.AddBoolean(false);
579*67e74705SXin Li       continue;
580*67e74705SXin Li     }
581*67e74705SXin Li 
582*67e74705SXin Li     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
583*67e74705SXin Li     ID.AddInteger(2);
584*67e74705SXin Li     Profile(ID, TTP);
585*67e74705SXin Li   }
586*67e74705SXin Li }
587*67e74705SXin Li 
588*67e74705SXin Li TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl * TTP) const589*67e74705SXin Li ASTContext::getCanonicalTemplateTemplateParmDecl(
590*67e74705SXin Li                                           TemplateTemplateParmDecl *TTP) const {
591*67e74705SXin Li   // Check if we already have a canonical template template parameter.
592*67e74705SXin Li   llvm::FoldingSetNodeID ID;
593*67e74705SXin Li   CanonicalTemplateTemplateParm::Profile(ID, TTP);
594*67e74705SXin Li   void *InsertPos = nullptr;
595*67e74705SXin Li   CanonicalTemplateTemplateParm *Canonical
596*67e74705SXin Li     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597*67e74705SXin Li   if (Canonical)
598*67e74705SXin Li     return Canonical->getParam();
599*67e74705SXin Li 
600*67e74705SXin Li   // Build a canonical template parameter list.
601*67e74705SXin Li   TemplateParameterList *Params = TTP->getTemplateParameters();
602*67e74705SXin Li   SmallVector<NamedDecl *, 4> CanonParams;
603*67e74705SXin Li   CanonParams.reserve(Params->size());
604*67e74705SXin Li   for (TemplateParameterList::const_iterator P = Params->begin(),
605*67e74705SXin Li                                           PEnd = Params->end();
606*67e74705SXin Li        P != PEnd; ++P) {
607*67e74705SXin Li     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608*67e74705SXin Li       CanonParams.push_back(
609*67e74705SXin Li                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
610*67e74705SXin Li                                                SourceLocation(),
611*67e74705SXin Li                                                SourceLocation(),
612*67e74705SXin Li                                                TTP->getDepth(),
613*67e74705SXin Li                                                TTP->getIndex(), nullptr, false,
614*67e74705SXin Li                                                TTP->isParameterPack()));
615*67e74705SXin Li     else if (NonTypeTemplateParmDecl *NTTP
616*67e74705SXin Li              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617*67e74705SXin Li       QualType T = getCanonicalType(NTTP->getType());
618*67e74705SXin Li       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619*67e74705SXin Li       NonTypeTemplateParmDecl *Param;
620*67e74705SXin Li       if (NTTP->isExpandedParameterPack()) {
621*67e74705SXin Li         SmallVector<QualType, 2> ExpandedTypes;
622*67e74705SXin Li         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
623*67e74705SXin Li         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624*67e74705SXin Li           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625*67e74705SXin Li           ExpandedTInfos.push_back(
626*67e74705SXin Li                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627*67e74705SXin Li         }
628*67e74705SXin Li 
629*67e74705SXin Li         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
630*67e74705SXin Li                                                 SourceLocation(),
631*67e74705SXin Li                                                 SourceLocation(),
632*67e74705SXin Li                                                 NTTP->getDepth(),
633*67e74705SXin Li                                                 NTTP->getPosition(), nullptr,
634*67e74705SXin Li                                                 T,
635*67e74705SXin Li                                                 TInfo,
636*67e74705SXin Li                                                 ExpandedTypes,
637*67e74705SXin Li                                                 ExpandedTInfos);
638*67e74705SXin Li       } else {
639*67e74705SXin Li         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
640*67e74705SXin Li                                                 SourceLocation(),
641*67e74705SXin Li                                                 SourceLocation(),
642*67e74705SXin Li                                                 NTTP->getDepth(),
643*67e74705SXin Li                                                 NTTP->getPosition(), nullptr,
644*67e74705SXin Li                                                 T,
645*67e74705SXin Li                                                 NTTP->isParameterPack(),
646*67e74705SXin Li                                                 TInfo);
647*67e74705SXin Li       }
648*67e74705SXin Li       CanonParams.push_back(Param);
649*67e74705SXin Li 
650*67e74705SXin Li     } else
651*67e74705SXin Li       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652*67e74705SXin Li                                            cast<TemplateTemplateParmDecl>(*P)));
653*67e74705SXin Li   }
654*67e74705SXin Li 
655*67e74705SXin Li   TemplateTemplateParmDecl *CanonTTP
656*67e74705SXin Li     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657*67e74705SXin Li                                        SourceLocation(), TTP->getDepth(),
658*67e74705SXin Li                                        TTP->getPosition(),
659*67e74705SXin Li                                        TTP->isParameterPack(),
660*67e74705SXin Li                                        nullptr,
661*67e74705SXin Li                          TemplateParameterList::Create(*this, SourceLocation(),
662*67e74705SXin Li                                                        SourceLocation(),
663*67e74705SXin Li                                                        CanonParams,
664*67e74705SXin Li                                                        SourceLocation()));
665*67e74705SXin Li 
666*67e74705SXin Li   // Get the new insert position for the node we care about.
667*67e74705SXin Li   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
668*67e74705SXin Li   assert(!Canonical && "Shouldn't be in the map!");
669*67e74705SXin Li   (void)Canonical;
670*67e74705SXin Li 
671*67e74705SXin Li   // Create the canonical template template parameter entry.
672*67e74705SXin Li   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673*67e74705SXin Li   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674*67e74705SXin Li   return CanonTTP;
675*67e74705SXin Li }
676*67e74705SXin Li 
createCXXABI(const TargetInfo & T)677*67e74705SXin Li CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
678*67e74705SXin Li   if (!LangOpts.CPlusPlus) return nullptr;
679*67e74705SXin Li 
680*67e74705SXin Li   switch (T.getCXXABI().getKind()) {
681*67e74705SXin Li   case TargetCXXABI::GenericARM: // Same as Itanium at this level
682*67e74705SXin Li   case TargetCXXABI::iOS:
683*67e74705SXin Li   case TargetCXXABI::iOS64:
684*67e74705SXin Li   case TargetCXXABI::WatchOS:
685*67e74705SXin Li   case TargetCXXABI::GenericAArch64:
686*67e74705SXin Li   case TargetCXXABI::GenericMIPS:
687*67e74705SXin Li   case TargetCXXABI::GenericItanium:
688*67e74705SXin Li   case TargetCXXABI::WebAssembly:
689*67e74705SXin Li     return CreateItaniumCXXABI(*this);
690*67e74705SXin Li   case TargetCXXABI::Microsoft:
691*67e74705SXin Li     return CreateMicrosoftCXXABI(*this);
692*67e74705SXin Li   }
693*67e74705SXin Li   llvm_unreachable("Invalid CXXABI type!");
694*67e74705SXin Li }
695*67e74705SXin Li 
getAddressSpaceMap(const TargetInfo & T,const LangOptions & LOpts)696*67e74705SXin Li static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
697*67e74705SXin Li                                              const LangOptions &LOpts) {
698*67e74705SXin Li   if (LOpts.FakeAddressSpaceMap) {
699*67e74705SXin Li     // The fake address space map must have a distinct entry for each
700*67e74705SXin Li     // language-specific address space.
701*67e74705SXin Li     static const unsigned FakeAddrSpaceMap[] = {
702*67e74705SXin Li       1, // opencl_global
703*67e74705SXin Li       2, // opencl_local
704*67e74705SXin Li       3, // opencl_constant
705*67e74705SXin Li       4, // opencl_generic
706*67e74705SXin Li       5, // cuda_device
707*67e74705SXin Li       6, // cuda_constant
708*67e74705SXin Li       7  // cuda_shared
709*67e74705SXin Li     };
710*67e74705SXin Li     return &FakeAddrSpaceMap;
711*67e74705SXin Li   } else {
712*67e74705SXin Li     return &T.getAddressSpaceMap();
713*67e74705SXin Li   }
714*67e74705SXin Li }
715*67e74705SXin Li 
isAddrSpaceMapManglingEnabled(const TargetInfo & TI,const LangOptions & LangOpts)716*67e74705SXin Li static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
717*67e74705SXin Li                                           const LangOptions &LangOpts) {
718*67e74705SXin Li   switch (LangOpts.getAddressSpaceMapMangling()) {
719*67e74705SXin Li   case LangOptions::ASMM_Target:
720*67e74705SXin Li     return TI.useAddressSpaceMapMangling();
721*67e74705SXin Li   case LangOptions::ASMM_On:
722*67e74705SXin Li     return true;
723*67e74705SXin Li   case LangOptions::ASMM_Off:
724*67e74705SXin Li     return false;
725*67e74705SXin Li   }
726*67e74705SXin Li   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
727*67e74705SXin Li }
728*67e74705SXin Li 
ASTContext(LangOptions & LOpts,SourceManager & SM,IdentifierTable & idents,SelectorTable & sels,Builtin::Context & builtins)729*67e74705SXin Li ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
730*67e74705SXin Li                        IdentifierTable &idents, SelectorTable &sels,
731*67e74705SXin Li                        Builtin::Context &builtins)
732*67e74705SXin Li     : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
733*67e74705SXin Li       DependentTemplateSpecializationTypes(this_()),
734*67e74705SXin Li       SubstTemplateTemplateParmPacks(this_()),
735*67e74705SXin Li       GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
736*67e74705SXin Li       UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
737*67e74705SXin Li       BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
738*67e74705SXin Li       ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
739*67e74705SXin Li       CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
740*67e74705SXin Li       ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
741*67e74705SXin Li       sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
742*67e74705SXin Li       BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
743*67e74705SXin Li       cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
744*67e74705SXin Li       ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
745*67e74705SXin Li       TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
746*67e74705SXin Li       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
747*67e74705SXin Li       AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
748*67e74705SXin Li       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
749*67e74705SXin Li       BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
750*67e74705SXin Li       Listener(nullptr), Comments(SM), CommentsLoaded(false),
751*67e74705SXin Li       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
752*67e74705SXin Li   TUDecl = TranslationUnitDecl::Create(*this);
753*67e74705SXin Li }
754*67e74705SXin Li 
~ASTContext()755*67e74705SXin Li ASTContext::~ASTContext() {
756*67e74705SXin Li   ReleaseParentMapEntries();
757*67e74705SXin Li 
758*67e74705SXin Li   // Release the DenseMaps associated with DeclContext objects.
759*67e74705SXin Li   // FIXME: Is this the ideal solution?
760*67e74705SXin Li   ReleaseDeclContextMaps();
761*67e74705SXin Li 
762*67e74705SXin Li   // Call all of the deallocation functions on all of their targets.
763*67e74705SXin Li   for (auto &Pair : Deallocations)
764*67e74705SXin Li     (Pair.first)(Pair.second);
765*67e74705SXin Li 
766*67e74705SXin Li   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
767*67e74705SXin Li   // because they can contain DenseMaps.
768*67e74705SXin Li   for (llvm::DenseMap<const ObjCContainerDecl*,
769*67e74705SXin Li        const ASTRecordLayout*>::iterator
770*67e74705SXin Li        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
771*67e74705SXin Li     // Increment in loop to prevent using deallocated memory.
772*67e74705SXin Li     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773*67e74705SXin Li       R->Destroy(*this);
774*67e74705SXin Li 
775*67e74705SXin Li   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
776*67e74705SXin Li        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
777*67e74705SXin Li     // Increment in loop to prevent using deallocated memory.
778*67e74705SXin Li     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779*67e74705SXin Li       R->Destroy(*this);
780*67e74705SXin Li   }
781*67e74705SXin Li 
782*67e74705SXin Li   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
783*67e74705SXin Li                                                     AEnd = DeclAttrs.end();
784*67e74705SXin Li        A != AEnd; ++A)
785*67e74705SXin Li     A->second->~AttrVec();
786*67e74705SXin Li 
787*67e74705SXin Li   for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
788*67e74705SXin Li        MaterializedTemporaryValues)
789*67e74705SXin Li     MTVPair.second->~APValue();
790*67e74705SXin Li 
791*67e74705SXin Li   llvm::DeleteContainerSeconds(MangleNumberingContexts);
792*67e74705SXin Li }
793*67e74705SXin Li 
ReleaseParentMapEntries()794*67e74705SXin Li void ASTContext::ReleaseParentMapEntries() {
795*67e74705SXin Li   if (!PointerParents) return;
796*67e74705SXin Li   for (const auto &Entry : *PointerParents) {
797*67e74705SXin Li     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798*67e74705SXin Li       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799*67e74705SXin Li     } else if (Entry.second.is<ParentVector *>()) {
800*67e74705SXin Li       delete Entry.second.get<ParentVector *>();
801*67e74705SXin Li     }
802*67e74705SXin Li   }
803*67e74705SXin Li   for (const auto &Entry : *OtherParents) {
804*67e74705SXin Li     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
805*67e74705SXin Li       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
806*67e74705SXin Li     } else if (Entry.second.is<ParentVector *>()) {
807*67e74705SXin Li       delete Entry.second.get<ParentVector *>();
808*67e74705SXin Li     }
809*67e74705SXin Li   }
810*67e74705SXin Li }
811*67e74705SXin Li 
AddDeallocation(void (* Callback)(void *),void * Data)812*67e74705SXin Li void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
813*67e74705SXin Li   Deallocations.push_back({Callback, Data});
814*67e74705SXin Li }
815*67e74705SXin Li 
816*67e74705SXin Li void
setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source)817*67e74705SXin Li ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
818*67e74705SXin Li   ExternalSource = std::move(Source);
819*67e74705SXin Li }
820*67e74705SXin Li 
PrintStats() const821*67e74705SXin Li void ASTContext::PrintStats() const {
822*67e74705SXin Li   llvm::errs() << "\n*** AST Context Stats:\n";
823*67e74705SXin Li   llvm::errs() << "  " << Types.size() << " types total.\n";
824*67e74705SXin Li 
825*67e74705SXin Li   unsigned counts[] = {
826*67e74705SXin Li #define TYPE(Name, Parent) 0,
827*67e74705SXin Li #define ABSTRACT_TYPE(Name, Parent)
828*67e74705SXin Li #include "clang/AST/TypeNodes.def"
829*67e74705SXin Li     0 // Extra
830*67e74705SXin Li   };
831*67e74705SXin Li 
832*67e74705SXin Li   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
833*67e74705SXin Li     Type *T = Types[i];
834*67e74705SXin Li     counts[(unsigned)T->getTypeClass()]++;
835*67e74705SXin Li   }
836*67e74705SXin Li 
837*67e74705SXin Li   unsigned Idx = 0;
838*67e74705SXin Li   unsigned TotalBytes = 0;
839*67e74705SXin Li #define TYPE(Name, Parent)                                              \
840*67e74705SXin Li   if (counts[Idx])                                                      \
841*67e74705SXin Li     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
842*67e74705SXin Li                  << " types\n";                                         \
843*67e74705SXin Li   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
844*67e74705SXin Li   ++Idx;
845*67e74705SXin Li #define ABSTRACT_TYPE(Name, Parent)
846*67e74705SXin Li #include "clang/AST/TypeNodes.def"
847*67e74705SXin Li 
848*67e74705SXin Li   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
849*67e74705SXin Li 
850*67e74705SXin Li   // Implicit special member functions.
851*67e74705SXin Li   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
852*67e74705SXin Li                << NumImplicitDefaultConstructors
853*67e74705SXin Li                << " implicit default constructors created\n";
854*67e74705SXin Li   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
855*67e74705SXin Li                << NumImplicitCopyConstructors
856*67e74705SXin Li                << " implicit copy constructors created\n";
857*67e74705SXin Li   if (getLangOpts().CPlusPlus)
858*67e74705SXin Li     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
859*67e74705SXin Li                  << NumImplicitMoveConstructors
860*67e74705SXin Li                  << " implicit move constructors created\n";
861*67e74705SXin Li   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
862*67e74705SXin Li                << NumImplicitCopyAssignmentOperators
863*67e74705SXin Li                << " implicit copy assignment operators created\n";
864*67e74705SXin Li   if (getLangOpts().CPlusPlus)
865*67e74705SXin Li     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
866*67e74705SXin Li                  << NumImplicitMoveAssignmentOperators
867*67e74705SXin Li                  << " implicit move assignment operators created\n";
868*67e74705SXin Li   llvm::errs() << NumImplicitDestructorsDeclared << "/"
869*67e74705SXin Li                << NumImplicitDestructors
870*67e74705SXin Li                << " implicit destructors created\n";
871*67e74705SXin Li 
872*67e74705SXin Li   if (ExternalSource) {
873*67e74705SXin Li     llvm::errs() << "\n";
874*67e74705SXin Li     ExternalSource->PrintStats();
875*67e74705SXin Li   }
876*67e74705SXin Li 
877*67e74705SXin Li   BumpAlloc.PrintStats();
878*67e74705SXin Li }
879*67e74705SXin Li 
mergeDefinitionIntoModule(NamedDecl * ND,Module * M,bool NotifyListeners)880*67e74705SXin Li void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
881*67e74705SXin Li                                            bool NotifyListeners) {
882*67e74705SXin Li   if (NotifyListeners)
883*67e74705SXin Li     if (auto *Listener = getASTMutationListener())
884*67e74705SXin Li       Listener->RedefinedHiddenDefinition(ND, M);
885*67e74705SXin Li 
886*67e74705SXin Li   if (getLangOpts().ModulesLocalVisibility)
887*67e74705SXin Li     MergedDefModules[ND].push_back(M);
888*67e74705SXin Li   else
889*67e74705SXin Li     ND->setHidden(false);
890*67e74705SXin Li }
891*67e74705SXin Li 
deduplicateMergedDefinitonsFor(NamedDecl * ND)892*67e74705SXin Li void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
893*67e74705SXin Li   auto It = MergedDefModules.find(ND);
894*67e74705SXin Li   if (It == MergedDefModules.end())
895*67e74705SXin Li     return;
896*67e74705SXin Li 
897*67e74705SXin Li   auto &Merged = It->second;
898*67e74705SXin Li   llvm::DenseSet<Module*> Found;
899*67e74705SXin Li   for (Module *&M : Merged)
900*67e74705SXin Li     if (!Found.insert(M).second)
901*67e74705SXin Li       M = nullptr;
902*67e74705SXin Li   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
903*67e74705SXin Li }
904*67e74705SXin Li 
getExternCContextDecl() const905*67e74705SXin Li ExternCContextDecl *ASTContext::getExternCContextDecl() const {
906*67e74705SXin Li   if (!ExternCContext)
907*67e74705SXin Li     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
908*67e74705SXin Li 
909*67e74705SXin Li   return ExternCContext;
910*67e74705SXin Li }
911*67e74705SXin Li 
912*67e74705SXin Li BuiltinTemplateDecl *
buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,const IdentifierInfo * II) const913*67e74705SXin Li ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
914*67e74705SXin Li                                      const IdentifierInfo *II) const {
915*67e74705SXin Li   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
916*67e74705SXin Li   BuiltinTemplate->setImplicit();
917*67e74705SXin Li   TUDecl->addDecl(BuiltinTemplate);
918*67e74705SXin Li 
919*67e74705SXin Li   return BuiltinTemplate;
920*67e74705SXin Li }
921*67e74705SXin Li 
922*67e74705SXin Li BuiltinTemplateDecl *
getMakeIntegerSeqDecl() const923*67e74705SXin Li ASTContext::getMakeIntegerSeqDecl() const {
924*67e74705SXin Li   if (!MakeIntegerSeqDecl)
925*67e74705SXin Li     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
926*67e74705SXin Li                                                   getMakeIntegerSeqName());
927*67e74705SXin Li   return MakeIntegerSeqDecl;
928*67e74705SXin Li }
929*67e74705SXin Li 
930*67e74705SXin Li BuiltinTemplateDecl *
getTypePackElementDecl() const931*67e74705SXin Li ASTContext::getTypePackElementDecl() const {
932*67e74705SXin Li   if (!TypePackElementDecl)
933*67e74705SXin Li     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
934*67e74705SXin Li                                                    getTypePackElementName());
935*67e74705SXin Li   return TypePackElementDecl;
936*67e74705SXin Li }
937*67e74705SXin Li 
buildImplicitRecord(StringRef Name,RecordDecl::TagKind TK) const938*67e74705SXin Li RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
939*67e74705SXin Li                                             RecordDecl::TagKind TK) const {
940*67e74705SXin Li   SourceLocation Loc;
941*67e74705SXin Li   RecordDecl *NewDecl;
942*67e74705SXin Li   if (getLangOpts().CPlusPlus)
943*67e74705SXin Li     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
944*67e74705SXin Li                                     Loc, &Idents.get(Name));
945*67e74705SXin Li   else
946*67e74705SXin Li     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
947*67e74705SXin Li                                  &Idents.get(Name));
948*67e74705SXin Li   NewDecl->setImplicit();
949*67e74705SXin Li   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
950*67e74705SXin Li       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
951*67e74705SXin Li   return NewDecl;
952*67e74705SXin Li }
953*67e74705SXin Li 
buildImplicitTypedef(QualType T,StringRef Name) const954*67e74705SXin Li TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
955*67e74705SXin Li                                               StringRef Name) const {
956*67e74705SXin Li   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
957*67e74705SXin Li   TypedefDecl *NewDecl = TypedefDecl::Create(
958*67e74705SXin Li       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
959*67e74705SXin Li       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
960*67e74705SXin Li   NewDecl->setImplicit();
961*67e74705SXin Li   return NewDecl;
962*67e74705SXin Li }
963*67e74705SXin Li 
getInt128Decl() const964*67e74705SXin Li TypedefDecl *ASTContext::getInt128Decl() const {
965*67e74705SXin Li   if (!Int128Decl)
966*67e74705SXin Li     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
967*67e74705SXin Li   return Int128Decl;
968*67e74705SXin Li }
969*67e74705SXin Li 
getUInt128Decl() const970*67e74705SXin Li TypedefDecl *ASTContext::getUInt128Decl() const {
971*67e74705SXin Li   if (!UInt128Decl)
972*67e74705SXin Li     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
973*67e74705SXin Li   return UInt128Decl;
974*67e74705SXin Li }
975*67e74705SXin Li 
InitBuiltinType(CanQualType & R,BuiltinType::Kind K)976*67e74705SXin Li void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
977*67e74705SXin Li   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
978*67e74705SXin Li   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
979*67e74705SXin Li   Types.push_back(Ty);
980*67e74705SXin Li }
981*67e74705SXin Li 
InitBuiltinTypes(const TargetInfo & Target,const TargetInfo * AuxTarget)982*67e74705SXin Li void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
983*67e74705SXin Li                                   const TargetInfo *AuxTarget) {
984*67e74705SXin Li   assert((!this->Target || this->Target == &Target) &&
985*67e74705SXin Li          "Incorrect target reinitialization");
986*67e74705SXin Li   assert(VoidTy.isNull() && "Context reinitialized?");
987*67e74705SXin Li 
988*67e74705SXin Li   this->Target = &Target;
989*67e74705SXin Li   this->AuxTarget = AuxTarget;
990*67e74705SXin Li 
991*67e74705SXin Li   ABI.reset(createCXXABI(Target));
992*67e74705SXin Li   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
993*67e74705SXin Li   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
994*67e74705SXin Li 
995*67e74705SXin Li   // C99 6.2.5p19.
996*67e74705SXin Li   InitBuiltinType(VoidTy,              BuiltinType::Void);
997*67e74705SXin Li 
998*67e74705SXin Li   // C99 6.2.5p2.
999*67e74705SXin Li   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1000*67e74705SXin Li   // C99 6.2.5p3.
1001*67e74705SXin Li   if (LangOpts.CharIsSigned)
1002*67e74705SXin Li     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1003*67e74705SXin Li   else
1004*67e74705SXin Li     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1005*67e74705SXin Li   // C99 6.2.5p4.
1006*67e74705SXin Li   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1007*67e74705SXin Li   InitBuiltinType(ShortTy,             BuiltinType::Short);
1008*67e74705SXin Li   InitBuiltinType(IntTy,               BuiltinType::Int);
1009*67e74705SXin Li   InitBuiltinType(LongTy,              BuiltinType::Long);
1010*67e74705SXin Li   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1011*67e74705SXin Li 
1012*67e74705SXin Li   // C99 6.2.5p6.
1013*67e74705SXin Li   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1014*67e74705SXin Li   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1015*67e74705SXin Li   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1016*67e74705SXin Li   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1017*67e74705SXin Li   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1018*67e74705SXin Li 
1019*67e74705SXin Li   // C99 6.2.5p10.
1020*67e74705SXin Li   InitBuiltinType(FloatTy,             BuiltinType::Float);
1021*67e74705SXin Li   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1022*67e74705SXin Li   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1023*67e74705SXin Li 
1024*67e74705SXin Li   // GNU extension, __float128 for IEEE quadruple precision
1025*67e74705SXin Li   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1026*67e74705SXin Li 
1027*67e74705SXin Li   // GNU extension, 128-bit integers.
1028*67e74705SXin Li   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1029*67e74705SXin Li   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1030*67e74705SXin Li 
1031*67e74705SXin Li   // C++ 3.9.1p5
1032*67e74705SXin Li   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1033*67e74705SXin Li     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1034*67e74705SXin Li   else  // -fshort-wchar makes wchar_t be unsigned.
1035*67e74705SXin Li     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1036*67e74705SXin Li   if (LangOpts.CPlusPlus && LangOpts.WChar)
1037*67e74705SXin Li     WideCharTy = WCharTy;
1038*67e74705SXin Li   else {
1039*67e74705SXin Li     // C99 (or C++ using -fno-wchar).
1040*67e74705SXin Li     WideCharTy = getFromTargetType(Target.getWCharType());
1041*67e74705SXin Li   }
1042*67e74705SXin Li 
1043*67e74705SXin Li   WIntTy = getFromTargetType(Target.getWIntType());
1044*67e74705SXin Li 
1045*67e74705SXin Li   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1046*67e74705SXin Li     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1047*67e74705SXin Li   else // C99
1048*67e74705SXin Li     Char16Ty = getFromTargetType(Target.getChar16Type());
1049*67e74705SXin Li 
1050*67e74705SXin Li   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1051*67e74705SXin Li     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1052*67e74705SXin Li   else // C99
1053*67e74705SXin Li     Char32Ty = getFromTargetType(Target.getChar32Type());
1054*67e74705SXin Li 
1055*67e74705SXin Li   // Placeholder type for type-dependent expressions whose type is
1056*67e74705SXin Li   // completely unknown. No code should ever check a type against
1057*67e74705SXin Li   // DependentTy and users should never see it; however, it is here to
1058*67e74705SXin Li   // help diagnose failures to properly check for type-dependent
1059*67e74705SXin Li   // expressions.
1060*67e74705SXin Li   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1061*67e74705SXin Li 
1062*67e74705SXin Li   // Placeholder type for functions.
1063*67e74705SXin Li   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1064*67e74705SXin Li 
1065*67e74705SXin Li   // Placeholder type for bound members.
1066*67e74705SXin Li   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1067*67e74705SXin Li 
1068*67e74705SXin Li   // Placeholder type for pseudo-objects.
1069*67e74705SXin Li   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1070*67e74705SXin Li 
1071*67e74705SXin Li   // "any" type; useful for debugger-like clients.
1072*67e74705SXin Li   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1073*67e74705SXin Li 
1074*67e74705SXin Li   // Placeholder type for unbridged ARC casts.
1075*67e74705SXin Li   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1076*67e74705SXin Li 
1077*67e74705SXin Li   // Placeholder type for builtin functions.
1078*67e74705SXin Li   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1079*67e74705SXin Li 
1080*67e74705SXin Li   // Placeholder type for OMP array sections.
1081*67e74705SXin Li   if (LangOpts.OpenMP)
1082*67e74705SXin Li     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1083*67e74705SXin Li 
1084*67e74705SXin Li   // C99 6.2.5p11.
1085*67e74705SXin Li   FloatComplexTy      = getComplexType(FloatTy);
1086*67e74705SXin Li   DoubleComplexTy     = getComplexType(DoubleTy);
1087*67e74705SXin Li   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1088*67e74705SXin Li   Float128ComplexTy   = getComplexType(Float128Ty);
1089*67e74705SXin Li 
1090*67e74705SXin Li   // Builtin types for 'id', 'Class', and 'SEL'.
1091*67e74705SXin Li   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1092*67e74705SXin Li   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1093*67e74705SXin Li   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1094*67e74705SXin Li 
1095*67e74705SXin Li   if (LangOpts.OpenCL) {
1096*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1097*67e74705SXin Li     InitBuiltinType(SingletonId, BuiltinType::Id);
1098*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
1099*67e74705SXin Li 
1100*67e74705SXin Li     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1101*67e74705SXin Li     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1102*67e74705SXin Li     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1103*67e74705SXin Li     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1104*67e74705SXin Li     InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1105*67e74705SXin Li     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1106*67e74705SXin Li   }
1107*67e74705SXin Li 
1108*67e74705SXin Li   // Builtin type for __objc_yes and __objc_no
1109*67e74705SXin Li   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1110*67e74705SXin Li                        SignedCharTy : BoolTy);
1111*67e74705SXin Li 
1112*67e74705SXin Li   ObjCConstantStringType = QualType();
1113*67e74705SXin Li 
1114*67e74705SXin Li   ObjCSuperType = QualType();
1115*67e74705SXin Li 
1116*67e74705SXin Li   // void * type
1117*67e74705SXin Li   VoidPtrTy = getPointerType(VoidTy);
1118*67e74705SXin Li 
1119*67e74705SXin Li   // nullptr type (C++0x 2.14.7)
1120*67e74705SXin Li   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1121*67e74705SXin Li 
1122*67e74705SXin Li   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1123*67e74705SXin Li   InitBuiltinType(HalfTy, BuiltinType::Half);
1124*67e74705SXin Li 
1125*67e74705SXin Li   // Builtin type used to help define __builtin_va_list.
1126*67e74705SXin Li   VaListTagDecl = nullptr;
1127*67e74705SXin Li }
1128*67e74705SXin Li 
getDiagnostics() const1129*67e74705SXin Li DiagnosticsEngine &ASTContext::getDiagnostics() const {
1130*67e74705SXin Li   return SourceMgr.getDiagnostics();
1131*67e74705SXin Li }
1132*67e74705SXin Li 
getDeclAttrs(const Decl * D)1133*67e74705SXin Li AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1134*67e74705SXin Li   AttrVec *&Result = DeclAttrs[D];
1135*67e74705SXin Li   if (!Result) {
1136*67e74705SXin Li     void *Mem = Allocate(sizeof(AttrVec));
1137*67e74705SXin Li     Result = new (Mem) AttrVec;
1138*67e74705SXin Li   }
1139*67e74705SXin Li 
1140*67e74705SXin Li   return *Result;
1141*67e74705SXin Li }
1142*67e74705SXin Li 
1143*67e74705SXin Li /// \brief Erase the attributes corresponding to the given declaration.
eraseDeclAttrs(const Decl * D)1144*67e74705SXin Li void ASTContext::eraseDeclAttrs(const Decl *D) {
1145*67e74705SXin Li   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1146*67e74705SXin Li   if (Pos != DeclAttrs.end()) {
1147*67e74705SXin Li     Pos->second->~AttrVec();
1148*67e74705SXin Li     DeclAttrs.erase(Pos);
1149*67e74705SXin Li   }
1150*67e74705SXin Li }
1151*67e74705SXin Li 
1152*67e74705SXin Li // FIXME: Remove ?
1153*67e74705SXin Li MemberSpecializationInfo *
getInstantiatedFromStaticDataMember(const VarDecl * Var)1154*67e74705SXin Li ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1155*67e74705SXin Li   assert(Var->isStaticDataMember() && "Not a static data member");
1156*67e74705SXin Li   return getTemplateOrSpecializationInfo(Var)
1157*67e74705SXin Li       .dyn_cast<MemberSpecializationInfo *>();
1158*67e74705SXin Li }
1159*67e74705SXin Li 
1160*67e74705SXin Li ASTContext::TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl * Var)1161*67e74705SXin Li ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1162*67e74705SXin Li   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1163*67e74705SXin Li       TemplateOrInstantiation.find(Var);
1164*67e74705SXin Li   if (Pos == TemplateOrInstantiation.end())
1165*67e74705SXin Li     return TemplateOrSpecializationInfo();
1166*67e74705SXin Li 
1167*67e74705SXin Li   return Pos->second;
1168*67e74705SXin Li }
1169*67e74705SXin Li 
1170*67e74705SXin Li void
setInstantiatedFromStaticDataMember(VarDecl * Inst,VarDecl * Tmpl,TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)1171*67e74705SXin Li ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1172*67e74705SXin Li                                                 TemplateSpecializationKind TSK,
1173*67e74705SXin Li                                           SourceLocation PointOfInstantiation) {
1174*67e74705SXin Li   assert(Inst->isStaticDataMember() && "Not a static data member");
1175*67e74705SXin Li   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1176*67e74705SXin Li   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1177*67e74705SXin Li                                             Tmpl, TSK, PointOfInstantiation));
1178*67e74705SXin Li }
1179*67e74705SXin Li 
1180*67e74705SXin Li void
setTemplateOrSpecializationInfo(VarDecl * Inst,TemplateOrSpecializationInfo TSI)1181*67e74705SXin Li ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1182*67e74705SXin Li                                             TemplateOrSpecializationInfo TSI) {
1183*67e74705SXin Li   assert(!TemplateOrInstantiation[Inst] &&
1184*67e74705SXin Li          "Already noted what the variable was instantiated from");
1185*67e74705SXin Li   TemplateOrInstantiation[Inst] = TSI;
1186*67e74705SXin Li }
1187*67e74705SXin Li 
getClassScopeSpecializationPattern(const FunctionDecl * FD)1188*67e74705SXin Li FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1189*67e74705SXin Li                                                      const FunctionDecl *FD){
1190*67e74705SXin Li   assert(FD && "Specialization is 0");
1191*67e74705SXin Li   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1192*67e74705SXin Li     = ClassScopeSpecializationPattern.find(FD);
1193*67e74705SXin Li   if (Pos == ClassScopeSpecializationPattern.end())
1194*67e74705SXin Li     return nullptr;
1195*67e74705SXin Li 
1196*67e74705SXin Li   return Pos->second;
1197*67e74705SXin Li }
1198*67e74705SXin Li 
setClassScopeSpecializationPattern(FunctionDecl * FD,FunctionDecl * Pattern)1199*67e74705SXin Li void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1200*67e74705SXin Li                                         FunctionDecl *Pattern) {
1201*67e74705SXin Li   assert(FD && "Specialization is 0");
1202*67e74705SXin Li   assert(Pattern && "Class scope specialization pattern is 0");
1203*67e74705SXin Li   ClassScopeSpecializationPattern[FD] = Pattern;
1204*67e74705SXin Li }
1205*67e74705SXin Li 
1206*67e74705SXin Li NamedDecl *
getInstantiatedFromUsingDecl(UsingDecl * UUD)1207*67e74705SXin Li ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1208*67e74705SXin Li   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1209*67e74705SXin Li     = InstantiatedFromUsingDecl.find(UUD);
1210*67e74705SXin Li   if (Pos == InstantiatedFromUsingDecl.end())
1211*67e74705SXin Li     return nullptr;
1212*67e74705SXin Li 
1213*67e74705SXin Li   return Pos->second;
1214*67e74705SXin Li }
1215*67e74705SXin Li 
1216*67e74705SXin Li void
setInstantiatedFromUsingDecl(UsingDecl * Inst,NamedDecl * Pattern)1217*67e74705SXin Li ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1218*67e74705SXin Li   assert((isa<UsingDecl>(Pattern) ||
1219*67e74705SXin Li           isa<UnresolvedUsingValueDecl>(Pattern) ||
1220*67e74705SXin Li           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1221*67e74705SXin Li          "pattern decl is not a using decl");
1222*67e74705SXin Li   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1223*67e74705SXin Li   InstantiatedFromUsingDecl[Inst] = Pattern;
1224*67e74705SXin Li }
1225*67e74705SXin Li 
1226*67e74705SXin Li UsingShadowDecl *
getInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst)1227*67e74705SXin Li ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1228*67e74705SXin Li   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1229*67e74705SXin Li     = InstantiatedFromUsingShadowDecl.find(Inst);
1230*67e74705SXin Li   if (Pos == InstantiatedFromUsingShadowDecl.end())
1231*67e74705SXin Li     return nullptr;
1232*67e74705SXin Li 
1233*67e74705SXin Li   return Pos->second;
1234*67e74705SXin Li }
1235*67e74705SXin Li 
1236*67e74705SXin Li void
setInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst,UsingShadowDecl * Pattern)1237*67e74705SXin Li ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1238*67e74705SXin Li                                                UsingShadowDecl *Pattern) {
1239*67e74705SXin Li   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1240*67e74705SXin Li   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1241*67e74705SXin Li }
1242*67e74705SXin Li 
getInstantiatedFromUnnamedFieldDecl(FieldDecl * Field)1243*67e74705SXin Li FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1244*67e74705SXin Li   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1245*67e74705SXin Li     = InstantiatedFromUnnamedFieldDecl.find(Field);
1246*67e74705SXin Li   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1247*67e74705SXin Li     return nullptr;
1248*67e74705SXin Li 
1249*67e74705SXin Li   return Pos->second;
1250*67e74705SXin Li }
1251*67e74705SXin Li 
setInstantiatedFromUnnamedFieldDecl(FieldDecl * Inst,FieldDecl * Tmpl)1252*67e74705SXin Li void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1253*67e74705SXin Li                                                      FieldDecl *Tmpl) {
1254*67e74705SXin Li   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1255*67e74705SXin Li   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1256*67e74705SXin Li   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1257*67e74705SXin Li          "Already noted what unnamed field was instantiated from");
1258*67e74705SXin Li 
1259*67e74705SXin Li   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1260*67e74705SXin Li }
1261*67e74705SXin Li 
1262*67e74705SXin Li ASTContext::overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl * Method) const1263*67e74705SXin Li ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1264*67e74705SXin Li   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1265*67e74705SXin Li       OverriddenMethods.find(Method->getCanonicalDecl());
1266*67e74705SXin Li   if (Pos == OverriddenMethods.end())
1267*67e74705SXin Li     return nullptr;
1268*67e74705SXin Li   return Pos->second.begin();
1269*67e74705SXin Li }
1270*67e74705SXin Li 
1271*67e74705SXin Li ASTContext::overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl * Method) const1272*67e74705SXin Li ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1273*67e74705SXin Li   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1274*67e74705SXin Li       OverriddenMethods.find(Method->getCanonicalDecl());
1275*67e74705SXin Li   if (Pos == OverriddenMethods.end())
1276*67e74705SXin Li     return nullptr;
1277*67e74705SXin Li   return Pos->second.end();
1278*67e74705SXin Li }
1279*67e74705SXin Li 
1280*67e74705SXin Li unsigned
overridden_methods_size(const CXXMethodDecl * Method) const1281*67e74705SXin Li ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1282*67e74705SXin Li   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1283*67e74705SXin Li       OverriddenMethods.find(Method->getCanonicalDecl());
1284*67e74705SXin Li   if (Pos == OverriddenMethods.end())
1285*67e74705SXin Li     return 0;
1286*67e74705SXin Li   return Pos->second.size();
1287*67e74705SXin Li }
1288*67e74705SXin Li 
1289*67e74705SXin Li ASTContext::overridden_method_range
overridden_methods(const CXXMethodDecl * Method) const1290*67e74705SXin Li ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1291*67e74705SXin Li   return overridden_method_range(overridden_methods_begin(Method),
1292*67e74705SXin Li                                  overridden_methods_end(Method));
1293*67e74705SXin Li }
1294*67e74705SXin Li 
addOverriddenMethod(const CXXMethodDecl * Method,const CXXMethodDecl * Overridden)1295*67e74705SXin Li void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1296*67e74705SXin Li                                      const CXXMethodDecl *Overridden) {
1297*67e74705SXin Li   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1298*67e74705SXin Li   OverriddenMethods[Method].push_back(Overridden);
1299*67e74705SXin Li }
1300*67e74705SXin Li 
getOverriddenMethods(const NamedDecl * D,SmallVectorImpl<const NamedDecl * > & Overridden) const1301*67e74705SXin Li void ASTContext::getOverriddenMethods(
1302*67e74705SXin Li                       const NamedDecl *D,
1303*67e74705SXin Li                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1304*67e74705SXin Li   assert(D);
1305*67e74705SXin Li 
1306*67e74705SXin Li   if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1307*67e74705SXin Li     Overridden.append(overridden_methods_begin(CXXMethod),
1308*67e74705SXin Li                       overridden_methods_end(CXXMethod));
1309*67e74705SXin Li     return;
1310*67e74705SXin Li   }
1311*67e74705SXin Li 
1312*67e74705SXin Li   const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1313*67e74705SXin Li   if (!Method)
1314*67e74705SXin Li     return;
1315*67e74705SXin Li 
1316*67e74705SXin Li   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1317*67e74705SXin Li   Method->getOverriddenMethods(OverDecls);
1318*67e74705SXin Li   Overridden.append(OverDecls.begin(), OverDecls.end());
1319*67e74705SXin Li }
1320*67e74705SXin Li 
addedLocalImportDecl(ImportDecl * Import)1321*67e74705SXin Li void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1322*67e74705SXin Li   assert(!Import->NextLocalImport && "Import declaration already in the chain");
1323*67e74705SXin Li   assert(!Import->isFromASTFile() && "Non-local import declaration");
1324*67e74705SXin Li   if (!FirstLocalImport) {
1325*67e74705SXin Li     FirstLocalImport = Import;
1326*67e74705SXin Li     LastLocalImport = Import;
1327*67e74705SXin Li     return;
1328*67e74705SXin Li   }
1329*67e74705SXin Li 
1330*67e74705SXin Li   LastLocalImport->NextLocalImport = Import;
1331*67e74705SXin Li   LastLocalImport = Import;
1332*67e74705SXin Li }
1333*67e74705SXin Li 
1334*67e74705SXin Li //===----------------------------------------------------------------------===//
1335*67e74705SXin Li //                         Type Sizing and Analysis
1336*67e74705SXin Li //===----------------------------------------------------------------------===//
1337*67e74705SXin Li 
1338*67e74705SXin Li /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1339*67e74705SXin Li /// scalar floating point type.
getFloatTypeSemantics(QualType T) const1340*67e74705SXin Li const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1341*67e74705SXin Li   const BuiltinType *BT = T->getAs<BuiltinType>();
1342*67e74705SXin Li   assert(BT && "Not a floating point type!");
1343*67e74705SXin Li   switch (BT->getKind()) {
1344*67e74705SXin Li   default: llvm_unreachable("Not a floating point type!");
1345*67e74705SXin Li   case BuiltinType::Half:       return Target->getHalfFormat();
1346*67e74705SXin Li   case BuiltinType::Float:      return Target->getFloatFormat();
1347*67e74705SXin Li   case BuiltinType::Double:     return Target->getDoubleFormat();
1348*67e74705SXin Li   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1349*67e74705SXin Li   case BuiltinType::Float128:   return Target->getFloat128Format();
1350*67e74705SXin Li   }
1351*67e74705SXin Li }
1352*67e74705SXin Li 
getDeclAlign(const Decl * D,bool ForAlignof) const1353*67e74705SXin Li CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1354*67e74705SXin Li   unsigned Align = Target->getCharWidth();
1355*67e74705SXin Li 
1356*67e74705SXin Li   bool UseAlignAttrOnly = false;
1357*67e74705SXin Li   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1358*67e74705SXin Li     Align = AlignFromAttr;
1359*67e74705SXin Li 
1360*67e74705SXin Li     // __attribute__((aligned)) can increase or decrease alignment
1361*67e74705SXin Li     // *except* on a struct or struct member, where it only increases
1362*67e74705SXin Li     // alignment unless 'packed' is also specified.
1363*67e74705SXin Li     //
1364*67e74705SXin Li     // It is an error for alignas to decrease alignment, so we can
1365*67e74705SXin Li     // ignore that possibility;  Sema should diagnose it.
1366*67e74705SXin Li     if (isa<FieldDecl>(D)) {
1367*67e74705SXin Li       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1368*67e74705SXin Li         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1369*67e74705SXin Li     } else {
1370*67e74705SXin Li       UseAlignAttrOnly = true;
1371*67e74705SXin Li     }
1372*67e74705SXin Li   }
1373*67e74705SXin Li   else if (isa<FieldDecl>(D))
1374*67e74705SXin Li       UseAlignAttrOnly =
1375*67e74705SXin Li         D->hasAttr<PackedAttr>() ||
1376*67e74705SXin Li         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1377*67e74705SXin Li 
1378*67e74705SXin Li   // If we're using the align attribute only, just ignore everything
1379*67e74705SXin Li   // else about the declaration and its type.
1380*67e74705SXin Li   if (UseAlignAttrOnly) {
1381*67e74705SXin Li     // do nothing
1382*67e74705SXin Li 
1383*67e74705SXin Li   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1384*67e74705SXin Li     QualType T = VD->getType();
1385*67e74705SXin Li     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1386*67e74705SXin Li       if (ForAlignof)
1387*67e74705SXin Li         T = RT->getPointeeType();
1388*67e74705SXin Li       else
1389*67e74705SXin Li         T = getPointerType(RT->getPointeeType());
1390*67e74705SXin Li     }
1391*67e74705SXin Li     QualType BaseT = getBaseElementType(T);
1392*67e74705SXin Li     if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1393*67e74705SXin Li       // Adjust alignments of declarations with array type by the
1394*67e74705SXin Li       // large-array alignment on the target.
1395*67e74705SXin Li       if (const ArrayType *arrayType = getAsArrayType(T)) {
1396*67e74705SXin Li         unsigned MinWidth = Target->getLargeArrayMinWidth();
1397*67e74705SXin Li         if (!ForAlignof && MinWidth) {
1398*67e74705SXin Li           if (isa<VariableArrayType>(arrayType))
1399*67e74705SXin Li             Align = std::max(Align, Target->getLargeArrayAlign());
1400*67e74705SXin Li           else if (isa<ConstantArrayType>(arrayType) &&
1401*67e74705SXin Li                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1402*67e74705SXin Li             Align = std::max(Align, Target->getLargeArrayAlign());
1403*67e74705SXin Li         }
1404*67e74705SXin Li       }
1405*67e74705SXin Li       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1406*67e74705SXin Li       if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1407*67e74705SXin Li         if (VD->hasGlobalStorage() && !ForAlignof)
1408*67e74705SXin Li           Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1409*67e74705SXin Li       }
1410*67e74705SXin Li     }
1411*67e74705SXin Li 
1412*67e74705SXin Li     // Fields can be subject to extra alignment constraints, like if
1413*67e74705SXin Li     // the field is packed, the struct is packed, or the struct has a
1414*67e74705SXin Li     // a max-field-alignment constraint (#pragma pack).  So calculate
1415*67e74705SXin Li     // the actual alignment of the field within the struct, and then
1416*67e74705SXin Li     // (as we're expected to) constrain that by the alignment of the type.
1417*67e74705SXin Li     if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1418*67e74705SXin Li       const RecordDecl *Parent = Field->getParent();
1419*67e74705SXin Li       // We can only produce a sensible answer if the record is valid.
1420*67e74705SXin Li       if (!Parent->isInvalidDecl()) {
1421*67e74705SXin Li         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1422*67e74705SXin Li 
1423*67e74705SXin Li         // Start with the record's overall alignment.
1424*67e74705SXin Li         unsigned FieldAlign = toBits(Layout.getAlignment());
1425*67e74705SXin Li 
1426*67e74705SXin Li         // Use the GCD of that and the offset within the record.
1427*67e74705SXin Li         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1428*67e74705SXin Li         if (Offset > 0) {
1429*67e74705SXin Li           // Alignment is always a power of 2, so the GCD will be a power of 2,
1430*67e74705SXin Li           // which means we get to do this crazy thing instead of Euclid's.
1431*67e74705SXin Li           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1432*67e74705SXin Li           if (LowBitOfOffset < FieldAlign)
1433*67e74705SXin Li             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1434*67e74705SXin Li         }
1435*67e74705SXin Li 
1436*67e74705SXin Li         Align = std::min(Align, FieldAlign);
1437*67e74705SXin Li       }
1438*67e74705SXin Li     }
1439*67e74705SXin Li   }
1440*67e74705SXin Li 
1441*67e74705SXin Li   return toCharUnitsFromBits(Align);
1442*67e74705SXin Li }
1443*67e74705SXin Li 
1444*67e74705SXin Li // getTypeInfoDataSizeInChars - Return the size of a type, in
1445*67e74705SXin Li // chars. If the type is a record, its data size is returned.  This is
1446*67e74705SXin Li // the size of the memcpy that's performed when assigning this type
1447*67e74705SXin Li // using a trivial copy/move assignment operator.
1448*67e74705SXin Li std::pair<CharUnits, CharUnits>
getTypeInfoDataSizeInChars(QualType T) const1449*67e74705SXin Li ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1450*67e74705SXin Li   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1451*67e74705SXin Li 
1452*67e74705SXin Li   // In C++, objects can sometimes be allocated into the tail padding
1453*67e74705SXin Li   // of a base-class subobject.  We decide whether that's possible
1454*67e74705SXin Li   // during class layout, so here we can just trust the layout results.
1455*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
1456*67e74705SXin Li     if (const RecordType *RT = T->getAs<RecordType>()) {
1457*67e74705SXin Li       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1458*67e74705SXin Li       sizeAndAlign.first = layout.getDataSize();
1459*67e74705SXin Li     }
1460*67e74705SXin Li   }
1461*67e74705SXin Li 
1462*67e74705SXin Li   return sizeAndAlign;
1463*67e74705SXin Li }
1464*67e74705SXin Li 
1465*67e74705SXin Li /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1466*67e74705SXin Li /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1467*67e74705SXin Li std::pair<CharUnits, CharUnits>
getConstantArrayInfoInChars(const ASTContext & Context,const ConstantArrayType * CAT)1468*67e74705SXin Li static getConstantArrayInfoInChars(const ASTContext &Context,
1469*67e74705SXin Li                                    const ConstantArrayType *CAT) {
1470*67e74705SXin Li   std::pair<CharUnits, CharUnits> EltInfo =
1471*67e74705SXin Li       Context.getTypeInfoInChars(CAT->getElementType());
1472*67e74705SXin Li   uint64_t Size = CAT->getSize().getZExtValue();
1473*67e74705SXin Li   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1474*67e74705SXin Li               (uint64_t)(-1)/Size) &&
1475*67e74705SXin Li          "Overflow in array type char size evaluation");
1476*67e74705SXin Li   uint64_t Width = EltInfo.first.getQuantity() * Size;
1477*67e74705SXin Li   unsigned Align = EltInfo.second.getQuantity();
1478*67e74705SXin Li   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1479*67e74705SXin Li       Context.getTargetInfo().getPointerWidth(0) == 64)
1480*67e74705SXin Li     Width = llvm::alignTo(Width, Align);
1481*67e74705SXin Li   return std::make_pair(CharUnits::fromQuantity(Width),
1482*67e74705SXin Li                         CharUnits::fromQuantity(Align));
1483*67e74705SXin Li }
1484*67e74705SXin Li 
1485*67e74705SXin Li std::pair<CharUnits, CharUnits>
getTypeInfoInChars(const Type * T) const1486*67e74705SXin Li ASTContext::getTypeInfoInChars(const Type *T) const {
1487*67e74705SXin Li   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1488*67e74705SXin Li     return getConstantArrayInfoInChars(*this, CAT);
1489*67e74705SXin Li   TypeInfo Info = getTypeInfo(T);
1490*67e74705SXin Li   return std::make_pair(toCharUnitsFromBits(Info.Width),
1491*67e74705SXin Li                         toCharUnitsFromBits(Info.Align));
1492*67e74705SXin Li }
1493*67e74705SXin Li 
1494*67e74705SXin Li std::pair<CharUnits, CharUnits>
getTypeInfoInChars(QualType T) const1495*67e74705SXin Li ASTContext::getTypeInfoInChars(QualType T) const {
1496*67e74705SXin Li   return getTypeInfoInChars(T.getTypePtr());
1497*67e74705SXin Li }
1498*67e74705SXin Li 
isAlignmentRequired(const Type * T) const1499*67e74705SXin Li bool ASTContext::isAlignmentRequired(const Type *T) const {
1500*67e74705SXin Li   return getTypeInfo(T).AlignIsRequired;
1501*67e74705SXin Li }
1502*67e74705SXin Li 
isAlignmentRequired(QualType T) const1503*67e74705SXin Li bool ASTContext::isAlignmentRequired(QualType T) const {
1504*67e74705SXin Li   return isAlignmentRequired(T.getTypePtr());
1505*67e74705SXin Li }
1506*67e74705SXin Li 
getTypeInfo(const Type * T) const1507*67e74705SXin Li TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1508*67e74705SXin Li   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1509*67e74705SXin Li   if (I != MemoizedTypeInfo.end())
1510*67e74705SXin Li     return I->second;
1511*67e74705SXin Li 
1512*67e74705SXin Li   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1513*67e74705SXin Li   TypeInfo TI = getTypeInfoImpl(T);
1514*67e74705SXin Li   MemoizedTypeInfo[T] = TI;
1515*67e74705SXin Li   return TI;
1516*67e74705SXin Li }
1517*67e74705SXin Li 
1518*67e74705SXin Li /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1519*67e74705SXin Li /// method does not work on incomplete types.
1520*67e74705SXin Li ///
1521*67e74705SXin Li /// FIXME: Pointers into different addr spaces could have different sizes and
1522*67e74705SXin Li /// alignment requirements: getPointerInfo should take an AddrSpace, this
1523*67e74705SXin Li /// should take a QualType, &c.
getTypeInfoImpl(const Type * T) const1524*67e74705SXin Li TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1525*67e74705SXin Li   uint64_t Width = 0;
1526*67e74705SXin Li   unsigned Align = 8;
1527*67e74705SXin Li   bool AlignIsRequired = false;
1528*67e74705SXin Li   switch (T->getTypeClass()) {
1529*67e74705SXin Li #define TYPE(Class, Base)
1530*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
1531*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base)
1532*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1533*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1534*67e74705SXin Li   case Type::Class:                                                            \
1535*67e74705SXin Li   assert(!T->isDependentType() && "should not see dependent types here");      \
1536*67e74705SXin Li   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1537*67e74705SXin Li #include "clang/AST/TypeNodes.def"
1538*67e74705SXin Li     llvm_unreachable("Should not see dependent types");
1539*67e74705SXin Li 
1540*67e74705SXin Li   case Type::FunctionNoProto:
1541*67e74705SXin Li   case Type::FunctionProto:
1542*67e74705SXin Li     // GCC extension: alignof(function) = 32 bits
1543*67e74705SXin Li     Width = 0;
1544*67e74705SXin Li     Align = 32;
1545*67e74705SXin Li     break;
1546*67e74705SXin Li 
1547*67e74705SXin Li   case Type::IncompleteArray:
1548*67e74705SXin Li   case Type::VariableArray:
1549*67e74705SXin Li     Width = 0;
1550*67e74705SXin Li     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1551*67e74705SXin Li     break;
1552*67e74705SXin Li 
1553*67e74705SXin Li   case Type::ConstantArray: {
1554*67e74705SXin Li     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1555*67e74705SXin Li 
1556*67e74705SXin Li     TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1557*67e74705SXin Li     uint64_t Size = CAT->getSize().getZExtValue();
1558*67e74705SXin Li     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1559*67e74705SXin Li            "Overflow in array type bit size evaluation");
1560*67e74705SXin Li     Width = EltInfo.Width * Size;
1561*67e74705SXin Li     Align = EltInfo.Align;
1562*67e74705SXin Li     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1563*67e74705SXin Li         getTargetInfo().getPointerWidth(0) == 64)
1564*67e74705SXin Li       Width = llvm::alignTo(Width, Align);
1565*67e74705SXin Li     break;
1566*67e74705SXin Li   }
1567*67e74705SXin Li   case Type::ExtVector:
1568*67e74705SXin Li   case Type::Vector: {
1569*67e74705SXin Li     const VectorType *VT = cast<VectorType>(T);
1570*67e74705SXin Li     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1571*67e74705SXin Li     Width = EltInfo.Width * VT->getNumElements();
1572*67e74705SXin Li     Align = Width;
1573*67e74705SXin Li     // If the alignment is not a power of 2, round up to the next power of 2.
1574*67e74705SXin Li     // This happens for non-power-of-2 length vectors.
1575*67e74705SXin Li     if (Align & (Align-1)) {
1576*67e74705SXin Li       Align = llvm::NextPowerOf2(Align);
1577*67e74705SXin Li       Width = llvm::alignTo(Width, Align);
1578*67e74705SXin Li     }
1579*67e74705SXin Li     // Adjust the alignment based on the target max.
1580*67e74705SXin Li     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1581*67e74705SXin Li     if (TargetVectorAlign && TargetVectorAlign < Align)
1582*67e74705SXin Li       Align = TargetVectorAlign;
1583*67e74705SXin Li     break;
1584*67e74705SXin Li   }
1585*67e74705SXin Li 
1586*67e74705SXin Li   case Type::Builtin:
1587*67e74705SXin Li     switch (cast<BuiltinType>(T)->getKind()) {
1588*67e74705SXin Li     default: llvm_unreachable("Unknown builtin type!");
1589*67e74705SXin Li     case BuiltinType::Void:
1590*67e74705SXin Li       // GCC extension: alignof(void) = 8 bits.
1591*67e74705SXin Li       Width = 0;
1592*67e74705SXin Li       Align = 8;
1593*67e74705SXin Li       break;
1594*67e74705SXin Li 
1595*67e74705SXin Li     case BuiltinType::Bool:
1596*67e74705SXin Li       Width = Target->getBoolWidth();
1597*67e74705SXin Li       Align = Target->getBoolAlign();
1598*67e74705SXin Li       break;
1599*67e74705SXin Li     case BuiltinType::Char_S:
1600*67e74705SXin Li     case BuiltinType::Char_U:
1601*67e74705SXin Li     case BuiltinType::UChar:
1602*67e74705SXin Li     case BuiltinType::SChar:
1603*67e74705SXin Li       Width = Target->getCharWidth();
1604*67e74705SXin Li       Align = Target->getCharAlign();
1605*67e74705SXin Li       break;
1606*67e74705SXin Li     case BuiltinType::WChar_S:
1607*67e74705SXin Li     case BuiltinType::WChar_U:
1608*67e74705SXin Li       Width = Target->getWCharWidth();
1609*67e74705SXin Li       Align = Target->getWCharAlign();
1610*67e74705SXin Li       break;
1611*67e74705SXin Li     case BuiltinType::Char16:
1612*67e74705SXin Li       Width = Target->getChar16Width();
1613*67e74705SXin Li       Align = Target->getChar16Align();
1614*67e74705SXin Li       break;
1615*67e74705SXin Li     case BuiltinType::Char32:
1616*67e74705SXin Li       Width = Target->getChar32Width();
1617*67e74705SXin Li       Align = Target->getChar32Align();
1618*67e74705SXin Li       break;
1619*67e74705SXin Li     case BuiltinType::UShort:
1620*67e74705SXin Li     case BuiltinType::Short:
1621*67e74705SXin Li       Width = Target->getShortWidth();
1622*67e74705SXin Li       Align = Target->getShortAlign();
1623*67e74705SXin Li       break;
1624*67e74705SXin Li     case BuiltinType::UInt:
1625*67e74705SXin Li     case BuiltinType::Int:
1626*67e74705SXin Li       Width = Target->getIntWidth();
1627*67e74705SXin Li       Align = Target->getIntAlign();
1628*67e74705SXin Li       break;
1629*67e74705SXin Li     case BuiltinType::ULong:
1630*67e74705SXin Li     case BuiltinType::Long:
1631*67e74705SXin Li       Width = Target->getLongWidth();
1632*67e74705SXin Li       Align = Target->getLongAlign();
1633*67e74705SXin Li       break;
1634*67e74705SXin Li     case BuiltinType::ULongLong:
1635*67e74705SXin Li     case BuiltinType::LongLong:
1636*67e74705SXin Li       Width = Target->getLongLongWidth();
1637*67e74705SXin Li       Align = Target->getLongLongAlign();
1638*67e74705SXin Li       break;
1639*67e74705SXin Li     case BuiltinType::Int128:
1640*67e74705SXin Li     case BuiltinType::UInt128:
1641*67e74705SXin Li       Width = 128;
1642*67e74705SXin Li       Align = 128; // int128_t is 128-bit aligned on all targets.
1643*67e74705SXin Li       break;
1644*67e74705SXin Li     case BuiltinType::Half:
1645*67e74705SXin Li       Width = Target->getHalfWidth();
1646*67e74705SXin Li       Align = Target->getHalfAlign();
1647*67e74705SXin Li       break;
1648*67e74705SXin Li     case BuiltinType::Float:
1649*67e74705SXin Li       Width = Target->getFloatWidth();
1650*67e74705SXin Li       Align = Target->getFloatAlign();
1651*67e74705SXin Li       break;
1652*67e74705SXin Li     case BuiltinType::Double:
1653*67e74705SXin Li       Width = Target->getDoubleWidth();
1654*67e74705SXin Li       Align = Target->getDoubleAlign();
1655*67e74705SXin Li       break;
1656*67e74705SXin Li     case BuiltinType::LongDouble:
1657*67e74705SXin Li       Width = Target->getLongDoubleWidth();
1658*67e74705SXin Li       Align = Target->getLongDoubleAlign();
1659*67e74705SXin Li       break;
1660*67e74705SXin Li     case BuiltinType::Float128:
1661*67e74705SXin Li       Width = Target->getFloat128Width();
1662*67e74705SXin Li       Align = Target->getFloat128Align();
1663*67e74705SXin Li       break;
1664*67e74705SXin Li     case BuiltinType::NullPtr:
1665*67e74705SXin Li       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1666*67e74705SXin Li       Align = Target->getPointerAlign(0); //   == sizeof(void*)
1667*67e74705SXin Li       break;
1668*67e74705SXin Li     case BuiltinType::ObjCId:
1669*67e74705SXin Li     case BuiltinType::ObjCClass:
1670*67e74705SXin Li     case BuiltinType::ObjCSel:
1671*67e74705SXin Li       Width = Target->getPointerWidth(0);
1672*67e74705SXin Li       Align = Target->getPointerAlign(0);
1673*67e74705SXin Li       break;
1674*67e74705SXin Li     case BuiltinType::OCLSampler:
1675*67e74705SXin Li       // Samplers are modeled as integers.
1676*67e74705SXin Li       Width = Target->getIntWidth();
1677*67e74705SXin Li       Align = Target->getIntAlign();
1678*67e74705SXin Li       break;
1679*67e74705SXin Li     case BuiltinType::OCLEvent:
1680*67e74705SXin Li     case BuiltinType::OCLClkEvent:
1681*67e74705SXin Li     case BuiltinType::OCLQueue:
1682*67e74705SXin Li     case BuiltinType::OCLNDRange:
1683*67e74705SXin Li     case BuiltinType::OCLReserveID:
1684*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1685*67e74705SXin Li     case BuiltinType::Id:
1686*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
1687*67e74705SXin Li 
1688*67e74705SXin Li       // Currently these types are pointers to opaque types.
1689*67e74705SXin Li       Width = Target->getPointerWidth(0);
1690*67e74705SXin Li       Align = Target->getPointerAlign(0);
1691*67e74705SXin Li       break;
1692*67e74705SXin Li     }
1693*67e74705SXin Li     break;
1694*67e74705SXin Li   case Type::ObjCObjectPointer:
1695*67e74705SXin Li     Width = Target->getPointerWidth(0);
1696*67e74705SXin Li     Align = Target->getPointerAlign(0);
1697*67e74705SXin Li     break;
1698*67e74705SXin Li   case Type::BlockPointer: {
1699*67e74705SXin Li     unsigned AS = getTargetAddressSpace(
1700*67e74705SXin Li         cast<BlockPointerType>(T)->getPointeeType());
1701*67e74705SXin Li     Width = Target->getPointerWidth(AS);
1702*67e74705SXin Li     Align = Target->getPointerAlign(AS);
1703*67e74705SXin Li     break;
1704*67e74705SXin Li   }
1705*67e74705SXin Li   case Type::LValueReference:
1706*67e74705SXin Li   case Type::RValueReference: {
1707*67e74705SXin Li     // alignof and sizeof should never enter this code path here, so we go
1708*67e74705SXin Li     // the pointer route.
1709*67e74705SXin Li     unsigned AS = getTargetAddressSpace(
1710*67e74705SXin Li         cast<ReferenceType>(T)->getPointeeType());
1711*67e74705SXin Li     Width = Target->getPointerWidth(AS);
1712*67e74705SXin Li     Align = Target->getPointerAlign(AS);
1713*67e74705SXin Li     break;
1714*67e74705SXin Li   }
1715*67e74705SXin Li   case Type::Pointer: {
1716*67e74705SXin Li     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1717*67e74705SXin Li     Width = Target->getPointerWidth(AS);
1718*67e74705SXin Li     Align = Target->getPointerAlign(AS);
1719*67e74705SXin Li     break;
1720*67e74705SXin Li   }
1721*67e74705SXin Li   case Type::MemberPointer: {
1722*67e74705SXin Li     const MemberPointerType *MPT = cast<MemberPointerType>(T);
1723*67e74705SXin Li     std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1724*67e74705SXin Li     break;
1725*67e74705SXin Li   }
1726*67e74705SXin Li   case Type::Complex: {
1727*67e74705SXin Li     // Complex types have the same alignment as their elements, but twice the
1728*67e74705SXin Li     // size.
1729*67e74705SXin Li     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1730*67e74705SXin Li     Width = EltInfo.Width * 2;
1731*67e74705SXin Li     Align = EltInfo.Align;
1732*67e74705SXin Li     break;
1733*67e74705SXin Li   }
1734*67e74705SXin Li   case Type::ObjCObject:
1735*67e74705SXin Li     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1736*67e74705SXin Li   case Type::Adjusted:
1737*67e74705SXin Li   case Type::Decayed:
1738*67e74705SXin Li     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1739*67e74705SXin Li   case Type::ObjCInterface: {
1740*67e74705SXin Li     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1741*67e74705SXin Li     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1742*67e74705SXin Li     Width = toBits(Layout.getSize());
1743*67e74705SXin Li     Align = toBits(Layout.getAlignment());
1744*67e74705SXin Li     break;
1745*67e74705SXin Li   }
1746*67e74705SXin Li   case Type::Record:
1747*67e74705SXin Li   case Type::Enum: {
1748*67e74705SXin Li     const TagType *TT = cast<TagType>(T);
1749*67e74705SXin Li 
1750*67e74705SXin Li     if (TT->getDecl()->isInvalidDecl()) {
1751*67e74705SXin Li       Width = 8;
1752*67e74705SXin Li       Align = 8;
1753*67e74705SXin Li       break;
1754*67e74705SXin Li     }
1755*67e74705SXin Li 
1756*67e74705SXin Li     if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1757*67e74705SXin Li       const EnumDecl *ED = ET->getDecl();
1758*67e74705SXin Li       TypeInfo Info =
1759*67e74705SXin Li           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1760*67e74705SXin Li       if (unsigned AttrAlign = ED->getMaxAlignment()) {
1761*67e74705SXin Li         Info.Align = AttrAlign;
1762*67e74705SXin Li         Info.AlignIsRequired = true;
1763*67e74705SXin Li       }
1764*67e74705SXin Li       return Info;
1765*67e74705SXin Li     }
1766*67e74705SXin Li 
1767*67e74705SXin Li     const RecordType *RT = cast<RecordType>(TT);
1768*67e74705SXin Li     const RecordDecl *RD = RT->getDecl();
1769*67e74705SXin Li     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1770*67e74705SXin Li     Width = toBits(Layout.getSize());
1771*67e74705SXin Li     Align = toBits(Layout.getAlignment());
1772*67e74705SXin Li     AlignIsRequired = RD->hasAttr<AlignedAttr>();
1773*67e74705SXin Li     break;
1774*67e74705SXin Li   }
1775*67e74705SXin Li 
1776*67e74705SXin Li   case Type::SubstTemplateTypeParm:
1777*67e74705SXin Li     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1778*67e74705SXin Li                        getReplacementType().getTypePtr());
1779*67e74705SXin Li 
1780*67e74705SXin Li   case Type::Auto: {
1781*67e74705SXin Li     const AutoType *A = cast<AutoType>(T);
1782*67e74705SXin Li     assert(!A->getDeducedType().isNull() &&
1783*67e74705SXin Li            "cannot request the size of an undeduced or dependent auto type");
1784*67e74705SXin Li     return getTypeInfo(A->getDeducedType().getTypePtr());
1785*67e74705SXin Li   }
1786*67e74705SXin Li 
1787*67e74705SXin Li   case Type::Paren:
1788*67e74705SXin Li     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1789*67e74705SXin Li 
1790*67e74705SXin Li   case Type::Typedef: {
1791*67e74705SXin Li     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1792*67e74705SXin Li     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1793*67e74705SXin Li     // If the typedef has an aligned attribute on it, it overrides any computed
1794*67e74705SXin Li     // alignment we have.  This violates the GCC documentation (which says that
1795*67e74705SXin Li     // attribute(aligned) can only round up) but matches its implementation.
1796*67e74705SXin Li     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1797*67e74705SXin Li       Align = AttrAlign;
1798*67e74705SXin Li       AlignIsRequired = true;
1799*67e74705SXin Li     } else {
1800*67e74705SXin Li       Align = Info.Align;
1801*67e74705SXin Li       AlignIsRequired = Info.AlignIsRequired;
1802*67e74705SXin Li     }
1803*67e74705SXin Li     Width = Info.Width;
1804*67e74705SXin Li     break;
1805*67e74705SXin Li   }
1806*67e74705SXin Li 
1807*67e74705SXin Li   case Type::Elaborated:
1808*67e74705SXin Li     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1809*67e74705SXin Li 
1810*67e74705SXin Li   case Type::Attributed:
1811*67e74705SXin Li     return getTypeInfo(
1812*67e74705SXin Li                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1813*67e74705SXin Li 
1814*67e74705SXin Li   case Type::Atomic: {
1815*67e74705SXin Li     // Start with the base type information.
1816*67e74705SXin Li     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1817*67e74705SXin Li     Width = Info.Width;
1818*67e74705SXin Li     Align = Info.Align;
1819*67e74705SXin Li 
1820*67e74705SXin Li     // If the size of the type doesn't exceed the platform's max
1821*67e74705SXin Li     // atomic promotion width, make the size and alignment more
1822*67e74705SXin Li     // favorable to atomic operations:
1823*67e74705SXin Li     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1824*67e74705SXin Li       // Round the size up to a power of 2.
1825*67e74705SXin Li       if (!llvm::isPowerOf2_64(Width))
1826*67e74705SXin Li         Width = llvm::NextPowerOf2(Width);
1827*67e74705SXin Li 
1828*67e74705SXin Li       // Set the alignment equal to the size.
1829*67e74705SXin Li       Align = static_cast<unsigned>(Width);
1830*67e74705SXin Li     }
1831*67e74705SXin Li   }
1832*67e74705SXin Li   break;
1833*67e74705SXin Li 
1834*67e74705SXin Li   case Type::Pipe: {
1835*67e74705SXin Li     TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1836*67e74705SXin Li     Width = Info.Width;
1837*67e74705SXin Li     Align = Info.Align;
1838*67e74705SXin Li   }
1839*67e74705SXin Li 
1840*67e74705SXin Li   }
1841*67e74705SXin Li 
1842*67e74705SXin Li   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1843*67e74705SXin Li   return TypeInfo(Width, Align, AlignIsRequired);
1844*67e74705SXin Li }
1845*67e74705SXin Li 
getOpenMPDefaultSimdAlign(QualType T) const1846*67e74705SXin Li unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1847*67e74705SXin Li   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1848*67e74705SXin Li   // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1849*67e74705SXin Li   if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1850*67e74705SXin Li        getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1851*67e74705SXin Li       getTargetInfo().getABI() == "elfv1-qpx" &&
1852*67e74705SXin Li       T->isSpecificBuiltinType(BuiltinType::Double))
1853*67e74705SXin Li     SimdAlign = 256;
1854*67e74705SXin Li   return SimdAlign;
1855*67e74705SXin Li }
1856*67e74705SXin Li 
1857*67e74705SXin Li /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
toCharUnitsFromBits(int64_t BitSize) const1858*67e74705SXin Li CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1859*67e74705SXin Li   return CharUnits::fromQuantity(BitSize / getCharWidth());
1860*67e74705SXin Li }
1861*67e74705SXin Li 
1862*67e74705SXin Li /// toBits - Convert a size in characters to a size in characters.
toBits(CharUnits CharSize) const1863*67e74705SXin Li int64_t ASTContext::toBits(CharUnits CharSize) const {
1864*67e74705SXin Li   return CharSize.getQuantity() * getCharWidth();
1865*67e74705SXin Li }
1866*67e74705SXin Li 
1867*67e74705SXin Li /// getTypeSizeInChars - Return the size of the specified type, in characters.
1868*67e74705SXin Li /// This method does not work on incomplete types.
getTypeSizeInChars(QualType T) const1869*67e74705SXin Li CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1870*67e74705SXin Li   return getTypeInfoInChars(T).first;
1871*67e74705SXin Li }
getTypeSizeInChars(const Type * T) const1872*67e74705SXin Li CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1873*67e74705SXin Li   return getTypeInfoInChars(T).first;
1874*67e74705SXin Li }
1875*67e74705SXin Li 
1876*67e74705SXin Li /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1877*67e74705SXin Li /// characters. This method does not work on incomplete types.
getTypeAlignInChars(QualType T) const1878*67e74705SXin Li CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1879*67e74705SXin Li   return toCharUnitsFromBits(getTypeAlign(T));
1880*67e74705SXin Li }
getTypeAlignInChars(const Type * T) const1881*67e74705SXin Li CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1882*67e74705SXin Li   return toCharUnitsFromBits(getTypeAlign(T));
1883*67e74705SXin Li }
1884*67e74705SXin Li 
1885*67e74705SXin Li /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1886*67e74705SXin Li /// type for the current target in bits.  This can be different than the ABI
1887*67e74705SXin Li /// alignment in cases where it is beneficial for performance to overalign
1888*67e74705SXin Li /// a data type.
getPreferredTypeAlign(const Type * T) const1889*67e74705SXin Li unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1890*67e74705SXin Li   TypeInfo TI = getTypeInfo(T);
1891*67e74705SXin Li   unsigned ABIAlign = TI.Align;
1892*67e74705SXin Li 
1893*67e74705SXin Li   T = T->getBaseElementTypeUnsafe();
1894*67e74705SXin Li 
1895*67e74705SXin Li   // The preferred alignment of member pointers is that of a pointer.
1896*67e74705SXin Li   if (T->isMemberPointerType())
1897*67e74705SXin Li     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1898*67e74705SXin Li 
1899*67e74705SXin Li   if (!Target->allowsLargerPreferedTypeAlignment())
1900*67e74705SXin Li     return ABIAlign;
1901*67e74705SXin Li 
1902*67e74705SXin Li   // Double and long long should be naturally aligned if possible.
1903*67e74705SXin Li   if (const ComplexType *CT = T->getAs<ComplexType>())
1904*67e74705SXin Li     T = CT->getElementType().getTypePtr();
1905*67e74705SXin Li   if (const EnumType *ET = T->getAs<EnumType>())
1906*67e74705SXin Li     T = ET->getDecl()->getIntegerType().getTypePtr();
1907*67e74705SXin Li   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1908*67e74705SXin Li       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1909*67e74705SXin Li       T->isSpecificBuiltinType(BuiltinType::ULongLong))
1910*67e74705SXin Li     // Don't increase the alignment if an alignment attribute was specified on a
1911*67e74705SXin Li     // typedef declaration.
1912*67e74705SXin Li     if (!TI.AlignIsRequired)
1913*67e74705SXin Li       return std::max(ABIAlign, (unsigned)getTypeSize(T));
1914*67e74705SXin Li 
1915*67e74705SXin Li   return ABIAlign;
1916*67e74705SXin Li }
1917*67e74705SXin Li 
1918*67e74705SXin Li /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1919*67e74705SXin Li /// for __attribute__((aligned)) on this target, to be used if no alignment
1920*67e74705SXin Li /// value is specified.
getTargetDefaultAlignForAttributeAligned() const1921*67e74705SXin Li unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
1922*67e74705SXin Li   return getTargetInfo().getDefaultAlignForAttributeAligned();
1923*67e74705SXin Li }
1924*67e74705SXin Li 
1925*67e74705SXin Li /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1926*67e74705SXin Li /// to a global variable of the specified type.
getAlignOfGlobalVar(QualType T) const1927*67e74705SXin Li unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1928*67e74705SXin Li   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1929*67e74705SXin Li }
1930*67e74705SXin Li 
1931*67e74705SXin Li /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1932*67e74705SXin Li /// should be given to a global variable of the specified type.
getAlignOfGlobalVarInChars(QualType T) const1933*67e74705SXin Li CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1934*67e74705SXin Li   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1935*67e74705SXin Li }
1936*67e74705SXin Li 
getOffsetOfBaseWithVBPtr(const CXXRecordDecl * RD) const1937*67e74705SXin Li CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1938*67e74705SXin Li   CharUnits Offset = CharUnits::Zero();
1939*67e74705SXin Li   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1940*67e74705SXin Li   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1941*67e74705SXin Li     Offset += Layout->getBaseClassOffset(Base);
1942*67e74705SXin Li     Layout = &getASTRecordLayout(Base);
1943*67e74705SXin Li   }
1944*67e74705SXin Li   return Offset;
1945*67e74705SXin Li }
1946*67e74705SXin Li 
1947*67e74705SXin Li /// DeepCollectObjCIvars -
1948*67e74705SXin Li /// This routine first collects all declared, but not synthesized, ivars in
1949*67e74705SXin Li /// super class and then collects all ivars, including those synthesized for
1950*67e74705SXin Li /// current class. This routine is used for implementation of current class
1951*67e74705SXin Li /// when all ivars, declared and synthesized are known.
1952*67e74705SXin Li ///
DeepCollectObjCIvars(const ObjCInterfaceDecl * OI,bool leafClass,SmallVectorImpl<const ObjCIvarDecl * > & Ivars) const1953*67e74705SXin Li void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1954*67e74705SXin Li                                       bool leafClass,
1955*67e74705SXin Li                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1956*67e74705SXin Li   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1957*67e74705SXin Li     DeepCollectObjCIvars(SuperClass, false, Ivars);
1958*67e74705SXin Li   if (!leafClass) {
1959*67e74705SXin Li     for (const auto *I : OI->ivars())
1960*67e74705SXin Li       Ivars.push_back(I);
1961*67e74705SXin Li   } else {
1962*67e74705SXin Li     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1963*67e74705SXin Li     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1964*67e74705SXin Li          Iv= Iv->getNextIvar())
1965*67e74705SXin Li       Ivars.push_back(Iv);
1966*67e74705SXin Li   }
1967*67e74705SXin Li }
1968*67e74705SXin Li 
1969*67e74705SXin Li /// CollectInheritedProtocols - Collect all protocols in current class and
1970*67e74705SXin Li /// those inherited by it.
CollectInheritedProtocols(const Decl * CDecl,llvm::SmallPtrSet<ObjCProtocolDecl *,8> & Protocols)1971*67e74705SXin Li void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1972*67e74705SXin Li                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1973*67e74705SXin Li   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1974*67e74705SXin Li     // We can use protocol_iterator here instead of
1975*67e74705SXin Li     // all_referenced_protocol_iterator since we are walking all categories.
1976*67e74705SXin Li     for (auto *Proto : OI->all_referenced_protocols()) {
1977*67e74705SXin Li       CollectInheritedProtocols(Proto, Protocols);
1978*67e74705SXin Li     }
1979*67e74705SXin Li 
1980*67e74705SXin Li     // Categories of this Interface.
1981*67e74705SXin Li     for (const auto *Cat : OI->visible_categories())
1982*67e74705SXin Li       CollectInheritedProtocols(Cat, Protocols);
1983*67e74705SXin Li 
1984*67e74705SXin Li     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1985*67e74705SXin Li       while (SD) {
1986*67e74705SXin Li         CollectInheritedProtocols(SD, Protocols);
1987*67e74705SXin Li         SD = SD->getSuperClass();
1988*67e74705SXin Li       }
1989*67e74705SXin Li   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1990*67e74705SXin Li     for (auto *Proto : OC->protocols()) {
1991*67e74705SXin Li       CollectInheritedProtocols(Proto, Protocols);
1992*67e74705SXin Li     }
1993*67e74705SXin Li   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1994*67e74705SXin Li     // Insert the protocol.
1995*67e74705SXin Li     if (!Protocols.insert(
1996*67e74705SXin Li           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1997*67e74705SXin Li       return;
1998*67e74705SXin Li 
1999*67e74705SXin Li     for (auto *Proto : OP->protocols())
2000*67e74705SXin Li       CollectInheritedProtocols(Proto, Protocols);
2001*67e74705SXin Li   }
2002*67e74705SXin Li }
2003*67e74705SXin Li 
CountNonClassIvars(const ObjCInterfaceDecl * OI) const2004*67e74705SXin Li unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2005*67e74705SXin Li   unsigned count = 0;
2006*67e74705SXin Li   // Count ivars declared in class extension.
2007*67e74705SXin Li   for (const auto *Ext : OI->known_extensions())
2008*67e74705SXin Li     count += Ext->ivar_size();
2009*67e74705SXin Li 
2010*67e74705SXin Li   // Count ivar defined in this class's implementation.  This
2011*67e74705SXin Li   // includes synthesized ivars.
2012*67e74705SXin Li   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2013*67e74705SXin Li     count += ImplDecl->ivar_size();
2014*67e74705SXin Li 
2015*67e74705SXin Li   return count;
2016*67e74705SXin Li }
2017*67e74705SXin Li 
isSentinelNullExpr(const Expr * E)2018*67e74705SXin Li bool ASTContext::isSentinelNullExpr(const Expr *E) {
2019*67e74705SXin Li   if (!E)
2020*67e74705SXin Li     return false;
2021*67e74705SXin Li 
2022*67e74705SXin Li   // nullptr_t is always treated as null.
2023*67e74705SXin Li   if (E->getType()->isNullPtrType()) return true;
2024*67e74705SXin Li 
2025*67e74705SXin Li   if (E->getType()->isAnyPointerType() &&
2026*67e74705SXin Li       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2027*67e74705SXin Li                                                 Expr::NPC_ValueDependentIsNull))
2028*67e74705SXin Li     return true;
2029*67e74705SXin Li 
2030*67e74705SXin Li   // Unfortunately, __null has type 'int'.
2031*67e74705SXin Li   if (isa<GNUNullExpr>(E)) return true;
2032*67e74705SXin Li 
2033*67e74705SXin Li   return false;
2034*67e74705SXin Li }
2035*67e74705SXin Li 
2036*67e74705SXin Li /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
getObjCImplementation(ObjCInterfaceDecl * D)2037*67e74705SXin Li ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2038*67e74705SXin Li   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2039*67e74705SXin Li     I = ObjCImpls.find(D);
2040*67e74705SXin Li   if (I != ObjCImpls.end())
2041*67e74705SXin Li     return cast<ObjCImplementationDecl>(I->second);
2042*67e74705SXin Li   return nullptr;
2043*67e74705SXin Li }
2044*67e74705SXin Li /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
getObjCImplementation(ObjCCategoryDecl * D)2045*67e74705SXin Li ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2046*67e74705SXin Li   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2047*67e74705SXin Li     I = ObjCImpls.find(D);
2048*67e74705SXin Li   if (I != ObjCImpls.end())
2049*67e74705SXin Li     return cast<ObjCCategoryImplDecl>(I->second);
2050*67e74705SXin Li   return nullptr;
2051*67e74705SXin Li }
2052*67e74705SXin Li 
2053*67e74705SXin Li /// \brief Set the implementation of ObjCInterfaceDecl.
setObjCImplementation(ObjCInterfaceDecl * IFaceD,ObjCImplementationDecl * ImplD)2054*67e74705SXin Li void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2055*67e74705SXin Li                            ObjCImplementationDecl *ImplD) {
2056*67e74705SXin Li   assert(IFaceD && ImplD && "Passed null params");
2057*67e74705SXin Li   ObjCImpls[IFaceD] = ImplD;
2058*67e74705SXin Li }
2059*67e74705SXin Li /// \brief Set the implementation of ObjCCategoryDecl.
setObjCImplementation(ObjCCategoryDecl * CatD,ObjCCategoryImplDecl * ImplD)2060*67e74705SXin Li void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2061*67e74705SXin Li                            ObjCCategoryImplDecl *ImplD) {
2062*67e74705SXin Li   assert(CatD && ImplD && "Passed null params");
2063*67e74705SXin Li   ObjCImpls[CatD] = ImplD;
2064*67e74705SXin Li }
2065*67e74705SXin Li 
2066*67e74705SXin Li const ObjCMethodDecl *
getObjCMethodRedeclaration(const ObjCMethodDecl * MD) const2067*67e74705SXin Li ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2068*67e74705SXin Li   return ObjCMethodRedecls.lookup(MD);
2069*67e74705SXin Li }
2070*67e74705SXin Li 
setObjCMethodRedeclaration(const ObjCMethodDecl * MD,const ObjCMethodDecl * Redecl)2071*67e74705SXin Li void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2072*67e74705SXin Li                                             const ObjCMethodDecl *Redecl) {
2073*67e74705SXin Li   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2074*67e74705SXin Li   ObjCMethodRedecls[MD] = Redecl;
2075*67e74705SXin Li }
2076*67e74705SXin Li 
getObjContainingInterface(const NamedDecl * ND) const2077*67e74705SXin Li const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2078*67e74705SXin Li                                               const NamedDecl *ND) const {
2079*67e74705SXin Li   if (const ObjCInterfaceDecl *ID =
2080*67e74705SXin Li           dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2081*67e74705SXin Li     return ID;
2082*67e74705SXin Li   if (const ObjCCategoryDecl *CD =
2083*67e74705SXin Li           dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2084*67e74705SXin Li     return CD->getClassInterface();
2085*67e74705SXin Li   if (const ObjCImplDecl *IMD =
2086*67e74705SXin Li           dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2087*67e74705SXin Li     return IMD->getClassInterface();
2088*67e74705SXin Li 
2089*67e74705SXin Li   return nullptr;
2090*67e74705SXin Li }
2091*67e74705SXin Li 
2092*67e74705SXin Li /// \brief Get the copy initialization expression of VarDecl,or NULL if
2093*67e74705SXin Li /// none exists.
getBlockVarCopyInits(const VarDecl * VD)2094*67e74705SXin Li Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2095*67e74705SXin Li   assert(VD && "Passed null params");
2096*67e74705SXin Li   assert(VD->hasAttr<BlocksAttr>() &&
2097*67e74705SXin Li          "getBlockVarCopyInits - not __block var");
2098*67e74705SXin Li   llvm::DenseMap<const VarDecl*, Expr*>::iterator
2099*67e74705SXin Li     I = BlockVarCopyInits.find(VD);
2100*67e74705SXin Li   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2101*67e74705SXin Li }
2102*67e74705SXin Li 
2103*67e74705SXin Li /// \brief Set the copy inialization expression of a block var decl.
setBlockVarCopyInits(VarDecl * VD,Expr * Init)2104*67e74705SXin Li void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2105*67e74705SXin Li   assert(VD && Init && "Passed null params");
2106*67e74705SXin Li   assert(VD->hasAttr<BlocksAttr>() &&
2107*67e74705SXin Li          "setBlockVarCopyInits - not __block var");
2108*67e74705SXin Li   BlockVarCopyInits[VD] = Init;
2109*67e74705SXin Li }
2110*67e74705SXin Li 
CreateTypeSourceInfo(QualType T,unsigned DataSize) const2111*67e74705SXin Li TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2112*67e74705SXin Li                                                  unsigned DataSize) const {
2113*67e74705SXin Li   if (!DataSize)
2114*67e74705SXin Li     DataSize = TypeLoc::getFullDataSizeForType(T);
2115*67e74705SXin Li   else
2116*67e74705SXin Li     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2117*67e74705SXin Li            "incorrect data size provided to CreateTypeSourceInfo!");
2118*67e74705SXin Li 
2119*67e74705SXin Li   TypeSourceInfo *TInfo =
2120*67e74705SXin Li     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2121*67e74705SXin Li   new (TInfo) TypeSourceInfo(T);
2122*67e74705SXin Li   return TInfo;
2123*67e74705SXin Li }
2124*67e74705SXin Li 
getTrivialTypeSourceInfo(QualType T,SourceLocation L) const2125*67e74705SXin Li TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2126*67e74705SXin Li                                                      SourceLocation L) const {
2127*67e74705SXin Li   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2128*67e74705SXin Li   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2129*67e74705SXin Li   return DI;
2130*67e74705SXin Li }
2131*67e74705SXin Li 
2132*67e74705SXin Li const ASTRecordLayout &
getASTObjCInterfaceLayout(const ObjCInterfaceDecl * D) const2133*67e74705SXin Li ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2134*67e74705SXin Li   return getObjCLayout(D, nullptr);
2135*67e74705SXin Li }
2136*67e74705SXin Li 
2137*67e74705SXin Li const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl * D) const2138*67e74705SXin Li ASTContext::getASTObjCImplementationLayout(
2139*67e74705SXin Li                                         const ObjCImplementationDecl *D) const {
2140*67e74705SXin Li   return getObjCLayout(D->getClassInterface(), D);
2141*67e74705SXin Li }
2142*67e74705SXin Li 
2143*67e74705SXin Li //===----------------------------------------------------------------------===//
2144*67e74705SXin Li //                   Type creation/memoization methods
2145*67e74705SXin Li //===----------------------------------------------------------------------===//
2146*67e74705SXin Li 
2147*67e74705SXin Li QualType
getExtQualType(const Type * baseType,Qualifiers quals) const2148*67e74705SXin Li ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2149*67e74705SXin Li   unsigned fastQuals = quals.getFastQualifiers();
2150*67e74705SXin Li   quals.removeFastQualifiers();
2151*67e74705SXin Li 
2152*67e74705SXin Li   // Check if we've already instantiated this type.
2153*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2154*67e74705SXin Li   ExtQuals::Profile(ID, baseType, quals);
2155*67e74705SXin Li   void *insertPos = nullptr;
2156*67e74705SXin Li   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2157*67e74705SXin Li     assert(eq->getQualifiers() == quals);
2158*67e74705SXin Li     return QualType(eq, fastQuals);
2159*67e74705SXin Li   }
2160*67e74705SXin Li 
2161*67e74705SXin Li   // If the base type is not canonical, make the appropriate canonical type.
2162*67e74705SXin Li   QualType canon;
2163*67e74705SXin Li   if (!baseType->isCanonicalUnqualified()) {
2164*67e74705SXin Li     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2165*67e74705SXin Li     canonSplit.Quals.addConsistentQualifiers(quals);
2166*67e74705SXin Li     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2167*67e74705SXin Li 
2168*67e74705SXin Li     // Re-find the insert position.
2169*67e74705SXin Li     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2170*67e74705SXin Li   }
2171*67e74705SXin Li 
2172*67e74705SXin Li   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2173*67e74705SXin Li   ExtQualNodes.InsertNode(eq, insertPos);
2174*67e74705SXin Li   return QualType(eq, fastQuals);
2175*67e74705SXin Li }
2176*67e74705SXin Li 
2177*67e74705SXin Li QualType
getAddrSpaceQualType(QualType T,unsigned AddressSpace) const2178*67e74705SXin Li ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2179*67e74705SXin Li   QualType CanT = getCanonicalType(T);
2180*67e74705SXin Li   if (CanT.getAddressSpace() == AddressSpace)
2181*67e74705SXin Li     return T;
2182*67e74705SXin Li 
2183*67e74705SXin Li   // If we are composing extended qualifiers together, merge together
2184*67e74705SXin Li   // into one ExtQuals node.
2185*67e74705SXin Li   QualifierCollector Quals;
2186*67e74705SXin Li   const Type *TypeNode = Quals.strip(T);
2187*67e74705SXin Li 
2188*67e74705SXin Li   // If this type already has an address space specified, it cannot get
2189*67e74705SXin Li   // another one.
2190*67e74705SXin Li   assert(!Quals.hasAddressSpace() &&
2191*67e74705SXin Li          "Type cannot be in multiple addr spaces!");
2192*67e74705SXin Li   Quals.addAddressSpace(AddressSpace);
2193*67e74705SXin Li 
2194*67e74705SXin Li   return getExtQualType(TypeNode, Quals);
2195*67e74705SXin Li }
2196*67e74705SXin Li 
getObjCGCQualType(QualType T,Qualifiers::GC GCAttr) const2197*67e74705SXin Li QualType ASTContext::getObjCGCQualType(QualType T,
2198*67e74705SXin Li                                        Qualifiers::GC GCAttr) const {
2199*67e74705SXin Li   QualType CanT = getCanonicalType(T);
2200*67e74705SXin Li   if (CanT.getObjCGCAttr() == GCAttr)
2201*67e74705SXin Li     return T;
2202*67e74705SXin Li 
2203*67e74705SXin Li   if (const PointerType *ptr = T->getAs<PointerType>()) {
2204*67e74705SXin Li     QualType Pointee = ptr->getPointeeType();
2205*67e74705SXin Li     if (Pointee->isAnyPointerType()) {
2206*67e74705SXin Li       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2207*67e74705SXin Li       return getPointerType(ResultType);
2208*67e74705SXin Li     }
2209*67e74705SXin Li   }
2210*67e74705SXin Li 
2211*67e74705SXin Li   // If we are composing extended qualifiers together, merge together
2212*67e74705SXin Li   // into one ExtQuals node.
2213*67e74705SXin Li   QualifierCollector Quals;
2214*67e74705SXin Li   const Type *TypeNode = Quals.strip(T);
2215*67e74705SXin Li 
2216*67e74705SXin Li   // If this type already has an ObjCGC specified, it cannot get
2217*67e74705SXin Li   // another one.
2218*67e74705SXin Li   assert(!Quals.hasObjCGCAttr() &&
2219*67e74705SXin Li          "Type cannot have multiple ObjCGCs!");
2220*67e74705SXin Li   Quals.addObjCGCAttr(GCAttr);
2221*67e74705SXin Li 
2222*67e74705SXin Li   return getExtQualType(TypeNode, Quals);
2223*67e74705SXin Li }
2224*67e74705SXin Li 
adjustFunctionType(const FunctionType * T,FunctionType::ExtInfo Info)2225*67e74705SXin Li const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2226*67e74705SXin Li                                                    FunctionType::ExtInfo Info) {
2227*67e74705SXin Li   if (T->getExtInfo() == Info)
2228*67e74705SXin Li     return T;
2229*67e74705SXin Li 
2230*67e74705SXin Li   QualType Result;
2231*67e74705SXin Li   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2232*67e74705SXin Li     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2233*67e74705SXin Li   } else {
2234*67e74705SXin Li     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2235*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2236*67e74705SXin Li     EPI.ExtInfo = Info;
2237*67e74705SXin Li     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2238*67e74705SXin Li   }
2239*67e74705SXin Li 
2240*67e74705SXin Li   return cast<FunctionType>(Result.getTypePtr());
2241*67e74705SXin Li }
2242*67e74705SXin Li 
adjustDeducedFunctionResultType(FunctionDecl * FD,QualType ResultType)2243*67e74705SXin Li void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2244*67e74705SXin Li                                                  QualType ResultType) {
2245*67e74705SXin Li   FD = FD->getMostRecentDecl();
2246*67e74705SXin Li   while (true) {
2247*67e74705SXin Li     const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2248*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2249*67e74705SXin Li     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2250*67e74705SXin Li     if (FunctionDecl *Next = FD->getPreviousDecl())
2251*67e74705SXin Li       FD = Next;
2252*67e74705SXin Li     else
2253*67e74705SXin Li       break;
2254*67e74705SXin Li   }
2255*67e74705SXin Li   if (ASTMutationListener *L = getASTMutationListener())
2256*67e74705SXin Li     L->DeducedReturnType(FD, ResultType);
2257*67e74705SXin Li }
2258*67e74705SXin Li 
2259*67e74705SXin Li /// Get a function type and produce the equivalent function type with the
2260*67e74705SXin Li /// specified exception specification. Type sugar that can be present on a
2261*67e74705SXin Li /// declaration of a function with an exception specification is permitted
2262*67e74705SXin Li /// and preserved. Other type sugar (for instance, typedefs) is not.
getFunctionTypeWithExceptionSpec(ASTContext & Context,QualType Orig,const FunctionProtoType::ExceptionSpecInfo & ESI)2263*67e74705SXin Li static QualType getFunctionTypeWithExceptionSpec(
2264*67e74705SXin Li     ASTContext &Context, QualType Orig,
2265*67e74705SXin Li     const FunctionProtoType::ExceptionSpecInfo &ESI) {
2266*67e74705SXin Li   // Might have some parens.
2267*67e74705SXin Li   if (auto *PT = dyn_cast<ParenType>(Orig))
2268*67e74705SXin Li     return Context.getParenType(
2269*67e74705SXin Li         getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2270*67e74705SXin Li 
2271*67e74705SXin Li   // Might have a calling-convention attribute.
2272*67e74705SXin Li   if (auto *AT = dyn_cast<AttributedType>(Orig))
2273*67e74705SXin Li     return Context.getAttributedType(
2274*67e74705SXin Li         AT->getAttrKind(),
2275*67e74705SXin Li         getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2276*67e74705SXin Li         getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2277*67e74705SXin Li                                          ESI));
2278*67e74705SXin Li 
2279*67e74705SXin Li   // Anything else must be a function type. Rebuild it with the new exception
2280*67e74705SXin Li   // specification.
2281*67e74705SXin Li   const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2282*67e74705SXin Li   return Context.getFunctionType(
2283*67e74705SXin Li       Proto->getReturnType(), Proto->getParamTypes(),
2284*67e74705SXin Li       Proto->getExtProtoInfo().withExceptionSpec(ESI));
2285*67e74705SXin Li }
2286*67e74705SXin Li 
adjustExceptionSpec(FunctionDecl * FD,const FunctionProtoType::ExceptionSpecInfo & ESI,bool AsWritten)2287*67e74705SXin Li void ASTContext::adjustExceptionSpec(
2288*67e74705SXin Li     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2289*67e74705SXin Li     bool AsWritten) {
2290*67e74705SXin Li   // Update the type.
2291*67e74705SXin Li   QualType Updated =
2292*67e74705SXin Li       getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2293*67e74705SXin Li   FD->setType(Updated);
2294*67e74705SXin Li 
2295*67e74705SXin Li   if (!AsWritten)
2296*67e74705SXin Li     return;
2297*67e74705SXin Li 
2298*67e74705SXin Li   // Update the type in the type source information too.
2299*67e74705SXin Li   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2300*67e74705SXin Li     // If the type and the type-as-written differ, we may need to update
2301*67e74705SXin Li     // the type-as-written too.
2302*67e74705SXin Li     if (TSInfo->getType() != FD->getType())
2303*67e74705SXin Li       Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2304*67e74705SXin Li 
2305*67e74705SXin Li     // FIXME: When we get proper type location information for exceptions,
2306*67e74705SXin Li     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2307*67e74705SXin Li     // up the TypeSourceInfo;
2308*67e74705SXin Li     assert(TypeLoc::getFullDataSizeForType(Updated) ==
2309*67e74705SXin Li                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2310*67e74705SXin Li            "TypeLoc size mismatch from updating exception specification");
2311*67e74705SXin Li     TSInfo->overrideType(Updated);
2312*67e74705SXin Li   }
2313*67e74705SXin Li }
2314*67e74705SXin Li 
2315*67e74705SXin Li /// getComplexType - Return the uniqued reference to the type for a complex
2316*67e74705SXin Li /// number with the specified element type.
getComplexType(QualType T) const2317*67e74705SXin Li QualType ASTContext::getComplexType(QualType T) const {
2318*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
2319*67e74705SXin Li   // structure.
2320*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2321*67e74705SXin Li   ComplexType::Profile(ID, T);
2322*67e74705SXin Li 
2323*67e74705SXin Li   void *InsertPos = nullptr;
2324*67e74705SXin Li   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2325*67e74705SXin Li     return QualType(CT, 0);
2326*67e74705SXin Li 
2327*67e74705SXin Li   // If the pointee type isn't canonical, this won't be a canonical type either,
2328*67e74705SXin Li   // so fill in the canonical type field.
2329*67e74705SXin Li   QualType Canonical;
2330*67e74705SXin Li   if (!T.isCanonical()) {
2331*67e74705SXin Li     Canonical = getComplexType(getCanonicalType(T));
2332*67e74705SXin Li 
2333*67e74705SXin Li     // Get the new insert position for the node we care about.
2334*67e74705SXin Li     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2335*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2336*67e74705SXin Li   }
2337*67e74705SXin Li   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2338*67e74705SXin Li   Types.push_back(New);
2339*67e74705SXin Li   ComplexTypes.InsertNode(New, InsertPos);
2340*67e74705SXin Li   return QualType(New, 0);
2341*67e74705SXin Li }
2342*67e74705SXin Li 
2343*67e74705SXin Li /// getPointerType - Return the uniqued reference to the type for a pointer to
2344*67e74705SXin Li /// the specified type.
getPointerType(QualType T) const2345*67e74705SXin Li QualType ASTContext::getPointerType(QualType T) const {
2346*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
2347*67e74705SXin Li   // structure.
2348*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2349*67e74705SXin Li   PointerType::Profile(ID, T);
2350*67e74705SXin Li 
2351*67e74705SXin Li   void *InsertPos = nullptr;
2352*67e74705SXin Li   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2353*67e74705SXin Li     return QualType(PT, 0);
2354*67e74705SXin Li 
2355*67e74705SXin Li   // If the pointee type isn't canonical, this won't be a canonical type either,
2356*67e74705SXin Li   // so fill in the canonical type field.
2357*67e74705SXin Li   QualType Canonical;
2358*67e74705SXin Li   if (!T.isCanonical()) {
2359*67e74705SXin Li     Canonical = getPointerType(getCanonicalType(T));
2360*67e74705SXin Li 
2361*67e74705SXin Li     // Get the new insert position for the node we care about.
2362*67e74705SXin Li     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2363*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2364*67e74705SXin Li   }
2365*67e74705SXin Li   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2366*67e74705SXin Li   Types.push_back(New);
2367*67e74705SXin Li   PointerTypes.InsertNode(New, InsertPos);
2368*67e74705SXin Li   return QualType(New, 0);
2369*67e74705SXin Li }
2370*67e74705SXin Li 
getAdjustedType(QualType Orig,QualType New) const2371*67e74705SXin Li QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2372*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2373*67e74705SXin Li   AdjustedType::Profile(ID, Orig, New);
2374*67e74705SXin Li   void *InsertPos = nullptr;
2375*67e74705SXin Li   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2376*67e74705SXin Li   if (AT)
2377*67e74705SXin Li     return QualType(AT, 0);
2378*67e74705SXin Li 
2379*67e74705SXin Li   QualType Canonical = getCanonicalType(New);
2380*67e74705SXin Li 
2381*67e74705SXin Li   // Get the new insert position for the node we care about.
2382*67e74705SXin Li   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2383*67e74705SXin Li   assert(!AT && "Shouldn't be in the map!");
2384*67e74705SXin Li 
2385*67e74705SXin Li   AT = new (*this, TypeAlignment)
2386*67e74705SXin Li       AdjustedType(Type::Adjusted, Orig, New, Canonical);
2387*67e74705SXin Li   Types.push_back(AT);
2388*67e74705SXin Li   AdjustedTypes.InsertNode(AT, InsertPos);
2389*67e74705SXin Li   return QualType(AT, 0);
2390*67e74705SXin Li }
2391*67e74705SXin Li 
getDecayedType(QualType T) const2392*67e74705SXin Li QualType ASTContext::getDecayedType(QualType T) const {
2393*67e74705SXin Li   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2394*67e74705SXin Li 
2395*67e74705SXin Li   QualType Decayed;
2396*67e74705SXin Li 
2397*67e74705SXin Li   // C99 6.7.5.3p7:
2398*67e74705SXin Li   //   A declaration of a parameter as "array of type" shall be
2399*67e74705SXin Li   //   adjusted to "qualified pointer to type", where the type
2400*67e74705SXin Li   //   qualifiers (if any) are those specified within the [ and ] of
2401*67e74705SXin Li   //   the array type derivation.
2402*67e74705SXin Li   if (T->isArrayType())
2403*67e74705SXin Li     Decayed = getArrayDecayedType(T);
2404*67e74705SXin Li 
2405*67e74705SXin Li   // C99 6.7.5.3p8:
2406*67e74705SXin Li   //   A declaration of a parameter as "function returning type"
2407*67e74705SXin Li   //   shall be adjusted to "pointer to function returning type", as
2408*67e74705SXin Li   //   in 6.3.2.1.
2409*67e74705SXin Li   if (T->isFunctionType())
2410*67e74705SXin Li     Decayed = getPointerType(T);
2411*67e74705SXin Li 
2412*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2413*67e74705SXin Li   AdjustedType::Profile(ID, T, Decayed);
2414*67e74705SXin Li   void *InsertPos = nullptr;
2415*67e74705SXin Li   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2416*67e74705SXin Li   if (AT)
2417*67e74705SXin Li     return QualType(AT, 0);
2418*67e74705SXin Li 
2419*67e74705SXin Li   QualType Canonical = getCanonicalType(Decayed);
2420*67e74705SXin Li 
2421*67e74705SXin Li   // Get the new insert position for the node we care about.
2422*67e74705SXin Li   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2423*67e74705SXin Li   assert(!AT && "Shouldn't be in the map!");
2424*67e74705SXin Li 
2425*67e74705SXin Li   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2426*67e74705SXin Li   Types.push_back(AT);
2427*67e74705SXin Li   AdjustedTypes.InsertNode(AT, InsertPos);
2428*67e74705SXin Li   return QualType(AT, 0);
2429*67e74705SXin Li }
2430*67e74705SXin Li 
2431*67e74705SXin Li /// getBlockPointerType - Return the uniqued reference to the type for
2432*67e74705SXin Li /// a pointer to the specified block.
getBlockPointerType(QualType T) const2433*67e74705SXin Li QualType ASTContext::getBlockPointerType(QualType T) const {
2434*67e74705SXin Li   assert(T->isFunctionType() && "block of function types only");
2435*67e74705SXin Li   // Unique pointers, to guarantee there is only one block of a particular
2436*67e74705SXin Li   // structure.
2437*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2438*67e74705SXin Li   BlockPointerType::Profile(ID, T);
2439*67e74705SXin Li 
2440*67e74705SXin Li   void *InsertPos = nullptr;
2441*67e74705SXin Li   if (BlockPointerType *PT =
2442*67e74705SXin Li         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2443*67e74705SXin Li     return QualType(PT, 0);
2444*67e74705SXin Li 
2445*67e74705SXin Li   // If the block pointee type isn't canonical, this won't be a canonical
2446*67e74705SXin Li   // type either so fill in the canonical type field.
2447*67e74705SXin Li   QualType Canonical;
2448*67e74705SXin Li   if (!T.isCanonical()) {
2449*67e74705SXin Li     Canonical = getBlockPointerType(getCanonicalType(T));
2450*67e74705SXin Li 
2451*67e74705SXin Li     // Get the new insert position for the node we care about.
2452*67e74705SXin Li     BlockPointerType *NewIP =
2453*67e74705SXin Li       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2454*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2455*67e74705SXin Li   }
2456*67e74705SXin Li   BlockPointerType *New
2457*67e74705SXin Li     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2458*67e74705SXin Li   Types.push_back(New);
2459*67e74705SXin Li   BlockPointerTypes.InsertNode(New, InsertPos);
2460*67e74705SXin Li   return QualType(New, 0);
2461*67e74705SXin Li }
2462*67e74705SXin Li 
2463*67e74705SXin Li /// getLValueReferenceType - Return the uniqued reference to the type for an
2464*67e74705SXin Li /// lvalue reference to the specified type.
2465*67e74705SXin Li QualType
getLValueReferenceType(QualType T,bool SpelledAsLValue) const2466*67e74705SXin Li ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2467*67e74705SXin Li   assert(getCanonicalType(T) != OverloadTy &&
2468*67e74705SXin Li          "Unresolved overloaded function type");
2469*67e74705SXin Li 
2470*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
2471*67e74705SXin Li   // structure.
2472*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2473*67e74705SXin Li   ReferenceType::Profile(ID, T, SpelledAsLValue);
2474*67e74705SXin Li 
2475*67e74705SXin Li   void *InsertPos = nullptr;
2476*67e74705SXin Li   if (LValueReferenceType *RT =
2477*67e74705SXin Li         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2478*67e74705SXin Li     return QualType(RT, 0);
2479*67e74705SXin Li 
2480*67e74705SXin Li   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2481*67e74705SXin Li 
2482*67e74705SXin Li   // If the referencee type isn't canonical, this won't be a canonical type
2483*67e74705SXin Li   // either, so fill in the canonical type field.
2484*67e74705SXin Li   QualType Canonical;
2485*67e74705SXin Li   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2486*67e74705SXin Li     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2487*67e74705SXin Li     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2488*67e74705SXin Li 
2489*67e74705SXin Li     // Get the new insert position for the node we care about.
2490*67e74705SXin Li     LValueReferenceType *NewIP =
2491*67e74705SXin Li       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2492*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2493*67e74705SXin Li   }
2494*67e74705SXin Li 
2495*67e74705SXin Li   LValueReferenceType *New
2496*67e74705SXin Li     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2497*67e74705SXin Li                                                      SpelledAsLValue);
2498*67e74705SXin Li   Types.push_back(New);
2499*67e74705SXin Li   LValueReferenceTypes.InsertNode(New, InsertPos);
2500*67e74705SXin Li 
2501*67e74705SXin Li   return QualType(New, 0);
2502*67e74705SXin Li }
2503*67e74705SXin Li 
2504*67e74705SXin Li /// getRValueReferenceType - Return the uniqued reference to the type for an
2505*67e74705SXin Li /// rvalue reference to the specified type.
getRValueReferenceType(QualType T) const2506*67e74705SXin Li QualType ASTContext::getRValueReferenceType(QualType T) const {
2507*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
2508*67e74705SXin Li   // structure.
2509*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2510*67e74705SXin Li   ReferenceType::Profile(ID, T, false);
2511*67e74705SXin Li 
2512*67e74705SXin Li   void *InsertPos = nullptr;
2513*67e74705SXin Li   if (RValueReferenceType *RT =
2514*67e74705SXin Li         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2515*67e74705SXin Li     return QualType(RT, 0);
2516*67e74705SXin Li 
2517*67e74705SXin Li   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2518*67e74705SXin Li 
2519*67e74705SXin Li   // If the referencee type isn't canonical, this won't be a canonical type
2520*67e74705SXin Li   // either, so fill in the canonical type field.
2521*67e74705SXin Li   QualType Canonical;
2522*67e74705SXin Li   if (InnerRef || !T.isCanonical()) {
2523*67e74705SXin Li     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2524*67e74705SXin Li     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2525*67e74705SXin Li 
2526*67e74705SXin Li     // Get the new insert position for the node we care about.
2527*67e74705SXin Li     RValueReferenceType *NewIP =
2528*67e74705SXin Li       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2529*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2530*67e74705SXin Li   }
2531*67e74705SXin Li 
2532*67e74705SXin Li   RValueReferenceType *New
2533*67e74705SXin Li     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2534*67e74705SXin Li   Types.push_back(New);
2535*67e74705SXin Li   RValueReferenceTypes.InsertNode(New, InsertPos);
2536*67e74705SXin Li   return QualType(New, 0);
2537*67e74705SXin Li }
2538*67e74705SXin Li 
2539*67e74705SXin Li /// getMemberPointerType - Return the uniqued reference to the type for a
2540*67e74705SXin Li /// member pointer to the specified type, in the specified class.
getMemberPointerType(QualType T,const Type * Cls) const2541*67e74705SXin Li QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2542*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
2543*67e74705SXin Li   // structure.
2544*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2545*67e74705SXin Li   MemberPointerType::Profile(ID, T, Cls);
2546*67e74705SXin Li 
2547*67e74705SXin Li   void *InsertPos = nullptr;
2548*67e74705SXin Li   if (MemberPointerType *PT =
2549*67e74705SXin Li       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2550*67e74705SXin Li     return QualType(PT, 0);
2551*67e74705SXin Li 
2552*67e74705SXin Li   // If the pointee or class type isn't canonical, this won't be a canonical
2553*67e74705SXin Li   // type either, so fill in the canonical type field.
2554*67e74705SXin Li   QualType Canonical;
2555*67e74705SXin Li   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2556*67e74705SXin Li     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2557*67e74705SXin Li 
2558*67e74705SXin Li     // Get the new insert position for the node we care about.
2559*67e74705SXin Li     MemberPointerType *NewIP =
2560*67e74705SXin Li       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2561*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2562*67e74705SXin Li   }
2563*67e74705SXin Li   MemberPointerType *New
2564*67e74705SXin Li     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2565*67e74705SXin Li   Types.push_back(New);
2566*67e74705SXin Li   MemberPointerTypes.InsertNode(New, InsertPos);
2567*67e74705SXin Li   return QualType(New, 0);
2568*67e74705SXin Li }
2569*67e74705SXin Li 
2570*67e74705SXin Li /// getConstantArrayType - Return the unique reference to the type for an
2571*67e74705SXin Li /// array of the specified element type.
getConstantArrayType(QualType EltTy,const llvm::APInt & ArySizeIn,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals) const2572*67e74705SXin Li QualType ASTContext::getConstantArrayType(QualType EltTy,
2573*67e74705SXin Li                                           const llvm::APInt &ArySizeIn,
2574*67e74705SXin Li                                           ArrayType::ArraySizeModifier ASM,
2575*67e74705SXin Li                                           unsigned IndexTypeQuals) const {
2576*67e74705SXin Li   assert((EltTy->isDependentType() ||
2577*67e74705SXin Li           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2578*67e74705SXin Li          "Constant array of VLAs is illegal!");
2579*67e74705SXin Li 
2580*67e74705SXin Li   // Convert the array size into a canonical width matching the pointer size for
2581*67e74705SXin Li   // the target.
2582*67e74705SXin Li   llvm::APInt ArySize(ArySizeIn);
2583*67e74705SXin Li   ArySize =
2584*67e74705SXin Li     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2585*67e74705SXin Li 
2586*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2587*67e74705SXin Li   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2588*67e74705SXin Li 
2589*67e74705SXin Li   void *InsertPos = nullptr;
2590*67e74705SXin Li   if (ConstantArrayType *ATP =
2591*67e74705SXin Li       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2592*67e74705SXin Li     return QualType(ATP, 0);
2593*67e74705SXin Li 
2594*67e74705SXin Li   // If the element type isn't canonical or has qualifiers, this won't
2595*67e74705SXin Li   // be a canonical type either, so fill in the canonical type field.
2596*67e74705SXin Li   QualType Canon;
2597*67e74705SXin Li   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2598*67e74705SXin Li     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2599*67e74705SXin Li     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2600*67e74705SXin Li                                  ASM, IndexTypeQuals);
2601*67e74705SXin Li     Canon = getQualifiedType(Canon, canonSplit.Quals);
2602*67e74705SXin Li 
2603*67e74705SXin Li     // Get the new insert position for the node we care about.
2604*67e74705SXin Li     ConstantArrayType *NewIP =
2605*67e74705SXin Li       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2606*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2607*67e74705SXin Li   }
2608*67e74705SXin Li 
2609*67e74705SXin Li   ConstantArrayType *New = new(*this,TypeAlignment)
2610*67e74705SXin Li     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2611*67e74705SXin Li   ConstantArrayTypes.InsertNode(New, InsertPos);
2612*67e74705SXin Li   Types.push_back(New);
2613*67e74705SXin Li   return QualType(New, 0);
2614*67e74705SXin Li }
2615*67e74705SXin Li 
2616*67e74705SXin Li /// getVariableArrayDecayedType - Turns the given type, which may be
2617*67e74705SXin Li /// variably-modified, into the corresponding type with all the known
2618*67e74705SXin Li /// sizes replaced with [*].
getVariableArrayDecayedType(QualType type) const2619*67e74705SXin Li QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2620*67e74705SXin Li   // Vastly most common case.
2621*67e74705SXin Li   if (!type->isVariablyModifiedType()) return type;
2622*67e74705SXin Li 
2623*67e74705SXin Li   QualType result;
2624*67e74705SXin Li 
2625*67e74705SXin Li   SplitQualType split = type.getSplitDesugaredType();
2626*67e74705SXin Li   const Type *ty = split.Ty;
2627*67e74705SXin Li   switch (ty->getTypeClass()) {
2628*67e74705SXin Li #define TYPE(Class, Base)
2629*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
2630*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2631*67e74705SXin Li #include "clang/AST/TypeNodes.def"
2632*67e74705SXin Li     llvm_unreachable("didn't desugar past all non-canonical types?");
2633*67e74705SXin Li 
2634*67e74705SXin Li   // These types should never be variably-modified.
2635*67e74705SXin Li   case Type::Builtin:
2636*67e74705SXin Li   case Type::Complex:
2637*67e74705SXin Li   case Type::Vector:
2638*67e74705SXin Li   case Type::ExtVector:
2639*67e74705SXin Li   case Type::DependentSizedExtVector:
2640*67e74705SXin Li   case Type::ObjCObject:
2641*67e74705SXin Li   case Type::ObjCInterface:
2642*67e74705SXin Li   case Type::ObjCObjectPointer:
2643*67e74705SXin Li   case Type::Record:
2644*67e74705SXin Li   case Type::Enum:
2645*67e74705SXin Li   case Type::UnresolvedUsing:
2646*67e74705SXin Li   case Type::TypeOfExpr:
2647*67e74705SXin Li   case Type::TypeOf:
2648*67e74705SXin Li   case Type::Decltype:
2649*67e74705SXin Li   case Type::UnaryTransform:
2650*67e74705SXin Li   case Type::DependentName:
2651*67e74705SXin Li   case Type::InjectedClassName:
2652*67e74705SXin Li   case Type::TemplateSpecialization:
2653*67e74705SXin Li   case Type::DependentTemplateSpecialization:
2654*67e74705SXin Li   case Type::TemplateTypeParm:
2655*67e74705SXin Li   case Type::SubstTemplateTypeParmPack:
2656*67e74705SXin Li   case Type::Auto:
2657*67e74705SXin Li   case Type::PackExpansion:
2658*67e74705SXin Li     llvm_unreachable("type should never be variably-modified");
2659*67e74705SXin Li 
2660*67e74705SXin Li   // These types can be variably-modified but should never need to
2661*67e74705SXin Li   // further decay.
2662*67e74705SXin Li   case Type::FunctionNoProto:
2663*67e74705SXin Li   case Type::FunctionProto:
2664*67e74705SXin Li   case Type::BlockPointer:
2665*67e74705SXin Li   case Type::MemberPointer:
2666*67e74705SXin Li   case Type::Pipe:
2667*67e74705SXin Li     return type;
2668*67e74705SXin Li 
2669*67e74705SXin Li   // These types can be variably-modified.  All these modifications
2670*67e74705SXin Li   // preserve structure except as noted by comments.
2671*67e74705SXin Li   // TODO: if we ever care about optimizing VLAs, there are no-op
2672*67e74705SXin Li   // optimizations available here.
2673*67e74705SXin Li   case Type::Pointer:
2674*67e74705SXin Li     result = getPointerType(getVariableArrayDecayedType(
2675*67e74705SXin Li                               cast<PointerType>(ty)->getPointeeType()));
2676*67e74705SXin Li     break;
2677*67e74705SXin Li 
2678*67e74705SXin Li   case Type::LValueReference: {
2679*67e74705SXin Li     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2680*67e74705SXin Li     result = getLValueReferenceType(
2681*67e74705SXin Li                  getVariableArrayDecayedType(lv->getPointeeType()),
2682*67e74705SXin Li                                     lv->isSpelledAsLValue());
2683*67e74705SXin Li     break;
2684*67e74705SXin Li   }
2685*67e74705SXin Li 
2686*67e74705SXin Li   case Type::RValueReference: {
2687*67e74705SXin Li     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2688*67e74705SXin Li     result = getRValueReferenceType(
2689*67e74705SXin Li                  getVariableArrayDecayedType(lv->getPointeeType()));
2690*67e74705SXin Li     break;
2691*67e74705SXin Li   }
2692*67e74705SXin Li 
2693*67e74705SXin Li   case Type::Atomic: {
2694*67e74705SXin Li     const AtomicType *at = cast<AtomicType>(ty);
2695*67e74705SXin Li     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2696*67e74705SXin Li     break;
2697*67e74705SXin Li   }
2698*67e74705SXin Li 
2699*67e74705SXin Li   case Type::ConstantArray: {
2700*67e74705SXin Li     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2701*67e74705SXin Li     result = getConstantArrayType(
2702*67e74705SXin Li                  getVariableArrayDecayedType(cat->getElementType()),
2703*67e74705SXin Li                                   cat->getSize(),
2704*67e74705SXin Li                                   cat->getSizeModifier(),
2705*67e74705SXin Li                                   cat->getIndexTypeCVRQualifiers());
2706*67e74705SXin Li     break;
2707*67e74705SXin Li   }
2708*67e74705SXin Li 
2709*67e74705SXin Li   case Type::DependentSizedArray: {
2710*67e74705SXin Li     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2711*67e74705SXin Li     result = getDependentSizedArrayType(
2712*67e74705SXin Li                  getVariableArrayDecayedType(dat->getElementType()),
2713*67e74705SXin Li                                         dat->getSizeExpr(),
2714*67e74705SXin Li                                         dat->getSizeModifier(),
2715*67e74705SXin Li                                         dat->getIndexTypeCVRQualifiers(),
2716*67e74705SXin Li                                         dat->getBracketsRange());
2717*67e74705SXin Li     break;
2718*67e74705SXin Li   }
2719*67e74705SXin Li 
2720*67e74705SXin Li   // Turn incomplete types into [*] types.
2721*67e74705SXin Li   case Type::IncompleteArray: {
2722*67e74705SXin Li     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2723*67e74705SXin Li     result = getVariableArrayType(
2724*67e74705SXin Li                  getVariableArrayDecayedType(iat->getElementType()),
2725*67e74705SXin Li                                   /*size*/ nullptr,
2726*67e74705SXin Li                                   ArrayType::Normal,
2727*67e74705SXin Li                                   iat->getIndexTypeCVRQualifiers(),
2728*67e74705SXin Li                                   SourceRange());
2729*67e74705SXin Li     break;
2730*67e74705SXin Li   }
2731*67e74705SXin Li 
2732*67e74705SXin Li   // Turn VLA types into [*] types.
2733*67e74705SXin Li   case Type::VariableArray: {
2734*67e74705SXin Li     const VariableArrayType *vat = cast<VariableArrayType>(ty);
2735*67e74705SXin Li     result = getVariableArrayType(
2736*67e74705SXin Li                  getVariableArrayDecayedType(vat->getElementType()),
2737*67e74705SXin Li                                   /*size*/ nullptr,
2738*67e74705SXin Li                                   ArrayType::Star,
2739*67e74705SXin Li                                   vat->getIndexTypeCVRQualifiers(),
2740*67e74705SXin Li                                   vat->getBracketsRange());
2741*67e74705SXin Li     break;
2742*67e74705SXin Li   }
2743*67e74705SXin Li   }
2744*67e74705SXin Li 
2745*67e74705SXin Li   // Apply the top-level qualifiers from the original.
2746*67e74705SXin Li   return getQualifiedType(result, split.Quals);
2747*67e74705SXin Li }
2748*67e74705SXin Li 
2749*67e74705SXin Li /// getVariableArrayType - Returns a non-unique reference to the type for a
2750*67e74705SXin Li /// variable array of the specified element type.
getVariableArrayType(QualType EltTy,Expr * NumElts,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals,SourceRange Brackets) const2751*67e74705SXin Li QualType ASTContext::getVariableArrayType(QualType EltTy,
2752*67e74705SXin Li                                           Expr *NumElts,
2753*67e74705SXin Li                                           ArrayType::ArraySizeModifier ASM,
2754*67e74705SXin Li                                           unsigned IndexTypeQuals,
2755*67e74705SXin Li                                           SourceRange Brackets) const {
2756*67e74705SXin Li   // Since we don't unique expressions, it isn't possible to unique VLA's
2757*67e74705SXin Li   // that have an expression provided for their size.
2758*67e74705SXin Li   QualType Canon;
2759*67e74705SXin Li 
2760*67e74705SXin Li   // Be sure to pull qualifiers off the element type.
2761*67e74705SXin Li   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2762*67e74705SXin Li     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2763*67e74705SXin Li     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2764*67e74705SXin Li                                  IndexTypeQuals, Brackets);
2765*67e74705SXin Li     Canon = getQualifiedType(Canon, canonSplit.Quals);
2766*67e74705SXin Li   }
2767*67e74705SXin Li 
2768*67e74705SXin Li   VariableArrayType *New = new(*this, TypeAlignment)
2769*67e74705SXin Li     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2770*67e74705SXin Li 
2771*67e74705SXin Li   VariableArrayTypes.push_back(New);
2772*67e74705SXin Li   Types.push_back(New);
2773*67e74705SXin Li   return QualType(New, 0);
2774*67e74705SXin Li }
2775*67e74705SXin Li 
2776*67e74705SXin Li /// getDependentSizedArrayType - Returns a non-unique reference to
2777*67e74705SXin Li /// the type for a dependently-sized array of the specified element
2778*67e74705SXin Li /// type.
getDependentSizedArrayType(QualType elementType,Expr * numElements,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals,SourceRange brackets) const2779*67e74705SXin Li QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2780*67e74705SXin Li                                                 Expr *numElements,
2781*67e74705SXin Li                                                 ArrayType::ArraySizeModifier ASM,
2782*67e74705SXin Li                                                 unsigned elementTypeQuals,
2783*67e74705SXin Li                                                 SourceRange brackets) const {
2784*67e74705SXin Li   assert((!numElements || numElements->isTypeDependent() ||
2785*67e74705SXin Li           numElements->isValueDependent()) &&
2786*67e74705SXin Li          "Size must be type- or value-dependent!");
2787*67e74705SXin Li 
2788*67e74705SXin Li   // Dependently-sized array types that do not have a specified number
2789*67e74705SXin Li   // of elements will have their sizes deduced from a dependent
2790*67e74705SXin Li   // initializer.  We do no canonicalization here at all, which is okay
2791*67e74705SXin Li   // because they can't be used in most locations.
2792*67e74705SXin Li   if (!numElements) {
2793*67e74705SXin Li     DependentSizedArrayType *newType
2794*67e74705SXin Li       = new (*this, TypeAlignment)
2795*67e74705SXin Li           DependentSizedArrayType(*this, elementType, QualType(),
2796*67e74705SXin Li                                   numElements, ASM, elementTypeQuals,
2797*67e74705SXin Li                                   brackets);
2798*67e74705SXin Li     Types.push_back(newType);
2799*67e74705SXin Li     return QualType(newType, 0);
2800*67e74705SXin Li   }
2801*67e74705SXin Li 
2802*67e74705SXin Li   // Otherwise, we actually build a new type every time, but we
2803*67e74705SXin Li   // also build a canonical type.
2804*67e74705SXin Li 
2805*67e74705SXin Li   SplitQualType canonElementType = getCanonicalType(elementType).split();
2806*67e74705SXin Li 
2807*67e74705SXin Li   void *insertPos = nullptr;
2808*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2809*67e74705SXin Li   DependentSizedArrayType::Profile(ID, *this,
2810*67e74705SXin Li                                    QualType(canonElementType.Ty, 0),
2811*67e74705SXin Li                                    ASM, elementTypeQuals, numElements);
2812*67e74705SXin Li 
2813*67e74705SXin Li   // Look for an existing type with these properties.
2814*67e74705SXin Li   DependentSizedArrayType *canonTy =
2815*67e74705SXin Li     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2816*67e74705SXin Li 
2817*67e74705SXin Li   // If we don't have one, build one.
2818*67e74705SXin Li   if (!canonTy) {
2819*67e74705SXin Li     canonTy = new (*this, TypeAlignment)
2820*67e74705SXin Li       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2821*67e74705SXin Li                               QualType(), numElements, ASM, elementTypeQuals,
2822*67e74705SXin Li                               brackets);
2823*67e74705SXin Li     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2824*67e74705SXin Li     Types.push_back(canonTy);
2825*67e74705SXin Li   }
2826*67e74705SXin Li 
2827*67e74705SXin Li   // Apply qualifiers from the element type to the array.
2828*67e74705SXin Li   QualType canon = getQualifiedType(QualType(canonTy,0),
2829*67e74705SXin Li                                     canonElementType.Quals);
2830*67e74705SXin Li 
2831*67e74705SXin Li   // If we didn't need extra canonicalization for the element type or the size
2832*67e74705SXin Li   // expression, then just use that as our result.
2833*67e74705SXin Li   if (QualType(canonElementType.Ty, 0) == elementType &&
2834*67e74705SXin Li       canonTy->getSizeExpr() == numElements)
2835*67e74705SXin Li     return canon;
2836*67e74705SXin Li 
2837*67e74705SXin Li   // Otherwise, we need to build a type which follows the spelling
2838*67e74705SXin Li   // of the element type.
2839*67e74705SXin Li   DependentSizedArrayType *sugaredType
2840*67e74705SXin Li     = new (*this, TypeAlignment)
2841*67e74705SXin Li         DependentSizedArrayType(*this, elementType, canon, numElements,
2842*67e74705SXin Li                                 ASM, elementTypeQuals, brackets);
2843*67e74705SXin Li   Types.push_back(sugaredType);
2844*67e74705SXin Li   return QualType(sugaredType, 0);
2845*67e74705SXin Li }
2846*67e74705SXin Li 
getIncompleteArrayType(QualType elementType,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals) const2847*67e74705SXin Li QualType ASTContext::getIncompleteArrayType(QualType elementType,
2848*67e74705SXin Li                                             ArrayType::ArraySizeModifier ASM,
2849*67e74705SXin Li                                             unsigned elementTypeQuals) const {
2850*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2851*67e74705SXin Li   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2852*67e74705SXin Li 
2853*67e74705SXin Li   void *insertPos = nullptr;
2854*67e74705SXin Li   if (IncompleteArrayType *iat =
2855*67e74705SXin Li        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2856*67e74705SXin Li     return QualType(iat, 0);
2857*67e74705SXin Li 
2858*67e74705SXin Li   // If the element type isn't canonical, this won't be a canonical type
2859*67e74705SXin Li   // either, so fill in the canonical type field.  We also have to pull
2860*67e74705SXin Li   // qualifiers off the element type.
2861*67e74705SXin Li   QualType canon;
2862*67e74705SXin Li 
2863*67e74705SXin Li   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2864*67e74705SXin Li     SplitQualType canonSplit = getCanonicalType(elementType).split();
2865*67e74705SXin Li     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2866*67e74705SXin Li                                    ASM, elementTypeQuals);
2867*67e74705SXin Li     canon = getQualifiedType(canon, canonSplit.Quals);
2868*67e74705SXin Li 
2869*67e74705SXin Li     // Get the new insert position for the node we care about.
2870*67e74705SXin Li     IncompleteArrayType *existing =
2871*67e74705SXin Li       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2872*67e74705SXin Li     assert(!existing && "Shouldn't be in the map!"); (void) existing;
2873*67e74705SXin Li   }
2874*67e74705SXin Li 
2875*67e74705SXin Li   IncompleteArrayType *newType = new (*this, TypeAlignment)
2876*67e74705SXin Li     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2877*67e74705SXin Li 
2878*67e74705SXin Li   IncompleteArrayTypes.InsertNode(newType, insertPos);
2879*67e74705SXin Li   Types.push_back(newType);
2880*67e74705SXin Li   return QualType(newType, 0);
2881*67e74705SXin Li }
2882*67e74705SXin Li 
2883*67e74705SXin Li /// getVectorType - Return the unique reference to a vector type of
2884*67e74705SXin Li /// the specified element type and size. VectorType must be a built-in type.
getVectorType(QualType vecType,unsigned NumElts,VectorType::VectorKind VecKind) const2885*67e74705SXin Li QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2886*67e74705SXin Li                                    VectorType::VectorKind VecKind) const {
2887*67e74705SXin Li   assert(vecType->isBuiltinType());
2888*67e74705SXin Li 
2889*67e74705SXin Li   // Check if we've already instantiated a vector of this type.
2890*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2891*67e74705SXin Li   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2892*67e74705SXin Li 
2893*67e74705SXin Li   void *InsertPos = nullptr;
2894*67e74705SXin Li   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2895*67e74705SXin Li     return QualType(VTP, 0);
2896*67e74705SXin Li 
2897*67e74705SXin Li   // If the element type isn't canonical, this won't be a canonical type either,
2898*67e74705SXin Li   // so fill in the canonical type field.
2899*67e74705SXin Li   QualType Canonical;
2900*67e74705SXin Li   if (!vecType.isCanonical()) {
2901*67e74705SXin Li     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2902*67e74705SXin Li 
2903*67e74705SXin Li     // Get the new insert position for the node we care about.
2904*67e74705SXin Li     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2905*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2906*67e74705SXin Li   }
2907*67e74705SXin Li   VectorType *New = new (*this, TypeAlignment)
2908*67e74705SXin Li     VectorType(vecType, NumElts, Canonical, VecKind);
2909*67e74705SXin Li   VectorTypes.InsertNode(New, InsertPos);
2910*67e74705SXin Li   Types.push_back(New);
2911*67e74705SXin Li   return QualType(New, 0);
2912*67e74705SXin Li }
2913*67e74705SXin Li 
2914*67e74705SXin Li /// getExtVectorType - Return the unique reference to an extended vector type of
2915*67e74705SXin Li /// the specified element type and size. VectorType must be a built-in type.
2916*67e74705SXin Li QualType
getExtVectorType(QualType vecType,unsigned NumElts) const2917*67e74705SXin Li ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2918*67e74705SXin Li   assert(vecType->isBuiltinType() || vecType->isDependentType());
2919*67e74705SXin Li 
2920*67e74705SXin Li   // Check if we've already instantiated a vector of this type.
2921*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2922*67e74705SXin Li   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2923*67e74705SXin Li                       VectorType::GenericVector);
2924*67e74705SXin Li   void *InsertPos = nullptr;
2925*67e74705SXin Li   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2926*67e74705SXin Li     return QualType(VTP, 0);
2927*67e74705SXin Li 
2928*67e74705SXin Li   // If the element type isn't canonical, this won't be a canonical type either,
2929*67e74705SXin Li   // so fill in the canonical type field.
2930*67e74705SXin Li   QualType Canonical;
2931*67e74705SXin Li   if (!vecType.isCanonical()) {
2932*67e74705SXin Li     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2933*67e74705SXin Li 
2934*67e74705SXin Li     // Get the new insert position for the node we care about.
2935*67e74705SXin Li     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2936*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2937*67e74705SXin Li   }
2938*67e74705SXin Li   ExtVectorType *New = new (*this, TypeAlignment)
2939*67e74705SXin Li     ExtVectorType(vecType, NumElts, Canonical);
2940*67e74705SXin Li   VectorTypes.InsertNode(New, InsertPos);
2941*67e74705SXin Li   Types.push_back(New);
2942*67e74705SXin Li   return QualType(New, 0);
2943*67e74705SXin Li }
2944*67e74705SXin Li 
2945*67e74705SXin Li QualType
getDependentSizedExtVectorType(QualType vecType,Expr * SizeExpr,SourceLocation AttrLoc) const2946*67e74705SXin Li ASTContext::getDependentSizedExtVectorType(QualType vecType,
2947*67e74705SXin Li                                            Expr *SizeExpr,
2948*67e74705SXin Li                                            SourceLocation AttrLoc) const {
2949*67e74705SXin Li   llvm::FoldingSetNodeID ID;
2950*67e74705SXin Li   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2951*67e74705SXin Li                                        SizeExpr);
2952*67e74705SXin Li 
2953*67e74705SXin Li   void *InsertPos = nullptr;
2954*67e74705SXin Li   DependentSizedExtVectorType *Canon
2955*67e74705SXin Li     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2956*67e74705SXin Li   DependentSizedExtVectorType *New;
2957*67e74705SXin Li   if (Canon) {
2958*67e74705SXin Li     // We already have a canonical version of this array type; use it as
2959*67e74705SXin Li     // the canonical type for a newly-built type.
2960*67e74705SXin Li     New = new (*this, TypeAlignment)
2961*67e74705SXin Li       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2962*67e74705SXin Li                                   SizeExpr, AttrLoc);
2963*67e74705SXin Li   } else {
2964*67e74705SXin Li     QualType CanonVecTy = getCanonicalType(vecType);
2965*67e74705SXin Li     if (CanonVecTy == vecType) {
2966*67e74705SXin Li       New = new (*this, TypeAlignment)
2967*67e74705SXin Li         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2968*67e74705SXin Li                                     AttrLoc);
2969*67e74705SXin Li 
2970*67e74705SXin Li       DependentSizedExtVectorType *CanonCheck
2971*67e74705SXin Li         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2972*67e74705SXin Li       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2973*67e74705SXin Li       (void)CanonCheck;
2974*67e74705SXin Li       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2975*67e74705SXin Li     } else {
2976*67e74705SXin Li       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2977*67e74705SXin Li                                                       SourceLocation());
2978*67e74705SXin Li       New = new (*this, TypeAlignment)
2979*67e74705SXin Li         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2980*67e74705SXin Li     }
2981*67e74705SXin Li   }
2982*67e74705SXin Li 
2983*67e74705SXin Li   Types.push_back(New);
2984*67e74705SXin Li   return QualType(New, 0);
2985*67e74705SXin Li }
2986*67e74705SXin Li 
2987*67e74705SXin Li /// \brief Determine whether \p T is canonical as the result type of a function.
isCanonicalResultType(QualType T)2988*67e74705SXin Li static bool isCanonicalResultType(QualType T) {
2989*67e74705SXin Li   return T.isCanonical() &&
2990*67e74705SXin Li          (T.getObjCLifetime() == Qualifiers::OCL_None ||
2991*67e74705SXin Li           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2992*67e74705SXin Li }
2993*67e74705SXin Li 
2994*67e74705SXin Li /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2995*67e74705SXin Li ///
2996*67e74705SXin Li QualType
getFunctionNoProtoType(QualType ResultTy,const FunctionType::ExtInfo & Info) const2997*67e74705SXin Li ASTContext::getFunctionNoProtoType(QualType ResultTy,
2998*67e74705SXin Li                                    const FunctionType::ExtInfo &Info) const {
2999*67e74705SXin Li   // Unique functions, to guarantee there is only one function of a particular
3000*67e74705SXin Li   // structure.
3001*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3002*67e74705SXin Li   FunctionNoProtoType::Profile(ID, ResultTy, Info);
3003*67e74705SXin Li 
3004*67e74705SXin Li   void *InsertPos = nullptr;
3005*67e74705SXin Li   if (FunctionNoProtoType *FT =
3006*67e74705SXin Li         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3007*67e74705SXin Li     return QualType(FT, 0);
3008*67e74705SXin Li 
3009*67e74705SXin Li   QualType Canonical;
3010*67e74705SXin Li   if (!isCanonicalResultType(ResultTy)) {
3011*67e74705SXin Li     Canonical =
3012*67e74705SXin Li       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3013*67e74705SXin Li 
3014*67e74705SXin Li     // Get the new insert position for the node we care about.
3015*67e74705SXin Li     FunctionNoProtoType *NewIP =
3016*67e74705SXin Li       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3017*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3018*67e74705SXin Li   }
3019*67e74705SXin Li 
3020*67e74705SXin Li   FunctionNoProtoType *New = new (*this, TypeAlignment)
3021*67e74705SXin Li     FunctionNoProtoType(ResultTy, Canonical, Info);
3022*67e74705SXin Li   Types.push_back(New);
3023*67e74705SXin Li   FunctionNoProtoTypes.InsertNode(New, InsertPos);
3024*67e74705SXin Li   return QualType(New, 0);
3025*67e74705SXin Li }
3026*67e74705SXin Li 
3027*67e74705SXin Li CanQualType
getCanonicalFunctionResultType(QualType ResultType) const3028*67e74705SXin Li ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3029*67e74705SXin Li   CanQualType CanResultType = getCanonicalType(ResultType);
3030*67e74705SXin Li 
3031*67e74705SXin Li   // Canonical result types do not have ARC lifetime qualifiers.
3032*67e74705SXin Li   if (CanResultType.getQualifiers().hasObjCLifetime()) {
3033*67e74705SXin Li     Qualifiers Qs = CanResultType.getQualifiers();
3034*67e74705SXin Li     Qs.removeObjCLifetime();
3035*67e74705SXin Li     return CanQualType::CreateUnsafe(
3036*67e74705SXin Li              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3037*67e74705SXin Li   }
3038*67e74705SXin Li 
3039*67e74705SXin Li   return CanResultType;
3040*67e74705SXin Li }
3041*67e74705SXin Li 
3042*67e74705SXin Li QualType
getFunctionType(QualType ResultTy,ArrayRef<QualType> ArgArray,const FunctionProtoType::ExtProtoInfo & EPI) const3043*67e74705SXin Li ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
3044*67e74705SXin Li                             const FunctionProtoType::ExtProtoInfo &EPI) const {
3045*67e74705SXin Li   size_t NumArgs = ArgArray.size();
3046*67e74705SXin Li 
3047*67e74705SXin Li   // Unique functions, to guarantee there is only one function of a particular
3048*67e74705SXin Li   // structure.
3049*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3050*67e74705SXin Li   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3051*67e74705SXin Li                              *this);
3052*67e74705SXin Li 
3053*67e74705SXin Li   void *InsertPos = nullptr;
3054*67e74705SXin Li   if (FunctionProtoType *FTP =
3055*67e74705SXin Li         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3056*67e74705SXin Li     return QualType(FTP, 0);
3057*67e74705SXin Li 
3058*67e74705SXin Li   // Determine whether the type being created is already canonical or not.
3059*67e74705SXin Li   bool isCanonical =
3060*67e74705SXin Li     EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
3061*67e74705SXin Li     !EPI.HasTrailingReturn;
3062*67e74705SXin Li   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3063*67e74705SXin Li     if (!ArgArray[i].isCanonicalAsParam())
3064*67e74705SXin Li       isCanonical = false;
3065*67e74705SXin Li 
3066*67e74705SXin Li   // If this type isn't canonical, get the canonical version of it.
3067*67e74705SXin Li   // The exception spec is not part of the canonical type.
3068*67e74705SXin Li   QualType Canonical;
3069*67e74705SXin Li   if (!isCanonical) {
3070*67e74705SXin Li     SmallVector<QualType, 16> CanonicalArgs;
3071*67e74705SXin Li     CanonicalArgs.reserve(NumArgs);
3072*67e74705SXin Li     for (unsigned i = 0; i != NumArgs; ++i)
3073*67e74705SXin Li       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3074*67e74705SXin Li 
3075*67e74705SXin Li     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3076*67e74705SXin Li     CanonicalEPI.HasTrailingReturn = false;
3077*67e74705SXin Li     CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3078*67e74705SXin Li 
3079*67e74705SXin Li     // Adjust the canonical function result type.
3080*67e74705SXin Li     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3081*67e74705SXin Li     Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3082*67e74705SXin Li 
3083*67e74705SXin Li     // Get the new insert position for the node we care about.
3084*67e74705SXin Li     FunctionProtoType *NewIP =
3085*67e74705SXin Li       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3086*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3087*67e74705SXin Li   }
3088*67e74705SXin Li 
3089*67e74705SXin Li   // FunctionProtoType objects are allocated with extra bytes after
3090*67e74705SXin Li   // them for three variable size arrays at the end:
3091*67e74705SXin Li   //  - parameter types
3092*67e74705SXin Li   //  - exception types
3093*67e74705SXin Li   //  - extended parameter information
3094*67e74705SXin Li   // Instead of the exception types, there could be a noexcept
3095*67e74705SXin Li   // expression, or information used to resolve the exception
3096*67e74705SXin Li   // specification.
3097*67e74705SXin Li   size_t Size = sizeof(FunctionProtoType) +
3098*67e74705SXin Li                 NumArgs * sizeof(QualType);
3099*67e74705SXin Li 
3100*67e74705SXin Li   if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3101*67e74705SXin Li     Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3102*67e74705SXin Li   } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3103*67e74705SXin Li     Size += sizeof(Expr*);
3104*67e74705SXin Li   } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3105*67e74705SXin Li     Size += 2 * sizeof(FunctionDecl*);
3106*67e74705SXin Li   } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3107*67e74705SXin Li     Size += sizeof(FunctionDecl*);
3108*67e74705SXin Li   }
3109*67e74705SXin Li 
3110*67e74705SXin Li   // Put the ExtParameterInfos last.  If all were equal, it would make
3111*67e74705SXin Li   // more sense to put these before the exception specification, because
3112*67e74705SXin Li   // it's much easier to skip past them compared to the elaborate switch
3113*67e74705SXin Li   // required to skip the exception specification.  However, all is not
3114*67e74705SXin Li   // equal; ExtParameterInfos are used to model very uncommon features,
3115*67e74705SXin Li   // and it's better not to burden the more common paths.
3116*67e74705SXin Li   if (EPI.ExtParameterInfos) {
3117*67e74705SXin Li     Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3118*67e74705SXin Li   }
3119*67e74705SXin Li 
3120*67e74705SXin Li   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3121*67e74705SXin Li   FunctionProtoType::ExtProtoInfo newEPI = EPI;
3122*67e74705SXin Li   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3123*67e74705SXin Li   Types.push_back(FTP);
3124*67e74705SXin Li   FunctionProtoTypes.InsertNode(FTP, InsertPos);
3125*67e74705SXin Li   return QualType(FTP, 0);
3126*67e74705SXin Li }
3127*67e74705SXin Li 
3128*67e74705SXin Li /// Return pipe type for the specified type.
getPipeType(QualType T) const3129*67e74705SXin Li QualType ASTContext::getPipeType(QualType T) const {
3130*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3131*67e74705SXin Li   PipeType::Profile(ID, T);
3132*67e74705SXin Li 
3133*67e74705SXin Li   void *InsertPos = 0;
3134*67e74705SXin Li   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3135*67e74705SXin Li     return QualType(PT, 0);
3136*67e74705SXin Li 
3137*67e74705SXin Li   // If the pipe element type isn't canonical, this won't be a canonical type
3138*67e74705SXin Li   // either, so fill in the canonical type field.
3139*67e74705SXin Li   QualType Canonical;
3140*67e74705SXin Li   if (!T.isCanonical()) {
3141*67e74705SXin Li     Canonical = getPipeType(getCanonicalType(T));
3142*67e74705SXin Li 
3143*67e74705SXin Li     // Get the new insert position for the node we care about.
3144*67e74705SXin Li     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3145*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!");
3146*67e74705SXin Li     (void)NewIP;
3147*67e74705SXin Li   }
3148*67e74705SXin Li   PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3149*67e74705SXin Li   Types.push_back(New);
3150*67e74705SXin Li   PipeTypes.InsertNode(New, InsertPos);
3151*67e74705SXin Li   return QualType(New, 0);
3152*67e74705SXin Li }
3153*67e74705SXin Li 
3154*67e74705SXin Li #ifndef NDEBUG
NeedsInjectedClassNameType(const RecordDecl * D)3155*67e74705SXin Li static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3156*67e74705SXin Li   if (!isa<CXXRecordDecl>(D)) return false;
3157*67e74705SXin Li   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3158*67e74705SXin Li   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3159*67e74705SXin Li     return true;
3160*67e74705SXin Li   if (RD->getDescribedClassTemplate() &&
3161*67e74705SXin Li       !isa<ClassTemplateSpecializationDecl>(RD))
3162*67e74705SXin Li     return true;
3163*67e74705SXin Li   return false;
3164*67e74705SXin Li }
3165*67e74705SXin Li #endif
3166*67e74705SXin Li 
3167*67e74705SXin Li /// getInjectedClassNameType - Return the unique reference to the
3168*67e74705SXin Li /// injected class name type for the specified templated declaration.
getInjectedClassNameType(CXXRecordDecl * Decl,QualType TST) const3169*67e74705SXin Li QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3170*67e74705SXin Li                                               QualType TST) const {
3171*67e74705SXin Li   assert(NeedsInjectedClassNameType(Decl));
3172*67e74705SXin Li   if (Decl->TypeForDecl) {
3173*67e74705SXin Li     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3174*67e74705SXin Li   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3175*67e74705SXin Li     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3176*67e74705SXin Li     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3177*67e74705SXin Li     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3178*67e74705SXin Li   } else {
3179*67e74705SXin Li     Type *newType =
3180*67e74705SXin Li       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3181*67e74705SXin Li     Decl->TypeForDecl = newType;
3182*67e74705SXin Li     Types.push_back(newType);
3183*67e74705SXin Li   }
3184*67e74705SXin Li   return QualType(Decl->TypeForDecl, 0);
3185*67e74705SXin Li }
3186*67e74705SXin Li 
3187*67e74705SXin Li /// getTypeDeclType - Return the unique reference to the type for the
3188*67e74705SXin Li /// specified type declaration.
getTypeDeclTypeSlow(const TypeDecl * Decl) const3189*67e74705SXin Li QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3190*67e74705SXin Li   assert(Decl && "Passed null for Decl param");
3191*67e74705SXin Li   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3192*67e74705SXin Li 
3193*67e74705SXin Li   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3194*67e74705SXin Li     return getTypedefType(Typedef);
3195*67e74705SXin Li 
3196*67e74705SXin Li   assert(!isa<TemplateTypeParmDecl>(Decl) &&
3197*67e74705SXin Li          "Template type parameter types are always available.");
3198*67e74705SXin Li 
3199*67e74705SXin Li   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3200*67e74705SXin Li     assert(Record->isFirstDecl() && "struct/union has previous declaration");
3201*67e74705SXin Li     assert(!NeedsInjectedClassNameType(Record));
3202*67e74705SXin Li     return getRecordType(Record);
3203*67e74705SXin Li   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3204*67e74705SXin Li     assert(Enum->isFirstDecl() && "enum has previous declaration");
3205*67e74705SXin Li     return getEnumType(Enum);
3206*67e74705SXin Li   } else if (const UnresolvedUsingTypenameDecl *Using =
3207*67e74705SXin Li                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3208*67e74705SXin Li     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3209*67e74705SXin Li     Decl->TypeForDecl = newType;
3210*67e74705SXin Li     Types.push_back(newType);
3211*67e74705SXin Li   } else
3212*67e74705SXin Li     llvm_unreachable("TypeDecl without a type?");
3213*67e74705SXin Li 
3214*67e74705SXin Li   return QualType(Decl->TypeForDecl, 0);
3215*67e74705SXin Li }
3216*67e74705SXin Li 
3217*67e74705SXin Li /// getTypedefType - Return the unique reference to the type for the
3218*67e74705SXin Li /// specified typedef name decl.
3219*67e74705SXin Li QualType
getTypedefType(const TypedefNameDecl * Decl,QualType Canonical) const3220*67e74705SXin Li ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3221*67e74705SXin Li                            QualType Canonical) const {
3222*67e74705SXin Li   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3223*67e74705SXin Li 
3224*67e74705SXin Li   if (Canonical.isNull())
3225*67e74705SXin Li     Canonical = getCanonicalType(Decl->getUnderlyingType());
3226*67e74705SXin Li   TypedefType *newType = new(*this, TypeAlignment)
3227*67e74705SXin Li     TypedefType(Type::Typedef, Decl, Canonical);
3228*67e74705SXin Li   Decl->TypeForDecl = newType;
3229*67e74705SXin Li   Types.push_back(newType);
3230*67e74705SXin Li   return QualType(newType, 0);
3231*67e74705SXin Li }
3232*67e74705SXin Li 
getRecordType(const RecordDecl * Decl) const3233*67e74705SXin Li QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3234*67e74705SXin Li   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3235*67e74705SXin Li 
3236*67e74705SXin Li   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3237*67e74705SXin Li     if (PrevDecl->TypeForDecl)
3238*67e74705SXin Li       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3239*67e74705SXin Li 
3240*67e74705SXin Li   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3241*67e74705SXin Li   Decl->TypeForDecl = newType;
3242*67e74705SXin Li   Types.push_back(newType);
3243*67e74705SXin Li   return QualType(newType, 0);
3244*67e74705SXin Li }
3245*67e74705SXin Li 
getEnumType(const EnumDecl * Decl) const3246*67e74705SXin Li QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3247*67e74705SXin Li   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3248*67e74705SXin Li 
3249*67e74705SXin Li   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3250*67e74705SXin Li     if (PrevDecl->TypeForDecl)
3251*67e74705SXin Li       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3252*67e74705SXin Li 
3253*67e74705SXin Li   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3254*67e74705SXin Li   Decl->TypeForDecl = newType;
3255*67e74705SXin Li   Types.push_back(newType);
3256*67e74705SXin Li   return QualType(newType, 0);
3257*67e74705SXin Li }
3258*67e74705SXin Li 
getAttributedType(AttributedType::Kind attrKind,QualType modifiedType,QualType equivalentType)3259*67e74705SXin Li QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3260*67e74705SXin Li                                        QualType modifiedType,
3261*67e74705SXin Li                                        QualType equivalentType) {
3262*67e74705SXin Li   llvm::FoldingSetNodeID id;
3263*67e74705SXin Li   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3264*67e74705SXin Li 
3265*67e74705SXin Li   void *insertPos = nullptr;
3266*67e74705SXin Li   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3267*67e74705SXin Li   if (type) return QualType(type, 0);
3268*67e74705SXin Li 
3269*67e74705SXin Li   QualType canon = getCanonicalType(equivalentType);
3270*67e74705SXin Li   type = new (*this, TypeAlignment)
3271*67e74705SXin Li            AttributedType(canon, attrKind, modifiedType, equivalentType);
3272*67e74705SXin Li 
3273*67e74705SXin Li   Types.push_back(type);
3274*67e74705SXin Li   AttributedTypes.InsertNode(type, insertPos);
3275*67e74705SXin Li 
3276*67e74705SXin Li   return QualType(type, 0);
3277*67e74705SXin Li }
3278*67e74705SXin Li 
3279*67e74705SXin Li /// \brief Retrieve a substitution-result type.
3280*67e74705SXin Li QualType
getSubstTemplateTypeParmType(const TemplateTypeParmType * Parm,QualType Replacement) const3281*67e74705SXin Li ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3282*67e74705SXin Li                                          QualType Replacement) const {
3283*67e74705SXin Li   assert(Replacement.isCanonical()
3284*67e74705SXin Li          && "replacement types must always be canonical");
3285*67e74705SXin Li 
3286*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3287*67e74705SXin Li   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3288*67e74705SXin Li   void *InsertPos = nullptr;
3289*67e74705SXin Li   SubstTemplateTypeParmType *SubstParm
3290*67e74705SXin Li     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3291*67e74705SXin Li 
3292*67e74705SXin Li   if (!SubstParm) {
3293*67e74705SXin Li     SubstParm = new (*this, TypeAlignment)
3294*67e74705SXin Li       SubstTemplateTypeParmType(Parm, Replacement);
3295*67e74705SXin Li     Types.push_back(SubstParm);
3296*67e74705SXin Li     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3297*67e74705SXin Li   }
3298*67e74705SXin Li 
3299*67e74705SXin Li   return QualType(SubstParm, 0);
3300*67e74705SXin Li }
3301*67e74705SXin Li 
3302*67e74705SXin Li /// \brief Retrieve a
getSubstTemplateTypeParmPackType(const TemplateTypeParmType * Parm,const TemplateArgument & ArgPack)3303*67e74705SXin Li QualType ASTContext::getSubstTemplateTypeParmPackType(
3304*67e74705SXin Li                                           const TemplateTypeParmType *Parm,
3305*67e74705SXin Li                                               const TemplateArgument &ArgPack) {
3306*67e74705SXin Li #ifndef NDEBUG
3307*67e74705SXin Li   for (const auto &P : ArgPack.pack_elements()) {
3308*67e74705SXin Li     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3309*67e74705SXin Li     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3310*67e74705SXin Li   }
3311*67e74705SXin Li #endif
3312*67e74705SXin Li 
3313*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3314*67e74705SXin Li   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3315*67e74705SXin Li   void *InsertPos = nullptr;
3316*67e74705SXin Li   if (SubstTemplateTypeParmPackType *SubstParm
3317*67e74705SXin Li         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3318*67e74705SXin Li     return QualType(SubstParm, 0);
3319*67e74705SXin Li 
3320*67e74705SXin Li   QualType Canon;
3321*67e74705SXin Li   if (!Parm->isCanonicalUnqualified()) {
3322*67e74705SXin Li     Canon = getCanonicalType(QualType(Parm, 0));
3323*67e74705SXin Li     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3324*67e74705SXin Li                                              ArgPack);
3325*67e74705SXin Li     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3326*67e74705SXin Li   }
3327*67e74705SXin Li 
3328*67e74705SXin Li   SubstTemplateTypeParmPackType *SubstParm
3329*67e74705SXin Li     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3330*67e74705SXin Li                                                                ArgPack);
3331*67e74705SXin Li   Types.push_back(SubstParm);
3332*67e74705SXin Li   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3333*67e74705SXin Li   return QualType(SubstParm, 0);
3334*67e74705SXin Li }
3335*67e74705SXin Li 
3336*67e74705SXin Li /// \brief Retrieve the template type parameter type for a template
3337*67e74705SXin Li /// parameter or parameter pack with the given depth, index, and (optionally)
3338*67e74705SXin Li /// name.
getTemplateTypeParmType(unsigned Depth,unsigned Index,bool ParameterPack,TemplateTypeParmDecl * TTPDecl) const3339*67e74705SXin Li QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3340*67e74705SXin Li                                              bool ParameterPack,
3341*67e74705SXin Li                                              TemplateTypeParmDecl *TTPDecl) const {
3342*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3343*67e74705SXin Li   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3344*67e74705SXin Li   void *InsertPos = nullptr;
3345*67e74705SXin Li   TemplateTypeParmType *TypeParm
3346*67e74705SXin Li     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3347*67e74705SXin Li 
3348*67e74705SXin Li   if (TypeParm)
3349*67e74705SXin Li     return QualType(TypeParm, 0);
3350*67e74705SXin Li 
3351*67e74705SXin Li   if (TTPDecl) {
3352*67e74705SXin Li     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3353*67e74705SXin Li     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3354*67e74705SXin Li 
3355*67e74705SXin Li     TemplateTypeParmType *TypeCheck
3356*67e74705SXin Li       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3357*67e74705SXin Li     assert(!TypeCheck && "Template type parameter canonical type broken");
3358*67e74705SXin Li     (void)TypeCheck;
3359*67e74705SXin Li   } else
3360*67e74705SXin Li     TypeParm = new (*this, TypeAlignment)
3361*67e74705SXin Li       TemplateTypeParmType(Depth, Index, ParameterPack);
3362*67e74705SXin Li 
3363*67e74705SXin Li   Types.push_back(TypeParm);
3364*67e74705SXin Li   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3365*67e74705SXin Li 
3366*67e74705SXin Li   return QualType(TypeParm, 0);
3367*67e74705SXin Li }
3368*67e74705SXin Li 
3369*67e74705SXin Li TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName Name,SourceLocation NameLoc,const TemplateArgumentListInfo & Args,QualType Underlying) const3370*67e74705SXin Li ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3371*67e74705SXin Li                                               SourceLocation NameLoc,
3372*67e74705SXin Li                                         const TemplateArgumentListInfo &Args,
3373*67e74705SXin Li                                               QualType Underlying) const {
3374*67e74705SXin Li   assert(!Name.getAsDependentTemplateName() &&
3375*67e74705SXin Li          "No dependent template names here!");
3376*67e74705SXin Li   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3377*67e74705SXin Li 
3378*67e74705SXin Li   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3379*67e74705SXin Li   TemplateSpecializationTypeLoc TL =
3380*67e74705SXin Li       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3381*67e74705SXin Li   TL.setTemplateKeywordLoc(SourceLocation());
3382*67e74705SXin Li   TL.setTemplateNameLoc(NameLoc);
3383*67e74705SXin Li   TL.setLAngleLoc(Args.getLAngleLoc());
3384*67e74705SXin Li   TL.setRAngleLoc(Args.getRAngleLoc());
3385*67e74705SXin Li   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3386*67e74705SXin Li     TL.setArgLocInfo(i, Args[i].getLocInfo());
3387*67e74705SXin Li   return DI;
3388*67e74705SXin Li }
3389*67e74705SXin Li 
3390*67e74705SXin Li QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgumentListInfo & Args,QualType Underlying) const3391*67e74705SXin Li ASTContext::getTemplateSpecializationType(TemplateName Template,
3392*67e74705SXin Li                                           const TemplateArgumentListInfo &Args,
3393*67e74705SXin Li                                           QualType Underlying) const {
3394*67e74705SXin Li   assert(!Template.getAsDependentTemplateName() &&
3395*67e74705SXin Li          "No dependent template names here!");
3396*67e74705SXin Li 
3397*67e74705SXin Li   SmallVector<TemplateArgument, 4> ArgVec;
3398*67e74705SXin Li   ArgVec.reserve(Args.size());
3399*67e74705SXin Li   for (const TemplateArgumentLoc &Arg : Args.arguments())
3400*67e74705SXin Li     ArgVec.push_back(Arg.getArgument());
3401*67e74705SXin Li 
3402*67e74705SXin Li   return getTemplateSpecializationType(Template, ArgVec, Underlying);
3403*67e74705SXin Li }
3404*67e74705SXin Li 
3405*67e74705SXin Li #ifndef NDEBUG
hasAnyPackExpansions(ArrayRef<TemplateArgument> Args)3406*67e74705SXin Li static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3407*67e74705SXin Li   for (const TemplateArgument &Arg : Args)
3408*67e74705SXin Li     if (Arg.isPackExpansion())
3409*67e74705SXin Li       return true;
3410*67e74705SXin Li 
3411*67e74705SXin Li   return true;
3412*67e74705SXin Li }
3413*67e74705SXin Li #endif
3414*67e74705SXin Li 
3415*67e74705SXin Li QualType
getTemplateSpecializationType(TemplateName Template,ArrayRef<TemplateArgument> Args,QualType Underlying) const3416*67e74705SXin Li ASTContext::getTemplateSpecializationType(TemplateName Template,
3417*67e74705SXin Li                                           ArrayRef<TemplateArgument> Args,
3418*67e74705SXin Li                                           QualType Underlying) const {
3419*67e74705SXin Li   assert(!Template.getAsDependentTemplateName() &&
3420*67e74705SXin Li          "No dependent template names here!");
3421*67e74705SXin Li   // Look through qualified template names.
3422*67e74705SXin Li   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3423*67e74705SXin Li     Template = TemplateName(QTN->getTemplateDecl());
3424*67e74705SXin Li 
3425*67e74705SXin Li   bool IsTypeAlias =
3426*67e74705SXin Li     Template.getAsTemplateDecl() &&
3427*67e74705SXin Li     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3428*67e74705SXin Li   QualType CanonType;
3429*67e74705SXin Li   if (!Underlying.isNull())
3430*67e74705SXin Li     CanonType = getCanonicalType(Underlying);
3431*67e74705SXin Li   else {
3432*67e74705SXin Li     // We can get here with an alias template when the specialization contains
3433*67e74705SXin Li     // a pack expansion that does not match up with a parameter pack.
3434*67e74705SXin Li     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3435*67e74705SXin Li            "Caller must compute aliased type");
3436*67e74705SXin Li     IsTypeAlias = false;
3437*67e74705SXin Li     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3438*67e74705SXin Li   }
3439*67e74705SXin Li 
3440*67e74705SXin Li   // Allocate the (non-canonical) template specialization type, but don't
3441*67e74705SXin Li   // try to unique it: these types typically have location information that
3442*67e74705SXin Li   // we don't unique and don't want to lose.
3443*67e74705SXin Li   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3444*67e74705SXin Li                        sizeof(TemplateArgument) * Args.size() +
3445*67e74705SXin Li                        (IsTypeAlias? sizeof(QualType) : 0),
3446*67e74705SXin Li                        TypeAlignment);
3447*67e74705SXin Li   TemplateSpecializationType *Spec
3448*67e74705SXin Li     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3449*67e74705SXin Li                                          IsTypeAlias ? Underlying : QualType());
3450*67e74705SXin Li 
3451*67e74705SXin Li   Types.push_back(Spec);
3452*67e74705SXin Li   return QualType(Spec, 0);
3453*67e74705SXin Li }
3454*67e74705SXin Li 
getCanonicalTemplateSpecializationType(TemplateName Template,ArrayRef<TemplateArgument> Args) const3455*67e74705SXin Li QualType ASTContext::getCanonicalTemplateSpecializationType(
3456*67e74705SXin Li     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3457*67e74705SXin Li   assert(!Template.getAsDependentTemplateName() &&
3458*67e74705SXin Li          "No dependent template names here!");
3459*67e74705SXin Li 
3460*67e74705SXin Li   // Look through qualified template names.
3461*67e74705SXin Li   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3462*67e74705SXin Li     Template = TemplateName(QTN->getTemplateDecl());
3463*67e74705SXin Li 
3464*67e74705SXin Li   // Build the canonical template specialization type.
3465*67e74705SXin Li   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3466*67e74705SXin Li   SmallVector<TemplateArgument, 4> CanonArgs;
3467*67e74705SXin Li   unsigned NumArgs = Args.size();
3468*67e74705SXin Li   CanonArgs.reserve(NumArgs);
3469*67e74705SXin Li   for (const TemplateArgument &Arg : Args)
3470*67e74705SXin Li     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3471*67e74705SXin Li 
3472*67e74705SXin Li   // Determine whether this canonical template specialization type already
3473*67e74705SXin Li   // exists.
3474*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3475*67e74705SXin Li   TemplateSpecializationType::Profile(ID, CanonTemplate,
3476*67e74705SXin Li                                       CanonArgs, *this);
3477*67e74705SXin Li 
3478*67e74705SXin Li   void *InsertPos = nullptr;
3479*67e74705SXin Li   TemplateSpecializationType *Spec
3480*67e74705SXin Li     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3481*67e74705SXin Li 
3482*67e74705SXin Li   if (!Spec) {
3483*67e74705SXin Li     // Allocate a new canonical template specialization type.
3484*67e74705SXin Li     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3485*67e74705SXin Li                           sizeof(TemplateArgument) * NumArgs),
3486*67e74705SXin Li                          TypeAlignment);
3487*67e74705SXin Li     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3488*67e74705SXin Li                                                 CanonArgs,
3489*67e74705SXin Li                                                 QualType(), QualType());
3490*67e74705SXin Li     Types.push_back(Spec);
3491*67e74705SXin Li     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3492*67e74705SXin Li   }
3493*67e74705SXin Li 
3494*67e74705SXin Li   assert(Spec->isDependentType() &&
3495*67e74705SXin Li          "Non-dependent template-id type must have a canonical type");
3496*67e74705SXin Li   return QualType(Spec, 0);
3497*67e74705SXin Li }
3498*67e74705SXin Li 
3499*67e74705SXin Li QualType
getElaboratedType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,QualType NamedType) const3500*67e74705SXin Li ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3501*67e74705SXin Li                               NestedNameSpecifier *NNS,
3502*67e74705SXin Li                               QualType NamedType) const {
3503*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3504*67e74705SXin Li   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3505*67e74705SXin Li 
3506*67e74705SXin Li   void *InsertPos = nullptr;
3507*67e74705SXin Li   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3508*67e74705SXin Li   if (T)
3509*67e74705SXin Li     return QualType(T, 0);
3510*67e74705SXin Li 
3511*67e74705SXin Li   QualType Canon = NamedType;
3512*67e74705SXin Li   if (!Canon.isCanonical()) {
3513*67e74705SXin Li     Canon = getCanonicalType(NamedType);
3514*67e74705SXin Li     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3515*67e74705SXin Li     assert(!CheckT && "Elaborated canonical type broken");
3516*67e74705SXin Li     (void)CheckT;
3517*67e74705SXin Li   }
3518*67e74705SXin Li 
3519*67e74705SXin Li   T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3520*67e74705SXin Li   Types.push_back(T);
3521*67e74705SXin Li   ElaboratedTypes.InsertNode(T, InsertPos);
3522*67e74705SXin Li   return QualType(T, 0);
3523*67e74705SXin Li }
3524*67e74705SXin Li 
3525*67e74705SXin Li QualType
getParenType(QualType InnerType) const3526*67e74705SXin Li ASTContext::getParenType(QualType InnerType) const {
3527*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3528*67e74705SXin Li   ParenType::Profile(ID, InnerType);
3529*67e74705SXin Li 
3530*67e74705SXin Li   void *InsertPos = nullptr;
3531*67e74705SXin Li   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3532*67e74705SXin Li   if (T)
3533*67e74705SXin Li     return QualType(T, 0);
3534*67e74705SXin Li 
3535*67e74705SXin Li   QualType Canon = InnerType;
3536*67e74705SXin Li   if (!Canon.isCanonical()) {
3537*67e74705SXin Li     Canon = getCanonicalType(InnerType);
3538*67e74705SXin Li     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3539*67e74705SXin Li     assert(!CheckT && "Paren canonical type broken");
3540*67e74705SXin Li     (void)CheckT;
3541*67e74705SXin Li   }
3542*67e74705SXin Li 
3543*67e74705SXin Li   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3544*67e74705SXin Li   Types.push_back(T);
3545*67e74705SXin Li   ParenTypes.InsertNode(T, InsertPos);
3546*67e74705SXin Li   return QualType(T, 0);
3547*67e74705SXin Li }
3548*67e74705SXin Li 
getDependentNameType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,QualType Canon) const3549*67e74705SXin Li QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3550*67e74705SXin Li                                           NestedNameSpecifier *NNS,
3551*67e74705SXin Li                                           const IdentifierInfo *Name,
3552*67e74705SXin Li                                           QualType Canon) const {
3553*67e74705SXin Li   if (Canon.isNull()) {
3554*67e74705SXin Li     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3555*67e74705SXin Li     ElaboratedTypeKeyword CanonKeyword = Keyword;
3556*67e74705SXin Li     if (Keyword == ETK_None)
3557*67e74705SXin Li       CanonKeyword = ETK_Typename;
3558*67e74705SXin Li 
3559*67e74705SXin Li     if (CanonNNS != NNS || CanonKeyword != Keyword)
3560*67e74705SXin Li       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3561*67e74705SXin Li   }
3562*67e74705SXin Li 
3563*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3564*67e74705SXin Li   DependentNameType::Profile(ID, Keyword, NNS, Name);
3565*67e74705SXin Li 
3566*67e74705SXin Li   void *InsertPos = nullptr;
3567*67e74705SXin Li   DependentNameType *T
3568*67e74705SXin Li     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3569*67e74705SXin Li   if (T)
3570*67e74705SXin Li     return QualType(T, 0);
3571*67e74705SXin Li 
3572*67e74705SXin Li   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3573*67e74705SXin Li   Types.push_back(T);
3574*67e74705SXin Li   DependentNameTypes.InsertNode(T, InsertPos);
3575*67e74705SXin Li   return QualType(T, 0);
3576*67e74705SXin Li }
3577*67e74705SXin Li 
3578*67e74705SXin Li QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,const TemplateArgumentListInfo & Args) const3579*67e74705SXin Li ASTContext::getDependentTemplateSpecializationType(
3580*67e74705SXin Li                                  ElaboratedTypeKeyword Keyword,
3581*67e74705SXin Li                                  NestedNameSpecifier *NNS,
3582*67e74705SXin Li                                  const IdentifierInfo *Name,
3583*67e74705SXin Li                                  const TemplateArgumentListInfo &Args) const {
3584*67e74705SXin Li   // TODO: avoid this copy
3585*67e74705SXin Li   SmallVector<TemplateArgument, 16> ArgCopy;
3586*67e74705SXin Li   for (unsigned I = 0, E = Args.size(); I != E; ++I)
3587*67e74705SXin Li     ArgCopy.push_back(Args[I].getArgument());
3588*67e74705SXin Li   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3589*67e74705SXin Li }
3590*67e74705SXin Li 
3591*67e74705SXin Li QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,ArrayRef<TemplateArgument> Args) const3592*67e74705SXin Li ASTContext::getDependentTemplateSpecializationType(
3593*67e74705SXin Li                                  ElaboratedTypeKeyword Keyword,
3594*67e74705SXin Li                                  NestedNameSpecifier *NNS,
3595*67e74705SXin Li                                  const IdentifierInfo *Name,
3596*67e74705SXin Li                                  ArrayRef<TemplateArgument> Args) const {
3597*67e74705SXin Li   assert((!NNS || NNS->isDependent()) &&
3598*67e74705SXin Li          "nested-name-specifier must be dependent");
3599*67e74705SXin Li 
3600*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3601*67e74705SXin Li   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3602*67e74705SXin Li                                                Name, Args);
3603*67e74705SXin Li 
3604*67e74705SXin Li   void *InsertPos = nullptr;
3605*67e74705SXin Li   DependentTemplateSpecializationType *T
3606*67e74705SXin Li     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3607*67e74705SXin Li   if (T)
3608*67e74705SXin Li     return QualType(T, 0);
3609*67e74705SXin Li 
3610*67e74705SXin Li   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3611*67e74705SXin Li 
3612*67e74705SXin Li   ElaboratedTypeKeyword CanonKeyword = Keyword;
3613*67e74705SXin Li   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3614*67e74705SXin Li 
3615*67e74705SXin Li   bool AnyNonCanonArgs = false;
3616*67e74705SXin Li   unsigned NumArgs = Args.size();
3617*67e74705SXin Li   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3618*67e74705SXin Li   for (unsigned I = 0; I != NumArgs; ++I) {
3619*67e74705SXin Li     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3620*67e74705SXin Li     if (!CanonArgs[I].structurallyEquals(Args[I]))
3621*67e74705SXin Li       AnyNonCanonArgs = true;
3622*67e74705SXin Li   }
3623*67e74705SXin Li 
3624*67e74705SXin Li   QualType Canon;
3625*67e74705SXin Li   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3626*67e74705SXin Li     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3627*67e74705SXin Li                                                    Name,
3628*67e74705SXin Li                                                    CanonArgs);
3629*67e74705SXin Li 
3630*67e74705SXin Li     // Find the insert position again.
3631*67e74705SXin Li     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3632*67e74705SXin Li   }
3633*67e74705SXin Li 
3634*67e74705SXin Li   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3635*67e74705SXin Li                         sizeof(TemplateArgument) * NumArgs),
3636*67e74705SXin Li                        TypeAlignment);
3637*67e74705SXin Li   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3638*67e74705SXin Li                                                     Name, Args, Canon);
3639*67e74705SXin Li   Types.push_back(T);
3640*67e74705SXin Li   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3641*67e74705SXin Li   return QualType(T, 0);
3642*67e74705SXin Li }
3643*67e74705SXin Li 
getPackExpansionType(QualType Pattern,Optional<unsigned> NumExpansions)3644*67e74705SXin Li QualType ASTContext::getPackExpansionType(QualType Pattern,
3645*67e74705SXin Li                                           Optional<unsigned> NumExpansions) {
3646*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3647*67e74705SXin Li   PackExpansionType::Profile(ID, Pattern, NumExpansions);
3648*67e74705SXin Li 
3649*67e74705SXin Li   assert(Pattern->containsUnexpandedParameterPack() &&
3650*67e74705SXin Li          "Pack expansions must expand one or more parameter packs");
3651*67e74705SXin Li   void *InsertPos = nullptr;
3652*67e74705SXin Li   PackExpansionType *T
3653*67e74705SXin Li     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3654*67e74705SXin Li   if (T)
3655*67e74705SXin Li     return QualType(T, 0);
3656*67e74705SXin Li 
3657*67e74705SXin Li   QualType Canon;
3658*67e74705SXin Li   if (!Pattern.isCanonical()) {
3659*67e74705SXin Li     Canon = getCanonicalType(Pattern);
3660*67e74705SXin Li     // The canonical type might not contain an unexpanded parameter pack, if it
3661*67e74705SXin Li     // contains an alias template specialization which ignores one of its
3662*67e74705SXin Li     // parameters.
3663*67e74705SXin Li     if (Canon->containsUnexpandedParameterPack()) {
3664*67e74705SXin Li       Canon = getPackExpansionType(Canon, NumExpansions);
3665*67e74705SXin Li 
3666*67e74705SXin Li       // Find the insert position again, in case we inserted an element into
3667*67e74705SXin Li       // PackExpansionTypes and invalidated our insert position.
3668*67e74705SXin Li       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3669*67e74705SXin Li     }
3670*67e74705SXin Li   }
3671*67e74705SXin Li 
3672*67e74705SXin Li   T = new (*this, TypeAlignment)
3673*67e74705SXin Li       PackExpansionType(Pattern, Canon, NumExpansions);
3674*67e74705SXin Li   Types.push_back(T);
3675*67e74705SXin Li   PackExpansionTypes.InsertNode(T, InsertPos);
3676*67e74705SXin Li   return QualType(T, 0);
3677*67e74705SXin Li }
3678*67e74705SXin Li 
3679*67e74705SXin Li /// CmpProtocolNames - Comparison predicate for sorting protocols
3680*67e74705SXin Li /// alphabetically.
CmpProtocolNames(ObjCProtocolDecl * const * LHS,ObjCProtocolDecl * const * RHS)3681*67e74705SXin Li static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3682*67e74705SXin Li                             ObjCProtocolDecl *const *RHS) {
3683*67e74705SXin Li   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3684*67e74705SXin Li }
3685*67e74705SXin Li 
areSortedAndUniqued(ArrayRef<ObjCProtocolDecl * > Protocols)3686*67e74705SXin Li static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3687*67e74705SXin Li   if (Protocols.empty()) return true;
3688*67e74705SXin Li 
3689*67e74705SXin Li   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3690*67e74705SXin Li     return false;
3691*67e74705SXin Li 
3692*67e74705SXin Li   for (unsigned i = 1; i != Protocols.size(); ++i)
3693*67e74705SXin Li     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3694*67e74705SXin Li         Protocols[i]->getCanonicalDecl() != Protocols[i])
3695*67e74705SXin Li       return false;
3696*67e74705SXin Li   return true;
3697*67e74705SXin Li }
3698*67e74705SXin Li 
3699*67e74705SXin Li static void
SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl * > & Protocols)3700*67e74705SXin Li SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3701*67e74705SXin Li   // Sort protocols, keyed by name.
3702*67e74705SXin Li   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3703*67e74705SXin Li 
3704*67e74705SXin Li   // Canonicalize.
3705*67e74705SXin Li   for (ObjCProtocolDecl *&P : Protocols)
3706*67e74705SXin Li     P = P->getCanonicalDecl();
3707*67e74705SXin Li 
3708*67e74705SXin Li   // Remove duplicates.
3709*67e74705SXin Li   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3710*67e74705SXin Li   Protocols.erase(ProtocolsEnd, Protocols.end());
3711*67e74705SXin Li }
3712*67e74705SXin Li 
getObjCObjectType(QualType BaseType,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols) const3713*67e74705SXin Li QualType ASTContext::getObjCObjectType(QualType BaseType,
3714*67e74705SXin Li                                        ObjCProtocolDecl * const *Protocols,
3715*67e74705SXin Li                                        unsigned NumProtocols) const {
3716*67e74705SXin Li   return getObjCObjectType(BaseType, { },
3717*67e74705SXin Li                            llvm::makeArrayRef(Protocols, NumProtocols),
3718*67e74705SXin Li                            /*isKindOf=*/false);
3719*67e74705SXin Li }
3720*67e74705SXin Li 
getObjCObjectType(QualType baseType,ArrayRef<QualType> typeArgs,ArrayRef<ObjCProtocolDecl * > protocols,bool isKindOf) const3721*67e74705SXin Li QualType ASTContext::getObjCObjectType(
3722*67e74705SXin Li            QualType baseType,
3723*67e74705SXin Li            ArrayRef<QualType> typeArgs,
3724*67e74705SXin Li            ArrayRef<ObjCProtocolDecl *> protocols,
3725*67e74705SXin Li            bool isKindOf) const {
3726*67e74705SXin Li   // If the base type is an interface and there aren't any protocols or
3727*67e74705SXin Li   // type arguments to add, then the interface type will do just fine.
3728*67e74705SXin Li   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3729*67e74705SXin Li       isa<ObjCInterfaceType>(baseType))
3730*67e74705SXin Li     return baseType;
3731*67e74705SXin Li 
3732*67e74705SXin Li   // Look in the folding set for an existing type.
3733*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3734*67e74705SXin Li   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3735*67e74705SXin Li   void *InsertPos = nullptr;
3736*67e74705SXin Li   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3737*67e74705SXin Li     return QualType(QT, 0);
3738*67e74705SXin Li 
3739*67e74705SXin Li   // Determine the type arguments to be used for canonicalization,
3740*67e74705SXin Li   // which may be explicitly specified here or written on the base
3741*67e74705SXin Li   // type.
3742*67e74705SXin Li   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3743*67e74705SXin Li   if (effectiveTypeArgs.empty()) {
3744*67e74705SXin Li     if (auto baseObject = baseType->getAs<ObjCObjectType>())
3745*67e74705SXin Li       effectiveTypeArgs = baseObject->getTypeArgs();
3746*67e74705SXin Li   }
3747*67e74705SXin Li 
3748*67e74705SXin Li   // Build the canonical type, which has the canonical base type and a
3749*67e74705SXin Li   // sorted-and-uniqued list of protocols and the type arguments
3750*67e74705SXin Li   // canonicalized.
3751*67e74705SXin Li   QualType canonical;
3752*67e74705SXin Li   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3753*67e74705SXin Li                                           effectiveTypeArgs.end(),
3754*67e74705SXin Li                                           [&](QualType type) {
3755*67e74705SXin Li                                             return type.isCanonical();
3756*67e74705SXin Li                                           });
3757*67e74705SXin Li   bool protocolsSorted = areSortedAndUniqued(protocols);
3758*67e74705SXin Li   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3759*67e74705SXin Li     // Determine the canonical type arguments.
3760*67e74705SXin Li     ArrayRef<QualType> canonTypeArgs;
3761*67e74705SXin Li     SmallVector<QualType, 4> canonTypeArgsVec;
3762*67e74705SXin Li     if (!typeArgsAreCanonical) {
3763*67e74705SXin Li       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3764*67e74705SXin Li       for (auto typeArg : effectiveTypeArgs)
3765*67e74705SXin Li         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3766*67e74705SXin Li       canonTypeArgs = canonTypeArgsVec;
3767*67e74705SXin Li     } else {
3768*67e74705SXin Li       canonTypeArgs = effectiveTypeArgs;
3769*67e74705SXin Li     }
3770*67e74705SXin Li 
3771*67e74705SXin Li     ArrayRef<ObjCProtocolDecl *> canonProtocols;
3772*67e74705SXin Li     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3773*67e74705SXin Li     if (!protocolsSorted) {
3774*67e74705SXin Li       canonProtocolsVec.append(protocols.begin(), protocols.end());
3775*67e74705SXin Li       SortAndUniqueProtocols(canonProtocolsVec);
3776*67e74705SXin Li       canonProtocols = canonProtocolsVec;
3777*67e74705SXin Li     } else {
3778*67e74705SXin Li       canonProtocols = protocols;
3779*67e74705SXin Li     }
3780*67e74705SXin Li 
3781*67e74705SXin Li     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3782*67e74705SXin Li                                   canonProtocols, isKindOf);
3783*67e74705SXin Li 
3784*67e74705SXin Li     // Regenerate InsertPos.
3785*67e74705SXin Li     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3786*67e74705SXin Li   }
3787*67e74705SXin Li 
3788*67e74705SXin Li   unsigned size = sizeof(ObjCObjectTypeImpl);
3789*67e74705SXin Li   size += typeArgs.size() * sizeof(QualType);
3790*67e74705SXin Li   size += protocols.size() * sizeof(ObjCProtocolDecl *);
3791*67e74705SXin Li   void *mem = Allocate(size, TypeAlignment);
3792*67e74705SXin Li   ObjCObjectTypeImpl *T =
3793*67e74705SXin Li     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3794*67e74705SXin Li                                  isKindOf);
3795*67e74705SXin Li 
3796*67e74705SXin Li   Types.push_back(T);
3797*67e74705SXin Li   ObjCObjectTypes.InsertNode(T, InsertPos);
3798*67e74705SXin Li   return QualType(T, 0);
3799*67e74705SXin Li }
3800*67e74705SXin Li 
3801*67e74705SXin Li /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3802*67e74705SXin Li /// protocol list adopt all protocols in QT's qualified-id protocol
3803*67e74705SXin Li /// list.
ObjCObjectAdoptsQTypeProtocols(QualType QT,ObjCInterfaceDecl * IC)3804*67e74705SXin Li bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3805*67e74705SXin Li                                                 ObjCInterfaceDecl *IC) {
3806*67e74705SXin Li   if (!QT->isObjCQualifiedIdType())
3807*67e74705SXin Li     return false;
3808*67e74705SXin Li 
3809*67e74705SXin Li   if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3810*67e74705SXin Li     // If both the right and left sides have qualifiers.
3811*67e74705SXin Li     for (auto *Proto : OPT->quals()) {
3812*67e74705SXin Li       if (!IC->ClassImplementsProtocol(Proto, false))
3813*67e74705SXin Li         return false;
3814*67e74705SXin Li     }
3815*67e74705SXin Li     return true;
3816*67e74705SXin Li   }
3817*67e74705SXin Li   return false;
3818*67e74705SXin Li }
3819*67e74705SXin Li 
3820*67e74705SXin Li /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3821*67e74705SXin Li /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3822*67e74705SXin Li /// of protocols.
QIdProtocolsAdoptObjCObjectProtocols(QualType QT,ObjCInterfaceDecl * IDecl)3823*67e74705SXin Li bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3824*67e74705SXin Li                                                 ObjCInterfaceDecl *IDecl) {
3825*67e74705SXin Li   if (!QT->isObjCQualifiedIdType())
3826*67e74705SXin Li     return false;
3827*67e74705SXin Li   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3828*67e74705SXin Li   if (!OPT)
3829*67e74705SXin Li     return false;
3830*67e74705SXin Li   if (!IDecl->hasDefinition())
3831*67e74705SXin Li     return false;
3832*67e74705SXin Li   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3833*67e74705SXin Li   CollectInheritedProtocols(IDecl, InheritedProtocols);
3834*67e74705SXin Li   if (InheritedProtocols.empty())
3835*67e74705SXin Li     return false;
3836*67e74705SXin Li   // Check that if every protocol in list of id<plist> conforms to a protcol
3837*67e74705SXin Li   // of IDecl's, then bridge casting is ok.
3838*67e74705SXin Li   bool Conforms = false;
3839*67e74705SXin Li   for (auto *Proto : OPT->quals()) {
3840*67e74705SXin Li     Conforms = false;
3841*67e74705SXin Li     for (auto *PI : InheritedProtocols) {
3842*67e74705SXin Li       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3843*67e74705SXin Li         Conforms = true;
3844*67e74705SXin Li         break;
3845*67e74705SXin Li       }
3846*67e74705SXin Li     }
3847*67e74705SXin Li     if (!Conforms)
3848*67e74705SXin Li       break;
3849*67e74705SXin Li   }
3850*67e74705SXin Li   if (Conforms)
3851*67e74705SXin Li     return true;
3852*67e74705SXin Li 
3853*67e74705SXin Li   for (auto *PI : InheritedProtocols) {
3854*67e74705SXin Li     // If both the right and left sides have qualifiers.
3855*67e74705SXin Li     bool Adopts = false;
3856*67e74705SXin Li     for (auto *Proto : OPT->quals()) {
3857*67e74705SXin Li       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3858*67e74705SXin Li       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3859*67e74705SXin Li         break;
3860*67e74705SXin Li     }
3861*67e74705SXin Li     if (!Adopts)
3862*67e74705SXin Li       return false;
3863*67e74705SXin Li   }
3864*67e74705SXin Li   return true;
3865*67e74705SXin Li }
3866*67e74705SXin Li 
3867*67e74705SXin Li /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3868*67e74705SXin Li /// the given object type.
getObjCObjectPointerType(QualType ObjectT) const3869*67e74705SXin Li QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3870*67e74705SXin Li   llvm::FoldingSetNodeID ID;
3871*67e74705SXin Li   ObjCObjectPointerType::Profile(ID, ObjectT);
3872*67e74705SXin Li 
3873*67e74705SXin Li   void *InsertPos = nullptr;
3874*67e74705SXin Li   if (ObjCObjectPointerType *QT =
3875*67e74705SXin Li               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3876*67e74705SXin Li     return QualType(QT, 0);
3877*67e74705SXin Li 
3878*67e74705SXin Li   // Find the canonical object type.
3879*67e74705SXin Li   QualType Canonical;
3880*67e74705SXin Li   if (!ObjectT.isCanonical()) {
3881*67e74705SXin Li     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3882*67e74705SXin Li 
3883*67e74705SXin Li     // Regenerate InsertPos.
3884*67e74705SXin Li     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3885*67e74705SXin Li   }
3886*67e74705SXin Li 
3887*67e74705SXin Li   // No match.
3888*67e74705SXin Li   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3889*67e74705SXin Li   ObjCObjectPointerType *QType =
3890*67e74705SXin Li     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3891*67e74705SXin Li 
3892*67e74705SXin Li   Types.push_back(QType);
3893*67e74705SXin Li   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3894*67e74705SXin Li   return QualType(QType, 0);
3895*67e74705SXin Li }
3896*67e74705SXin Li 
3897*67e74705SXin Li /// getObjCInterfaceType - Return the unique reference to the type for the
3898*67e74705SXin Li /// specified ObjC interface decl. The list of protocols is optional.
getObjCInterfaceType(const ObjCInterfaceDecl * Decl,ObjCInterfaceDecl * PrevDecl) const3899*67e74705SXin Li QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3900*67e74705SXin Li                                           ObjCInterfaceDecl *PrevDecl) const {
3901*67e74705SXin Li   if (Decl->TypeForDecl)
3902*67e74705SXin Li     return QualType(Decl->TypeForDecl, 0);
3903*67e74705SXin Li 
3904*67e74705SXin Li   if (PrevDecl) {
3905*67e74705SXin Li     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3906*67e74705SXin Li     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3907*67e74705SXin Li     return QualType(PrevDecl->TypeForDecl, 0);
3908*67e74705SXin Li   }
3909*67e74705SXin Li 
3910*67e74705SXin Li   // Prefer the definition, if there is one.
3911*67e74705SXin Li   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3912*67e74705SXin Li     Decl = Def;
3913*67e74705SXin Li 
3914*67e74705SXin Li   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3915*67e74705SXin Li   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3916*67e74705SXin Li   Decl->TypeForDecl = T;
3917*67e74705SXin Li   Types.push_back(T);
3918*67e74705SXin Li   return QualType(T, 0);
3919*67e74705SXin Li }
3920*67e74705SXin Li 
3921*67e74705SXin Li /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3922*67e74705SXin Li /// TypeOfExprType AST's (since expression's are never shared). For example,
3923*67e74705SXin Li /// multiple declarations that refer to "typeof(x)" all contain different
3924*67e74705SXin Li /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3925*67e74705SXin Li /// on canonical type's (which are always unique).
getTypeOfExprType(Expr * tofExpr) const3926*67e74705SXin Li QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3927*67e74705SXin Li   TypeOfExprType *toe;
3928*67e74705SXin Li   if (tofExpr->isTypeDependent()) {
3929*67e74705SXin Li     llvm::FoldingSetNodeID ID;
3930*67e74705SXin Li     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3931*67e74705SXin Li 
3932*67e74705SXin Li     void *InsertPos = nullptr;
3933*67e74705SXin Li     DependentTypeOfExprType *Canon
3934*67e74705SXin Li       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3935*67e74705SXin Li     if (Canon) {
3936*67e74705SXin Li       // We already have a "canonical" version of an identical, dependent
3937*67e74705SXin Li       // typeof(expr) type. Use that as our canonical type.
3938*67e74705SXin Li       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3939*67e74705SXin Li                                           QualType((TypeOfExprType*)Canon, 0));
3940*67e74705SXin Li     } else {
3941*67e74705SXin Li       // Build a new, canonical typeof(expr) type.
3942*67e74705SXin Li       Canon
3943*67e74705SXin Li         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3944*67e74705SXin Li       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3945*67e74705SXin Li       toe = Canon;
3946*67e74705SXin Li     }
3947*67e74705SXin Li   } else {
3948*67e74705SXin Li     QualType Canonical = getCanonicalType(tofExpr->getType());
3949*67e74705SXin Li     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3950*67e74705SXin Li   }
3951*67e74705SXin Li   Types.push_back(toe);
3952*67e74705SXin Li   return QualType(toe, 0);
3953*67e74705SXin Li }
3954*67e74705SXin Li 
3955*67e74705SXin Li /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3956*67e74705SXin Li /// TypeOfType nodes. The only motivation to unique these nodes would be
3957*67e74705SXin Li /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3958*67e74705SXin Li /// an issue. This doesn't affect the type checker, since it operates
3959*67e74705SXin Li /// on canonical types (which are always unique).
getTypeOfType(QualType tofType) const3960*67e74705SXin Li QualType ASTContext::getTypeOfType(QualType tofType) const {
3961*67e74705SXin Li   QualType Canonical = getCanonicalType(tofType);
3962*67e74705SXin Li   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3963*67e74705SXin Li   Types.push_back(tot);
3964*67e74705SXin Li   return QualType(tot, 0);
3965*67e74705SXin Li }
3966*67e74705SXin Li 
3967*67e74705SXin Li /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3968*67e74705SXin Li /// nodes. This would never be helpful, since each such type has its own
3969*67e74705SXin Li /// expression, and would not give a significant memory saving, since there
3970*67e74705SXin Li /// is an Expr tree under each such type.
getDecltypeType(Expr * e,QualType UnderlyingType) const3971*67e74705SXin Li QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3972*67e74705SXin Li   DecltypeType *dt;
3973*67e74705SXin Li 
3974*67e74705SXin Li   // C++11 [temp.type]p2:
3975*67e74705SXin Li   //   If an expression e involves a template parameter, decltype(e) denotes a
3976*67e74705SXin Li   //   unique dependent type. Two such decltype-specifiers refer to the same
3977*67e74705SXin Li   //   type only if their expressions are equivalent (14.5.6.1).
3978*67e74705SXin Li   if (e->isInstantiationDependent()) {
3979*67e74705SXin Li     llvm::FoldingSetNodeID ID;
3980*67e74705SXin Li     DependentDecltypeType::Profile(ID, *this, e);
3981*67e74705SXin Li 
3982*67e74705SXin Li     void *InsertPos = nullptr;
3983*67e74705SXin Li     DependentDecltypeType *Canon
3984*67e74705SXin Li       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3985*67e74705SXin Li     if (!Canon) {
3986*67e74705SXin Li       // Build a new, canonical typeof(expr) type.
3987*67e74705SXin Li       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3988*67e74705SXin Li       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3989*67e74705SXin Li     }
3990*67e74705SXin Li     dt = new (*this, TypeAlignment)
3991*67e74705SXin Li         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3992*67e74705SXin Li   } else {
3993*67e74705SXin Li     dt = new (*this, TypeAlignment)
3994*67e74705SXin Li         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3995*67e74705SXin Li   }
3996*67e74705SXin Li   Types.push_back(dt);
3997*67e74705SXin Li   return QualType(dt, 0);
3998*67e74705SXin Li }
3999*67e74705SXin Li 
4000*67e74705SXin Li /// getUnaryTransformationType - We don't unique these, since the memory
4001*67e74705SXin Li /// savings are minimal and these are rare.
getUnaryTransformType(QualType BaseType,QualType UnderlyingType,UnaryTransformType::UTTKind Kind) const4002*67e74705SXin Li QualType ASTContext::getUnaryTransformType(QualType BaseType,
4003*67e74705SXin Li                                            QualType UnderlyingType,
4004*67e74705SXin Li                                            UnaryTransformType::UTTKind Kind)
4005*67e74705SXin Li     const {
4006*67e74705SXin Li   UnaryTransformType *ut = nullptr;
4007*67e74705SXin Li 
4008*67e74705SXin Li   if (BaseType->isDependentType()) {
4009*67e74705SXin Li     // Look in the folding set for an existing type.
4010*67e74705SXin Li     llvm::FoldingSetNodeID ID;
4011*67e74705SXin Li     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4012*67e74705SXin Li 
4013*67e74705SXin Li     void *InsertPos = nullptr;
4014*67e74705SXin Li     DependentUnaryTransformType *Canon
4015*67e74705SXin Li       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4016*67e74705SXin Li 
4017*67e74705SXin Li     if (!Canon) {
4018*67e74705SXin Li       // Build a new, canonical __underlying_type(type) type.
4019*67e74705SXin Li       Canon = new (*this, TypeAlignment)
4020*67e74705SXin Li              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4021*67e74705SXin Li                                          Kind);
4022*67e74705SXin Li       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4023*67e74705SXin Li     }
4024*67e74705SXin Li     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4025*67e74705SXin Li                                                         QualType(), Kind,
4026*67e74705SXin Li                                                         QualType(Canon, 0));
4027*67e74705SXin Li   } else {
4028*67e74705SXin Li     QualType CanonType = getCanonicalType(UnderlyingType);
4029*67e74705SXin Li     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4030*67e74705SXin Li                                                         UnderlyingType, Kind,
4031*67e74705SXin Li                                                         CanonType);
4032*67e74705SXin Li   }
4033*67e74705SXin Li   Types.push_back(ut);
4034*67e74705SXin Li   return QualType(ut, 0);
4035*67e74705SXin Li }
4036*67e74705SXin Li 
4037*67e74705SXin Li /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4038*67e74705SXin Li /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4039*67e74705SXin Li /// canonical deduced-but-dependent 'auto' type.
getAutoType(QualType DeducedType,AutoTypeKeyword Keyword,bool IsDependent) const4040*67e74705SXin Li QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4041*67e74705SXin Li                                  bool IsDependent) const {
4042*67e74705SXin Li   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4043*67e74705SXin Li     return getAutoDeductType();
4044*67e74705SXin Li 
4045*67e74705SXin Li   // Look in the folding set for an existing type.
4046*67e74705SXin Li   void *InsertPos = nullptr;
4047*67e74705SXin Li   llvm::FoldingSetNodeID ID;
4048*67e74705SXin Li   AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4049*67e74705SXin Li   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4050*67e74705SXin Li     return QualType(AT, 0);
4051*67e74705SXin Li 
4052*67e74705SXin Li   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4053*67e74705SXin Li                                                      Keyword,
4054*67e74705SXin Li                                                      IsDependent);
4055*67e74705SXin Li   Types.push_back(AT);
4056*67e74705SXin Li   if (InsertPos)
4057*67e74705SXin Li     AutoTypes.InsertNode(AT, InsertPos);
4058*67e74705SXin Li   return QualType(AT, 0);
4059*67e74705SXin Li }
4060*67e74705SXin Li 
4061*67e74705SXin Li /// getAtomicType - Return the uniqued reference to the atomic type for
4062*67e74705SXin Li /// the given value type.
getAtomicType(QualType T) const4063*67e74705SXin Li QualType ASTContext::getAtomicType(QualType T) const {
4064*67e74705SXin Li   // Unique pointers, to guarantee there is only one pointer of a particular
4065*67e74705SXin Li   // structure.
4066*67e74705SXin Li   llvm::FoldingSetNodeID ID;
4067*67e74705SXin Li   AtomicType::Profile(ID, T);
4068*67e74705SXin Li 
4069*67e74705SXin Li   void *InsertPos = nullptr;
4070*67e74705SXin Li   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4071*67e74705SXin Li     return QualType(AT, 0);
4072*67e74705SXin Li 
4073*67e74705SXin Li   // If the atomic value type isn't canonical, this won't be a canonical type
4074*67e74705SXin Li   // either, so fill in the canonical type field.
4075*67e74705SXin Li   QualType Canonical;
4076*67e74705SXin Li   if (!T.isCanonical()) {
4077*67e74705SXin Li     Canonical = getAtomicType(getCanonicalType(T));
4078*67e74705SXin Li 
4079*67e74705SXin Li     // Get the new insert position for the node we care about.
4080*67e74705SXin Li     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4081*67e74705SXin Li     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4082*67e74705SXin Li   }
4083*67e74705SXin Li   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4084*67e74705SXin Li   Types.push_back(New);
4085*67e74705SXin Li   AtomicTypes.InsertNode(New, InsertPos);
4086*67e74705SXin Li   return QualType(New, 0);
4087*67e74705SXin Li }
4088*67e74705SXin Li 
4089*67e74705SXin Li /// getAutoDeductType - Get type pattern for deducing against 'auto'.
getAutoDeductType() const4090*67e74705SXin Li QualType ASTContext::getAutoDeductType() const {
4091*67e74705SXin Li   if (AutoDeductTy.isNull())
4092*67e74705SXin Li     AutoDeductTy = QualType(
4093*67e74705SXin Li       new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4094*67e74705SXin Li                                           /*dependent*/false),
4095*67e74705SXin Li       0);
4096*67e74705SXin Li   return AutoDeductTy;
4097*67e74705SXin Li }
4098*67e74705SXin Li 
4099*67e74705SXin Li /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
getAutoRRefDeductType() const4100*67e74705SXin Li QualType ASTContext::getAutoRRefDeductType() const {
4101*67e74705SXin Li   if (AutoRRefDeductTy.isNull())
4102*67e74705SXin Li     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4103*67e74705SXin Li   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4104*67e74705SXin Li   return AutoRRefDeductTy;
4105*67e74705SXin Li }
4106*67e74705SXin Li 
4107*67e74705SXin Li /// getTagDeclType - Return the unique reference to the type for the
4108*67e74705SXin Li /// specified TagDecl (struct/union/class/enum) decl.
getTagDeclType(const TagDecl * Decl) const4109*67e74705SXin Li QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4110*67e74705SXin Li   assert (Decl);
4111*67e74705SXin Li   // FIXME: What is the design on getTagDeclType when it requires casting
4112*67e74705SXin Li   // away const?  mutable?
4113*67e74705SXin Li   return getTypeDeclType(const_cast<TagDecl*>(Decl));
4114*67e74705SXin Li }
4115*67e74705SXin Li 
4116*67e74705SXin Li /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4117*67e74705SXin Li /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4118*67e74705SXin Li /// needs to agree with the definition in <stddef.h>.
getSizeType() const4119*67e74705SXin Li CanQualType ASTContext::getSizeType() const {
4120*67e74705SXin Li   return getFromTargetType(Target->getSizeType());
4121*67e74705SXin Li }
4122*67e74705SXin Li 
4123*67e74705SXin Li /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
getIntMaxType() const4124*67e74705SXin Li CanQualType ASTContext::getIntMaxType() const {
4125*67e74705SXin Li   return getFromTargetType(Target->getIntMaxType());
4126*67e74705SXin Li }
4127*67e74705SXin Li 
4128*67e74705SXin Li /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
getUIntMaxType() const4129*67e74705SXin Li CanQualType ASTContext::getUIntMaxType() const {
4130*67e74705SXin Li   return getFromTargetType(Target->getUIntMaxType());
4131*67e74705SXin Li }
4132*67e74705SXin Li 
4133*67e74705SXin Li /// getSignedWCharType - Return the type of "signed wchar_t".
4134*67e74705SXin Li /// Used when in C++, as a GCC extension.
getSignedWCharType() const4135*67e74705SXin Li QualType ASTContext::getSignedWCharType() const {
4136*67e74705SXin Li   // FIXME: derive from "Target" ?
4137*67e74705SXin Li   return WCharTy;
4138*67e74705SXin Li }
4139*67e74705SXin Li 
4140*67e74705SXin Li /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4141*67e74705SXin Li /// Used when in C++, as a GCC extension.
getUnsignedWCharType() const4142*67e74705SXin Li QualType ASTContext::getUnsignedWCharType() const {
4143*67e74705SXin Li   // FIXME: derive from "Target" ?
4144*67e74705SXin Li   return UnsignedIntTy;
4145*67e74705SXin Li }
4146*67e74705SXin Li 
getIntPtrType() const4147*67e74705SXin Li QualType ASTContext::getIntPtrType() const {
4148*67e74705SXin Li   return getFromTargetType(Target->getIntPtrType());
4149*67e74705SXin Li }
4150*67e74705SXin Li 
getUIntPtrType() const4151*67e74705SXin Li QualType ASTContext::getUIntPtrType() const {
4152*67e74705SXin Li   return getCorrespondingUnsignedType(getIntPtrType());
4153*67e74705SXin Li }
4154*67e74705SXin Li 
4155*67e74705SXin Li /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4156*67e74705SXin Li /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
getPointerDiffType() const4157*67e74705SXin Li QualType ASTContext::getPointerDiffType() const {
4158*67e74705SXin Li   return getFromTargetType(Target->getPtrDiffType(0));
4159*67e74705SXin Li }
4160*67e74705SXin Li 
4161*67e74705SXin Li /// \brief Return the unique type for "pid_t" defined in
4162*67e74705SXin Li /// <sys/types.h>. We need this to compute the correct type for vfork().
getProcessIDType() const4163*67e74705SXin Li QualType ASTContext::getProcessIDType() const {
4164*67e74705SXin Li   return getFromTargetType(Target->getProcessIDType());
4165*67e74705SXin Li }
4166*67e74705SXin Li 
4167*67e74705SXin Li //===----------------------------------------------------------------------===//
4168*67e74705SXin Li //                              Type Operators
4169*67e74705SXin Li //===----------------------------------------------------------------------===//
4170*67e74705SXin Li 
getCanonicalParamType(QualType T) const4171*67e74705SXin Li CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4172*67e74705SXin Li   // Push qualifiers into arrays, and then discard any remaining
4173*67e74705SXin Li   // qualifiers.
4174*67e74705SXin Li   T = getCanonicalType(T);
4175*67e74705SXin Li   T = getVariableArrayDecayedType(T);
4176*67e74705SXin Li   const Type *Ty = T.getTypePtr();
4177*67e74705SXin Li   QualType Result;
4178*67e74705SXin Li   if (isa<ArrayType>(Ty)) {
4179*67e74705SXin Li     Result = getArrayDecayedType(QualType(Ty,0));
4180*67e74705SXin Li   } else if (isa<FunctionType>(Ty)) {
4181*67e74705SXin Li     Result = getPointerType(QualType(Ty, 0));
4182*67e74705SXin Li   } else {
4183*67e74705SXin Li     Result = QualType(Ty, 0);
4184*67e74705SXin Li   }
4185*67e74705SXin Li 
4186*67e74705SXin Li   return CanQualType::CreateUnsafe(Result);
4187*67e74705SXin Li }
4188*67e74705SXin Li 
getUnqualifiedArrayType(QualType type,Qualifiers & quals)4189*67e74705SXin Li QualType ASTContext::getUnqualifiedArrayType(QualType type,
4190*67e74705SXin Li                                              Qualifiers &quals) {
4191*67e74705SXin Li   SplitQualType splitType = type.getSplitUnqualifiedType();
4192*67e74705SXin Li 
4193*67e74705SXin Li   // FIXME: getSplitUnqualifiedType() actually walks all the way to
4194*67e74705SXin Li   // the unqualified desugared type and then drops it on the floor.
4195*67e74705SXin Li   // We then have to strip that sugar back off with
4196*67e74705SXin Li   // getUnqualifiedDesugaredType(), which is silly.
4197*67e74705SXin Li   const ArrayType *AT =
4198*67e74705SXin Li     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4199*67e74705SXin Li 
4200*67e74705SXin Li   // If we don't have an array, just use the results in splitType.
4201*67e74705SXin Li   if (!AT) {
4202*67e74705SXin Li     quals = splitType.Quals;
4203*67e74705SXin Li     return QualType(splitType.Ty, 0);
4204*67e74705SXin Li   }
4205*67e74705SXin Li 
4206*67e74705SXin Li   // Otherwise, recurse on the array's element type.
4207*67e74705SXin Li   QualType elementType = AT->getElementType();
4208*67e74705SXin Li   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4209*67e74705SXin Li 
4210*67e74705SXin Li   // If that didn't change the element type, AT has no qualifiers, so we
4211*67e74705SXin Li   // can just use the results in splitType.
4212*67e74705SXin Li   if (elementType == unqualElementType) {
4213*67e74705SXin Li     assert(quals.empty()); // from the recursive call
4214*67e74705SXin Li     quals = splitType.Quals;
4215*67e74705SXin Li     return QualType(splitType.Ty, 0);
4216*67e74705SXin Li   }
4217*67e74705SXin Li 
4218*67e74705SXin Li   // Otherwise, add in the qualifiers from the outermost type, then
4219*67e74705SXin Li   // build the type back up.
4220*67e74705SXin Li   quals.addConsistentQualifiers(splitType.Quals);
4221*67e74705SXin Li 
4222*67e74705SXin Li   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4223*67e74705SXin Li     return getConstantArrayType(unqualElementType, CAT->getSize(),
4224*67e74705SXin Li                                 CAT->getSizeModifier(), 0);
4225*67e74705SXin Li   }
4226*67e74705SXin Li 
4227*67e74705SXin Li   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4228*67e74705SXin Li     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4229*67e74705SXin Li   }
4230*67e74705SXin Li 
4231*67e74705SXin Li   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4232*67e74705SXin Li     return getVariableArrayType(unqualElementType,
4233*67e74705SXin Li                                 VAT->getSizeExpr(),
4234*67e74705SXin Li                                 VAT->getSizeModifier(),
4235*67e74705SXin Li                                 VAT->getIndexTypeCVRQualifiers(),
4236*67e74705SXin Li                                 VAT->getBracketsRange());
4237*67e74705SXin Li   }
4238*67e74705SXin Li 
4239*67e74705SXin Li   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4240*67e74705SXin Li   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4241*67e74705SXin Li                                     DSAT->getSizeModifier(), 0,
4242*67e74705SXin Li                                     SourceRange());
4243*67e74705SXin Li }
4244*67e74705SXin Li 
4245*67e74705SXin Li /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
4246*67e74705SXin Li /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4247*67e74705SXin Li /// they point to and return true. If T1 and T2 aren't pointer types
4248*67e74705SXin Li /// or pointer-to-member types, or if they are not similar at this
4249*67e74705SXin Li /// level, returns false and leaves T1 and T2 unchanged. Top-level
4250*67e74705SXin Li /// qualifiers on T1 and T2 are ignored. This function will typically
4251*67e74705SXin Li /// be called in a loop that successively "unwraps" pointer and
4252*67e74705SXin Li /// pointer-to-member types to compare them at each level.
UnwrapSimilarPointerTypes(QualType & T1,QualType & T2)4253*67e74705SXin Li bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4254*67e74705SXin Li   const PointerType *T1PtrType = T1->getAs<PointerType>(),
4255*67e74705SXin Li                     *T2PtrType = T2->getAs<PointerType>();
4256*67e74705SXin Li   if (T1PtrType && T2PtrType) {
4257*67e74705SXin Li     T1 = T1PtrType->getPointeeType();
4258*67e74705SXin Li     T2 = T2PtrType->getPointeeType();
4259*67e74705SXin Li     return true;
4260*67e74705SXin Li   }
4261*67e74705SXin Li 
4262*67e74705SXin Li   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4263*67e74705SXin Li                           *T2MPType = T2->getAs<MemberPointerType>();
4264*67e74705SXin Li   if (T1MPType && T2MPType &&
4265*67e74705SXin Li       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4266*67e74705SXin Li                              QualType(T2MPType->getClass(), 0))) {
4267*67e74705SXin Li     T1 = T1MPType->getPointeeType();
4268*67e74705SXin Li     T2 = T2MPType->getPointeeType();
4269*67e74705SXin Li     return true;
4270*67e74705SXin Li   }
4271*67e74705SXin Li 
4272*67e74705SXin Li   if (getLangOpts().ObjC1) {
4273*67e74705SXin Li     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4274*67e74705SXin Li                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4275*67e74705SXin Li     if (T1OPType && T2OPType) {
4276*67e74705SXin Li       T1 = T1OPType->getPointeeType();
4277*67e74705SXin Li       T2 = T2OPType->getPointeeType();
4278*67e74705SXin Li       return true;
4279*67e74705SXin Li     }
4280*67e74705SXin Li   }
4281*67e74705SXin Li 
4282*67e74705SXin Li   // FIXME: Block pointers, too?
4283*67e74705SXin Li 
4284*67e74705SXin Li   return false;
4285*67e74705SXin Li }
4286*67e74705SXin Li 
4287*67e74705SXin Li DeclarationNameInfo
getNameForTemplate(TemplateName Name,SourceLocation NameLoc) const4288*67e74705SXin Li ASTContext::getNameForTemplate(TemplateName Name,
4289*67e74705SXin Li                                SourceLocation NameLoc) const {
4290*67e74705SXin Li   switch (Name.getKind()) {
4291*67e74705SXin Li   case TemplateName::QualifiedTemplate:
4292*67e74705SXin Li   case TemplateName::Template:
4293*67e74705SXin Li     // DNInfo work in progress: CHECKME: what about DNLoc?
4294*67e74705SXin Li     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4295*67e74705SXin Li                                NameLoc);
4296*67e74705SXin Li 
4297*67e74705SXin Li   case TemplateName::OverloadedTemplate: {
4298*67e74705SXin Li     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4299*67e74705SXin Li     // DNInfo work in progress: CHECKME: what about DNLoc?
4300*67e74705SXin Li     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4301*67e74705SXin Li   }
4302*67e74705SXin Li 
4303*67e74705SXin Li   case TemplateName::DependentTemplate: {
4304*67e74705SXin Li     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4305*67e74705SXin Li     DeclarationName DName;
4306*67e74705SXin Li     if (DTN->isIdentifier()) {
4307*67e74705SXin Li       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4308*67e74705SXin Li       return DeclarationNameInfo(DName, NameLoc);
4309*67e74705SXin Li     } else {
4310*67e74705SXin Li       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4311*67e74705SXin Li       // DNInfo work in progress: FIXME: source locations?
4312*67e74705SXin Li       DeclarationNameLoc DNLoc;
4313*67e74705SXin Li       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4314*67e74705SXin Li       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4315*67e74705SXin Li       return DeclarationNameInfo(DName, NameLoc, DNLoc);
4316*67e74705SXin Li     }
4317*67e74705SXin Li   }
4318*67e74705SXin Li 
4319*67e74705SXin Li   case TemplateName::SubstTemplateTemplateParm: {
4320*67e74705SXin Li     SubstTemplateTemplateParmStorage *subst
4321*67e74705SXin Li       = Name.getAsSubstTemplateTemplateParm();
4322*67e74705SXin Li     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4323*67e74705SXin Li                                NameLoc);
4324*67e74705SXin Li   }
4325*67e74705SXin Li 
4326*67e74705SXin Li   case TemplateName::SubstTemplateTemplateParmPack: {
4327*67e74705SXin Li     SubstTemplateTemplateParmPackStorage *subst
4328*67e74705SXin Li       = Name.getAsSubstTemplateTemplateParmPack();
4329*67e74705SXin Li     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4330*67e74705SXin Li                                NameLoc);
4331*67e74705SXin Li   }
4332*67e74705SXin Li   }
4333*67e74705SXin Li 
4334*67e74705SXin Li   llvm_unreachable("bad template name kind!");
4335*67e74705SXin Li }
4336*67e74705SXin Li 
getCanonicalTemplateName(TemplateName Name) const4337*67e74705SXin Li TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4338*67e74705SXin Li   switch (Name.getKind()) {
4339*67e74705SXin Li   case TemplateName::QualifiedTemplate:
4340*67e74705SXin Li   case TemplateName::Template: {
4341*67e74705SXin Li     TemplateDecl *Template = Name.getAsTemplateDecl();
4342*67e74705SXin Li     if (TemplateTemplateParmDecl *TTP
4343*67e74705SXin Li           = dyn_cast<TemplateTemplateParmDecl>(Template))
4344*67e74705SXin Li       Template = getCanonicalTemplateTemplateParmDecl(TTP);
4345*67e74705SXin Li 
4346*67e74705SXin Li     // The canonical template name is the canonical template declaration.
4347*67e74705SXin Li     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4348*67e74705SXin Li   }
4349*67e74705SXin Li 
4350*67e74705SXin Li   case TemplateName::OverloadedTemplate:
4351*67e74705SXin Li     llvm_unreachable("cannot canonicalize overloaded template");
4352*67e74705SXin Li 
4353*67e74705SXin Li   case TemplateName::DependentTemplate: {
4354*67e74705SXin Li     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4355*67e74705SXin Li     assert(DTN && "Non-dependent template names must refer to template decls.");
4356*67e74705SXin Li     return DTN->CanonicalTemplateName;
4357*67e74705SXin Li   }
4358*67e74705SXin Li 
4359*67e74705SXin Li   case TemplateName::SubstTemplateTemplateParm: {
4360*67e74705SXin Li     SubstTemplateTemplateParmStorage *subst
4361*67e74705SXin Li       = Name.getAsSubstTemplateTemplateParm();
4362*67e74705SXin Li     return getCanonicalTemplateName(subst->getReplacement());
4363*67e74705SXin Li   }
4364*67e74705SXin Li 
4365*67e74705SXin Li   case TemplateName::SubstTemplateTemplateParmPack: {
4366*67e74705SXin Li     SubstTemplateTemplateParmPackStorage *subst
4367*67e74705SXin Li                                   = Name.getAsSubstTemplateTemplateParmPack();
4368*67e74705SXin Li     TemplateTemplateParmDecl *canonParameter
4369*67e74705SXin Li       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4370*67e74705SXin Li     TemplateArgument canonArgPack
4371*67e74705SXin Li       = getCanonicalTemplateArgument(subst->getArgumentPack());
4372*67e74705SXin Li     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4373*67e74705SXin Li   }
4374*67e74705SXin Li   }
4375*67e74705SXin Li 
4376*67e74705SXin Li   llvm_unreachable("bad template name!");
4377*67e74705SXin Li }
4378*67e74705SXin Li 
hasSameTemplateName(TemplateName X,TemplateName Y)4379*67e74705SXin Li bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4380*67e74705SXin Li   X = getCanonicalTemplateName(X);
4381*67e74705SXin Li   Y = getCanonicalTemplateName(Y);
4382*67e74705SXin Li   return X.getAsVoidPointer() == Y.getAsVoidPointer();
4383*67e74705SXin Li }
4384*67e74705SXin Li 
4385*67e74705SXin Li TemplateArgument
getCanonicalTemplateArgument(const TemplateArgument & Arg) const4386*67e74705SXin Li ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4387*67e74705SXin Li   switch (Arg.getKind()) {
4388*67e74705SXin Li     case TemplateArgument::Null:
4389*67e74705SXin Li       return Arg;
4390*67e74705SXin Li 
4391*67e74705SXin Li     case TemplateArgument::Expression:
4392*67e74705SXin Li       return Arg;
4393*67e74705SXin Li 
4394*67e74705SXin Li     case TemplateArgument::Declaration: {
4395*67e74705SXin Li       ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4396*67e74705SXin Li       return TemplateArgument(D, Arg.getParamTypeForDecl());
4397*67e74705SXin Li     }
4398*67e74705SXin Li 
4399*67e74705SXin Li     case TemplateArgument::NullPtr:
4400*67e74705SXin Li       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4401*67e74705SXin Li                               /*isNullPtr*/true);
4402*67e74705SXin Li 
4403*67e74705SXin Li     case TemplateArgument::Template:
4404*67e74705SXin Li       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4405*67e74705SXin Li 
4406*67e74705SXin Li     case TemplateArgument::TemplateExpansion:
4407*67e74705SXin Li       return TemplateArgument(getCanonicalTemplateName(
4408*67e74705SXin Li                                          Arg.getAsTemplateOrTemplatePattern()),
4409*67e74705SXin Li                               Arg.getNumTemplateExpansions());
4410*67e74705SXin Li 
4411*67e74705SXin Li     case TemplateArgument::Integral:
4412*67e74705SXin Li       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4413*67e74705SXin Li 
4414*67e74705SXin Li     case TemplateArgument::Type:
4415*67e74705SXin Li       return TemplateArgument(getCanonicalType(Arg.getAsType()));
4416*67e74705SXin Li 
4417*67e74705SXin Li     case TemplateArgument::Pack: {
4418*67e74705SXin Li       if (Arg.pack_size() == 0)
4419*67e74705SXin Li         return Arg;
4420*67e74705SXin Li 
4421*67e74705SXin Li       TemplateArgument *CanonArgs
4422*67e74705SXin Li         = new (*this) TemplateArgument[Arg.pack_size()];
4423*67e74705SXin Li       unsigned Idx = 0;
4424*67e74705SXin Li       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4425*67e74705SXin Li                                         AEnd = Arg.pack_end();
4426*67e74705SXin Li            A != AEnd; (void)++A, ++Idx)
4427*67e74705SXin Li         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4428*67e74705SXin Li 
4429*67e74705SXin Li       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4430*67e74705SXin Li     }
4431*67e74705SXin Li   }
4432*67e74705SXin Li 
4433*67e74705SXin Li   // Silence GCC warning
4434*67e74705SXin Li   llvm_unreachable("Unhandled template argument kind");
4435*67e74705SXin Li }
4436*67e74705SXin Li 
4437*67e74705SXin Li NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier * NNS) const4438*67e74705SXin Li ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4439*67e74705SXin Li   if (!NNS)
4440*67e74705SXin Li     return nullptr;
4441*67e74705SXin Li 
4442*67e74705SXin Li   switch (NNS->getKind()) {
4443*67e74705SXin Li   case NestedNameSpecifier::Identifier:
4444*67e74705SXin Li     // Canonicalize the prefix but keep the identifier the same.
4445*67e74705SXin Li     return NestedNameSpecifier::Create(*this,
4446*67e74705SXin Li                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4447*67e74705SXin Li                                        NNS->getAsIdentifier());
4448*67e74705SXin Li 
4449*67e74705SXin Li   case NestedNameSpecifier::Namespace:
4450*67e74705SXin Li     // A namespace is canonical; build a nested-name-specifier with
4451*67e74705SXin Li     // this namespace and no prefix.
4452*67e74705SXin Li     return NestedNameSpecifier::Create(*this, nullptr,
4453*67e74705SXin Li                                  NNS->getAsNamespace()->getOriginalNamespace());
4454*67e74705SXin Li 
4455*67e74705SXin Li   case NestedNameSpecifier::NamespaceAlias:
4456*67e74705SXin Li     // A namespace is canonical; build a nested-name-specifier with
4457*67e74705SXin Li     // this namespace and no prefix.
4458*67e74705SXin Li     return NestedNameSpecifier::Create(*this, nullptr,
4459*67e74705SXin Li                                     NNS->getAsNamespaceAlias()->getNamespace()
4460*67e74705SXin Li                                                       ->getOriginalNamespace());
4461*67e74705SXin Li 
4462*67e74705SXin Li   case NestedNameSpecifier::TypeSpec:
4463*67e74705SXin Li   case NestedNameSpecifier::TypeSpecWithTemplate: {
4464*67e74705SXin Li     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4465*67e74705SXin Li 
4466*67e74705SXin Li     // If we have some kind of dependent-named type (e.g., "typename T::type"),
4467*67e74705SXin Li     // break it apart into its prefix and identifier, then reconsititute those
4468*67e74705SXin Li     // as the canonical nested-name-specifier. This is required to canonicalize
4469*67e74705SXin Li     // a dependent nested-name-specifier involving typedefs of dependent-name
4470*67e74705SXin Li     // types, e.g.,
4471*67e74705SXin Li     //   typedef typename T::type T1;
4472*67e74705SXin Li     //   typedef typename T1::type T2;
4473*67e74705SXin Li     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4474*67e74705SXin Li       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4475*67e74705SXin Li                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4476*67e74705SXin Li 
4477*67e74705SXin Li     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4478*67e74705SXin Li     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4479*67e74705SXin Li     // first place?
4480*67e74705SXin Li     return NestedNameSpecifier::Create(*this, nullptr, false,
4481*67e74705SXin Li                                        const_cast<Type *>(T.getTypePtr()));
4482*67e74705SXin Li   }
4483*67e74705SXin Li 
4484*67e74705SXin Li   case NestedNameSpecifier::Global:
4485*67e74705SXin Li   case NestedNameSpecifier::Super:
4486*67e74705SXin Li     // The global specifier and __super specifer are canonical and unique.
4487*67e74705SXin Li     return NNS;
4488*67e74705SXin Li   }
4489*67e74705SXin Li 
4490*67e74705SXin Li   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4491*67e74705SXin Li }
4492*67e74705SXin Li 
getAsArrayType(QualType T) const4493*67e74705SXin Li const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4494*67e74705SXin Li   // Handle the non-qualified case efficiently.
4495*67e74705SXin Li   if (!T.hasLocalQualifiers()) {
4496*67e74705SXin Li     // Handle the common positive case fast.
4497*67e74705SXin Li     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4498*67e74705SXin Li       return AT;
4499*67e74705SXin Li   }
4500*67e74705SXin Li 
4501*67e74705SXin Li   // Handle the common negative case fast.
4502*67e74705SXin Li   if (!isa<ArrayType>(T.getCanonicalType()))
4503*67e74705SXin Li     return nullptr;
4504*67e74705SXin Li 
4505*67e74705SXin Li   // Apply any qualifiers from the array type to the element type.  This
4506*67e74705SXin Li   // implements C99 6.7.3p8: "If the specification of an array type includes
4507*67e74705SXin Li   // any type qualifiers, the element type is so qualified, not the array type."
4508*67e74705SXin Li 
4509*67e74705SXin Li   // If we get here, we either have type qualifiers on the type, or we have
4510*67e74705SXin Li   // sugar such as a typedef in the way.  If we have type qualifiers on the type
4511*67e74705SXin Li   // we must propagate them down into the element type.
4512*67e74705SXin Li 
4513*67e74705SXin Li   SplitQualType split = T.getSplitDesugaredType();
4514*67e74705SXin Li   Qualifiers qs = split.Quals;
4515*67e74705SXin Li 
4516*67e74705SXin Li   // If we have a simple case, just return now.
4517*67e74705SXin Li   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4518*67e74705SXin Li   if (!ATy || qs.empty())
4519*67e74705SXin Li     return ATy;
4520*67e74705SXin Li 
4521*67e74705SXin Li   // Otherwise, we have an array and we have qualifiers on it.  Push the
4522*67e74705SXin Li   // qualifiers into the array element type and return a new array type.
4523*67e74705SXin Li   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4524*67e74705SXin Li 
4525*67e74705SXin Li   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4526*67e74705SXin Li     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4527*67e74705SXin Li                                                 CAT->getSizeModifier(),
4528*67e74705SXin Li                                            CAT->getIndexTypeCVRQualifiers()));
4529*67e74705SXin Li   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4530*67e74705SXin Li     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4531*67e74705SXin Li                                                   IAT->getSizeModifier(),
4532*67e74705SXin Li                                            IAT->getIndexTypeCVRQualifiers()));
4533*67e74705SXin Li 
4534*67e74705SXin Li   if (const DependentSizedArrayType *DSAT
4535*67e74705SXin Li         = dyn_cast<DependentSizedArrayType>(ATy))
4536*67e74705SXin Li     return cast<ArrayType>(
4537*67e74705SXin Li                      getDependentSizedArrayType(NewEltTy,
4538*67e74705SXin Li                                                 DSAT->getSizeExpr(),
4539*67e74705SXin Li                                                 DSAT->getSizeModifier(),
4540*67e74705SXin Li                                               DSAT->getIndexTypeCVRQualifiers(),
4541*67e74705SXin Li                                                 DSAT->getBracketsRange()));
4542*67e74705SXin Li 
4543*67e74705SXin Li   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4544*67e74705SXin Li   return cast<ArrayType>(getVariableArrayType(NewEltTy,
4545*67e74705SXin Li                                               VAT->getSizeExpr(),
4546*67e74705SXin Li                                               VAT->getSizeModifier(),
4547*67e74705SXin Li                                               VAT->getIndexTypeCVRQualifiers(),
4548*67e74705SXin Li                                               VAT->getBracketsRange()));
4549*67e74705SXin Li }
4550*67e74705SXin Li 
getAdjustedParameterType(QualType T) const4551*67e74705SXin Li QualType ASTContext::getAdjustedParameterType(QualType T) const {
4552*67e74705SXin Li   if (T->isArrayType() || T->isFunctionType())
4553*67e74705SXin Li     return getDecayedType(T);
4554*67e74705SXin Li   return T;
4555*67e74705SXin Li }
4556*67e74705SXin Li 
getSignatureParameterType(QualType T) const4557*67e74705SXin Li QualType ASTContext::getSignatureParameterType(QualType T) const {
4558*67e74705SXin Li   T = getVariableArrayDecayedType(T);
4559*67e74705SXin Li   T = getAdjustedParameterType(T);
4560*67e74705SXin Li   return T.getUnqualifiedType();
4561*67e74705SXin Li }
4562*67e74705SXin Li 
getExceptionObjectType(QualType T) const4563*67e74705SXin Li QualType ASTContext::getExceptionObjectType(QualType T) const {
4564*67e74705SXin Li   // C++ [except.throw]p3:
4565*67e74705SXin Li   //   A throw-expression initializes a temporary object, called the exception
4566*67e74705SXin Li   //   object, the type of which is determined by removing any top-level
4567*67e74705SXin Li   //   cv-qualifiers from the static type of the operand of throw and adjusting
4568*67e74705SXin Li   //   the type from "array of T" or "function returning T" to "pointer to T"
4569*67e74705SXin Li   //   or "pointer to function returning T", [...]
4570*67e74705SXin Li   T = getVariableArrayDecayedType(T);
4571*67e74705SXin Li   if (T->isArrayType() || T->isFunctionType())
4572*67e74705SXin Li     T = getDecayedType(T);
4573*67e74705SXin Li   return T.getUnqualifiedType();
4574*67e74705SXin Li }
4575*67e74705SXin Li 
4576*67e74705SXin Li /// getArrayDecayedType - Return the properly qualified result of decaying the
4577*67e74705SXin Li /// specified array type to a pointer.  This operation is non-trivial when
4578*67e74705SXin Li /// handling typedefs etc.  The canonical type of "T" must be an array type,
4579*67e74705SXin Li /// this returns a pointer to a properly qualified element of the array.
4580*67e74705SXin Li ///
4581*67e74705SXin Li /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
getArrayDecayedType(QualType Ty) const4582*67e74705SXin Li QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4583*67e74705SXin Li   // Get the element type with 'getAsArrayType' so that we don't lose any
4584*67e74705SXin Li   // typedefs in the element type of the array.  This also handles propagation
4585*67e74705SXin Li   // of type qualifiers from the array type into the element type if present
4586*67e74705SXin Li   // (C99 6.7.3p8).
4587*67e74705SXin Li   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4588*67e74705SXin Li   assert(PrettyArrayType && "Not an array type!");
4589*67e74705SXin Li 
4590*67e74705SXin Li   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4591*67e74705SXin Li 
4592*67e74705SXin Li   // int x[restrict 4] ->  int *restrict
4593*67e74705SXin Li   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4594*67e74705SXin Li }
4595*67e74705SXin Li 
getBaseElementType(const ArrayType * array) const4596*67e74705SXin Li QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4597*67e74705SXin Li   return getBaseElementType(array->getElementType());
4598*67e74705SXin Li }
4599*67e74705SXin Li 
getBaseElementType(QualType type) const4600*67e74705SXin Li QualType ASTContext::getBaseElementType(QualType type) const {
4601*67e74705SXin Li   Qualifiers qs;
4602*67e74705SXin Li   while (true) {
4603*67e74705SXin Li     SplitQualType split = type.getSplitDesugaredType();
4604*67e74705SXin Li     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4605*67e74705SXin Li     if (!array) break;
4606*67e74705SXin Li 
4607*67e74705SXin Li     type = array->getElementType();
4608*67e74705SXin Li     qs.addConsistentQualifiers(split.Quals);
4609*67e74705SXin Li   }
4610*67e74705SXin Li 
4611*67e74705SXin Li   return getQualifiedType(type, qs);
4612*67e74705SXin Li }
4613*67e74705SXin Li 
4614*67e74705SXin Li /// getConstantArrayElementCount - Returns number of constant array elements.
4615*67e74705SXin Li uint64_t
getConstantArrayElementCount(const ConstantArrayType * CA) const4616*67e74705SXin Li ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
4617*67e74705SXin Li   uint64_t ElementCount = 1;
4618*67e74705SXin Li   do {
4619*67e74705SXin Li     ElementCount *= CA->getSize().getZExtValue();
4620*67e74705SXin Li     CA = dyn_cast_or_null<ConstantArrayType>(
4621*67e74705SXin Li       CA->getElementType()->getAsArrayTypeUnsafe());
4622*67e74705SXin Li   } while (CA);
4623*67e74705SXin Li   return ElementCount;
4624*67e74705SXin Li }
4625*67e74705SXin Li 
4626*67e74705SXin Li /// getFloatingRank - Return a relative rank for floating point types.
4627*67e74705SXin Li /// This routine will assert if passed a built-in type that isn't a float.
getFloatingRank(QualType T)4628*67e74705SXin Li static FloatingRank getFloatingRank(QualType T) {
4629*67e74705SXin Li   if (const ComplexType *CT = T->getAs<ComplexType>())
4630*67e74705SXin Li     return getFloatingRank(CT->getElementType());
4631*67e74705SXin Li 
4632*67e74705SXin Li   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4633*67e74705SXin Li   switch (T->getAs<BuiltinType>()->getKind()) {
4634*67e74705SXin Li   default: llvm_unreachable("getFloatingRank(): not a floating type");
4635*67e74705SXin Li   case BuiltinType::Half:       return HalfRank;
4636*67e74705SXin Li   case BuiltinType::Float:      return FloatRank;
4637*67e74705SXin Li   case BuiltinType::Double:     return DoubleRank;
4638*67e74705SXin Li   case BuiltinType::LongDouble: return LongDoubleRank;
4639*67e74705SXin Li   case BuiltinType::Float128:   return Float128Rank;
4640*67e74705SXin Li   }
4641*67e74705SXin Li }
4642*67e74705SXin Li 
4643*67e74705SXin Li /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4644*67e74705SXin Li /// point or a complex type (based on typeDomain/typeSize).
4645*67e74705SXin Li /// 'typeDomain' is a real floating point or complex type.
4646*67e74705SXin Li /// 'typeSize' is a real floating point or complex type.
getFloatingTypeOfSizeWithinDomain(QualType Size,QualType Domain) const4647*67e74705SXin Li QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4648*67e74705SXin Li                                                        QualType Domain) const {
4649*67e74705SXin Li   FloatingRank EltRank = getFloatingRank(Size);
4650*67e74705SXin Li   if (Domain->isComplexType()) {
4651*67e74705SXin Li     switch (EltRank) {
4652*67e74705SXin Li     case HalfRank: llvm_unreachable("Complex half is not supported");
4653*67e74705SXin Li     case FloatRank:      return FloatComplexTy;
4654*67e74705SXin Li     case DoubleRank:     return DoubleComplexTy;
4655*67e74705SXin Li     case LongDoubleRank: return LongDoubleComplexTy;
4656*67e74705SXin Li     case Float128Rank:   return Float128ComplexTy;
4657*67e74705SXin Li     }
4658*67e74705SXin Li   }
4659*67e74705SXin Li 
4660*67e74705SXin Li   assert(Domain->isRealFloatingType() && "Unknown domain!");
4661*67e74705SXin Li   switch (EltRank) {
4662*67e74705SXin Li   case HalfRank:       return HalfTy;
4663*67e74705SXin Li   case FloatRank:      return FloatTy;
4664*67e74705SXin Li   case DoubleRank:     return DoubleTy;
4665*67e74705SXin Li   case LongDoubleRank: return LongDoubleTy;
4666*67e74705SXin Li   case Float128Rank:   return Float128Ty;
4667*67e74705SXin Li   }
4668*67e74705SXin Li   llvm_unreachable("getFloatingRank(): illegal value for rank");
4669*67e74705SXin Li }
4670*67e74705SXin Li 
4671*67e74705SXin Li /// getFloatingTypeOrder - Compare the rank of the two specified floating
4672*67e74705SXin Li /// point types, ignoring the domain of the type (i.e. 'double' ==
4673*67e74705SXin Li /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4674*67e74705SXin Li /// LHS < RHS, return -1.
getFloatingTypeOrder(QualType LHS,QualType RHS) const4675*67e74705SXin Li int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4676*67e74705SXin Li   FloatingRank LHSR = getFloatingRank(LHS);
4677*67e74705SXin Li   FloatingRank RHSR = getFloatingRank(RHS);
4678*67e74705SXin Li 
4679*67e74705SXin Li   if (LHSR == RHSR)
4680*67e74705SXin Li     return 0;
4681*67e74705SXin Li   if (LHSR > RHSR)
4682*67e74705SXin Li     return 1;
4683*67e74705SXin Li   return -1;
4684*67e74705SXin Li }
4685*67e74705SXin Li 
4686*67e74705SXin Li /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4687*67e74705SXin Li /// routine will assert if passed a built-in type that isn't an integer or enum,
4688*67e74705SXin Li /// or if it is not canonicalized.
getIntegerRank(const Type * T) const4689*67e74705SXin Li unsigned ASTContext::getIntegerRank(const Type *T) const {
4690*67e74705SXin Li   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4691*67e74705SXin Li 
4692*67e74705SXin Li   switch (cast<BuiltinType>(T)->getKind()) {
4693*67e74705SXin Li   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4694*67e74705SXin Li   case BuiltinType::Bool:
4695*67e74705SXin Li     return 1 + (getIntWidth(BoolTy) << 3);
4696*67e74705SXin Li   case BuiltinType::Char_S:
4697*67e74705SXin Li   case BuiltinType::Char_U:
4698*67e74705SXin Li   case BuiltinType::SChar:
4699*67e74705SXin Li   case BuiltinType::UChar:
4700*67e74705SXin Li     return 2 + (getIntWidth(CharTy) << 3);
4701*67e74705SXin Li   case BuiltinType::Short:
4702*67e74705SXin Li   case BuiltinType::UShort:
4703*67e74705SXin Li     return 3 + (getIntWidth(ShortTy) << 3);
4704*67e74705SXin Li   case BuiltinType::Int:
4705*67e74705SXin Li   case BuiltinType::UInt:
4706*67e74705SXin Li     return 4 + (getIntWidth(IntTy) << 3);
4707*67e74705SXin Li   case BuiltinType::Long:
4708*67e74705SXin Li   case BuiltinType::ULong:
4709*67e74705SXin Li     return 5 + (getIntWidth(LongTy) << 3);
4710*67e74705SXin Li   case BuiltinType::LongLong:
4711*67e74705SXin Li   case BuiltinType::ULongLong:
4712*67e74705SXin Li     return 6 + (getIntWidth(LongLongTy) << 3);
4713*67e74705SXin Li   case BuiltinType::Int128:
4714*67e74705SXin Li   case BuiltinType::UInt128:
4715*67e74705SXin Li     return 7 + (getIntWidth(Int128Ty) << 3);
4716*67e74705SXin Li   }
4717*67e74705SXin Li }
4718*67e74705SXin Li 
4719*67e74705SXin Li /// \brief Whether this is a promotable bitfield reference according
4720*67e74705SXin Li /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4721*67e74705SXin Li ///
4722*67e74705SXin Li /// \returns the type this bit-field will promote to, or NULL if no
4723*67e74705SXin Li /// promotion occurs.
isPromotableBitField(Expr * E) const4724*67e74705SXin Li QualType ASTContext::isPromotableBitField(Expr *E) const {
4725*67e74705SXin Li   if (E->isTypeDependent() || E->isValueDependent())
4726*67e74705SXin Li     return QualType();
4727*67e74705SXin Li 
4728*67e74705SXin Li   // FIXME: We should not do this unless E->refersToBitField() is true. This
4729*67e74705SXin Li   // matters in C where getSourceBitField() will find bit-fields for various
4730*67e74705SXin Li   // cases where the source expression is not a bit-field designator.
4731*67e74705SXin Li 
4732*67e74705SXin Li   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4733*67e74705SXin Li   if (!Field)
4734*67e74705SXin Li     return QualType();
4735*67e74705SXin Li 
4736*67e74705SXin Li   QualType FT = Field->getType();
4737*67e74705SXin Li 
4738*67e74705SXin Li   uint64_t BitWidth = Field->getBitWidthValue(*this);
4739*67e74705SXin Li   uint64_t IntSize = getTypeSize(IntTy);
4740*67e74705SXin Li   // C++ [conv.prom]p5:
4741*67e74705SXin Li   //   A prvalue for an integral bit-field can be converted to a prvalue of type
4742*67e74705SXin Li   //   int if int can represent all the values of the bit-field; otherwise, it
4743*67e74705SXin Li   //   can be converted to unsigned int if unsigned int can represent all the
4744*67e74705SXin Li   //   values of the bit-field. If the bit-field is larger yet, no integral
4745*67e74705SXin Li   //   promotion applies to it.
4746*67e74705SXin Li   // C11 6.3.1.1/2:
4747*67e74705SXin Li   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4748*67e74705SXin Li   //   If an int can represent all values of the original type (as restricted by
4749*67e74705SXin Li   //   the width, for a bit-field), the value is converted to an int; otherwise,
4750*67e74705SXin Li   //   it is converted to an unsigned int.
4751*67e74705SXin Li   //
4752*67e74705SXin Li   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4753*67e74705SXin Li   //        We perform that promotion here to match GCC and C++.
4754*67e74705SXin Li   if (BitWidth < IntSize)
4755*67e74705SXin Li     return IntTy;
4756*67e74705SXin Li 
4757*67e74705SXin Li   if (BitWidth == IntSize)
4758*67e74705SXin Li     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4759*67e74705SXin Li 
4760*67e74705SXin Li   // Types bigger than int are not subject to promotions, and therefore act
4761*67e74705SXin Li   // like the base type. GCC has some weird bugs in this area that we
4762*67e74705SXin Li   // deliberately do not follow (GCC follows a pre-standard resolution to
4763*67e74705SXin Li   // C's DR315 which treats bit-width as being part of the type, and this leaks
4764*67e74705SXin Li   // into their semantics in some cases).
4765*67e74705SXin Li   return QualType();
4766*67e74705SXin Li }
4767*67e74705SXin Li 
4768*67e74705SXin Li /// getPromotedIntegerType - Returns the type that Promotable will
4769*67e74705SXin Li /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4770*67e74705SXin Li /// integer type.
getPromotedIntegerType(QualType Promotable) const4771*67e74705SXin Li QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4772*67e74705SXin Li   assert(!Promotable.isNull());
4773*67e74705SXin Li   assert(Promotable->isPromotableIntegerType());
4774*67e74705SXin Li   if (const EnumType *ET = Promotable->getAs<EnumType>())
4775*67e74705SXin Li     return ET->getDecl()->getPromotionType();
4776*67e74705SXin Li 
4777*67e74705SXin Li   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4778*67e74705SXin Li     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4779*67e74705SXin Li     // (3.9.1) can be converted to a prvalue of the first of the following
4780*67e74705SXin Li     // types that can represent all the values of its underlying type:
4781*67e74705SXin Li     // int, unsigned int, long int, unsigned long int, long long int, or
4782*67e74705SXin Li     // unsigned long long int [...]
4783*67e74705SXin Li     // FIXME: Is there some better way to compute this?
4784*67e74705SXin Li     if (BT->getKind() == BuiltinType::WChar_S ||
4785*67e74705SXin Li         BT->getKind() == BuiltinType::WChar_U ||
4786*67e74705SXin Li         BT->getKind() == BuiltinType::Char16 ||
4787*67e74705SXin Li         BT->getKind() == BuiltinType::Char32) {
4788*67e74705SXin Li       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4789*67e74705SXin Li       uint64_t FromSize = getTypeSize(BT);
4790*67e74705SXin Li       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4791*67e74705SXin Li                                   LongLongTy, UnsignedLongLongTy };
4792*67e74705SXin Li       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4793*67e74705SXin Li         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4794*67e74705SXin Li         if (FromSize < ToSize ||
4795*67e74705SXin Li             (FromSize == ToSize &&
4796*67e74705SXin Li              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4797*67e74705SXin Li           return PromoteTypes[Idx];
4798*67e74705SXin Li       }
4799*67e74705SXin Li       llvm_unreachable("char type should fit into long long");
4800*67e74705SXin Li     }
4801*67e74705SXin Li   }
4802*67e74705SXin Li 
4803*67e74705SXin Li   // At this point, we should have a signed or unsigned integer type.
4804*67e74705SXin Li   if (Promotable->isSignedIntegerType())
4805*67e74705SXin Li     return IntTy;
4806*67e74705SXin Li   uint64_t PromotableSize = getIntWidth(Promotable);
4807*67e74705SXin Li   uint64_t IntSize = getIntWidth(IntTy);
4808*67e74705SXin Li   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4809*67e74705SXin Li   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4810*67e74705SXin Li }
4811*67e74705SXin Li 
4812*67e74705SXin Li /// \brief Recurses in pointer/array types until it finds an objc retainable
4813*67e74705SXin Li /// type and returns its ownership.
getInnerObjCOwnership(QualType T) const4814*67e74705SXin Li Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4815*67e74705SXin Li   while (!T.isNull()) {
4816*67e74705SXin Li     if (T.getObjCLifetime() != Qualifiers::OCL_None)
4817*67e74705SXin Li       return T.getObjCLifetime();
4818*67e74705SXin Li     if (T->isArrayType())
4819*67e74705SXin Li       T = getBaseElementType(T);
4820*67e74705SXin Li     else if (const PointerType *PT = T->getAs<PointerType>())
4821*67e74705SXin Li       T = PT->getPointeeType();
4822*67e74705SXin Li     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4823*67e74705SXin Li       T = RT->getPointeeType();
4824*67e74705SXin Li     else
4825*67e74705SXin Li       break;
4826*67e74705SXin Li   }
4827*67e74705SXin Li 
4828*67e74705SXin Li   return Qualifiers::OCL_None;
4829*67e74705SXin Li }
4830*67e74705SXin Li 
getIntegerTypeForEnum(const EnumType * ET)4831*67e74705SXin Li static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4832*67e74705SXin Li   // Incomplete enum types are not treated as integer types.
4833*67e74705SXin Li   // FIXME: In C++, enum types are never integer types.
4834*67e74705SXin Li   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4835*67e74705SXin Li     return ET->getDecl()->getIntegerType().getTypePtr();
4836*67e74705SXin Li   return nullptr;
4837*67e74705SXin Li }
4838*67e74705SXin Li 
4839*67e74705SXin Li /// getIntegerTypeOrder - Returns the highest ranked integer type:
4840*67e74705SXin Li /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4841*67e74705SXin Li /// LHS < RHS, return -1.
getIntegerTypeOrder(QualType LHS,QualType RHS) const4842*67e74705SXin Li int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4843*67e74705SXin Li   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4844*67e74705SXin Li   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4845*67e74705SXin Li 
4846*67e74705SXin Li   // Unwrap enums to their underlying type.
4847*67e74705SXin Li   if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4848*67e74705SXin Li     LHSC = getIntegerTypeForEnum(ET);
4849*67e74705SXin Li   if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4850*67e74705SXin Li     RHSC = getIntegerTypeForEnum(ET);
4851*67e74705SXin Li 
4852*67e74705SXin Li   if (LHSC == RHSC) return 0;
4853*67e74705SXin Li 
4854*67e74705SXin Li   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4855*67e74705SXin Li   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4856*67e74705SXin Li 
4857*67e74705SXin Li   unsigned LHSRank = getIntegerRank(LHSC);
4858*67e74705SXin Li   unsigned RHSRank = getIntegerRank(RHSC);
4859*67e74705SXin Li 
4860*67e74705SXin Li   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
4861*67e74705SXin Li     if (LHSRank == RHSRank) return 0;
4862*67e74705SXin Li     return LHSRank > RHSRank ? 1 : -1;
4863*67e74705SXin Li   }
4864*67e74705SXin Li 
4865*67e74705SXin Li   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4866*67e74705SXin Li   if (LHSUnsigned) {
4867*67e74705SXin Li     // If the unsigned [LHS] type is larger, return it.
4868*67e74705SXin Li     if (LHSRank >= RHSRank)
4869*67e74705SXin Li       return 1;
4870*67e74705SXin Li 
4871*67e74705SXin Li     // If the signed type can represent all values of the unsigned type, it
4872*67e74705SXin Li     // wins.  Because we are dealing with 2's complement and types that are
4873*67e74705SXin Li     // powers of two larger than each other, this is always safe.
4874*67e74705SXin Li     return -1;
4875*67e74705SXin Li   }
4876*67e74705SXin Li 
4877*67e74705SXin Li   // If the unsigned [RHS] type is larger, return it.
4878*67e74705SXin Li   if (RHSRank >= LHSRank)
4879*67e74705SXin Li     return -1;
4880*67e74705SXin Li 
4881*67e74705SXin Li   // If the signed type can represent all values of the unsigned type, it
4882*67e74705SXin Li   // wins.  Because we are dealing with 2's complement and types that are
4883*67e74705SXin Li   // powers of two larger than each other, this is always safe.
4884*67e74705SXin Li   return 1;
4885*67e74705SXin Li }
4886*67e74705SXin Li 
getCFConstantStringDecl() const4887*67e74705SXin Li TypedefDecl *ASTContext::getCFConstantStringDecl() const {
4888*67e74705SXin Li   if (!CFConstantStringTypeDecl) {
4889*67e74705SXin Li     assert(!CFConstantStringTagDecl &&
4890*67e74705SXin Li            "tag and typedef should be initialized together");
4891*67e74705SXin Li     CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4892*67e74705SXin Li     CFConstantStringTagDecl->startDefinition();
4893*67e74705SXin Li 
4894*67e74705SXin Li     QualType FieldTypes[4];
4895*67e74705SXin Li     const char *FieldNames[4];
4896*67e74705SXin Li 
4897*67e74705SXin Li     // const int *isa;
4898*67e74705SXin Li     FieldTypes[0] = getPointerType(IntTy.withConst());
4899*67e74705SXin Li     FieldNames[0] = "isa";
4900*67e74705SXin Li     // int flags;
4901*67e74705SXin Li     FieldTypes[1] = IntTy;
4902*67e74705SXin Li     FieldNames[1] = "flags";
4903*67e74705SXin Li     // const char *str;
4904*67e74705SXin Li     FieldTypes[2] = getPointerType(CharTy.withConst());
4905*67e74705SXin Li     FieldNames[2] = "str";
4906*67e74705SXin Li     // long length;
4907*67e74705SXin Li     FieldTypes[3] = LongTy;
4908*67e74705SXin Li     FieldNames[3] = "length";
4909*67e74705SXin Li 
4910*67e74705SXin Li     // Create fields
4911*67e74705SXin Li     for (unsigned i = 0; i < 4; ++i) {
4912*67e74705SXin Li       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
4913*67e74705SXin Li                                            SourceLocation(),
4914*67e74705SXin Li                                            SourceLocation(),
4915*67e74705SXin Li                                            &Idents.get(FieldNames[i]),
4916*67e74705SXin Li                                            FieldTypes[i], /*TInfo=*/nullptr,
4917*67e74705SXin Li                                            /*BitWidth=*/nullptr,
4918*67e74705SXin Li                                            /*Mutable=*/false,
4919*67e74705SXin Li                                            ICIS_NoInit);
4920*67e74705SXin Li       Field->setAccess(AS_public);
4921*67e74705SXin Li       CFConstantStringTagDecl->addDecl(Field);
4922*67e74705SXin Li     }
4923*67e74705SXin Li 
4924*67e74705SXin Li     CFConstantStringTagDecl->completeDefinition();
4925*67e74705SXin Li     // This type is designed to be compatible with NSConstantString, but cannot
4926*67e74705SXin Li     // use the same name, since NSConstantString is an interface.
4927*67e74705SXin Li     auto tagType = getTagDeclType(CFConstantStringTagDecl);
4928*67e74705SXin Li     CFConstantStringTypeDecl =
4929*67e74705SXin Li         buildImplicitTypedef(tagType, "__NSConstantString");
4930*67e74705SXin Li   }
4931*67e74705SXin Li 
4932*67e74705SXin Li   return CFConstantStringTypeDecl;
4933*67e74705SXin Li }
4934*67e74705SXin Li 
getCFConstantStringTagDecl() const4935*67e74705SXin Li RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4936*67e74705SXin Li   if (!CFConstantStringTagDecl)
4937*67e74705SXin Li     getCFConstantStringDecl(); // Build the tag and the typedef.
4938*67e74705SXin Li   return CFConstantStringTagDecl;
4939*67e74705SXin Li }
4940*67e74705SXin Li 
4941*67e74705SXin Li // getCFConstantStringType - Return the type used for constant CFStrings.
getCFConstantStringType() const4942*67e74705SXin Li QualType ASTContext::getCFConstantStringType() const {
4943*67e74705SXin Li   return getTypedefType(getCFConstantStringDecl());
4944*67e74705SXin Li }
4945*67e74705SXin Li 
getObjCSuperType() const4946*67e74705SXin Li QualType ASTContext::getObjCSuperType() const {
4947*67e74705SXin Li   if (ObjCSuperType.isNull()) {
4948*67e74705SXin Li     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4949*67e74705SXin Li     TUDecl->addDecl(ObjCSuperTypeDecl);
4950*67e74705SXin Li     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4951*67e74705SXin Li   }
4952*67e74705SXin Li   return ObjCSuperType;
4953*67e74705SXin Li }
4954*67e74705SXin Li 
setCFConstantStringType(QualType T)4955*67e74705SXin Li void ASTContext::setCFConstantStringType(QualType T) {
4956*67e74705SXin Li   const TypedefType *TD = T->getAs<TypedefType>();
4957*67e74705SXin Li   assert(TD && "Invalid CFConstantStringType");
4958*67e74705SXin Li   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4959*67e74705SXin Li   auto TagType =
4960*67e74705SXin Li       CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4961*67e74705SXin Li   assert(TagType && "Invalid CFConstantStringType");
4962*67e74705SXin Li   CFConstantStringTagDecl = TagType->getDecl();
4963*67e74705SXin Li }
4964*67e74705SXin Li 
getBlockDescriptorType() const4965*67e74705SXin Li QualType ASTContext::getBlockDescriptorType() const {
4966*67e74705SXin Li   if (BlockDescriptorType)
4967*67e74705SXin Li     return getTagDeclType(BlockDescriptorType);
4968*67e74705SXin Li 
4969*67e74705SXin Li   RecordDecl *RD;
4970*67e74705SXin Li   // FIXME: Needs the FlagAppleBlock bit.
4971*67e74705SXin Li   RD = buildImplicitRecord("__block_descriptor");
4972*67e74705SXin Li   RD->startDefinition();
4973*67e74705SXin Li 
4974*67e74705SXin Li   QualType FieldTypes[] = {
4975*67e74705SXin Li     UnsignedLongTy,
4976*67e74705SXin Li     UnsignedLongTy,
4977*67e74705SXin Li   };
4978*67e74705SXin Li 
4979*67e74705SXin Li   static const char *const FieldNames[] = {
4980*67e74705SXin Li     "reserved",
4981*67e74705SXin Li     "Size"
4982*67e74705SXin Li   };
4983*67e74705SXin Li 
4984*67e74705SXin Li   for (size_t i = 0; i < 2; ++i) {
4985*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(
4986*67e74705SXin Li         *this, RD, SourceLocation(), SourceLocation(),
4987*67e74705SXin Li         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4988*67e74705SXin Li         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4989*67e74705SXin Li     Field->setAccess(AS_public);
4990*67e74705SXin Li     RD->addDecl(Field);
4991*67e74705SXin Li   }
4992*67e74705SXin Li 
4993*67e74705SXin Li   RD->completeDefinition();
4994*67e74705SXin Li 
4995*67e74705SXin Li   BlockDescriptorType = RD;
4996*67e74705SXin Li 
4997*67e74705SXin Li   return getTagDeclType(BlockDescriptorType);
4998*67e74705SXin Li }
4999*67e74705SXin Li 
getBlockDescriptorExtendedType() const5000*67e74705SXin Li QualType ASTContext::getBlockDescriptorExtendedType() const {
5001*67e74705SXin Li   if (BlockDescriptorExtendedType)
5002*67e74705SXin Li     return getTagDeclType(BlockDescriptorExtendedType);
5003*67e74705SXin Li 
5004*67e74705SXin Li   RecordDecl *RD;
5005*67e74705SXin Li   // FIXME: Needs the FlagAppleBlock bit.
5006*67e74705SXin Li   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5007*67e74705SXin Li   RD->startDefinition();
5008*67e74705SXin Li 
5009*67e74705SXin Li   QualType FieldTypes[] = {
5010*67e74705SXin Li     UnsignedLongTy,
5011*67e74705SXin Li     UnsignedLongTy,
5012*67e74705SXin Li     getPointerType(VoidPtrTy),
5013*67e74705SXin Li     getPointerType(VoidPtrTy)
5014*67e74705SXin Li   };
5015*67e74705SXin Li 
5016*67e74705SXin Li   static const char *const FieldNames[] = {
5017*67e74705SXin Li     "reserved",
5018*67e74705SXin Li     "Size",
5019*67e74705SXin Li     "CopyFuncPtr",
5020*67e74705SXin Li     "DestroyFuncPtr"
5021*67e74705SXin Li   };
5022*67e74705SXin Li 
5023*67e74705SXin Li   for (size_t i = 0; i < 4; ++i) {
5024*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(
5025*67e74705SXin Li         *this, RD, SourceLocation(), SourceLocation(),
5026*67e74705SXin Li         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5027*67e74705SXin Li         /*BitWidth=*/nullptr,
5028*67e74705SXin Li         /*Mutable=*/false, ICIS_NoInit);
5029*67e74705SXin Li     Field->setAccess(AS_public);
5030*67e74705SXin Li     RD->addDecl(Field);
5031*67e74705SXin Li   }
5032*67e74705SXin Li 
5033*67e74705SXin Li   RD->completeDefinition();
5034*67e74705SXin Li 
5035*67e74705SXin Li   BlockDescriptorExtendedType = RD;
5036*67e74705SXin Li   return getTagDeclType(BlockDescriptorExtendedType);
5037*67e74705SXin Li }
5038*67e74705SXin Li 
5039*67e74705SXin Li /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5040*67e74705SXin Li /// requires copy/dispose. Note that this must match the logic
5041*67e74705SXin Li /// in buildByrefHelpers.
BlockRequiresCopying(QualType Ty,const VarDecl * D)5042*67e74705SXin Li bool ASTContext::BlockRequiresCopying(QualType Ty,
5043*67e74705SXin Li                                       const VarDecl *D) {
5044*67e74705SXin Li   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5045*67e74705SXin Li     const Expr *copyExpr = getBlockVarCopyInits(D);
5046*67e74705SXin Li     if (!copyExpr && record->hasTrivialDestructor()) return false;
5047*67e74705SXin Li 
5048*67e74705SXin Li     return true;
5049*67e74705SXin Li   }
5050*67e74705SXin Li 
5051*67e74705SXin Li   if (!Ty->isObjCRetainableType()) return false;
5052*67e74705SXin Li 
5053*67e74705SXin Li   Qualifiers qs = Ty.getQualifiers();
5054*67e74705SXin Li 
5055*67e74705SXin Li   // If we have lifetime, that dominates.
5056*67e74705SXin Li   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5057*67e74705SXin Li     switch (lifetime) {
5058*67e74705SXin Li       case Qualifiers::OCL_None: llvm_unreachable("impossible");
5059*67e74705SXin Li 
5060*67e74705SXin Li       // These are just bits as far as the runtime is concerned.
5061*67e74705SXin Li       case Qualifiers::OCL_ExplicitNone:
5062*67e74705SXin Li       case Qualifiers::OCL_Autoreleasing:
5063*67e74705SXin Li         return false;
5064*67e74705SXin Li 
5065*67e74705SXin Li       // Tell the runtime that this is ARC __weak, called by the
5066*67e74705SXin Li       // byref routines.
5067*67e74705SXin Li       case Qualifiers::OCL_Weak:
5068*67e74705SXin Li       // ARC __strong __block variables need to be retained.
5069*67e74705SXin Li       case Qualifiers::OCL_Strong:
5070*67e74705SXin Li         return true;
5071*67e74705SXin Li     }
5072*67e74705SXin Li     llvm_unreachable("fell out of lifetime switch!");
5073*67e74705SXin Li   }
5074*67e74705SXin Li   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5075*67e74705SXin Li           Ty->isObjCObjectPointerType());
5076*67e74705SXin Li }
5077*67e74705SXin Li 
getByrefLifetime(QualType Ty,Qualifiers::ObjCLifetime & LifeTime,bool & HasByrefExtendedLayout) const5078*67e74705SXin Li bool ASTContext::getByrefLifetime(QualType Ty,
5079*67e74705SXin Li                               Qualifiers::ObjCLifetime &LifeTime,
5080*67e74705SXin Li                               bool &HasByrefExtendedLayout) const {
5081*67e74705SXin Li 
5082*67e74705SXin Li   if (!getLangOpts().ObjC1 ||
5083*67e74705SXin Li       getLangOpts().getGC() != LangOptions::NonGC)
5084*67e74705SXin Li     return false;
5085*67e74705SXin Li 
5086*67e74705SXin Li   HasByrefExtendedLayout = false;
5087*67e74705SXin Li   if (Ty->isRecordType()) {
5088*67e74705SXin Li     HasByrefExtendedLayout = true;
5089*67e74705SXin Li     LifeTime = Qualifiers::OCL_None;
5090*67e74705SXin Li   } else if ((LifeTime = Ty.getObjCLifetime())) {
5091*67e74705SXin Li     // Honor the ARC qualifiers.
5092*67e74705SXin Li   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5093*67e74705SXin Li     // The MRR rule.
5094*67e74705SXin Li     LifeTime = Qualifiers::OCL_ExplicitNone;
5095*67e74705SXin Li   } else {
5096*67e74705SXin Li     LifeTime = Qualifiers::OCL_None;
5097*67e74705SXin Li   }
5098*67e74705SXin Li   return true;
5099*67e74705SXin Li }
5100*67e74705SXin Li 
getObjCInstanceTypeDecl()5101*67e74705SXin Li TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5102*67e74705SXin Li   if (!ObjCInstanceTypeDecl)
5103*67e74705SXin Li     ObjCInstanceTypeDecl =
5104*67e74705SXin Li         buildImplicitTypedef(getObjCIdType(), "instancetype");
5105*67e74705SXin Li   return ObjCInstanceTypeDecl;
5106*67e74705SXin Li }
5107*67e74705SXin Li 
5108*67e74705SXin Li // This returns true if a type has been typedefed to BOOL:
5109*67e74705SXin Li // typedef <type> BOOL;
isTypeTypedefedAsBOOL(QualType T)5110*67e74705SXin Li static bool isTypeTypedefedAsBOOL(QualType T) {
5111*67e74705SXin Li   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5112*67e74705SXin Li     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5113*67e74705SXin Li       return II->isStr("BOOL");
5114*67e74705SXin Li 
5115*67e74705SXin Li   return false;
5116*67e74705SXin Li }
5117*67e74705SXin Li 
5118*67e74705SXin Li /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5119*67e74705SXin Li /// purpose.
getObjCEncodingTypeSize(QualType type) const5120*67e74705SXin Li CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5121*67e74705SXin Li   if (!type->isIncompleteArrayType() && type->isIncompleteType())
5122*67e74705SXin Li     return CharUnits::Zero();
5123*67e74705SXin Li 
5124*67e74705SXin Li   CharUnits sz = getTypeSizeInChars(type);
5125*67e74705SXin Li 
5126*67e74705SXin Li   // Make all integer and enum types at least as large as an int
5127*67e74705SXin Li   if (sz.isPositive() && type->isIntegralOrEnumerationType())
5128*67e74705SXin Li     sz = std::max(sz, getTypeSizeInChars(IntTy));
5129*67e74705SXin Li   // Treat arrays as pointers, since that's how they're passed in.
5130*67e74705SXin Li   else if (type->isArrayType())
5131*67e74705SXin Li     sz = getTypeSizeInChars(VoidPtrTy);
5132*67e74705SXin Li   return sz;
5133*67e74705SXin Li }
5134*67e74705SXin Li 
isMSStaticDataMemberInlineDefinition(const VarDecl * VD) const5135*67e74705SXin Li bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5136*67e74705SXin Li   return getTargetInfo().getCXXABI().isMicrosoft() &&
5137*67e74705SXin Li          VD->isStaticDataMember() &&
5138*67e74705SXin Li          VD->getType()->isIntegralOrEnumerationType() &&
5139*67e74705SXin Li          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5140*67e74705SXin Li }
5141*67e74705SXin Li 
5142*67e74705SXin Li ASTContext::InlineVariableDefinitionKind
getInlineVariableDefinitionKind(const VarDecl * VD) const5143*67e74705SXin Li ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5144*67e74705SXin Li   if (!VD->isInline())
5145*67e74705SXin Li     return InlineVariableDefinitionKind::None;
5146*67e74705SXin Li 
5147*67e74705SXin Li   // In almost all cases, it's a weak definition.
5148*67e74705SXin Li   auto *First = VD->getFirstDecl();
5149*67e74705SXin Li   if (!First->isConstexpr() || First->isInlineSpecified() ||
5150*67e74705SXin Li       !VD->isStaticDataMember())
5151*67e74705SXin Li     return InlineVariableDefinitionKind::Weak;
5152*67e74705SXin Li 
5153*67e74705SXin Li   // If there's a file-context declaration in this translation unit, it's a
5154*67e74705SXin Li   // non-discardable definition.
5155*67e74705SXin Li   for (auto *D : VD->redecls())
5156*67e74705SXin Li     if (D->getLexicalDeclContext()->isFileContext())
5157*67e74705SXin Li       return InlineVariableDefinitionKind::Strong;
5158*67e74705SXin Li 
5159*67e74705SXin Li   // If we've not seen one yet, we don't know.
5160*67e74705SXin Li   return InlineVariableDefinitionKind::WeakUnknown;
5161*67e74705SXin Li }
5162*67e74705SXin Li 
5163*67e74705SXin Li static inline
charUnitsToString(const CharUnits & CU)5164*67e74705SXin Li std::string charUnitsToString(const CharUnits &CU) {
5165*67e74705SXin Li   return llvm::itostr(CU.getQuantity());
5166*67e74705SXin Li }
5167*67e74705SXin Li 
5168*67e74705SXin Li /// getObjCEncodingForBlock - Return the encoded type for this block
5169*67e74705SXin Li /// declaration.
getObjCEncodingForBlock(const BlockExpr * Expr) const5170*67e74705SXin Li std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5171*67e74705SXin Li   std::string S;
5172*67e74705SXin Li 
5173*67e74705SXin Li   const BlockDecl *Decl = Expr->getBlockDecl();
5174*67e74705SXin Li   QualType BlockTy =
5175*67e74705SXin Li       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5176*67e74705SXin Li   // Encode result type.
5177*67e74705SXin Li   if (getLangOpts().EncodeExtendedBlockSig)
5178*67e74705SXin Li     getObjCEncodingForMethodParameter(
5179*67e74705SXin Li         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5180*67e74705SXin Li         true /*Extended*/);
5181*67e74705SXin Li   else
5182*67e74705SXin Li     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5183*67e74705SXin Li   // Compute size of all parameters.
5184*67e74705SXin Li   // Start with computing size of a pointer in number of bytes.
5185*67e74705SXin Li   // FIXME: There might(should) be a better way of doing this computation!
5186*67e74705SXin Li   SourceLocation Loc;
5187*67e74705SXin Li   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5188*67e74705SXin Li   CharUnits ParmOffset = PtrSize;
5189*67e74705SXin Li   for (auto PI : Decl->parameters()) {
5190*67e74705SXin Li     QualType PType = PI->getType();
5191*67e74705SXin Li     CharUnits sz = getObjCEncodingTypeSize(PType);
5192*67e74705SXin Li     if (sz.isZero())
5193*67e74705SXin Li       continue;
5194*67e74705SXin Li     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5195*67e74705SXin Li     ParmOffset += sz;
5196*67e74705SXin Li   }
5197*67e74705SXin Li   // Size of the argument frame
5198*67e74705SXin Li   S += charUnitsToString(ParmOffset);
5199*67e74705SXin Li   // Block pointer and offset.
5200*67e74705SXin Li   S += "@?0";
5201*67e74705SXin Li 
5202*67e74705SXin Li   // Argument types.
5203*67e74705SXin Li   ParmOffset = PtrSize;
5204*67e74705SXin Li   for (auto PVDecl : Decl->parameters()) {
5205*67e74705SXin Li     QualType PType = PVDecl->getOriginalType();
5206*67e74705SXin Li     if (const ArrayType *AT =
5207*67e74705SXin Li           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5208*67e74705SXin Li       // Use array's original type only if it has known number of
5209*67e74705SXin Li       // elements.
5210*67e74705SXin Li       if (!isa<ConstantArrayType>(AT))
5211*67e74705SXin Li         PType = PVDecl->getType();
5212*67e74705SXin Li     } else if (PType->isFunctionType())
5213*67e74705SXin Li       PType = PVDecl->getType();
5214*67e74705SXin Li     if (getLangOpts().EncodeExtendedBlockSig)
5215*67e74705SXin Li       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5216*67e74705SXin Li                                       S, true /*Extended*/);
5217*67e74705SXin Li     else
5218*67e74705SXin Li       getObjCEncodingForType(PType, S);
5219*67e74705SXin Li     S += charUnitsToString(ParmOffset);
5220*67e74705SXin Li     ParmOffset += getObjCEncodingTypeSize(PType);
5221*67e74705SXin Li   }
5222*67e74705SXin Li 
5223*67e74705SXin Li   return S;
5224*67e74705SXin Li }
5225*67e74705SXin Li 
getObjCEncodingForFunctionDecl(const FunctionDecl * Decl,std::string & S)5226*67e74705SXin Li bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5227*67e74705SXin Li                                                 std::string& S) {
5228*67e74705SXin Li   // Encode result type.
5229*67e74705SXin Li   getObjCEncodingForType(Decl->getReturnType(), S);
5230*67e74705SXin Li   CharUnits ParmOffset;
5231*67e74705SXin Li   // Compute size of all parameters.
5232*67e74705SXin Li   for (auto PI : Decl->parameters()) {
5233*67e74705SXin Li     QualType PType = PI->getType();
5234*67e74705SXin Li     CharUnits sz = getObjCEncodingTypeSize(PType);
5235*67e74705SXin Li     if (sz.isZero())
5236*67e74705SXin Li       continue;
5237*67e74705SXin Li 
5238*67e74705SXin Li     assert (sz.isPositive() &&
5239*67e74705SXin Li         "getObjCEncodingForFunctionDecl - Incomplete param type");
5240*67e74705SXin Li     ParmOffset += sz;
5241*67e74705SXin Li   }
5242*67e74705SXin Li   S += charUnitsToString(ParmOffset);
5243*67e74705SXin Li   ParmOffset = CharUnits::Zero();
5244*67e74705SXin Li 
5245*67e74705SXin Li   // Argument types.
5246*67e74705SXin Li   for (auto PVDecl : Decl->parameters()) {
5247*67e74705SXin Li     QualType PType = PVDecl->getOriginalType();
5248*67e74705SXin Li     if (const ArrayType *AT =
5249*67e74705SXin Li           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5250*67e74705SXin Li       // Use array's original type only if it has known number of
5251*67e74705SXin Li       // elements.
5252*67e74705SXin Li       if (!isa<ConstantArrayType>(AT))
5253*67e74705SXin Li         PType = PVDecl->getType();
5254*67e74705SXin Li     } else if (PType->isFunctionType())
5255*67e74705SXin Li       PType = PVDecl->getType();
5256*67e74705SXin Li     getObjCEncodingForType(PType, S);
5257*67e74705SXin Li     S += charUnitsToString(ParmOffset);
5258*67e74705SXin Li     ParmOffset += getObjCEncodingTypeSize(PType);
5259*67e74705SXin Li   }
5260*67e74705SXin Li 
5261*67e74705SXin Li   return false;
5262*67e74705SXin Li }
5263*67e74705SXin Li 
5264*67e74705SXin Li /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5265*67e74705SXin Li /// method parameter or return type. If Extended, include class names and
5266*67e74705SXin Li /// block object types.
getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,QualType T,std::string & S,bool Extended) const5267*67e74705SXin Li void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5268*67e74705SXin Li                                                    QualType T, std::string& S,
5269*67e74705SXin Li                                                    bool Extended) const {
5270*67e74705SXin Li   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5271*67e74705SXin Li   getObjCEncodingForTypeQualifier(QT, S);
5272*67e74705SXin Li   // Encode parameter type.
5273*67e74705SXin Li   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5274*67e74705SXin Li                              true     /*OutermostType*/,
5275*67e74705SXin Li                              false    /*EncodingProperty*/,
5276*67e74705SXin Li                              false    /*StructField*/,
5277*67e74705SXin Li                              Extended /*EncodeBlockParameters*/,
5278*67e74705SXin Li                              Extended /*EncodeClassNames*/);
5279*67e74705SXin Li }
5280*67e74705SXin Li 
5281*67e74705SXin Li /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5282*67e74705SXin Li /// declaration.
getObjCEncodingForMethodDecl(const ObjCMethodDecl * Decl,std::string & S,bool Extended) const5283*67e74705SXin Li bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5284*67e74705SXin Li                                               std::string& S,
5285*67e74705SXin Li                                               bool Extended) const {
5286*67e74705SXin Li   // FIXME: This is not very efficient.
5287*67e74705SXin Li   // Encode return type.
5288*67e74705SXin Li   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5289*67e74705SXin Li                                     Decl->getReturnType(), S, Extended);
5290*67e74705SXin Li   // Compute size of all parameters.
5291*67e74705SXin Li   // Start with computing size of a pointer in number of bytes.
5292*67e74705SXin Li   // FIXME: There might(should) be a better way of doing this computation!
5293*67e74705SXin Li   SourceLocation Loc;
5294*67e74705SXin Li   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5295*67e74705SXin Li   // The first two arguments (self and _cmd) are pointers; account for
5296*67e74705SXin Li   // their size.
5297*67e74705SXin Li   CharUnits ParmOffset = 2 * PtrSize;
5298*67e74705SXin Li   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5299*67e74705SXin Li        E = Decl->sel_param_end(); PI != E; ++PI) {
5300*67e74705SXin Li     QualType PType = (*PI)->getType();
5301*67e74705SXin Li     CharUnits sz = getObjCEncodingTypeSize(PType);
5302*67e74705SXin Li     if (sz.isZero())
5303*67e74705SXin Li       continue;
5304*67e74705SXin Li 
5305*67e74705SXin Li     assert (sz.isPositive() &&
5306*67e74705SXin Li         "getObjCEncodingForMethodDecl - Incomplete param type");
5307*67e74705SXin Li     ParmOffset += sz;
5308*67e74705SXin Li   }
5309*67e74705SXin Li   S += charUnitsToString(ParmOffset);
5310*67e74705SXin Li   S += "@0:";
5311*67e74705SXin Li   S += charUnitsToString(PtrSize);
5312*67e74705SXin Li 
5313*67e74705SXin Li   // Argument types.
5314*67e74705SXin Li   ParmOffset = 2 * PtrSize;
5315*67e74705SXin Li   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5316*67e74705SXin Li        E = Decl->sel_param_end(); PI != E; ++PI) {
5317*67e74705SXin Li     const ParmVarDecl *PVDecl = *PI;
5318*67e74705SXin Li     QualType PType = PVDecl->getOriginalType();
5319*67e74705SXin Li     if (const ArrayType *AT =
5320*67e74705SXin Li           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5321*67e74705SXin Li       // Use array's original type only if it has known number of
5322*67e74705SXin Li       // elements.
5323*67e74705SXin Li       if (!isa<ConstantArrayType>(AT))
5324*67e74705SXin Li         PType = PVDecl->getType();
5325*67e74705SXin Li     } else if (PType->isFunctionType())
5326*67e74705SXin Li       PType = PVDecl->getType();
5327*67e74705SXin Li     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5328*67e74705SXin Li                                       PType, S, Extended);
5329*67e74705SXin Li     S += charUnitsToString(ParmOffset);
5330*67e74705SXin Li     ParmOffset += getObjCEncodingTypeSize(PType);
5331*67e74705SXin Li   }
5332*67e74705SXin Li 
5333*67e74705SXin Li   return false;
5334*67e74705SXin Li }
5335*67e74705SXin Li 
5336*67e74705SXin Li ObjCPropertyImplDecl *
getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container) const5337*67e74705SXin Li ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5338*67e74705SXin Li                                       const ObjCPropertyDecl *PD,
5339*67e74705SXin Li                                       const Decl *Container) const {
5340*67e74705SXin Li   if (!Container)
5341*67e74705SXin Li     return nullptr;
5342*67e74705SXin Li   if (const ObjCCategoryImplDecl *CID =
5343*67e74705SXin Li       dyn_cast<ObjCCategoryImplDecl>(Container)) {
5344*67e74705SXin Li     for (auto *PID : CID->property_impls())
5345*67e74705SXin Li       if (PID->getPropertyDecl() == PD)
5346*67e74705SXin Li         return PID;
5347*67e74705SXin Li   } else {
5348*67e74705SXin Li     const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5349*67e74705SXin Li     for (auto *PID : OID->property_impls())
5350*67e74705SXin Li       if (PID->getPropertyDecl() == PD)
5351*67e74705SXin Li         return PID;
5352*67e74705SXin Li   }
5353*67e74705SXin Li   return nullptr;
5354*67e74705SXin Li }
5355*67e74705SXin Li 
5356*67e74705SXin Li /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5357*67e74705SXin Li /// property declaration. If non-NULL, Container must be either an
5358*67e74705SXin Li /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5359*67e74705SXin Li /// NULL when getting encodings for protocol properties.
5360*67e74705SXin Li /// Property attributes are stored as a comma-delimited C string. The simple
5361*67e74705SXin Li /// attributes readonly and bycopy are encoded as single characters. The
5362*67e74705SXin Li /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5363*67e74705SXin Li /// encoded as single characters, followed by an identifier. Property types
5364*67e74705SXin Li /// are also encoded as a parametrized attribute. The characters used to encode
5365*67e74705SXin Li /// these attributes are defined by the following enumeration:
5366*67e74705SXin Li /// @code
5367*67e74705SXin Li /// enum PropertyAttributes {
5368*67e74705SXin Li /// kPropertyReadOnly = 'R',   // property is read-only.
5369*67e74705SXin Li /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
5370*67e74705SXin Li /// kPropertyByref = '&',  // property is a reference to the value last assigned
5371*67e74705SXin Li /// kPropertyDynamic = 'D',    // property is dynamic
5372*67e74705SXin Li /// kPropertyGetter = 'G',     // followed by getter selector name
5373*67e74705SXin Li /// kPropertySetter = 'S',     // followed by setter selector name
5374*67e74705SXin Li /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
5375*67e74705SXin Li /// kPropertyType = 'T'              // followed by old-style type encoding.
5376*67e74705SXin Li /// kPropertyWeak = 'W'              // 'weak' property
5377*67e74705SXin Li /// kPropertyStrong = 'P'            // property GC'able
5378*67e74705SXin Li /// kPropertyNonAtomic = 'N'         // property non-atomic
5379*67e74705SXin Li /// };
5380*67e74705SXin Li /// @endcode
getObjCEncodingForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container,std::string & S) const5381*67e74705SXin Li void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5382*67e74705SXin Li                                                 const Decl *Container,
5383*67e74705SXin Li                                                 std::string& S) const {
5384*67e74705SXin Li   // Collect information from the property implementation decl(s).
5385*67e74705SXin Li   bool Dynamic = false;
5386*67e74705SXin Li   ObjCPropertyImplDecl *SynthesizePID = nullptr;
5387*67e74705SXin Li 
5388*67e74705SXin Li   if (ObjCPropertyImplDecl *PropertyImpDecl =
5389*67e74705SXin Li       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5390*67e74705SXin Li     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5391*67e74705SXin Li       Dynamic = true;
5392*67e74705SXin Li     else
5393*67e74705SXin Li       SynthesizePID = PropertyImpDecl;
5394*67e74705SXin Li   }
5395*67e74705SXin Li 
5396*67e74705SXin Li   // FIXME: This is not very efficient.
5397*67e74705SXin Li   S = "T";
5398*67e74705SXin Li 
5399*67e74705SXin Li   // Encode result type.
5400*67e74705SXin Li   // GCC has some special rules regarding encoding of properties which
5401*67e74705SXin Li   // closely resembles encoding of ivars.
5402*67e74705SXin Li   getObjCEncodingForPropertyType(PD->getType(), S);
5403*67e74705SXin Li 
5404*67e74705SXin Li   if (PD->isReadOnly()) {
5405*67e74705SXin Li     S += ",R";
5406*67e74705SXin Li     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5407*67e74705SXin Li       S += ",C";
5408*67e74705SXin Li     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5409*67e74705SXin Li       S += ",&";
5410*67e74705SXin Li     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5411*67e74705SXin Li       S += ",W";
5412*67e74705SXin Li   } else {
5413*67e74705SXin Li     switch (PD->getSetterKind()) {
5414*67e74705SXin Li     case ObjCPropertyDecl::Assign: break;
5415*67e74705SXin Li     case ObjCPropertyDecl::Copy:   S += ",C"; break;
5416*67e74705SXin Li     case ObjCPropertyDecl::Retain: S += ",&"; break;
5417*67e74705SXin Li     case ObjCPropertyDecl::Weak:   S += ",W"; break;
5418*67e74705SXin Li     }
5419*67e74705SXin Li   }
5420*67e74705SXin Li 
5421*67e74705SXin Li   // It really isn't clear at all what this means, since properties
5422*67e74705SXin Li   // are "dynamic by default".
5423*67e74705SXin Li   if (Dynamic)
5424*67e74705SXin Li     S += ",D";
5425*67e74705SXin Li 
5426*67e74705SXin Li   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5427*67e74705SXin Li     S += ",N";
5428*67e74705SXin Li 
5429*67e74705SXin Li   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5430*67e74705SXin Li     S += ",G";
5431*67e74705SXin Li     S += PD->getGetterName().getAsString();
5432*67e74705SXin Li   }
5433*67e74705SXin Li 
5434*67e74705SXin Li   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5435*67e74705SXin Li     S += ",S";
5436*67e74705SXin Li     S += PD->getSetterName().getAsString();
5437*67e74705SXin Li   }
5438*67e74705SXin Li 
5439*67e74705SXin Li   if (SynthesizePID) {
5440*67e74705SXin Li     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5441*67e74705SXin Li     S += ",V";
5442*67e74705SXin Li     S += OID->getNameAsString();
5443*67e74705SXin Li   }
5444*67e74705SXin Li 
5445*67e74705SXin Li   // FIXME: OBJCGC: weak & strong
5446*67e74705SXin Li }
5447*67e74705SXin Li 
5448*67e74705SXin Li /// getLegacyIntegralTypeEncoding -
5449*67e74705SXin Li /// Another legacy compatibility encoding: 32-bit longs are encoded as
5450*67e74705SXin Li /// 'l' or 'L' , but not always.  For typedefs, we need to use
5451*67e74705SXin Li /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5452*67e74705SXin Li ///
getLegacyIntegralTypeEncoding(QualType & PointeeTy) const5453*67e74705SXin Li void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5454*67e74705SXin Li   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5455*67e74705SXin Li     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5456*67e74705SXin Li       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5457*67e74705SXin Li         PointeeTy = UnsignedIntTy;
5458*67e74705SXin Li       else
5459*67e74705SXin Li         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5460*67e74705SXin Li           PointeeTy = IntTy;
5461*67e74705SXin Li     }
5462*67e74705SXin Li   }
5463*67e74705SXin Li }
5464*67e74705SXin Li 
getObjCEncodingForType(QualType T,std::string & S,const FieldDecl * Field,QualType * NotEncodedT) const5465*67e74705SXin Li void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5466*67e74705SXin Li                                         const FieldDecl *Field,
5467*67e74705SXin Li                                         QualType *NotEncodedT) const {
5468*67e74705SXin Li   // We follow the behavior of gcc, expanding structures which are
5469*67e74705SXin Li   // directly pointed to, and expanding embedded structures. Note that
5470*67e74705SXin Li   // these rules are sufficient to prevent recursive encoding of the
5471*67e74705SXin Li   // same type.
5472*67e74705SXin Li   getObjCEncodingForTypeImpl(T, S, true, true, Field,
5473*67e74705SXin Li                              true /* outermost type */, false, false,
5474*67e74705SXin Li                              false, false, false, NotEncodedT);
5475*67e74705SXin Li }
5476*67e74705SXin Li 
getObjCEncodingForPropertyType(QualType T,std::string & S) const5477*67e74705SXin Li void ASTContext::getObjCEncodingForPropertyType(QualType T,
5478*67e74705SXin Li                                                 std::string& S) const {
5479*67e74705SXin Li   // Encode result type.
5480*67e74705SXin Li   // GCC has some special rules regarding encoding of properties which
5481*67e74705SXin Li   // closely resembles encoding of ivars.
5482*67e74705SXin Li   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5483*67e74705SXin Li                              true /* outermost type */,
5484*67e74705SXin Li                              true /* encoding property */);
5485*67e74705SXin Li }
5486*67e74705SXin Li 
getObjCEncodingForPrimitiveKind(const ASTContext * C,BuiltinType::Kind kind)5487*67e74705SXin Li static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5488*67e74705SXin Li                                             BuiltinType::Kind kind) {
5489*67e74705SXin Li     switch (kind) {
5490*67e74705SXin Li     case BuiltinType::Void:       return 'v';
5491*67e74705SXin Li     case BuiltinType::Bool:       return 'B';
5492*67e74705SXin Li     case BuiltinType::Char_U:
5493*67e74705SXin Li     case BuiltinType::UChar:      return 'C';
5494*67e74705SXin Li     case BuiltinType::Char16:
5495*67e74705SXin Li     case BuiltinType::UShort:     return 'S';
5496*67e74705SXin Li     case BuiltinType::Char32:
5497*67e74705SXin Li     case BuiltinType::UInt:       return 'I';
5498*67e74705SXin Li     case BuiltinType::ULong:
5499*67e74705SXin Li         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5500*67e74705SXin Li     case BuiltinType::UInt128:    return 'T';
5501*67e74705SXin Li     case BuiltinType::ULongLong:  return 'Q';
5502*67e74705SXin Li     case BuiltinType::Char_S:
5503*67e74705SXin Li     case BuiltinType::SChar:      return 'c';
5504*67e74705SXin Li     case BuiltinType::Short:      return 's';
5505*67e74705SXin Li     case BuiltinType::WChar_S:
5506*67e74705SXin Li     case BuiltinType::WChar_U:
5507*67e74705SXin Li     case BuiltinType::Int:        return 'i';
5508*67e74705SXin Li     case BuiltinType::Long:
5509*67e74705SXin Li       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5510*67e74705SXin Li     case BuiltinType::LongLong:   return 'q';
5511*67e74705SXin Li     case BuiltinType::Int128:     return 't';
5512*67e74705SXin Li     case BuiltinType::Float:      return 'f';
5513*67e74705SXin Li     case BuiltinType::Double:     return 'd';
5514*67e74705SXin Li     case BuiltinType::LongDouble: return 'D';
5515*67e74705SXin Li     case BuiltinType::NullPtr:    return '*'; // like char*
5516*67e74705SXin Li 
5517*67e74705SXin Li     case BuiltinType::Float128:
5518*67e74705SXin Li     case BuiltinType::Half:
5519*67e74705SXin Li       // FIXME: potentially need @encodes for these!
5520*67e74705SXin Li       return ' ';
5521*67e74705SXin Li 
5522*67e74705SXin Li     case BuiltinType::ObjCId:
5523*67e74705SXin Li     case BuiltinType::ObjCClass:
5524*67e74705SXin Li     case BuiltinType::ObjCSel:
5525*67e74705SXin Li       llvm_unreachable("@encoding ObjC primitive type");
5526*67e74705SXin Li 
5527*67e74705SXin Li     // OpenCL and placeholder types don't need @encodings.
5528*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5529*67e74705SXin Li     case BuiltinType::Id:
5530*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
5531*67e74705SXin Li     case BuiltinType::OCLEvent:
5532*67e74705SXin Li     case BuiltinType::OCLClkEvent:
5533*67e74705SXin Li     case BuiltinType::OCLQueue:
5534*67e74705SXin Li     case BuiltinType::OCLNDRange:
5535*67e74705SXin Li     case BuiltinType::OCLReserveID:
5536*67e74705SXin Li     case BuiltinType::OCLSampler:
5537*67e74705SXin Li     case BuiltinType::Dependent:
5538*67e74705SXin Li #define BUILTIN_TYPE(KIND, ID)
5539*67e74705SXin Li #define PLACEHOLDER_TYPE(KIND, ID) \
5540*67e74705SXin Li     case BuiltinType::KIND:
5541*67e74705SXin Li #include "clang/AST/BuiltinTypes.def"
5542*67e74705SXin Li       llvm_unreachable("invalid builtin type for @encode");
5543*67e74705SXin Li     }
5544*67e74705SXin Li     llvm_unreachable("invalid BuiltinType::Kind value");
5545*67e74705SXin Li }
5546*67e74705SXin Li 
ObjCEncodingForEnumType(const ASTContext * C,const EnumType * ET)5547*67e74705SXin Li static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5548*67e74705SXin Li   EnumDecl *Enum = ET->getDecl();
5549*67e74705SXin Li 
5550*67e74705SXin Li   // The encoding of an non-fixed enum type is always 'i', regardless of size.
5551*67e74705SXin Li   if (!Enum->isFixed())
5552*67e74705SXin Li     return 'i';
5553*67e74705SXin Li 
5554*67e74705SXin Li   // The encoding of a fixed enum type matches its fixed underlying type.
5555*67e74705SXin Li   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5556*67e74705SXin Li   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5557*67e74705SXin Li }
5558*67e74705SXin Li 
EncodeBitField(const ASTContext * Ctx,std::string & S,QualType T,const FieldDecl * FD)5559*67e74705SXin Li static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5560*67e74705SXin Li                            QualType T, const FieldDecl *FD) {
5561*67e74705SXin Li   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5562*67e74705SXin Li   S += 'b';
5563*67e74705SXin Li   // The NeXT runtime encodes bit fields as b followed by the number of bits.
5564*67e74705SXin Li   // The GNU runtime requires more information; bitfields are encoded as b,
5565*67e74705SXin Li   // then the offset (in bits) of the first element, then the type of the
5566*67e74705SXin Li   // bitfield, then the size in bits.  For example, in this structure:
5567*67e74705SXin Li   //
5568*67e74705SXin Li   // struct
5569*67e74705SXin Li   // {
5570*67e74705SXin Li   //    int integer;
5571*67e74705SXin Li   //    int flags:2;
5572*67e74705SXin Li   // };
5573*67e74705SXin Li   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5574*67e74705SXin Li   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
5575*67e74705SXin Li   // information is not especially sensible, but we're stuck with it for
5576*67e74705SXin Li   // compatibility with GCC, although providing it breaks anything that
5577*67e74705SXin Li   // actually uses runtime introspection and wants to work on both runtimes...
5578*67e74705SXin Li   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5579*67e74705SXin Li     const RecordDecl *RD = FD->getParent();
5580*67e74705SXin Li     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5581*67e74705SXin Li     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5582*67e74705SXin Li     if (const EnumType *ET = T->getAs<EnumType>())
5583*67e74705SXin Li       S += ObjCEncodingForEnumType(Ctx, ET);
5584*67e74705SXin Li     else {
5585*67e74705SXin Li       const BuiltinType *BT = T->castAs<BuiltinType>();
5586*67e74705SXin Li       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5587*67e74705SXin Li     }
5588*67e74705SXin Li   }
5589*67e74705SXin Li   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5590*67e74705SXin Li }
5591*67e74705SXin Li 
5592*67e74705SXin Li // FIXME: Use SmallString for accumulating string.
getObjCEncodingForTypeImpl(QualType T,std::string & S,bool ExpandPointedToStructures,bool ExpandStructures,const FieldDecl * FD,bool OutermostType,bool EncodingProperty,bool StructField,bool EncodeBlockParameters,bool EncodeClassNames,bool EncodePointerToObjCTypedef,QualType * NotEncodedT) const5593*67e74705SXin Li void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5594*67e74705SXin Li                                             bool ExpandPointedToStructures,
5595*67e74705SXin Li                                             bool ExpandStructures,
5596*67e74705SXin Li                                             const FieldDecl *FD,
5597*67e74705SXin Li                                             bool OutermostType,
5598*67e74705SXin Li                                             bool EncodingProperty,
5599*67e74705SXin Li                                             bool StructField,
5600*67e74705SXin Li                                             bool EncodeBlockParameters,
5601*67e74705SXin Li                                             bool EncodeClassNames,
5602*67e74705SXin Li                                             bool EncodePointerToObjCTypedef,
5603*67e74705SXin Li                                             QualType *NotEncodedT) const {
5604*67e74705SXin Li   CanQualType CT = getCanonicalType(T);
5605*67e74705SXin Li   switch (CT->getTypeClass()) {
5606*67e74705SXin Li   case Type::Builtin:
5607*67e74705SXin Li   case Type::Enum:
5608*67e74705SXin Li     if (FD && FD->isBitField())
5609*67e74705SXin Li       return EncodeBitField(this, S, T, FD);
5610*67e74705SXin Li     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5611*67e74705SXin Li       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5612*67e74705SXin Li     else
5613*67e74705SXin Li       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5614*67e74705SXin Li     return;
5615*67e74705SXin Li 
5616*67e74705SXin Li   case Type::Complex: {
5617*67e74705SXin Li     const ComplexType *CT = T->castAs<ComplexType>();
5618*67e74705SXin Li     S += 'j';
5619*67e74705SXin Li     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5620*67e74705SXin Li     return;
5621*67e74705SXin Li   }
5622*67e74705SXin Li 
5623*67e74705SXin Li   case Type::Atomic: {
5624*67e74705SXin Li     const AtomicType *AT = T->castAs<AtomicType>();
5625*67e74705SXin Li     S += 'A';
5626*67e74705SXin Li     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5627*67e74705SXin Li     return;
5628*67e74705SXin Li   }
5629*67e74705SXin Li 
5630*67e74705SXin Li   // encoding for pointer or reference types.
5631*67e74705SXin Li   case Type::Pointer:
5632*67e74705SXin Li   case Type::LValueReference:
5633*67e74705SXin Li   case Type::RValueReference: {
5634*67e74705SXin Li     QualType PointeeTy;
5635*67e74705SXin Li     if (isa<PointerType>(CT)) {
5636*67e74705SXin Li       const PointerType *PT = T->castAs<PointerType>();
5637*67e74705SXin Li       if (PT->isObjCSelType()) {
5638*67e74705SXin Li         S += ':';
5639*67e74705SXin Li         return;
5640*67e74705SXin Li       }
5641*67e74705SXin Li       PointeeTy = PT->getPointeeType();
5642*67e74705SXin Li     } else {
5643*67e74705SXin Li       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5644*67e74705SXin Li     }
5645*67e74705SXin Li 
5646*67e74705SXin Li     bool isReadOnly = false;
5647*67e74705SXin Li     // For historical/compatibility reasons, the read-only qualifier of the
5648*67e74705SXin Li     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
5649*67e74705SXin Li     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5650*67e74705SXin Li     // Also, do not emit the 'r' for anything but the outermost type!
5651*67e74705SXin Li     if (isa<TypedefType>(T.getTypePtr())) {
5652*67e74705SXin Li       if (OutermostType && T.isConstQualified()) {
5653*67e74705SXin Li         isReadOnly = true;
5654*67e74705SXin Li         S += 'r';
5655*67e74705SXin Li       }
5656*67e74705SXin Li     } else if (OutermostType) {
5657*67e74705SXin Li       QualType P = PointeeTy;
5658*67e74705SXin Li       while (P->getAs<PointerType>())
5659*67e74705SXin Li         P = P->getAs<PointerType>()->getPointeeType();
5660*67e74705SXin Li       if (P.isConstQualified()) {
5661*67e74705SXin Li         isReadOnly = true;
5662*67e74705SXin Li         S += 'r';
5663*67e74705SXin Li       }
5664*67e74705SXin Li     }
5665*67e74705SXin Li     if (isReadOnly) {
5666*67e74705SXin Li       // Another legacy compatibility encoding. Some ObjC qualifier and type
5667*67e74705SXin Li       // combinations need to be rearranged.
5668*67e74705SXin Li       // Rewrite "in const" from "nr" to "rn"
5669*67e74705SXin Li       if (StringRef(S).endswith("nr"))
5670*67e74705SXin Li         S.replace(S.end()-2, S.end(), "rn");
5671*67e74705SXin Li     }
5672*67e74705SXin Li 
5673*67e74705SXin Li     if (PointeeTy->isCharType()) {
5674*67e74705SXin Li       // char pointer types should be encoded as '*' unless it is a
5675*67e74705SXin Li       // type that has been typedef'd to 'BOOL'.
5676*67e74705SXin Li       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5677*67e74705SXin Li         S += '*';
5678*67e74705SXin Li         return;
5679*67e74705SXin Li       }
5680*67e74705SXin Li     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5681*67e74705SXin Li       // GCC binary compat: Need to convert "struct objc_class *" to "#".
5682*67e74705SXin Li       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5683*67e74705SXin Li         S += '#';
5684*67e74705SXin Li         return;
5685*67e74705SXin Li       }
5686*67e74705SXin Li       // GCC binary compat: Need to convert "struct objc_object *" to "@".
5687*67e74705SXin Li       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5688*67e74705SXin Li         S += '@';
5689*67e74705SXin Li         return;
5690*67e74705SXin Li       }
5691*67e74705SXin Li       // fall through...
5692*67e74705SXin Li     }
5693*67e74705SXin Li     S += '^';
5694*67e74705SXin Li     getLegacyIntegralTypeEncoding(PointeeTy);
5695*67e74705SXin Li 
5696*67e74705SXin Li     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5697*67e74705SXin Li                                nullptr, false, false, false, false, false, false,
5698*67e74705SXin Li                                NotEncodedT);
5699*67e74705SXin Li     return;
5700*67e74705SXin Li   }
5701*67e74705SXin Li 
5702*67e74705SXin Li   case Type::ConstantArray:
5703*67e74705SXin Li   case Type::IncompleteArray:
5704*67e74705SXin Li   case Type::VariableArray: {
5705*67e74705SXin Li     const ArrayType *AT = cast<ArrayType>(CT);
5706*67e74705SXin Li 
5707*67e74705SXin Li     if (isa<IncompleteArrayType>(AT) && !StructField) {
5708*67e74705SXin Li       // Incomplete arrays are encoded as a pointer to the array element.
5709*67e74705SXin Li       S += '^';
5710*67e74705SXin Li 
5711*67e74705SXin Li       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5712*67e74705SXin Li                                  false, ExpandStructures, FD);
5713*67e74705SXin Li     } else {
5714*67e74705SXin Li       S += '[';
5715*67e74705SXin Li 
5716*67e74705SXin Li       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5717*67e74705SXin Li         S += llvm::utostr(CAT->getSize().getZExtValue());
5718*67e74705SXin Li       else {
5719*67e74705SXin Li         //Variable length arrays are encoded as a regular array with 0 elements.
5720*67e74705SXin Li         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5721*67e74705SXin Li                "Unknown array type!");
5722*67e74705SXin Li         S += '0';
5723*67e74705SXin Li       }
5724*67e74705SXin Li 
5725*67e74705SXin Li       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5726*67e74705SXin Li                                  false, ExpandStructures, FD,
5727*67e74705SXin Li                                  false, false, false, false, false, false,
5728*67e74705SXin Li                                  NotEncodedT);
5729*67e74705SXin Li       S += ']';
5730*67e74705SXin Li     }
5731*67e74705SXin Li     return;
5732*67e74705SXin Li   }
5733*67e74705SXin Li 
5734*67e74705SXin Li   case Type::FunctionNoProto:
5735*67e74705SXin Li   case Type::FunctionProto:
5736*67e74705SXin Li     S += '?';
5737*67e74705SXin Li     return;
5738*67e74705SXin Li 
5739*67e74705SXin Li   case Type::Record: {
5740*67e74705SXin Li     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5741*67e74705SXin Li     S += RDecl->isUnion() ? '(' : '{';
5742*67e74705SXin Li     // Anonymous structures print as '?'
5743*67e74705SXin Li     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5744*67e74705SXin Li       S += II->getName();
5745*67e74705SXin Li       if (ClassTemplateSpecializationDecl *Spec
5746*67e74705SXin Li           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5747*67e74705SXin Li         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5748*67e74705SXin Li         llvm::raw_string_ostream OS(S);
5749*67e74705SXin Li         TemplateSpecializationType::PrintTemplateArgumentList(OS,
5750*67e74705SXin Li                                             TemplateArgs.asArray(),
5751*67e74705SXin Li                                             (*this).getPrintingPolicy());
5752*67e74705SXin Li       }
5753*67e74705SXin Li     } else {
5754*67e74705SXin Li       S += '?';
5755*67e74705SXin Li     }
5756*67e74705SXin Li     if (ExpandStructures) {
5757*67e74705SXin Li       S += '=';
5758*67e74705SXin Li       if (!RDecl->isUnion()) {
5759*67e74705SXin Li         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5760*67e74705SXin Li       } else {
5761*67e74705SXin Li         for (const auto *Field : RDecl->fields()) {
5762*67e74705SXin Li           if (FD) {
5763*67e74705SXin Li             S += '"';
5764*67e74705SXin Li             S += Field->getNameAsString();
5765*67e74705SXin Li             S += '"';
5766*67e74705SXin Li           }
5767*67e74705SXin Li 
5768*67e74705SXin Li           // Special case bit-fields.
5769*67e74705SXin Li           if (Field->isBitField()) {
5770*67e74705SXin Li             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5771*67e74705SXin Li                                        Field);
5772*67e74705SXin Li           } else {
5773*67e74705SXin Li             QualType qt = Field->getType();
5774*67e74705SXin Li             getLegacyIntegralTypeEncoding(qt);
5775*67e74705SXin Li             getObjCEncodingForTypeImpl(qt, S, false, true,
5776*67e74705SXin Li                                        FD, /*OutermostType*/false,
5777*67e74705SXin Li                                        /*EncodingProperty*/false,
5778*67e74705SXin Li                                        /*StructField*/true,
5779*67e74705SXin Li                                        false, false, false, NotEncodedT);
5780*67e74705SXin Li           }
5781*67e74705SXin Li         }
5782*67e74705SXin Li       }
5783*67e74705SXin Li     }
5784*67e74705SXin Li     S += RDecl->isUnion() ? ')' : '}';
5785*67e74705SXin Li     return;
5786*67e74705SXin Li   }
5787*67e74705SXin Li 
5788*67e74705SXin Li   case Type::BlockPointer: {
5789*67e74705SXin Li     const BlockPointerType *BT = T->castAs<BlockPointerType>();
5790*67e74705SXin Li     S += "@?"; // Unlike a pointer-to-function, which is "^?".
5791*67e74705SXin Li     if (EncodeBlockParameters) {
5792*67e74705SXin Li       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5793*67e74705SXin Li 
5794*67e74705SXin Li       S += '<';
5795*67e74705SXin Li       // Block return type
5796*67e74705SXin Li       getObjCEncodingForTypeImpl(
5797*67e74705SXin Li           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5798*67e74705SXin Li           FD, false /* OutermostType */, EncodingProperty,
5799*67e74705SXin Li           false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5800*67e74705SXin Li                                  NotEncodedT);
5801*67e74705SXin Li       // Block self
5802*67e74705SXin Li       S += "@?";
5803*67e74705SXin Li       // Block parameters
5804*67e74705SXin Li       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5805*67e74705SXin Li         for (const auto &I : FPT->param_types())
5806*67e74705SXin Li           getObjCEncodingForTypeImpl(
5807*67e74705SXin Li               I, S, ExpandPointedToStructures, ExpandStructures, FD,
5808*67e74705SXin Li               false /* OutermostType */, EncodingProperty,
5809*67e74705SXin Li               false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5810*67e74705SXin Li                                      false, NotEncodedT);
5811*67e74705SXin Li       }
5812*67e74705SXin Li       S += '>';
5813*67e74705SXin Li     }
5814*67e74705SXin Li     return;
5815*67e74705SXin Li   }
5816*67e74705SXin Li 
5817*67e74705SXin Li   case Type::ObjCObject: {
5818*67e74705SXin Li     // hack to match legacy encoding of *id and *Class
5819*67e74705SXin Li     QualType Ty = getObjCObjectPointerType(CT);
5820*67e74705SXin Li     if (Ty->isObjCIdType()) {
5821*67e74705SXin Li       S += "{objc_object=}";
5822*67e74705SXin Li       return;
5823*67e74705SXin Li     }
5824*67e74705SXin Li     else if (Ty->isObjCClassType()) {
5825*67e74705SXin Li       S += "{objc_class=}";
5826*67e74705SXin Li       return;
5827*67e74705SXin Li     }
5828*67e74705SXin Li   }
5829*67e74705SXin Li 
5830*67e74705SXin Li   case Type::ObjCInterface: {
5831*67e74705SXin Li     // Ignore protocol qualifiers when mangling at this level.
5832*67e74705SXin Li     // @encode(class_name)
5833*67e74705SXin Li     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5834*67e74705SXin Li     S += '{';
5835*67e74705SXin Li     S += OI->getObjCRuntimeNameAsString();
5836*67e74705SXin Li     S += '=';
5837*67e74705SXin Li     SmallVector<const ObjCIvarDecl*, 32> Ivars;
5838*67e74705SXin Li     DeepCollectObjCIvars(OI, true, Ivars);
5839*67e74705SXin Li     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5840*67e74705SXin Li       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5841*67e74705SXin Li       if (Field->isBitField())
5842*67e74705SXin Li         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5843*67e74705SXin Li       else
5844*67e74705SXin Li         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5845*67e74705SXin Li                                    false, false, false, false, false,
5846*67e74705SXin Li                                    EncodePointerToObjCTypedef,
5847*67e74705SXin Li                                    NotEncodedT);
5848*67e74705SXin Li     }
5849*67e74705SXin Li     S += '}';
5850*67e74705SXin Li     return;
5851*67e74705SXin Li   }
5852*67e74705SXin Li 
5853*67e74705SXin Li   case Type::ObjCObjectPointer: {
5854*67e74705SXin Li     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5855*67e74705SXin Li     if (OPT->isObjCIdType()) {
5856*67e74705SXin Li       S += '@';
5857*67e74705SXin Li       return;
5858*67e74705SXin Li     }
5859*67e74705SXin Li 
5860*67e74705SXin Li     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5861*67e74705SXin Li       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5862*67e74705SXin Li       // Since this is a binary compatibility issue, need to consult with runtime
5863*67e74705SXin Li       // folks. Fortunately, this is a *very* obsure construct.
5864*67e74705SXin Li       S += '#';
5865*67e74705SXin Li       return;
5866*67e74705SXin Li     }
5867*67e74705SXin Li 
5868*67e74705SXin Li     if (OPT->isObjCQualifiedIdType()) {
5869*67e74705SXin Li       getObjCEncodingForTypeImpl(getObjCIdType(), S,
5870*67e74705SXin Li                                  ExpandPointedToStructures,
5871*67e74705SXin Li                                  ExpandStructures, FD);
5872*67e74705SXin Li       if (FD || EncodingProperty || EncodeClassNames) {
5873*67e74705SXin Li         // Note that we do extended encoding of protocol qualifer list
5874*67e74705SXin Li         // Only when doing ivar or property encoding.
5875*67e74705SXin Li         S += '"';
5876*67e74705SXin Li         for (const auto *I : OPT->quals()) {
5877*67e74705SXin Li           S += '<';
5878*67e74705SXin Li           S += I->getObjCRuntimeNameAsString();
5879*67e74705SXin Li           S += '>';
5880*67e74705SXin Li         }
5881*67e74705SXin Li         S += '"';
5882*67e74705SXin Li       }
5883*67e74705SXin Li       return;
5884*67e74705SXin Li     }
5885*67e74705SXin Li 
5886*67e74705SXin Li     QualType PointeeTy = OPT->getPointeeType();
5887*67e74705SXin Li     if (!EncodingProperty &&
5888*67e74705SXin Li         isa<TypedefType>(PointeeTy.getTypePtr()) &&
5889*67e74705SXin Li         !EncodePointerToObjCTypedef) {
5890*67e74705SXin Li       // Another historical/compatibility reason.
5891*67e74705SXin Li       // We encode the underlying type which comes out as
5892*67e74705SXin Li       // {...};
5893*67e74705SXin Li       S += '^';
5894*67e74705SXin Li       if (FD && OPT->getInterfaceDecl()) {
5895*67e74705SXin Li         // Prevent recursive encoding of fields in some rare cases.
5896*67e74705SXin Li         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5897*67e74705SXin Li         SmallVector<const ObjCIvarDecl*, 32> Ivars;
5898*67e74705SXin Li         DeepCollectObjCIvars(OI, true, Ivars);
5899*67e74705SXin Li         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5900*67e74705SXin Li           if (cast<FieldDecl>(Ivars[i]) == FD) {
5901*67e74705SXin Li             S += '{';
5902*67e74705SXin Li             S += OI->getObjCRuntimeNameAsString();
5903*67e74705SXin Li             S += '}';
5904*67e74705SXin Li             return;
5905*67e74705SXin Li           }
5906*67e74705SXin Li         }
5907*67e74705SXin Li       }
5908*67e74705SXin Li       getObjCEncodingForTypeImpl(PointeeTy, S,
5909*67e74705SXin Li                                  false, ExpandPointedToStructures,
5910*67e74705SXin Li                                  nullptr,
5911*67e74705SXin Li                                  false, false, false, false, false,
5912*67e74705SXin Li                                  /*EncodePointerToObjCTypedef*/true);
5913*67e74705SXin Li       return;
5914*67e74705SXin Li     }
5915*67e74705SXin Li 
5916*67e74705SXin Li     S += '@';
5917*67e74705SXin Li     if (OPT->getInterfaceDecl() &&
5918*67e74705SXin Li         (FD || EncodingProperty || EncodeClassNames)) {
5919*67e74705SXin Li       S += '"';
5920*67e74705SXin Li       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5921*67e74705SXin Li       for (const auto *I : OPT->quals()) {
5922*67e74705SXin Li         S += '<';
5923*67e74705SXin Li         S += I->getObjCRuntimeNameAsString();
5924*67e74705SXin Li         S += '>';
5925*67e74705SXin Li       }
5926*67e74705SXin Li       S += '"';
5927*67e74705SXin Li     }
5928*67e74705SXin Li     return;
5929*67e74705SXin Li   }
5930*67e74705SXin Li 
5931*67e74705SXin Li   // gcc just blithely ignores member pointers.
5932*67e74705SXin Li   // FIXME: we shoul do better than that.  'M' is available.
5933*67e74705SXin Li   case Type::MemberPointer:
5934*67e74705SXin Li   // This matches gcc's encoding, even though technically it is insufficient.
5935*67e74705SXin Li   //FIXME. We should do a better job than gcc.
5936*67e74705SXin Li   case Type::Vector:
5937*67e74705SXin Li   case Type::ExtVector:
5938*67e74705SXin Li   // Until we have a coherent encoding of these three types, issue warning.
5939*67e74705SXin Li     { if (NotEncodedT)
5940*67e74705SXin Li         *NotEncodedT = T;
5941*67e74705SXin Li       return;
5942*67e74705SXin Li     }
5943*67e74705SXin Li 
5944*67e74705SXin Li   // We could see an undeduced auto type here during error recovery.
5945*67e74705SXin Li   // Just ignore it.
5946*67e74705SXin Li   case Type::Auto:
5947*67e74705SXin Li     return;
5948*67e74705SXin Li 
5949*67e74705SXin Li   case Type::Pipe:
5950*67e74705SXin Li #define ABSTRACT_TYPE(KIND, BASE)
5951*67e74705SXin Li #define TYPE(KIND, BASE)
5952*67e74705SXin Li #define DEPENDENT_TYPE(KIND, BASE) \
5953*67e74705SXin Li   case Type::KIND:
5954*67e74705SXin Li #define NON_CANONICAL_TYPE(KIND, BASE) \
5955*67e74705SXin Li   case Type::KIND:
5956*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5957*67e74705SXin Li   case Type::KIND:
5958*67e74705SXin Li #include "clang/AST/TypeNodes.def"
5959*67e74705SXin Li     llvm_unreachable("@encode for dependent type!");
5960*67e74705SXin Li   }
5961*67e74705SXin Li   llvm_unreachable("bad type kind!");
5962*67e74705SXin Li }
5963*67e74705SXin Li 
getObjCEncodingForStructureImpl(RecordDecl * RDecl,std::string & S,const FieldDecl * FD,bool includeVBases,QualType * NotEncodedT) const5964*67e74705SXin Li void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5965*67e74705SXin Li                                                  std::string &S,
5966*67e74705SXin Li                                                  const FieldDecl *FD,
5967*67e74705SXin Li                                                  bool includeVBases,
5968*67e74705SXin Li                                                  QualType *NotEncodedT) const {
5969*67e74705SXin Li   assert(RDecl && "Expected non-null RecordDecl");
5970*67e74705SXin Li   assert(!RDecl->isUnion() && "Should not be called for unions");
5971*67e74705SXin Li   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
5972*67e74705SXin Li     return;
5973*67e74705SXin Li 
5974*67e74705SXin Li   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5975*67e74705SXin Li   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5976*67e74705SXin Li   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5977*67e74705SXin Li 
5978*67e74705SXin Li   if (CXXRec) {
5979*67e74705SXin Li     for (const auto &BI : CXXRec->bases()) {
5980*67e74705SXin Li       if (!BI.isVirtual()) {
5981*67e74705SXin Li         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5982*67e74705SXin Li         if (base->isEmpty())
5983*67e74705SXin Li           continue;
5984*67e74705SXin Li         uint64_t offs = toBits(layout.getBaseClassOffset(base));
5985*67e74705SXin Li         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5986*67e74705SXin Li                                   std::make_pair(offs, base));
5987*67e74705SXin Li       }
5988*67e74705SXin Li     }
5989*67e74705SXin Li   }
5990*67e74705SXin Li 
5991*67e74705SXin Li   unsigned i = 0;
5992*67e74705SXin Li   for (auto *Field : RDecl->fields()) {
5993*67e74705SXin Li     uint64_t offs = layout.getFieldOffset(i);
5994*67e74705SXin Li     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5995*67e74705SXin Li                               std::make_pair(offs, Field));
5996*67e74705SXin Li     ++i;
5997*67e74705SXin Li   }
5998*67e74705SXin Li 
5999*67e74705SXin Li   if (CXXRec && includeVBases) {
6000*67e74705SXin Li     for (const auto &BI : CXXRec->vbases()) {
6001*67e74705SXin Li       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6002*67e74705SXin Li       if (base->isEmpty())
6003*67e74705SXin Li         continue;
6004*67e74705SXin Li       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6005*67e74705SXin Li       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6006*67e74705SXin Li           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6007*67e74705SXin Li         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6008*67e74705SXin Li                                   std::make_pair(offs, base));
6009*67e74705SXin Li     }
6010*67e74705SXin Li   }
6011*67e74705SXin Li 
6012*67e74705SXin Li   CharUnits size;
6013*67e74705SXin Li   if (CXXRec) {
6014*67e74705SXin Li     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6015*67e74705SXin Li   } else {
6016*67e74705SXin Li     size = layout.getSize();
6017*67e74705SXin Li   }
6018*67e74705SXin Li 
6019*67e74705SXin Li #ifndef NDEBUG
6020*67e74705SXin Li   uint64_t CurOffs = 0;
6021*67e74705SXin Li #endif
6022*67e74705SXin Li   std::multimap<uint64_t, NamedDecl *>::iterator
6023*67e74705SXin Li     CurLayObj = FieldOrBaseOffsets.begin();
6024*67e74705SXin Li 
6025*67e74705SXin Li   if (CXXRec && CXXRec->isDynamicClass() &&
6026*67e74705SXin Li       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6027*67e74705SXin Li     if (FD) {
6028*67e74705SXin Li       S += "\"_vptr$";
6029*67e74705SXin Li       std::string recname = CXXRec->getNameAsString();
6030*67e74705SXin Li       if (recname.empty()) recname = "?";
6031*67e74705SXin Li       S += recname;
6032*67e74705SXin Li       S += '"';
6033*67e74705SXin Li     }
6034*67e74705SXin Li     S += "^^?";
6035*67e74705SXin Li #ifndef NDEBUG
6036*67e74705SXin Li     CurOffs += getTypeSize(VoidPtrTy);
6037*67e74705SXin Li #endif
6038*67e74705SXin Li   }
6039*67e74705SXin Li 
6040*67e74705SXin Li   if (!RDecl->hasFlexibleArrayMember()) {
6041*67e74705SXin Li     // Mark the end of the structure.
6042*67e74705SXin Li     uint64_t offs = toBits(size);
6043*67e74705SXin Li     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6044*67e74705SXin Li                               std::make_pair(offs, nullptr));
6045*67e74705SXin Li   }
6046*67e74705SXin Li 
6047*67e74705SXin Li   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6048*67e74705SXin Li #ifndef NDEBUG
6049*67e74705SXin Li     assert(CurOffs <= CurLayObj->first);
6050*67e74705SXin Li     if (CurOffs < CurLayObj->first) {
6051*67e74705SXin Li       uint64_t padding = CurLayObj->first - CurOffs;
6052*67e74705SXin Li       // FIXME: There doesn't seem to be a way to indicate in the encoding that
6053*67e74705SXin Li       // packing/alignment of members is different that normal, in which case
6054*67e74705SXin Li       // the encoding will be out-of-sync with the real layout.
6055*67e74705SXin Li       // If the runtime switches to just consider the size of types without
6056*67e74705SXin Li       // taking into account alignment, we could make padding explicit in the
6057*67e74705SXin Li       // encoding (e.g. using arrays of chars). The encoding strings would be
6058*67e74705SXin Li       // longer then though.
6059*67e74705SXin Li       CurOffs += padding;
6060*67e74705SXin Li     }
6061*67e74705SXin Li #endif
6062*67e74705SXin Li 
6063*67e74705SXin Li     NamedDecl *dcl = CurLayObj->second;
6064*67e74705SXin Li     if (!dcl)
6065*67e74705SXin Li       break; // reached end of structure.
6066*67e74705SXin Li 
6067*67e74705SXin Li     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6068*67e74705SXin Li       // We expand the bases without their virtual bases since those are going
6069*67e74705SXin Li       // in the initial structure. Note that this differs from gcc which
6070*67e74705SXin Li       // expands virtual bases each time one is encountered in the hierarchy,
6071*67e74705SXin Li       // making the encoding type bigger than it really is.
6072*67e74705SXin Li       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6073*67e74705SXin Li                                       NotEncodedT);
6074*67e74705SXin Li       assert(!base->isEmpty());
6075*67e74705SXin Li #ifndef NDEBUG
6076*67e74705SXin Li       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6077*67e74705SXin Li #endif
6078*67e74705SXin Li     } else {
6079*67e74705SXin Li       FieldDecl *field = cast<FieldDecl>(dcl);
6080*67e74705SXin Li       if (FD) {
6081*67e74705SXin Li         S += '"';
6082*67e74705SXin Li         S += field->getNameAsString();
6083*67e74705SXin Li         S += '"';
6084*67e74705SXin Li       }
6085*67e74705SXin Li 
6086*67e74705SXin Li       if (field->isBitField()) {
6087*67e74705SXin Li         EncodeBitField(this, S, field->getType(), field);
6088*67e74705SXin Li #ifndef NDEBUG
6089*67e74705SXin Li         CurOffs += field->getBitWidthValue(*this);
6090*67e74705SXin Li #endif
6091*67e74705SXin Li       } else {
6092*67e74705SXin Li         QualType qt = field->getType();
6093*67e74705SXin Li         getLegacyIntegralTypeEncoding(qt);
6094*67e74705SXin Li         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6095*67e74705SXin Li                                    /*OutermostType*/false,
6096*67e74705SXin Li                                    /*EncodingProperty*/false,
6097*67e74705SXin Li                                    /*StructField*/true,
6098*67e74705SXin Li                                    false, false, false, NotEncodedT);
6099*67e74705SXin Li #ifndef NDEBUG
6100*67e74705SXin Li         CurOffs += getTypeSize(field->getType());
6101*67e74705SXin Li #endif
6102*67e74705SXin Li       }
6103*67e74705SXin Li     }
6104*67e74705SXin Li   }
6105*67e74705SXin Li }
6106*67e74705SXin Li 
getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,std::string & S) const6107*67e74705SXin Li void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6108*67e74705SXin Li                                                  std::string& S) const {
6109*67e74705SXin Li   if (QT & Decl::OBJC_TQ_In)
6110*67e74705SXin Li     S += 'n';
6111*67e74705SXin Li   if (QT & Decl::OBJC_TQ_Inout)
6112*67e74705SXin Li     S += 'N';
6113*67e74705SXin Li   if (QT & Decl::OBJC_TQ_Out)
6114*67e74705SXin Li     S += 'o';
6115*67e74705SXin Li   if (QT & Decl::OBJC_TQ_Bycopy)
6116*67e74705SXin Li     S += 'O';
6117*67e74705SXin Li   if (QT & Decl::OBJC_TQ_Byref)
6118*67e74705SXin Li     S += 'R';
6119*67e74705SXin Li   if (QT & Decl::OBJC_TQ_Oneway)
6120*67e74705SXin Li     S += 'V';
6121*67e74705SXin Li }
6122*67e74705SXin Li 
getObjCIdDecl() const6123*67e74705SXin Li TypedefDecl *ASTContext::getObjCIdDecl() const {
6124*67e74705SXin Li   if (!ObjCIdDecl) {
6125*67e74705SXin Li     QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6126*67e74705SXin Li     T = getObjCObjectPointerType(T);
6127*67e74705SXin Li     ObjCIdDecl = buildImplicitTypedef(T, "id");
6128*67e74705SXin Li   }
6129*67e74705SXin Li   return ObjCIdDecl;
6130*67e74705SXin Li }
6131*67e74705SXin Li 
getObjCSelDecl() const6132*67e74705SXin Li TypedefDecl *ASTContext::getObjCSelDecl() const {
6133*67e74705SXin Li   if (!ObjCSelDecl) {
6134*67e74705SXin Li     QualType T = getPointerType(ObjCBuiltinSelTy);
6135*67e74705SXin Li     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6136*67e74705SXin Li   }
6137*67e74705SXin Li   return ObjCSelDecl;
6138*67e74705SXin Li }
6139*67e74705SXin Li 
getObjCClassDecl() const6140*67e74705SXin Li TypedefDecl *ASTContext::getObjCClassDecl() const {
6141*67e74705SXin Li   if (!ObjCClassDecl) {
6142*67e74705SXin Li     QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6143*67e74705SXin Li     T = getObjCObjectPointerType(T);
6144*67e74705SXin Li     ObjCClassDecl = buildImplicitTypedef(T, "Class");
6145*67e74705SXin Li   }
6146*67e74705SXin Li   return ObjCClassDecl;
6147*67e74705SXin Li }
6148*67e74705SXin Li 
getObjCProtocolDecl() const6149*67e74705SXin Li ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6150*67e74705SXin Li   if (!ObjCProtocolClassDecl) {
6151*67e74705SXin Li     ObjCProtocolClassDecl
6152*67e74705SXin Li       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6153*67e74705SXin Li                                   SourceLocation(),
6154*67e74705SXin Li                                   &Idents.get("Protocol"),
6155*67e74705SXin Li                                   /*typeParamList=*/nullptr,
6156*67e74705SXin Li                                   /*PrevDecl=*/nullptr,
6157*67e74705SXin Li                                   SourceLocation(), true);
6158*67e74705SXin Li   }
6159*67e74705SXin Li 
6160*67e74705SXin Li   return ObjCProtocolClassDecl;
6161*67e74705SXin Li }
6162*67e74705SXin Li 
6163*67e74705SXin Li //===----------------------------------------------------------------------===//
6164*67e74705SXin Li // __builtin_va_list Construction Functions
6165*67e74705SXin Li //===----------------------------------------------------------------------===//
6166*67e74705SXin Li 
CreateCharPtrNamedVaListDecl(const ASTContext * Context,StringRef Name)6167*67e74705SXin Li static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6168*67e74705SXin Li                                                  StringRef Name) {
6169*67e74705SXin Li   // typedef char* __builtin[_ms]_va_list;
6170*67e74705SXin Li   QualType T = Context->getPointerType(Context->CharTy);
6171*67e74705SXin Li   return Context->buildImplicitTypedef(T, Name);
6172*67e74705SXin Li }
6173*67e74705SXin Li 
CreateMSVaListDecl(const ASTContext * Context)6174*67e74705SXin Li static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6175*67e74705SXin Li   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6176*67e74705SXin Li }
6177*67e74705SXin Li 
CreateCharPtrBuiltinVaListDecl(const ASTContext * Context)6178*67e74705SXin Li static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6179*67e74705SXin Li   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6180*67e74705SXin Li }
6181*67e74705SXin Li 
CreateVoidPtrBuiltinVaListDecl(const ASTContext * Context)6182*67e74705SXin Li static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6183*67e74705SXin Li   // typedef void* __builtin_va_list;
6184*67e74705SXin Li   QualType T = Context->getPointerType(Context->VoidTy);
6185*67e74705SXin Li   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6186*67e74705SXin Li }
6187*67e74705SXin Li 
6188*67e74705SXin Li static TypedefDecl *
CreateAArch64ABIBuiltinVaListDecl(const ASTContext * Context)6189*67e74705SXin Li CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6190*67e74705SXin Li   // struct __va_list
6191*67e74705SXin Li   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6192*67e74705SXin Li   if (Context->getLangOpts().CPlusPlus) {
6193*67e74705SXin Li     // namespace std { struct __va_list {
6194*67e74705SXin Li     NamespaceDecl *NS;
6195*67e74705SXin Li     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6196*67e74705SXin Li                                Context->getTranslationUnitDecl(),
6197*67e74705SXin Li                                /*Inline*/ false, SourceLocation(),
6198*67e74705SXin Li                                SourceLocation(), &Context->Idents.get("std"),
6199*67e74705SXin Li                                /*PrevDecl*/ nullptr);
6200*67e74705SXin Li     NS->setImplicit();
6201*67e74705SXin Li     VaListTagDecl->setDeclContext(NS);
6202*67e74705SXin Li   }
6203*67e74705SXin Li 
6204*67e74705SXin Li   VaListTagDecl->startDefinition();
6205*67e74705SXin Li 
6206*67e74705SXin Li   const size_t NumFields = 5;
6207*67e74705SXin Li   QualType FieldTypes[NumFields];
6208*67e74705SXin Li   const char *FieldNames[NumFields];
6209*67e74705SXin Li 
6210*67e74705SXin Li   // void *__stack;
6211*67e74705SXin Li   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6212*67e74705SXin Li   FieldNames[0] = "__stack";
6213*67e74705SXin Li 
6214*67e74705SXin Li   // void *__gr_top;
6215*67e74705SXin Li   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6216*67e74705SXin Li   FieldNames[1] = "__gr_top";
6217*67e74705SXin Li 
6218*67e74705SXin Li   // void *__vr_top;
6219*67e74705SXin Li   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6220*67e74705SXin Li   FieldNames[2] = "__vr_top";
6221*67e74705SXin Li 
6222*67e74705SXin Li   // int __gr_offs;
6223*67e74705SXin Li   FieldTypes[3] = Context->IntTy;
6224*67e74705SXin Li   FieldNames[3] = "__gr_offs";
6225*67e74705SXin Li 
6226*67e74705SXin Li   // int __vr_offs;
6227*67e74705SXin Li   FieldTypes[4] = Context->IntTy;
6228*67e74705SXin Li   FieldNames[4] = "__vr_offs";
6229*67e74705SXin Li 
6230*67e74705SXin Li   // Create fields
6231*67e74705SXin Li   for (unsigned i = 0; i < NumFields; ++i) {
6232*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6233*67e74705SXin Li                                          VaListTagDecl,
6234*67e74705SXin Li                                          SourceLocation(),
6235*67e74705SXin Li                                          SourceLocation(),
6236*67e74705SXin Li                                          &Context->Idents.get(FieldNames[i]),
6237*67e74705SXin Li                                          FieldTypes[i], /*TInfo=*/nullptr,
6238*67e74705SXin Li                                          /*BitWidth=*/nullptr,
6239*67e74705SXin Li                                          /*Mutable=*/false,
6240*67e74705SXin Li                                          ICIS_NoInit);
6241*67e74705SXin Li     Field->setAccess(AS_public);
6242*67e74705SXin Li     VaListTagDecl->addDecl(Field);
6243*67e74705SXin Li   }
6244*67e74705SXin Li   VaListTagDecl->completeDefinition();
6245*67e74705SXin Li   Context->VaListTagDecl = VaListTagDecl;
6246*67e74705SXin Li   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6247*67e74705SXin Li 
6248*67e74705SXin Li   // } __builtin_va_list;
6249*67e74705SXin Li   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6250*67e74705SXin Li }
6251*67e74705SXin Li 
CreatePowerABIBuiltinVaListDecl(const ASTContext * Context)6252*67e74705SXin Li static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6253*67e74705SXin Li   // typedef struct __va_list_tag {
6254*67e74705SXin Li   RecordDecl *VaListTagDecl;
6255*67e74705SXin Li 
6256*67e74705SXin Li   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6257*67e74705SXin Li   VaListTagDecl->startDefinition();
6258*67e74705SXin Li 
6259*67e74705SXin Li   const size_t NumFields = 5;
6260*67e74705SXin Li   QualType FieldTypes[NumFields];
6261*67e74705SXin Li   const char *FieldNames[NumFields];
6262*67e74705SXin Li 
6263*67e74705SXin Li   //   unsigned char gpr;
6264*67e74705SXin Li   FieldTypes[0] = Context->UnsignedCharTy;
6265*67e74705SXin Li   FieldNames[0] = "gpr";
6266*67e74705SXin Li 
6267*67e74705SXin Li   //   unsigned char fpr;
6268*67e74705SXin Li   FieldTypes[1] = Context->UnsignedCharTy;
6269*67e74705SXin Li   FieldNames[1] = "fpr";
6270*67e74705SXin Li 
6271*67e74705SXin Li   //   unsigned short reserved;
6272*67e74705SXin Li   FieldTypes[2] = Context->UnsignedShortTy;
6273*67e74705SXin Li   FieldNames[2] = "reserved";
6274*67e74705SXin Li 
6275*67e74705SXin Li   //   void* overflow_arg_area;
6276*67e74705SXin Li   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6277*67e74705SXin Li   FieldNames[3] = "overflow_arg_area";
6278*67e74705SXin Li 
6279*67e74705SXin Li   //   void* reg_save_area;
6280*67e74705SXin Li   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6281*67e74705SXin Li   FieldNames[4] = "reg_save_area";
6282*67e74705SXin Li 
6283*67e74705SXin Li   // Create fields
6284*67e74705SXin Li   for (unsigned i = 0; i < NumFields; ++i) {
6285*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6286*67e74705SXin Li                                          SourceLocation(),
6287*67e74705SXin Li                                          SourceLocation(),
6288*67e74705SXin Li                                          &Context->Idents.get(FieldNames[i]),
6289*67e74705SXin Li                                          FieldTypes[i], /*TInfo=*/nullptr,
6290*67e74705SXin Li                                          /*BitWidth=*/nullptr,
6291*67e74705SXin Li                                          /*Mutable=*/false,
6292*67e74705SXin Li                                          ICIS_NoInit);
6293*67e74705SXin Li     Field->setAccess(AS_public);
6294*67e74705SXin Li     VaListTagDecl->addDecl(Field);
6295*67e74705SXin Li   }
6296*67e74705SXin Li   VaListTagDecl->completeDefinition();
6297*67e74705SXin Li   Context->VaListTagDecl = VaListTagDecl;
6298*67e74705SXin Li   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6299*67e74705SXin Li 
6300*67e74705SXin Li   // } __va_list_tag;
6301*67e74705SXin Li   TypedefDecl *VaListTagTypedefDecl =
6302*67e74705SXin Li       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6303*67e74705SXin Li 
6304*67e74705SXin Li   QualType VaListTagTypedefType =
6305*67e74705SXin Li     Context->getTypedefType(VaListTagTypedefDecl);
6306*67e74705SXin Li 
6307*67e74705SXin Li   // typedef __va_list_tag __builtin_va_list[1];
6308*67e74705SXin Li   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6309*67e74705SXin Li   QualType VaListTagArrayType
6310*67e74705SXin Li     = Context->getConstantArrayType(VaListTagTypedefType,
6311*67e74705SXin Li                                     Size, ArrayType::Normal, 0);
6312*67e74705SXin Li   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6313*67e74705SXin Li }
6314*67e74705SXin Li 
6315*67e74705SXin Li static TypedefDecl *
CreateX86_64ABIBuiltinVaListDecl(const ASTContext * Context)6316*67e74705SXin Li CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6317*67e74705SXin Li   // struct __va_list_tag {
6318*67e74705SXin Li   RecordDecl *VaListTagDecl;
6319*67e74705SXin Li   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6320*67e74705SXin Li   VaListTagDecl->startDefinition();
6321*67e74705SXin Li 
6322*67e74705SXin Li   const size_t NumFields = 4;
6323*67e74705SXin Li   QualType FieldTypes[NumFields];
6324*67e74705SXin Li   const char *FieldNames[NumFields];
6325*67e74705SXin Li 
6326*67e74705SXin Li   //   unsigned gp_offset;
6327*67e74705SXin Li   FieldTypes[0] = Context->UnsignedIntTy;
6328*67e74705SXin Li   FieldNames[0] = "gp_offset";
6329*67e74705SXin Li 
6330*67e74705SXin Li   //   unsigned fp_offset;
6331*67e74705SXin Li   FieldTypes[1] = Context->UnsignedIntTy;
6332*67e74705SXin Li   FieldNames[1] = "fp_offset";
6333*67e74705SXin Li 
6334*67e74705SXin Li   //   void* overflow_arg_area;
6335*67e74705SXin Li   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6336*67e74705SXin Li   FieldNames[2] = "overflow_arg_area";
6337*67e74705SXin Li 
6338*67e74705SXin Li   //   void* reg_save_area;
6339*67e74705SXin Li   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6340*67e74705SXin Li   FieldNames[3] = "reg_save_area";
6341*67e74705SXin Li 
6342*67e74705SXin Li   // Create fields
6343*67e74705SXin Li   for (unsigned i = 0; i < NumFields; ++i) {
6344*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6345*67e74705SXin Li                                          VaListTagDecl,
6346*67e74705SXin Li                                          SourceLocation(),
6347*67e74705SXin Li                                          SourceLocation(),
6348*67e74705SXin Li                                          &Context->Idents.get(FieldNames[i]),
6349*67e74705SXin Li                                          FieldTypes[i], /*TInfo=*/nullptr,
6350*67e74705SXin Li                                          /*BitWidth=*/nullptr,
6351*67e74705SXin Li                                          /*Mutable=*/false,
6352*67e74705SXin Li                                          ICIS_NoInit);
6353*67e74705SXin Li     Field->setAccess(AS_public);
6354*67e74705SXin Li     VaListTagDecl->addDecl(Field);
6355*67e74705SXin Li   }
6356*67e74705SXin Li   VaListTagDecl->completeDefinition();
6357*67e74705SXin Li   Context->VaListTagDecl = VaListTagDecl;
6358*67e74705SXin Li   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6359*67e74705SXin Li 
6360*67e74705SXin Li   // };
6361*67e74705SXin Li 
6362*67e74705SXin Li   // typedef struct __va_list_tag __builtin_va_list[1];
6363*67e74705SXin Li   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6364*67e74705SXin Li   QualType VaListTagArrayType =
6365*67e74705SXin Li       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6366*67e74705SXin Li   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6367*67e74705SXin Li }
6368*67e74705SXin Li 
CreatePNaClABIBuiltinVaListDecl(const ASTContext * Context)6369*67e74705SXin Li static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6370*67e74705SXin Li   // typedef int __builtin_va_list[4];
6371*67e74705SXin Li   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6372*67e74705SXin Li   QualType IntArrayType
6373*67e74705SXin Li     = Context->getConstantArrayType(Context->IntTy,
6374*67e74705SXin Li 				    Size, ArrayType::Normal, 0);
6375*67e74705SXin Li   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6376*67e74705SXin Li }
6377*67e74705SXin Li 
6378*67e74705SXin Li static TypedefDecl *
CreateAAPCSABIBuiltinVaListDecl(const ASTContext * Context)6379*67e74705SXin Li CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6380*67e74705SXin Li   // struct __va_list
6381*67e74705SXin Li   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6382*67e74705SXin Li   if (Context->getLangOpts().CPlusPlus) {
6383*67e74705SXin Li     // namespace std { struct __va_list {
6384*67e74705SXin Li     NamespaceDecl *NS;
6385*67e74705SXin Li     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6386*67e74705SXin Li                                Context->getTranslationUnitDecl(),
6387*67e74705SXin Li                                /*Inline*/false, SourceLocation(),
6388*67e74705SXin Li                                SourceLocation(), &Context->Idents.get("std"),
6389*67e74705SXin Li                                /*PrevDecl*/ nullptr);
6390*67e74705SXin Li     NS->setImplicit();
6391*67e74705SXin Li     VaListDecl->setDeclContext(NS);
6392*67e74705SXin Li   }
6393*67e74705SXin Li 
6394*67e74705SXin Li   VaListDecl->startDefinition();
6395*67e74705SXin Li 
6396*67e74705SXin Li   // void * __ap;
6397*67e74705SXin Li   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6398*67e74705SXin Li                                        VaListDecl,
6399*67e74705SXin Li                                        SourceLocation(),
6400*67e74705SXin Li                                        SourceLocation(),
6401*67e74705SXin Li                                        &Context->Idents.get("__ap"),
6402*67e74705SXin Li                                        Context->getPointerType(Context->VoidTy),
6403*67e74705SXin Li                                        /*TInfo=*/nullptr,
6404*67e74705SXin Li                                        /*BitWidth=*/nullptr,
6405*67e74705SXin Li                                        /*Mutable=*/false,
6406*67e74705SXin Li                                        ICIS_NoInit);
6407*67e74705SXin Li   Field->setAccess(AS_public);
6408*67e74705SXin Li   VaListDecl->addDecl(Field);
6409*67e74705SXin Li 
6410*67e74705SXin Li   // };
6411*67e74705SXin Li   VaListDecl->completeDefinition();
6412*67e74705SXin Li   Context->VaListTagDecl = VaListDecl;
6413*67e74705SXin Li 
6414*67e74705SXin Li   // typedef struct __va_list __builtin_va_list;
6415*67e74705SXin Li   QualType T = Context->getRecordType(VaListDecl);
6416*67e74705SXin Li   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6417*67e74705SXin Li }
6418*67e74705SXin Li 
6419*67e74705SXin Li static TypedefDecl *
CreateSystemZBuiltinVaListDecl(const ASTContext * Context)6420*67e74705SXin Li CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6421*67e74705SXin Li   // struct __va_list_tag {
6422*67e74705SXin Li   RecordDecl *VaListTagDecl;
6423*67e74705SXin Li   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6424*67e74705SXin Li   VaListTagDecl->startDefinition();
6425*67e74705SXin Li 
6426*67e74705SXin Li   const size_t NumFields = 4;
6427*67e74705SXin Li   QualType FieldTypes[NumFields];
6428*67e74705SXin Li   const char *FieldNames[NumFields];
6429*67e74705SXin Li 
6430*67e74705SXin Li   //   long __gpr;
6431*67e74705SXin Li   FieldTypes[0] = Context->LongTy;
6432*67e74705SXin Li   FieldNames[0] = "__gpr";
6433*67e74705SXin Li 
6434*67e74705SXin Li   //   long __fpr;
6435*67e74705SXin Li   FieldTypes[1] = Context->LongTy;
6436*67e74705SXin Li   FieldNames[1] = "__fpr";
6437*67e74705SXin Li 
6438*67e74705SXin Li   //   void *__overflow_arg_area;
6439*67e74705SXin Li   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6440*67e74705SXin Li   FieldNames[2] = "__overflow_arg_area";
6441*67e74705SXin Li 
6442*67e74705SXin Li   //   void *__reg_save_area;
6443*67e74705SXin Li   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6444*67e74705SXin Li   FieldNames[3] = "__reg_save_area";
6445*67e74705SXin Li 
6446*67e74705SXin Li   // Create fields
6447*67e74705SXin Li   for (unsigned i = 0; i < NumFields; ++i) {
6448*67e74705SXin Li     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6449*67e74705SXin Li                                          VaListTagDecl,
6450*67e74705SXin Li                                          SourceLocation(),
6451*67e74705SXin Li                                          SourceLocation(),
6452*67e74705SXin Li                                          &Context->Idents.get(FieldNames[i]),
6453*67e74705SXin Li                                          FieldTypes[i], /*TInfo=*/nullptr,
6454*67e74705SXin Li                                          /*BitWidth=*/nullptr,
6455*67e74705SXin Li                                          /*Mutable=*/false,
6456*67e74705SXin Li                                          ICIS_NoInit);
6457*67e74705SXin Li     Field->setAccess(AS_public);
6458*67e74705SXin Li     VaListTagDecl->addDecl(Field);
6459*67e74705SXin Li   }
6460*67e74705SXin Li   VaListTagDecl->completeDefinition();
6461*67e74705SXin Li   Context->VaListTagDecl = VaListTagDecl;
6462*67e74705SXin Li   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6463*67e74705SXin Li 
6464*67e74705SXin Li   // };
6465*67e74705SXin Li 
6466*67e74705SXin Li   // typedef __va_list_tag __builtin_va_list[1];
6467*67e74705SXin Li   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6468*67e74705SXin Li   QualType VaListTagArrayType =
6469*67e74705SXin Li       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6470*67e74705SXin Li 
6471*67e74705SXin Li   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6472*67e74705SXin Li }
6473*67e74705SXin Li 
CreateVaListDecl(const ASTContext * Context,TargetInfo::BuiltinVaListKind Kind)6474*67e74705SXin Li static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6475*67e74705SXin Li                                      TargetInfo::BuiltinVaListKind Kind) {
6476*67e74705SXin Li   switch (Kind) {
6477*67e74705SXin Li   case TargetInfo::CharPtrBuiltinVaList:
6478*67e74705SXin Li     return CreateCharPtrBuiltinVaListDecl(Context);
6479*67e74705SXin Li   case TargetInfo::VoidPtrBuiltinVaList:
6480*67e74705SXin Li     return CreateVoidPtrBuiltinVaListDecl(Context);
6481*67e74705SXin Li   case TargetInfo::AArch64ABIBuiltinVaList:
6482*67e74705SXin Li     return CreateAArch64ABIBuiltinVaListDecl(Context);
6483*67e74705SXin Li   case TargetInfo::PowerABIBuiltinVaList:
6484*67e74705SXin Li     return CreatePowerABIBuiltinVaListDecl(Context);
6485*67e74705SXin Li   case TargetInfo::X86_64ABIBuiltinVaList:
6486*67e74705SXin Li     return CreateX86_64ABIBuiltinVaListDecl(Context);
6487*67e74705SXin Li   case TargetInfo::PNaClABIBuiltinVaList:
6488*67e74705SXin Li     return CreatePNaClABIBuiltinVaListDecl(Context);
6489*67e74705SXin Li   case TargetInfo::AAPCSABIBuiltinVaList:
6490*67e74705SXin Li     return CreateAAPCSABIBuiltinVaListDecl(Context);
6491*67e74705SXin Li   case TargetInfo::SystemZBuiltinVaList:
6492*67e74705SXin Li     return CreateSystemZBuiltinVaListDecl(Context);
6493*67e74705SXin Li   }
6494*67e74705SXin Li 
6495*67e74705SXin Li   llvm_unreachable("Unhandled __builtin_va_list type kind");
6496*67e74705SXin Li }
6497*67e74705SXin Li 
getBuiltinVaListDecl() const6498*67e74705SXin Li TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6499*67e74705SXin Li   if (!BuiltinVaListDecl) {
6500*67e74705SXin Li     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6501*67e74705SXin Li     assert(BuiltinVaListDecl->isImplicit());
6502*67e74705SXin Li   }
6503*67e74705SXin Li 
6504*67e74705SXin Li   return BuiltinVaListDecl;
6505*67e74705SXin Li }
6506*67e74705SXin Li 
getVaListTagDecl() const6507*67e74705SXin Li Decl *ASTContext::getVaListTagDecl() const {
6508*67e74705SXin Li   // Force the creation of VaListTagDecl by building the __builtin_va_list
6509*67e74705SXin Li   // declaration.
6510*67e74705SXin Li   if (!VaListTagDecl)
6511*67e74705SXin Li     (void)getBuiltinVaListDecl();
6512*67e74705SXin Li 
6513*67e74705SXin Li   return VaListTagDecl;
6514*67e74705SXin Li }
6515*67e74705SXin Li 
getBuiltinMSVaListDecl() const6516*67e74705SXin Li TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6517*67e74705SXin Li   if (!BuiltinMSVaListDecl)
6518*67e74705SXin Li     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6519*67e74705SXin Li 
6520*67e74705SXin Li   return BuiltinMSVaListDecl;
6521*67e74705SXin Li }
6522*67e74705SXin Li 
setObjCConstantStringInterface(ObjCInterfaceDecl * Decl)6523*67e74705SXin Li void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6524*67e74705SXin Li   assert(ObjCConstantStringType.isNull() &&
6525*67e74705SXin Li          "'NSConstantString' type already set!");
6526*67e74705SXin Li 
6527*67e74705SXin Li   ObjCConstantStringType = getObjCInterfaceType(Decl);
6528*67e74705SXin Li }
6529*67e74705SXin Li 
6530*67e74705SXin Li /// \brief Retrieve the template name that corresponds to a non-empty
6531*67e74705SXin Li /// lookup.
6532*67e74705SXin Li TemplateName
getOverloadedTemplateName(UnresolvedSetIterator Begin,UnresolvedSetIterator End) const6533*67e74705SXin Li ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6534*67e74705SXin Li                                       UnresolvedSetIterator End) const {
6535*67e74705SXin Li   unsigned size = End - Begin;
6536*67e74705SXin Li   assert(size > 1 && "set is not overloaded!");
6537*67e74705SXin Li 
6538*67e74705SXin Li   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6539*67e74705SXin Li                           size * sizeof(FunctionTemplateDecl*));
6540*67e74705SXin Li   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6541*67e74705SXin Li 
6542*67e74705SXin Li   NamedDecl **Storage = OT->getStorage();
6543*67e74705SXin Li   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6544*67e74705SXin Li     NamedDecl *D = *I;
6545*67e74705SXin Li     assert(isa<FunctionTemplateDecl>(D) ||
6546*67e74705SXin Li            (isa<UsingShadowDecl>(D) &&
6547*67e74705SXin Li             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6548*67e74705SXin Li     *Storage++ = D;
6549*67e74705SXin Li   }
6550*67e74705SXin Li 
6551*67e74705SXin Li   return TemplateName(OT);
6552*67e74705SXin Li }
6553*67e74705SXin Li 
6554*67e74705SXin Li /// \brief Retrieve the template name that represents a qualified
6555*67e74705SXin Li /// template name such as \c std::vector.
6556*67e74705SXin Li TemplateName
getQualifiedTemplateName(NestedNameSpecifier * NNS,bool TemplateKeyword,TemplateDecl * Template) const6557*67e74705SXin Li ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6558*67e74705SXin Li                                      bool TemplateKeyword,
6559*67e74705SXin Li                                      TemplateDecl *Template) const {
6560*67e74705SXin Li   assert(NNS && "Missing nested-name-specifier in qualified template name");
6561*67e74705SXin Li 
6562*67e74705SXin Li   // FIXME: Canonicalization?
6563*67e74705SXin Li   llvm::FoldingSetNodeID ID;
6564*67e74705SXin Li   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6565*67e74705SXin Li 
6566*67e74705SXin Li   void *InsertPos = nullptr;
6567*67e74705SXin Li   QualifiedTemplateName *QTN =
6568*67e74705SXin Li     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6569*67e74705SXin Li   if (!QTN) {
6570*67e74705SXin Li     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6571*67e74705SXin Li         QualifiedTemplateName(NNS, TemplateKeyword, Template);
6572*67e74705SXin Li     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6573*67e74705SXin Li   }
6574*67e74705SXin Li 
6575*67e74705SXin Li   return TemplateName(QTN);
6576*67e74705SXin Li }
6577*67e74705SXin Li 
6578*67e74705SXin Li /// \brief Retrieve the template name that represents a dependent
6579*67e74705SXin Li /// template name such as \c MetaFun::template apply.
6580*67e74705SXin Li TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,const IdentifierInfo * Name) const6581*67e74705SXin Li ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6582*67e74705SXin Li                                      const IdentifierInfo *Name) const {
6583*67e74705SXin Li   assert((!NNS || NNS->isDependent()) &&
6584*67e74705SXin Li          "Nested name specifier must be dependent");
6585*67e74705SXin Li 
6586*67e74705SXin Li   llvm::FoldingSetNodeID ID;
6587*67e74705SXin Li   DependentTemplateName::Profile(ID, NNS, Name);
6588*67e74705SXin Li 
6589*67e74705SXin Li   void *InsertPos = nullptr;
6590*67e74705SXin Li   DependentTemplateName *QTN =
6591*67e74705SXin Li     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6592*67e74705SXin Li 
6593*67e74705SXin Li   if (QTN)
6594*67e74705SXin Li     return TemplateName(QTN);
6595*67e74705SXin Li 
6596*67e74705SXin Li   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6597*67e74705SXin Li   if (CanonNNS == NNS) {
6598*67e74705SXin Li     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6599*67e74705SXin Li         DependentTemplateName(NNS, Name);
6600*67e74705SXin Li   } else {
6601*67e74705SXin Li     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6602*67e74705SXin Li     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6603*67e74705SXin Li         DependentTemplateName(NNS, Name, Canon);
6604*67e74705SXin Li     DependentTemplateName *CheckQTN =
6605*67e74705SXin Li       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6606*67e74705SXin Li     assert(!CheckQTN && "Dependent type name canonicalization broken");
6607*67e74705SXin Li     (void)CheckQTN;
6608*67e74705SXin Li   }
6609*67e74705SXin Li 
6610*67e74705SXin Li   DependentTemplateNames.InsertNode(QTN, InsertPos);
6611*67e74705SXin Li   return TemplateName(QTN);
6612*67e74705SXin Li }
6613*67e74705SXin Li 
6614*67e74705SXin Li /// \brief Retrieve the template name that represents a dependent
6615*67e74705SXin Li /// template name such as \c MetaFun::template operator+.
6616*67e74705SXin Li TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,OverloadedOperatorKind Operator) const6617*67e74705SXin Li ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6618*67e74705SXin Li                                      OverloadedOperatorKind Operator) const {
6619*67e74705SXin Li   assert((!NNS || NNS->isDependent()) &&
6620*67e74705SXin Li          "Nested name specifier must be dependent");
6621*67e74705SXin Li 
6622*67e74705SXin Li   llvm::FoldingSetNodeID ID;
6623*67e74705SXin Li   DependentTemplateName::Profile(ID, NNS, Operator);
6624*67e74705SXin Li 
6625*67e74705SXin Li   void *InsertPos = nullptr;
6626*67e74705SXin Li   DependentTemplateName *QTN
6627*67e74705SXin Li     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6628*67e74705SXin Li 
6629*67e74705SXin Li   if (QTN)
6630*67e74705SXin Li     return TemplateName(QTN);
6631*67e74705SXin Li 
6632*67e74705SXin Li   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6633*67e74705SXin Li   if (CanonNNS == NNS) {
6634*67e74705SXin Li     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6635*67e74705SXin Li         DependentTemplateName(NNS, Operator);
6636*67e74705SXin Li   } else {
6637*67e74705SXin Li     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6638*67e74705SXin Li     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6639*67e74705SXin Li         DependentTemplateName(NNS, Operator, Canon);
6640*67e74705SXin Li 
6641*67e74705SXin Li     DependentTemplateName *CheckQTN
6642*67e74705SXin Li       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6643*67e74705SXin Li     assert(!CheckQTN && "Dependent template name canonicalization broken");
6644*67e74705SXin Li     (void)CheckQTN;
6645*67e74705SXin Li   }
6646*67e74705SXin Li 
6647*67e74705SXin Li   DependentTemplateNames.InsertNode(QTN, InsertPos);
6648*67e74705SXin Li   return TemplateName(QTN);
6649*67e74705SXin Li }
6650*67e74705SXin Li 
6651*67e74705SXin Li TemplateName
getSubstTemplateTemplateParm(TemplateTemplateParmDecl * param,TemplateName replacement) const6652*67e74705SXin Li ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6653*67e74705SXin Li                                          TemplateName replacement) const {
6654*67e74705SXin Li   llvm::FoldingSetNodeID ID;
6655*67e74705SXin Li   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6656*67e74705SXin Li 
6657*67e74705SXin Li   void *insertPos = nullptr;
6658*67e74705SXin Li   SubstTemplateTemplateParmStorage *subst
6659*67e74705SXin Li     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6660*67e74705SXin Li 
6661*67e74705SXin Li   if (!subst) {
6662*67e74705SXin Li     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6663*67e74705SXin Li     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6664*67e74705SXin Li   }
6665*67e74705SXin Li 
6666*67e74705SXin Li   return TemplateName(subst);
6667*67e74705SXin Li }
6668*67e74705SXin Li 
6669*67e74705SXin Li TemplateName
getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl * Param,const TemplateArgument & ArgPack) const6670*67e74705SXin Li ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6671*67e74705SXin Li                                        const TemplateArgument &ArgPack) const {
6672*67e74705SXin Li   ASTContext &Self = const_cast<ASTContext &>(*this);
6673*67e74705SXin Li   llvm::FoldingSetNodeID ID;
6674*67e74705SXin Li   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6675*67e74705SXin Li 
6676*67e74705SXin Li   void *InsertPos = nullptr;
6677*67e74705SXin Li   SubstTemplateTemplateParmPackStorage *Subst
6678*67e74705SXin Li     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6679*67e74705SXin Li 
6680*67e74705SXin Li   if (!Subst) {
6681*67e74705SXin Li     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6682*67e74705SXin Li                                                            ArgPack.pack_size(),
6683*67e74705SXin Li                                                          ArgPack.pack_begin());
6684*67e74705SXin Li     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6685*67e74705SXin Li   }
6686*67e74705SXin Li 
6687*67e74705SXin Li   return TemplateName(Subst);
6688*67e74705SXin Li }
6689*67e74705SXin Li 
6690*67e74705SXin Li /// getFromTargetType - Given one of the integer types provided by
6691*67e74705SXin Li /// TargetInfo, produce the corresponding type. The unsigned @p Type
6692*67e74705SXin Li /// is actually a value of type @c TargetInfo::IntType.
getFromTargetType(unsigned Type) const6693*67e74705SXin Li CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6694*67e74705SXin Li   switch (Type) {
6695*67e74705SXin Li   case TargetInfo::NoInt: return CanQualType();
6696*67e74705SXin Li   case TargetInfo::SignedChar: return SignedCharTy;
6697*67e74705SXin Li   case TargetInfo::UnsignedChar: return UnsignedCharTy;
6698*67e74705SXin Li   case TargetInfo::SignedShort: return ShortTy;
6699*67e74705SXin Li   case TargetInfo::UnsignedShort: return UnsignedShortTy;
6700*67e74705SXin Li   case TargetInfo::SignedInt: return IntTy;
6701*67e74705SXin Li   case TargetInfo::UnsignedInt: return UnsignedIntTy;
6702*67e74705SXin Li   case TargetInfo::SignedLong: return LongTy;
6703*67e74705SXin Li   case TargetInfo::UnsignedLong: return UnsignedLongTy;
6704*67e74705SXin Li   case TargetInfo::SignedLongLong: return LongLongTy;
6705*67e74705SXin Li   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6706*67e74705SXin Li   }
6707*67e74705SXin Li 
6708*67e74705SXin Li   llvm_unreachable("Unhandled TargetInfo::IntType value");
6709*67e74705SXin Li }
6710*67e74705SXin Li 
6711*67e74705SXin Li //===----------------------------------------------------------------------===//
6712*67e74705SXin Li //                        Type Predicates.
6713*67e74705SXin Li //===----------------------------------------------------------------------===//
6714*67e74705SXin Li 
6715*67e74705SXin Li /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6716*67e74705SXin Li /// garbage collection attribute.
6717*67e74705SXin Li ///
getObjCGCAttrKind(QualType Ty) const6718*67e74705SXin Li Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6719*67e74705SXin Li   if (getLangOpts().getGC() == LangOptions::NonGC)
6720*67e74705SXin Li     return Qualifiers::GCNone;
6721*67e74705SXin Li 
6722*67e74705SXin Li   assert(getLangOpts().ObjC1);
6723*67e74705SXin Li   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6724*67e74705SXin Li 
6725*67e74705SXin Li   // Default behaviour under objective-C's gc is for ObjC pointers
6726*67e74705SXin Li   // (or pointers to them) be treated as though they were declared
6727*67e74705SXin Li   // as __strong.
6728*67e74705SXin Li   if (GCAttrs == Qualifiers::GCNone) {
6729*67e74705SXin Li     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6730*67e74705SXin Li       return Qualifiers::Strong;
6731*67e74705SXin Li     else if (Ty->isPointerType())
6732*67e74705SXin Li       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6733*67e74705SXin Li   } else {
6734*67e74705SXin Li     // It's not valid to set GC attributes on anything that isn't a
6735*67e74705SXin Li     // pointer.
6736*67e74705SXin Li #ifndef NDEBUG
6737*67e74705SXin Li     QualType CT = Ty->getCanonicalTypeInternal();
6738*67e74705SXin Li     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6739*67e74705SXin Li       CT = AT->getElementType();
6740*67e74705SXin Li     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6741*67e74705SXin Li #endif
6742*67e74705SXin Li   }
6743*67e74705SXin Li   return GCAttrs;
6744*67e74705SXin Li }
6745*67e74705SXin Li 
6746*67e74705SXin Li //===----------------------------------------------------------------------===//
6747*67e74705SXin Li //                        Type Compatibility Testing
6748*67e74705SXin Li //===----------------------------------------------------------------------===//
6749*67e74705SXin Li 
6750*67e74705SXin Li /// areCompatVectorTypes - Return true if the two specified vector types are
6751*67e74705SXin Li /// compatible.
areCompatVectorTypes(const VectorType * LHS,const VectorType * RHS)6752*67e74705SXin Li static bool areCompatVectorTypes(const VectorType *LHS,
6753*67e74705SXin Li                                  const VectorType *RHS) {
6754*67e74705SXin Li   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6755*67e74705SXin Li   return LHS->getElementType() == RHS->getElementType() &&
6756*67e74705SXin Li          LHS->getNumElements() == RHS->getNumElements();
6757*67e74705SXin Li }
6758*67e74705SXin Li 
areCompatibleVectorTypes(QualType FirstVec,QualType SecondVec)6759*67e74705SXin Li bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6760*67e74705SXin Li                                           QualType SecondVec) {
6761*67e74705SXin Li   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6762*67e74705SXin Li   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6763*67e74705SXin Li 
6764*67e74705SXin Li   if (hasSameUnqualifiedType(FirstVec, SecondVec))
6765*67e74705SXin Li     return true;
6766*67e74705SXin Li 
6767*67e74705SXin Li   // Treat Neon vector types and most AltiVec vector types as if they are the
6768*67e74705SXin Li   // equivalent GCC vector types.
6769*67e74705SXin Li   const VectorType *First = FirstVec->getAs<VectorType>();
6770*67e74705SXin Li   const VectorType *Second = SecondVec->getAs<VectorType>();
6771*67e74705SXin Li   if (First->getNumElements() == Second->getNumElements() &&
6772*67e74705SXin Li       hasSameType(First->getElementType(), Second->getElementType()) &&
6773*67e74705SXin Li       First->getVectorKind() != VectorType::AltiVecPixel &&
6774*67e74705SXin Li       First->getVectorKind() != VectorType::AltiVecBool &&
6775*67e74705SXin Li       Second->getVectorKind() != VectorType::AltiVecPixel &&
6776*67e74705SXin Li       Second->getVectorKind() != VectorType::AltiVecBool)
6777*67e74705SXin Li     return true;
6778*67e74705SXin Li 
6779*67e74705SXin Li   return false;
6780*67e74705SXin Li }
6781*67e74705SXin Li 
6782*67e74705SXin Li //===----------------------------------------------------------------------===//
6783*67e74705SXin Li // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6784*67e74705SXin Li //===----------------------------------------------------------------------===//
6785*67e74705SXin Li 
6786*67e74705SXin Li /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6787*67e74705SXin Li /// inheritance hierarchy of 'rProto'.
6788*67e74705SXin Li bool
ProtocolCompatibleWithProtocol(ObjCProtocolDecl * lProto,ObjCProtocolDecl * rProto) const6789*67e74705SXin Li ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6790*67e74705SXin Li                                            ObjCProtocolDecl *rProto) const {
6791*67e74705SXin Li   if (declaresSameEntity(lProto, rProto))
6792*67e74705SXin Li     return true;
6793*67e74705SXin Li   for (auto *PI : rProto->protocols())
6794*67e74705SXin Li     if (ProtocolCompatibleWithProtocol(lProto, PI))
6795*67e74705SXin Li       return true;
6796*67e74705SXin Li   return false;
6797*67e74705SXin Li }
6798*67e74705SXin Li 
6799*67e74705SXin Li /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
6800*67e74705SXin Li /// Class<pr1, ...>.
ObjCQualifiedClassTypesAreCompatible(QualType lhs,QualType rhs)6801*67e74705SXin Li bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6802*67e74705SXin Li                                                       QualType rhs) {
6803*67e74705SXin Li   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6804*67e74705SXin Li   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6805*67e74705SXin Li   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6806*67e74705SXin Li 
6807*67e74705SXin Li   for (auto *lhsProto : lhsQID->quals()) {
6808*67e74705SXin Li     bool match = false;
6809*67e74705SXin Li     for (auto *rhsProto : rhsOPT->quals()) {
6810*67e74705SXin Li       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6811*67e74705SXin Li         match = true;
6812*67e74705SXin Li         break;
6813*67e74705SXin Li       }
6814*67e74705SXin Li     }
6815*67e74705SXin Li     if (!match)
6816*67e74705SXin Li       return false;
6817*67e74705SXin Li   }
6818*67e74705SXin Li   return true;
6819*67e74705SXin Li }
6820*67e74705SXin Li 
6821*67e74705SXin Li /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6822*67e74705SXin Li /// ObjCQualifiedIDType.
ObjCQualifiedIdTypesAreCompatible(QualType lhs,QualType rhs,bool compare)6823*67e74705SXin Li bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6824*67e74705SXin Li                                                    bool compare) {
6825*67e74705SXin Li   // Allow id<P..> and an 'id' or void* type in all cases.
6826*67e74705SXin Li   if (lhs->isVoidPointerType() ||
6827*67e74705SXin Li       lhs->isObjCIdType() || lhs->isObjCClassType())
6828*67e74705SXin Li     return true;
6829*67e74705SXin Li   else if (rhs->isVoidPointerType() ||
6830*67e74705SXin Li            rhs->isObjCIdType() || rhs->isObjCClassType())
6831*67e74705SXin Li     return true;
6832*67e74705SXin Li 
6833*67e74705SXin Li   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6834*67e74705SXin Li     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6835*67e74705SXin Li 
6836*67e74705SXin Li     if (!rhsOPT) return false;
6837*67e74705SXin Li 
6838*67e74705SXin Li     if (rhsOPT->qual_empty()) {
6839*67e74705SXin Li       // If the RHS is a unqualified interface pointer "NSString*",
6840*67e74705SXin Li       // make sure we check the class hierarchy.
6841*67e74705SXin Li       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6842*67e74705SXin Li         for (auto *I : lhsQID->quals()) {
6843*67e74705SXin Li           // when comparing an id<P> on lhs with a static type on rhs,
6844*67e74705SXin Li           // see if static class implements all of id's protocols, directly or
6845*67e74705SXin Li           // through its super class and categories.
6846*67e74705SXin Li           if (!rhsID->ClassImplementsProtocol(I, true))
6847*67e74705SXin Li             return false;
6848*67e74705SXin Li         }
6849*67e74705SXin Li       }
6850*67e74705SXin Li       // If there are no qualifiers and no interface, we have an 'id'.
6851*67e74705SXin Li       return true;
6852*67e74705SXin Li     }
6853*67e74705SXin Li     // Both the right and left sides have qualifiers.
6854*67e74705SXin Li     for (auto *lhsProto : lhsQID->quals()) {
6855*67e74705SXin Li       bool match = false;
6856*67e74705SXin Li 
6857*67e74705SXin Li       // when comparing an id<P> on lhs with a static type on rhs,
6858*67e74705SXin Li       // see if static class implements all of id's protocols, directly or
6859*67e74705SXin Li       // through its super class and categories.
6860*67e74705SXin Li       for (auto *rhsProto : rhsOPT->quals()) {
6861*67e74705SXin Li         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6862*67e74705SXin Li             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6863*67e74705SXin Li           match = true;
6864*67e74705SXin Li           break;
6865*67e74705SXin Li         }
6866*67e74705SXin Li       }
6867*67e74705SXin Li       // If the RHS is a qualified interface pointer "NSString<P>*",
6868*67e74705SXin Li       // make sure we check the class hierarchy.
6869*67e74705SXin Li       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6870*67e74705SXin Li         for (auto *I : lhsQID->quals()) {
6871*67e74705SXin Li           // when comparing an id<P> on lhs with a static type on rhs,
6872*67e74705SXin Li           // see if static class implements all of id's protocols, directly or
6873*67e74705SXin Li           // through its super class and categories.
6874*67e74705SXin Li           if (rhsID->ClassImplementsProtocol(I, true)) {
6875*67e74705SXin Li             match = true;
6876*67e74705SXin Li             break;
6877*67e74705SXin Li           }
6878*67e74705SXin Li         }
6879*67e74705SXin Li       }
6880*67e74705SXin Li       if (!match)
6881*67e74705SXin Li         return false;
6882*67e74705SXin Li     }
6883*67e74705SXin Li 
6884*67e74705SXin Li     return true;
6885*67e74705SXin Li   }
6886*67e74705SXin Li 
6887*67e74705SXin Li   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6888*67e74705SXin Li   assert(rhsQID && "One of the LHS/RHS should be id<x>");
6889*67e74705SXin Li 
6890*67e74705SXin Li   if (const ObjCObjectPointerType *lhsOPT =
6891*67e74705SXin Li         lhs->getAsObjCInterfacePointerType()) {
6892*67e74705SXin Li     // If both the right and left sides have qualifiers.
6893*67e74705SXin Li     for (auto *lhsProto : lhsOPT->quals()) {
6894*67e74705SXin Li       bool match = false;
6895*67e74705SXin Li 
6896*67e74705SXin Li       // when comparing an id<P> on rhs with a static type on lhs,
6897*67e74705SXin Li       // see if static class implements all of id's protocols, directly or
6898*67e74705SXin Li       // through its super class and categories.
6899*67e74705SXin Li       // First, lhs protocols in the qualifier list must be found, direct
6900*67e74705SXin Li       // or indirect in rhs's qualifier list or it is a mismatch.
6901*67e74705SXin Li       for (auto *rhsProto : rhsQID->quals()) {
6902*67e74705SXin Li         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6903*67e74705SXin Li             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6904*67e74705SXin Li           match = true;
6905*67e74705SXin Li           break;
6906*67e74705SXin Li         }
6907*67e74705SXin Li       }
6908*67e74705SXin Li       if (!match)
6909*67e74705SXin Li         return false;
6910*67e74705SXin Li     }
6911*67e74705SXin Li 
6912*67e74705SXin Li     // Static class's protocols, or its super class or category protocols
6913*67e74705SXin Li     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6914*67e74705SXin Li     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6915*67e74705SXin Li       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6916*67e74705SXin Li       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6917*67e74705SXin Li       // This is rather dubious but matches gcc's behavior. If lhs has
6918*67e74705SXin Li       // no type qualifier and its class has no static protocol(s)
6919*67e74705SXin Li       // assume that it is mismatch.
6920*67e74705SXin Li       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6921*67e74705SXin Li         return false;
6922*67e74705SXin Li       for (auto *lhsProto : LHSInheritedProtocols) {
6923*67e74705SXin Li         bool match = false;
6924*67e74705SXin Li         for (auto *rhsProto : rhsQID->quals()) {
6925*67e74705SXin Li           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6926*67e74705SXin Li               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6927*67e74705SXin Li             match = true;
6928*67e74705SXin Li             break;
6929*67e74705SXin Li           }
6930*67e74705SXin Li         }
6931*67e74705SXin Li         if (!match)
6932*67e74705SXin Li           return false;
6933*67e74705SXin Li       }
6934*67e74705SXin Li     }
6935*67e74705SXin Li     return true;
6936*67e74705SXin Li   }
6937*67e74705SXin Li   return false;
6938*67e74705SXin Li }
6939*67e74705SXin Li 
6940*67e74705SXin Li /// canAssignObjCInterfaces - Return true if the two interface types are
6941*67e74705SXin Li /// compatible for assignment from RHS to LHS.  This handles validation of any
6942*67e74705SXin Li /// protocol qualifiers on the LHS or RHS.
6943*67e74705SXin Li ///
canAssignObjCInterfaces(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT)6944*67e74705SXin Li bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6945*67e74705SXin Li                                          const ObjCObjectPointerType *RHSOPT) {
6946*67e74705SXin Li   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6947*67e74705SXin Li   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6948*67e74705SXin Li 
6949*67e74705SXin Li   // If either type represents the built-in 'id' or 'Class' types, return true.
6950*67e74705SXin Li   if (LHS->isObjCUnqualifiedIdOrClass() ||
6951*67e74705SXin Li       RHS->isObjCUnqualifiedIdOrClass())
6952*67e74705SXin Li     return true;
6953*67e74705SXin Li 
6954*67e74705SXin Li   // Function object that propagates a successful result or handles
6955*67e74705SXin Li   // __kindof types.
6956*67e74705SXin Li   auto finish = [&](bool succeeded) -> bool {
6957*67e74705SXin Li     if (succeeded)
6958*67e74705SXin Li       return true;
6959*67e74705SXin Li 
6960*67e74705SXin Li     if (!RHS->isKindOfType())
6961*67e74705SXin Li       return false;
6962*67e74705SXin Li 
6963*67e74705SXin Li     // Strip off __kindof and protocol qualifiers, then check whether
6964*67e74705SXin Li     // we can assign the other way.
6965*67e74705SXin Li     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6966*67e74705SXin Li                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6967*67e74705SXin Li   };
6968*67e74705SXin Li 
6969*67e74705SXin Li   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6970*67e74705SXin Li     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6971*67e74705SXin Li                                                     QualType(RHSOPT,0),
6972*67e74705SXin Li                                                     false));
6973*67e74705SXin Li   }
6974*67e74705SXin Li 
6975*67e74705SXin Li   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6976*67e74705SXin Li     return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6977*67e74705SXin Li                                                        QualType(RHSOPT,0)));
6978*67e74705SXin Li   }
6979*67e74705SXin Li 
6980*67e74705SXin Li   // If we have 2 user-defined types, fall into that path.
6981*67e74705SXin Li   if (LHS->getInterface() && RHS->getInterface()) {
6982*67e74705SXin Li     return finish(canAssignObjCInterfaces(LHS, RHS));
6983*67e74705SXin Li   }
6984*67e74705SXin Li 
6985*67e74705SXin Li   return false;
6986*67e74705SXin Li }
6987*67e74705SXin Li 
6988*67e74705SXin Li /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6989*67e74705SXin Li /// for providing type-safety for objective-c pointers used to pass/return
6990*67e74705SXin Li /// arguments in block literals. When passed as arguments, passing 'A*' where
6991*67e74705SXin Li /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6992*67e74705SXin Li /// not OK. For the return type, the opposite is not OK.
canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,bool BlockReturnType)6993*67e74705SXin Li bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6994*67e74705SXin Li                                          const ObjCObjectPointerType *LHSOPT,
6995*67e74705SXin Li                                          const ObjCObjectPointerType *RHSOPT,
6996*67e74705SXin Li                                          bool BlockReturnType) {
6997*67e74705SXin Li 
6998*67e74705SXin Li   // Function object that propagates a successful result or handles
6999*67e74705SXin Li   // __kindof types.
7000*67e74705SXin Li   auto finish = [&](bool succeeded) -> bool {
7001*67e74705SXin Li     if (succeeded)
7002*67e74705SXin Li       return true;
7003*67e74705SXin Li 
7004*67e74705SXin Li     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7005*67e74705SXin Li     if (!Expected->isKindOfType())
7006*67e74705SXin Li       return false;
7007*67e74705SXin Li 
7008*67e74705SXin Li     // Strip off __kindof and protocol qualifiers, then check whether
7009*67e74705SXin Li     // we can assign the other way.
7010*67e74705SXin Li     return canAssignObjCInterfacesInBlockPointer(
7011*67e74705SXin Li              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7012*67e74705SXin Li              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7013*67e74705SXin Li              BlockReturnType);
7014*67e74705SXin Li   };
7015*67e74705SXin Li 
7016*67e74705SXin Li   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7017*67e74705SXin Li     return true;
7018*67e74705SXin Li 
7019*67e74705SXin Li   if (LHSOPT->isObjCBuiltinType()) {
7020*67e74705SXin Li     return finish(RHSOPT->isObjCBuiltinType() ||
7021*67e74705SXin Li                   RHSOPT->isObjCQualifiedIdType());
7022*67e74705SXin Li   }
7023*67e74705SXin Li 
7024*67e74705SXin Li   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7025*67e74705SXin Li     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7026*67e74705SXin Li                                                     QualType(RHSOPT,0),
7027*67e74705SXin Li                                                     false));
7028*67e74705SXin Li 
7029*67e74705SXin Li   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7030*67e74705SXin Li   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7031*67e74705SXin Li   if (LHS && RHS)  { // We have 2 user-defined types.
7032*67e74705SXin Li     if (LHS != RHS) {
7033*67e74705SXin Li       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7034*67e74705SXin Li         return finish(BlockReturnType);
7035*67e74705SXin Li       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7036*67e74705SXin Li         return finish(!BlockReturnType);
7037*67e74705SXin Li     }
7038*67e74705SXin Li     else
7039*67e74705SXin Li       return true;
7040*67e74705SXin Li   }
7041*67e74705SXin Li   return false;
7042*67e74705SXin Li }
7043*67e74705SXin Li 
7044*67e74705SXin Li /// Comparison routine for Objective-C protocols to be used with
7045*67e74705SXin Li /// llvm::array_pod_sort.
compareObjCProtocolsByName(ObjCProtocolDecl * const * lhs,ObjCProtocolDecl * const * rhs)7046*67e74705SXin Li static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7047*67e74705SXin Li                                       ObjCProtocolDecl * const *rhs) {
7048*67e74705SXin Li   return (*lhs)->getName().compare((*rhs)->getName());
7049*67e74705SXin Li 
7050*67e74705SXin Li }
7051*67e74705SXin Li 
7052*67e74705SXin Li /// getIntersectionOfProtocols - This routine finds the intersection of set
7053*67e74705SXin Li /// of protocols inherited from two distinct objective-c pointer objects with
7054*67e74705SXin Li /// the given common base.
7055*67e74705SXin Li /// It is used to build composite qualifier list of the composite type of
7056*67e74705SXin Li /// the conditional expression involving two objective-c pointer objects.
7057*67e74705SXin Li static
getIntersectionOfProtocols(ASTContext & Context,const ObjCInterfaceDecl * CommonBase,const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,SmallVectorImpl<ObjCProtocolDecl * > & IntersectionSet)7058*67e74705SXin Li void getIntersectionOfProtocols(ASTContext &Context,
7059*67e74705SXin Li                                 const ObjCInterfaceDecl *CommonBase,
7060*67e74705SXin Li                                 const ObjCObjectPointerType *LHSOPT,
7061*67e74705SXin Li                                 const ObjCObjectPointerType *RHSOPT,
7062*67e74705SXin Li       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7063*67e74705SXin Li 
7064*67e74705SXin Li   const ObjCObjectType* LHS = LHSOPT->getObjectType();
7065*67e74705SXin Li   const ObjCObjectType* RHS = RHSOPT->getObjectType();
7066*67e74705SXin Li   assert(LHS->getInterface() && "LHS must have an interface base");
7067*67e74705SXin Li   assert(RHS->getInterface() && "RHS must have an interface base");
7068*67e74705SXin Li 
7069*67e74705SXin Li   // Add all of the protocols for the LHS.
7070*67e74705SXin Li   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7071*67e74705SXin Li 
7072*67e74705SXin Li   // Start with the protocol qualifiers.
7073*67e74705SXin Li   for (auto proto : LHS->quals()) {
7074*67e74705SXin Li     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7075*67e74705SXin Li   }
7076*67e74705SXin Li 
7077*67e74705SXin Li   // Also add the protocols associated with the LHS interface.
7078*67e74705SXin Li   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7079*67e74705SXin Li 
7080*67e74705SXin Li   // Add all of the protocls for the RHS.
7081*67e74705SXin Li   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7082*67e74705SXin Li 
7083*67e74705SXin Li   // Start with the protocol qualifiers.
7084*67e74705SXin Li   for (auto proto : RHS->quals()) {
7085*67e74705SXin Li     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7086*67e74705SXin Li   }
7087*67e74705SXin Li 
7088*67e74705SXin Li   // Also add the protocols associated with the RHS interface.
7089*67e74705SXin Li   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7090*67e74705SXin Li 
7091*67e74705SXin Li   // Compute the intersection of the collected protocol sets.
7092*67e74705SXin Li   for (auto proto : LHSProtocolSet) {
7093*67e74705SXin Li     if (RHSProtocolSet.count(proto))
7094*67e74705SXin Li       IntersectionSet.push_back(proto);
7095*67e74705SXin Li   }
7096*67e74705SXin Li 
7097*67e74705SXin Li   // Compute the set of protocols that is implied by either the common type or
7098*67e74705SXin Li   // the protocols within the intersection.
7099*67e74705SXin Li   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7100*67e74705SXin Li   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7101*67e74705SXin Li 
7102*67e74705SXin Li   // Remove any implied protocols from the list of inherited protocols.
7103*67e74705SXin Li   if (!ImpliedProtocols.empty()) {
7104*67e74705SXin Li     IntersectionSet.erase(
7105*67e74705SXin Li       std::remove_if(IntersectionSet.begin(),
7106*67e74705SXin Li                      IntersectionSet.end(),
7107*67e74705SXin Li                      [&](ObjCProtocolDecl *proto) -> bool {
7108*67e74705SXin Li                        return ImpliedProtocols.count(proto) > 0;
7109*67e74705SXin Li                      }),
7110*67e74705SXin Li       IntersectionSet.end());
7111*67e74705SXin Li   }
7112*67e74705SXin Li 
7113*67e74705SXin Li   // Sort the remaining protocols by name.
7114*67e74705SXin Li   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7115*67e74705SXin Li                        compareObjCProtocolsByName);
7116*67e74705SXin Li }
7117*67e74705SXin Li 
7118*67e74705SXin Li /// Determine whether the first type is a subtype of the second.
canAssignObjCObjectTypes(ASTContext & ctx,QualType lhs,QualType rhs)7119*67e74705SXin Li static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7120*67e74705SXin Li                                      QualType rhs) {
7121*67e74705SXin Li   // Common case: two object pointers.
7122*67e74705SXin Li   const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7123*67e74705SXin Li   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7124*67e74705SXin Li   if (lhsOPT && rhsOPT)
7125*67e74705SXin Li     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7126*67e74705SXin Li 
7127*67e74705SXin Li   // Two block pointers.
7128*67e74705SXin Li   const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7129*67e74705SXin Li   const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7130*67e74705SXin Li   if (lhsBlock && rhsBlock)
7131*67e74705SXin Li     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7132*67e74705SXin Li 
7133*67e74705SXin Li   // If either is an unqualified 'id' and the other is a block, it's
7134*67e74705SXin Li   // acceptable.
7135*67e74705SXin Li   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7136*67e74705SXin Li       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7137*67e74705SXin Li     return true;
7138*67e74705SXin Li 
7139*67e74705SXin Li   return false;
7140*67e74705SXin Li }
7141*67e74705SXin Li 
7142*67e74705SXin Li // Check that the given Objective-C type argument lists are equivalent.
sameObjCTypeArgs(ASTContext & ctx,const ObjCInterfaceDecl * iface,ArrayRef<QualType> lhsArgs,ArrayRef<QualType> rhsArgs,bool stripKindOf)7143*67e74705SXin Li static bool sameObjCTypeArgs(ASTContext &ctx,
7144*67e74705SXin Li                              const ObjCInterfaceDecl *iface,
7145*67e74705SXin Li                              ArrayRef<QualType> lhsArgs,
7146*67e74705SXin Li                              ArrayRef<QualType> rhsArgs,
7147*67e74705SXin Li                              bool stripKindOf) {
7148*67e74705SXin Li   if (lhsArgs.size() != rhsArgs.size())
7149*67e74705SXin Li     return false;
7150*67e74705SXin Li 
7151*67e74705SXin Li   ObjCTypeParamList *typeParams = iface->getTypeParamList();
7152*67e74705SXin Li   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7153*67e74705SXin Li     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7154*67e74705SXin Li       continue;
7155*67e74705SXin Li 
7156*67e74705SXin Li     switch (typeParams->begin()[i]->getVariance()) {
7157*67e74705SXin Li     case ObjCTypeParamVariance::Invariant:
7158*67e74705SXin Li       if (!stripKindOf ||
7159*67e74705SXin Li           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7160*67e74705SXin Li                            rhsArgs[i].stripObjCKindOfType(ctx))) {
7161*67e74705SXin Li         return false;
7162*67e74705SXin Li       }
7163*67e74705SXin Li       break;
7164*67e74705SXin Li 
7165*67e74705SXin Li     case ObjCTypeParamVariance::Covariant:
7166*67e74705SXin Li       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7167*67e74705SXin Li         return false;
7168*67e74705SXin Li       break;
7169*67e74705SXin Li 
7170*67e74705SXin Li     case ObjCTypeParamVariance::Contravariant:
7171*67e74705SXin Li       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7172*67e74705SXin Li         return false;
7173*67e74705SXin Li       break;
7174*67e74705SXin Li     }
7175*67e74705SXin Li   }
7176*67e74705SXin Li 
7177*67e74705SXin Li   return true;
7178*67e74705SXin Li }
7179*67e74705SXin Li 
areCommonBaseCompatible(const ObjCObjectPointerType * Lptr,const ObjCObjectPointerType * Rptr)7180*67e74705SXin Li QualType ASTContext::areCommonBaseCompatible(
7181*67e74705SXin Li            const ObjCObjectPointerType *Lptr,
7182*67e74705SXin Li            const ObjCObjectPointerType *Rptr) {
7183*67e74705SXin Li   const ObjCObjectType *LHS = Lptr->getObjectType();
7184*67e74705SXin Li   const ObjCObjectType *RHS = Rptr->getObjectType();
7185*67e74705SXin Li   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7186*67e74705SXin Li   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7187*67e74705SXin Li 
7188*67e74705SXin Li   if (!LDecl || !RDecl)
7189*67e74705SXin Li     return QualType();
7190*67e74705SXin Li 
7191*67e74705SXin Li   // When either LHS or RHS is a kindof type, we should return a kindof type.
7192*67e74705SXin Li   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7193*67e74705SXin Li   // kindof(A).
7194*67e74705SXin Li   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7195*67e74705SXin Li 
7196*67e74705SXin Li   // Follow the left-hand side up the class hierarchy until we either hit a
7197*67e74705SXin Li   // root or find the RHS. Record the ancestors in case we don't find it.
7198*67e74705SXin Li   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7199*67e74705SXin Li     LHSAncestors;
7200*67e74705SXin Li   while (true) {
7201*67e74705SXin Li     // Record this ancestor. We'll need this if the common type isn't in the
7202*67e74705SXin Li     // path from the LHS to the root.
7203*67e74705SXin Li     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7204*67e74705SXin Li 
7205*67e74705SXin Li     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7206*67e74705SXin Li       // Get the type arguments.
7207*67e74705SXin Li       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7208*67e74705SXin Li       bool anyChanges = false;
7209*67e74705SXin Li       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7210*67e74705SXin Li         // Both have type arguments, compare them.
7211*67e74705SXin Li         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7212*67e74705SXin Li                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7213*67e74705SXin Li                               /*stripKindOf=*/true))
7214*67e74705SXin Li           return QualType();
7215*67e74705SXin Li       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7216*67e74705SXin Li         // If only one has type arguments, the result will not have type
7217*67e74705SXin Li         // arguments.
7218*67e74705SXin Li         LHSTypeArgs = { };
7219*67e74705SXin Li         anyChanges = true;
7220*67e74705SXin Li       }
7221*67e74705SXin Li 
7222*67e74705SXin Li       // Compute the intersection of protocols.
7223*67e74705SXin Li       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7224*67e74705SXin Li       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7225*67e74705SXin Li                                  Protocols);
7226*67e74705SXin Li       if (!Protocols.empty())
7227*67e74705SXin Li         anyChanges = true;
7228*67e74705SXin Li 
7229*67e74705SXin Li       // If anything in the LHS will have changed, build a new result type.
7230*67e74705SXin Li       // If we need to return a kindof type but LHS is not a kindof type, we
7231*67e74705SXin Li       // build a new result type.
7232*67e74705SXin Li       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7233*67e74705SXin Li         QualType Result = getObjCInterfaceType(LHS->getInterface());
7234*67e74705SXin Li         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7235*67e74705SXin Li                                    anyKindOf || LHS->isKindOfType());
7236*67e74705SXin Li         return getObjCObjectPointerType(Result);
7237*67e74705SXin Li       }
7238*67e74705SXin Li 
7239*67e74705SXin Li       return getObjCObjectPointerType(QualType(LHS, 0));
7240*67e74705SXin Li     }
7241*67e74705SXin Li 
7242*67e74705SXin Li     // Find the superclass.
7243*67e74705SXin Li     QualType LHSSuperType = LHS->getSuperClassType();
7244*67e74705SXin Li     if (LHSSuperType.isNull())
7245*67e74705SXin Li       break;
7246*67e74705SXin Li 
7247*67e74705SXin Li     LHS = LHSSuperType->castAs<ObjCObjectType>();
7248*67e74705SXin Li   }
7249*67e74705SXin Li 
7250*67e74705SXin Li   // We didn't find anything by following the LHS to its root; now check
7251*67e74705SXin Li   // the RHS against the cached set of ancestors.
7252*67e74705SXin Li   while (true) {
7253*67e74705SXin Li     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7254*67e74705SXin Li     if (KnownLHS != LHSAncestors.end()) {
7255*67e74705SXin Li       LHS = KnownLHS->second;
7256*67e74705SXin Li 
7257*67e74705SXin Li       // Get the type arguments.
7258*67e74705SXin Li       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7259*67e74705SXin Li       bool anyChanges = false;
7260*67e74705SXin Li       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7261*67e74705SXin Li         // Both have type arguments, compare them.
7262*67e74705SXin Li         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7263*67e74705SXin Li                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7264*67e74705SXin Li                               /*stripKindOf=*/true))
7265*67e74705SXin Li           return QualType();
7266*67e74705SXin Li       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7267*67e74705SXin Li         // If only one has type arguments, the result will not have type
7268*67e74705SXin Li         // arguments.
7269*67e74705SXin Li         RHSTypeArgs = { };
7270*67e74705SXin Li         anyChanges = true;
7271*67e74705SXin Li       }
7272*67e74705SXin Li 
7273*67e74705SXin Li       // Compute the intersection of protocols.
7274*67e74705SXin Li       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7275*67e74705SXin Li       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7276*67e74705SXin Li                                  Protocols);
7277*67e74705SXin Li       if (!Protocols.empty())
7278*67e74705SXin Li         anyChanges = true;
7279*67e74705SXin Li 
7280*67e74705SXin Li       // If we need to return a kindof type but RHS is not a kindof type, we
7281*67e74705SXin Li       // build a new result type.
7282*67e74705SXin Li       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7283*67e74705SXin Li         QualType Result = getObjCInterfaceType(RHS->getInterface());
7284*67e74705SXin Li         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7285*67e74705SXin Li                                    anyKindOf || RHS->isKindOfType());
7286*67e74705SXin Li         return getObjCObjectPointerType(Result);
7287*67e74705SXin Li       }
7288*67e74705SXin Li 
7289*67e74705SXin Li       return getObjCObjectPointerType(QualType(RHS, 0));
7290*67e74705SXin Li     }
7291*67e74705SXin Li 
7292*67e74705SXin Li     // Find the superclass of the RHS.
7293*67e74705SXin Li     QualType RHSSuperType = RHS->getSuperClassType();
7294*67e74705SXin Li     if (RHSSuperType.isNull())
7295*67e74705SXin Li       break;
7296*67e74705SXin Li 
7297*67e74705SXin Li     RHS = RHSSuperType->castAs<ObjCObjectType>();
7298*67e74705SXin Li   }
7299*67e74705SXin Li 
7300*67e74705SXin Li   return QualType();
7301*67e74705SXin Li }
7302*67e74705SXin Li 
canAssignObjCInterfaces(const ObjCObjectType * LHS,const ObjCObjectType * RHS)7303*67e74705SXin Li bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7304*67e74705SXin Li                                          const ObjCObjectType *RHS) {
7305*67e74705SXin Li   assert(LHS->getInterface() && "LHS is not an interface type");
7306*67e74705SXin Li   assert(RHS->getInterface() && "RHS is not an interface type");
7307*67e74705SXin Li 
7308*67e74705SXin Li   // Verify that the base decls are compatible: the RHS must be a subclass of
7309*67e74705SXin Li   // the LHS.
7310*67e74705SXin Li   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7311*67e74705SXin Li   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7312*67e74705SXin Li   if (!IsSuperClass)
7313*67e74705SXin Li     return false;
7314*67e74705SXin Li 
7315*67e74705SXin Li   // If the LHS has protocol qualifiers, determine whether all of them are
7316*67e74705SXin Li   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7317*67e74705SXin Li   // LHS).
7318*67e74705SXin Li   if (LHS->getNumProtocols() > 0) {
7319*67e74705SXin Li     // OK if conversion of LHS to SuperClass results in narrowing of types
7320*67e74705SXin Li     // ; i.e., SuperClass may implement at least one of the protocols
7321*67e74705SXin Li     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7322*67e74705SXin Li     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7323*67e74705SXin Li     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7324*67e74705SXin Li     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7325*67e74705SXin Li     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7326*67e74705SXin Li     // qualifiers.
7327*67e74705SXin Li     for (auto *RHSPI : RHS->quals())
7328*67e74705SXin Li       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7329*67e74705SXin Li     // If there is no protocols associated with RHS, it is not a match.
7330*67e74705SXin Li     if (SuperClassInheritedProtocols.empty())
7331*67e74705SXin Li       return false;
7332*67e74705SXin Li 
7333*67e74705SXin Li     for (const auto *LHSProto : LHS->quals()) {
7334*67e74705SXin Li       bool SuperImplementsProtocol = false;
7335*67e74705SXin Li       for (auto *SuperClassProto : SuperClassInheritedProtocols)
7336*67e74705SXin Li         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7337*67e74705SXin Li           SuperImplementsProtocol = true;
7338*67e74705SXin Li           break;
7339*67e74705SXin Li         }
7340*67e74705SXin Li       if (!SuperImplementsProtocol)
7341*67e74705SXin Li         return false;
7342*67e74705SXin Li     }
7343*67e74705SXin Li   }
7344*67e74705SXin Li 
7345*67e74705SXin Li   // If the LHS is specialized, we may need to check type arguments.
7346*67e74705SXin Li   if (LHS->isSpecialized()) {
7347*67e74705SXin Li     // Follow the superclass chain until we've matched the LHS class in the
7348*67e74705SXin Li     // hierarchy. This substitutes type arguments through.
7349*67e74705SXin Li     const ObjCObjectType *RHSSuper = RHS;
7350*67e74705SXin Li     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7351*67e74705SXin Li       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7352*67e74705SXin Li 
7353*67e74705SXin Li     // If the RHS is specializd, compare type arguments.
7354*67e74705SXin Li     if (RHSSuper->isSpecialized() &&
7355*67e74705SXin Li         !sameObjCTypeArgs(*this, LHS->getInterface(),
7356*67e74705SXin Li                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7357*67e74705SXin Li                           /*stripKindOf=*/true)) {
7358*67e74705SXin Li       return false;
7359*67e74705SXin Li     }
7360*67e74705SXin Li   }
7361*67e74705SXin Li 
7362*67e74705SXin Li   return true;
7363*67e74705SXin Li }
7364*67e74705SXin Li 
areComparableObjCPointerTypes(QualType LHS,QualType RHS)7365*67e74705SXin Li bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7366*67e74705SXin Li   // get the "pointed to" types
7367*67e74705SXin Li   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7368*67e74705SXin Li   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7369*67e74705SXin Li 
7370*67e74705SXin Li   if (!LHSOPT || !RHSOPT)
7371*67e74705SXin Li     return false;
7372*67e74705SXin Li 
7373*67e74705SXin Li   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7374*67e74705SXin Li          canAssignObjCInterfaces(RHSOPT, LHSOPT);
7375*67e74705SXin Li }
7376*67e74705SXin Li 
canBindObjCObjectType(QualType To,QualType From)7377*67e74705SXin Li bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7378*67e74705SXin Li   return canAssignObjCInterfaces(
7379*67e74705SXin Li                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7380*67e74705SXin Li                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7381*67e74705SXin Li }
7382*67e74705SXin Li 
7383*67e74705SXin Li /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7384*67e74705SXin Li /// both shall have the identically qualified version of a compatible type.
7385*67e74705SXin Li /// C99 6.2.7p1: Two types have compatible types if their types are the
7386*67e74705SXin Li /// same. See 6.7.[2,3,5] for additional rules.
typesAreCompatible(QualType LHS,QualType RHS,bool CompareUnqualified)7387*67e74705SXin Li bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7388*67e74705SXin Li                                     bool CompareUnqualified) {
7389*67e74705SXin Li   if (getLangOpts().CPlusPlus)
7390*67e74705SXin Li     return hasSameType(LHS, RHS);
7391*67e74705SXin Li 
7392*67e74705SXin Li   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7393*67e74705SXin Li }
7394*67e74705SXin Li 
propertyTypesAreCompatible(QualType LHS,QualType RHS)7395*67e74705SXin Li bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7396*67e74705SXin Li   return typesAreCompatible(LHS, RHS);
7397*67e74705SXin Li }
7398*67e74705SXin Li 
typesAreBlockPointerCompatible(QualType LHS,QualType RHS)7399*67e74705SXin Li bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7400*67e74705SXin Li   return !mergeTypes(LHS, RHS, true).isNull();
7401*67e74705SXin Li }
7402*67e74705SXin Li 
7403*67e74705SXin Li /// mergeTransparentUnionType - if T is a transparent union type and a member
7404*67e74705SXin Li /// of T is compatible with SubType, return the merged type, else return
7405*67e74705SXin Li /// QualType()
mergeTransparentUnionType(QualType T,QualType SubType,bool OfBlockPointer,bool Unqualified)7406*67e74705SXin Li QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7407*67e74705SXin Li                                                bool OfBlockPointer,
7408*67e74705SXin Li                                                bool Unqualified) {
7409*67e74705SXin Li   if (const RecordType *UT = T->getAsUnionType()) {
7410*67e74705SXin Li     RecordDecl *UD = UT->getDecl();
7411*67e74705SXin Li     if (UD->hasAttr<TransparentUnionAttr>()) {
7412*67e74705SXin Li       for (const auto *I : UD->fields()) {
7413*67e74705SXin Li         QualType ET = I->getType().getUnqualifiedType();
7414*67e74705SXin Li         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7415*67e74705SXin Li         if (!MT.isNull())
7416*67e74705SXin Li           return MT;
7417*67e74705SXin Li       }
7418*67e74705SXin Li     }
7419*67e74705SXin Li   }
7420*67e74705SXin Li 
7421*67e74705SXin Li   return QualType();
7422*67e74705SXin Li }
7423*67e74705SXin Li 
7424*67e74705SXin Li /// mergeFunctionParameterTypes - merge two types which appear as function
7425*67e74705SXin Li /// parameter types
mergeFunctionParameterTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7426*67e74705SXin Li QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7427*67e74705SXin Li                                                  bool OfBlockPointer,
7428*67e74705SXin Li                                                  bool Unqualified) {
7429*67e74705SXin Li   // GNU extension: two types are compatible if they appear as a function
7430*67e74705SXin Li   // argument, one of the types is a transparent union type and the other
7431*67e74705SXin Li   // type is compatible with a union member
7432*67e74705SXin Li   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7433*67e74705SXin Li                                               Unqualified);
7434*67e74705SXin Li   if (!lmerge.isNull())
7435*67e74705SXin Li     return lmerge;
7436*67e74705SXin Li 
7437*67e74705SXin Li   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7438*67e74705SXin Li                                               Unqualified);
7439*67e74705SXin Li   if (!rmerge.isNull())
7440*67e74705SXin Li     return rmerge;
7441*67e74705SXin Li 
7442*67e74705SXin Li   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7443*67e74705SXin Li }
7444*67e74705SXin Li 
mergeFunctionTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7445*67e74705SXin Li QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7446*67e74705SXin Li                                         bool OfBlockPointer,
7447*67e74705SXin Li                                         bool Unqualified) {
7448*67e74705SXin Li   const FunctionType *lbase = lhs->getAs<FunctionType>();
7449*67e74705SXin Li   const FunctionType *rbase = rhs->getAs<FunctionType>();
7450*67e74705SXin Li   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7451*67e74705SXin Li   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7452*67e74705SXin Li   bool allLTypes = true;
7453*67e74705SXin Li   bool allRTypes = true;
7454*67e74705SXin Li 
7455*67e74705SXin Li   // Check return type
7456*67e74705SXin Li   QualType retType;
7457*67e74705SXin Li   if (OfBlockPointer) {
7458*67e74705SXin Li     QualType RHS = rbase->getReturnType();
7459*67e74705SXin Li     QualType LHS = lbase->getReturnType();
7460*67e74705SXin Li     bool UnqualifiedResult = Unqualified;
7461*67e74705SXin Li     if (!UnqualifiedResult)
7462*67e74705SXin Li       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7463*67e74705SXin Li     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7464*67e74705SXin Li   }
7465*67e74705SXin Li   else
7466*67e74705SXin Li     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7467*67e74705SXin Li                          Unqualified);
7468*67e74705SXin Li   if (retType.isNull()) return QualType();
7469*67e74705SXin Li 
7470*67e74705SXin Li   if (Unqualified)
7471*67e74705SXin Li     retType = retType.getUnqualifiedType();
7472*67e74705SXin Li 
7473*67e74705SXin Li   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7474*67e74705SXin Li   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7475*67e74705SXin Li   if (Unqualified) {
7476*67e74705SXin Li     LRetType = LRetType.getUnqualifiedType();
7477*67e74705SXin Li     RRetType = RRetType.getUnqualifiedType();
7478*67e74705SXin Li   }
7479*67e74705SXin Li 
7480*67e74705SXin Li   if (getCanonicalType(retType) != LRetType)
7481*67e74705SXin Li     allLTypes = false;
7482*67e74705SXin Li   if (getCanonicalType(retType) != RRetType)
7483*67e74705SXin Li     allRTypes = false;
7484*67e74705SXin Li 
7485*67e74705SXin Li   // FIXME: double check this
7486*67e74705SXin Li   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7487*67e74705SXin Li   //                           rbase->getRegParmAttr() != 0 &&
7488*67e74705SXin Li   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7489*67e74705SXin Li   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7490*67e74705SXin Li   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7491*67e74705SXin Li 
7492*67e74705SXin Li   // Compatible functions must have compatible calling conventions
7493*67e74705SXin Li   if (lbaseInfo.getCC() != rbaseInfo.getCC())
7494*67e74705SXin Li     return QualType();
7495*67e74705SXin Li 
7496*67e74705SXin Li   // Regparm is part of the calling convention.
7497*67e74705SXin Li   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7498*67e74705SXin Li     return QualType();
7499*67e74705SXin Li   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7500*67e74705SXin Li     return QualType();
7501*67e74705SXin Li 
7502*67e74705SXin Li   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7503*67e74705SXin Li     return QualType();
7504*67e74705SXin Li 
7505*67e74705SXin Li   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7506*67e74705SXin Li   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7507*67e74705SXin Li 
7508*67e74705SXin Li   if (lbaseInfo.getNoReturn() != NoReturn)
7509*67e74705SXin Li     allLTypes = false;
7510*67e74705SXin Li   if (rbaseInfo.getNoReturn() != NoReturn)
7511*67e74705SXin Li     allRTypes = false;
7512*67e74705SXin Li 
7513*67e74705SXin Li   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7514*67e74705SXin Li 
7515*67e74705SXin Li   if (lproto && rproto) { // two C99 style function prototypes
7516*67e74705SXin Li     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7517*67e74705SXin Li            "C++ shouldn't be here");
7518*67e74705SXin Li     // Compatible functions must have the same number of parameters
7519*67e74705SXin Li     if (lproto->getNumParams() != rproto->getNumParams())
7520*67e74705SXin Li       return QualType();
7521*67e74705SXin Li 
7522*67e74705SXin Li     // Variadic and non-variadic functions aren't compatible
7523*67e74705SXin Li     if (lproto->isVariadic() != rproto->isVariadic())
7524*67e74705SXin Li       return QualType();
7525*67e74705SXin Li 
7526*67e74705SXin Li     if (lproto->getTypeQuals() != rproto->getTypeQuals())
7527*67e74705SXin Li       return QualType();
7528*67e74705SXin Li 
7529*67e74705SXin Li     if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7530*67e74705SXin Li       return QualType();
7531*67e74705SXin Li 
7532*67e74705SXin Li     // Check parameter type compatibility
7533*67e74705SXin Li     SmallVector<QualType, 10> types;
7534*67e74705SXin Li     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7535*67e74705SXin Li       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7536*67e74705SXin Li       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7537*67e74705SXin Li       QualType paramType = mergeFunctionParameterTypes(
7538*67e74705SXin Li           lParamType, rParamType, OfBlockPointer, Unqualified);
7539*67e74705SXin Li       if (paramType.isNull())
7540*67e74705SXin Li         return QualType();
7541*67e74705SXin Li 
7542*67e74705SXin Li       if (Unqualified)
7543*67e74705SXin Li         paramType = paramType.getUnqualifiedType();
7544*67e74705SXin Li 
7545*67e74705SXin Li       types.push_back(paramType);
7546*67e74705SXin Li       if (Unqualified) {
7547*67e74705SXin Li         lParamType = lParamType.getUnqualifiedType();
7548*67e74705SXin Li         rParamType = rParamType.getUnqualifiedType();
7549*67e74705SXin Li       }
7550*67e74705SXin Li 
7551*67e74705SXin Li       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7552*67e74705SXin Li         allLTypes = false;
7553*67e74705SXin Li       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7554*67e74705SXin Li         allRTypes = false;
7555*67e74705SXin Li     }
7556*67e74705SXin Li 
7557*67e74705SXin Li     if (allLTypes) return lhs;
7558*67e74705SXin Li     if (allRTypes) return rhs;
7559*67e74705SXin Li 
7560*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7561*67e74705SXin Li     EPI.ExtInfo = einfo;
7562*67e74705SXin Li     return getFunctionType(retType, types, EPI);
7563*67e74705SXin Li   }
7564*67e74705SXin Li 
7565*67e74705SXin Li   if (lproto) allRTypes = false;
7566*67e74705SXin Li   if (rproto) allLTypes = false;
7567*67e74705SXin Li 
7568*67e74705SXin Li   const FunctionProtoType *proto = lproto ? lproto : rproto;
7569*67e74705SXin Li   if (proto) {
7570*67e74705SXin Li     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7571*67e74705SXin Li     if (proto->isVariadic()) return QualType();
7572*67e74705SXin Li     // Check that the types are compatible with the types that
7573*67e74705SXin Li     // would result from default argument promotions (C99 6.7.5.3p15).
7574*67e74705SXin Li     // The only types actually affected are promotable integer
7575*67e74705SXin Li     // types and floats, which would be passed as a different
7576*67e74705SXin Li     // type depending on whether the prototype is visible.
7577*67e74705SXin Li     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7578*67e74705SXin Li       QualType paramTy = proto->getParamType(i);
7579*67e74705SXin Li 
7580*67e74705SXin Li       // Look at the converted type of enum types, since that is the type used
7581*67e74705SXin Li       // to pass enum values.
7582*67e74705SXin Li       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7583*67e74705SXin Li         paramTy = Enum->getDecl()->getIntegerType();
7584*67e74705SXin Li         if (paramTy.isNull())
7585*67e74705SXin Li           return QualType();
7586*67e74705SXin Li       }
7587*67e74705SXin Li 
7588*67e74705SXin Li       if (paramTy->isPromotableIntegerType() ||
7589*67e74705SXin Li           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7590*67e74705SXin Li         return QualType();
7591*67e74705SXin Li     }
7592*67e74705SXin Li 
7593*67e74705SXin Li     if (allLTypes) return lhs;
7594*67e74705SXin Li     if (allRTypes) return rhs;
7595*67e74705SXin Li 
7596*67e74705SXin Li     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7597*67e74705SXin Li     EPI.ExtInfo = einfo;
7598*67e74705SXin Li     return getFunctionType(retType, proto->getParamTypes(), EPI);
7599*67e74705SXin Li   }
7600*67e74705SXin Li 
7601*67e74705SXin Li   if (allLTypes) return lhs;
7602*67e74705SXin Li   if (allRTypes) return rhs;
7603*67e74705SXin Li   return getFunctionNoProtoType(retType, einfo);
7604*67e74705SXin Li }
7605*67e74705SXin Li 
7606*67e74705SXin Li /// Given that we have an enum type and a non-enum type, try to merge them.
mergeEnumWithInteger(ASTContext & Context,const EnumType * ET,QualType other,bool isBlockReturnType)7607*67e74705SXin Li static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7608*67e74705SXin Li                                      QualType other, bool isBlockReturnType) {
7609*67e74705SXin Li   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7610*67e74705SXin Li   // a signed integer type, or an unsigned integer type.
7611*67e74705SXin Li   // Compatibility is based on the underlying type, not the promotion
7612*67e74705SXin Li   // type.
7613*67e74705SXin Li   QualType underlyingType = ET->getDecl()->getIntegerType();
7614*67e74705SXin Li   if (underlyingType.isNull()) return QualType();
7615*67e74705SXin Li   if (Context.hasSameType(underlyingType, other))
7616*67e74705SXin Li     return other;
7617*67e74705SXin Li 
7618*67e74705SXin Li   // In block return types, we're more permissive and accept any
7619*67e74705SXin Li   // integral type of the same size.
7620*67e74705SXin Li   if (isBlockReturnType && other->isIntegerType() &&
7621*67e74705SXin Li       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7622*67e74705SXin Li     return other;
7623*67e74705SXin Li 
7624*67e74705SXin Li   return QualType();
7625*67e74705SXin Li }
7626*67e74705SXin Li 
mergeTypes(QualType LHS,QualType RHS,bool OfBlockPointer,bool Unqualified,bool BlockReturnType)7627*67e74705SXin Li QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7628*67e74705SXin Li                                 bool OfBlockPointer,
7629*67e74705SXin Li                                 bool Unqualified, bool BlockReturnType) {
7630*67e74705SXin Li   // C++ [expr]: If an expression initially has the type "reference to T", the
7631*67e74705SXin Li   // type is adjusted to "T" prior to any further analysis, the expression
7632*67e74705SXin Li   // designates the object or function denoted by the reference, and the
7633*67e74705SXin Li   // expression is an lvalue unless the reference is an rvalue reference and
7634*67e74705SXin Li   // the expression is a function call (possibly inside parentheses).
7635*67e74705SXin Li   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7636*67e74705SXin Li   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7637*67e74705SXin Li 
7638*67e74705SXin Li   if (Unqualified) {
7639*67e74705SXin Li     LHS = LHS.getUnqualifiedType();
7640*67e74705SXin Li     RHS = RHS.getUnqualifiedType();
7641*67e74705SXin Li   }
7642*67e74705SXin Li 
7643*67e74705SXin Li   QualType LHSCan = getCanonicalType(LHS),
7644*67e74705SXin Li            RHSCan = getCanonicalType(RHS);
7645*67e74705SXin Li 
7646*67e74705SXin Li   // If two types are identical, they are compatible.
7647*67e74705SXin Li   if (LHSCan == RHSCan)
7648*67e74705SXin Li     return LHS;
7649*67e74705SXin Li 
7650*67e74705SXin Li   // If the qualifiers are different, the types aren't compatible... mostly.
7651*67e74705SXin Li   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7652*67e74705SXin Li   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7653*67e74705SXin Li   if (LQuals != RQuals) {
7654*67e74705SXin Li     if (getLangOpts().OpenCL) {
7655*67e74705SXin Li       if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
7656*67e74705SXin Li           LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7657*67e74705SXin Li         return QualType();
7658*67e74705SXin Li       if (LQuals.isAddressSpaceSupersetOf(RQuals))
7659*67e74705SXin Li         return LHS;
7660*67e74705SXin Li       if (RQuals.isAddressSpaceSupersetOf(LQuals))
7661*67e74705SXin Li         return RHS;
7662*67e74705SXin Li     }
7663*67e74705SXin Li     // If any of these qualifiers are different, we have a type
7664*67e74705SXin Li     // mismatch.
7665*67e74705SXin Li     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7666*67e74705SXin Li         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7667*67e74705SXin Li         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7668*67e74705SXin Li       return QualType();
7669*67e74705SXin Li 
7670*67e74705SXin Li     // Exactly one GC qualifier difference is allowed: __strong is
7671*67e74705SXin Li     // okay if the other type has no GC qualifier but is an Objective
7672*67e74705SXin Li     // C object pointer (i.e. implicitly strong by default).  We fix
7673*67e74705SXin Li     // this by pretending that the unqualified type was actually
7674*67e74705SXin Li     // qualified __strong.
7675*67e74705SXin Li     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7676*67e74705SXin Li     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7677*67e74705SXin Li     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7678*67e74705SXin Li 
7679*67e74705SXin Li     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7680*67e74705SXin Li       return QualType();
7681*67e74705SXin Li 
7682*67e74705SXin Li     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7683*67e74705SXin Li       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7684*67e74705SXin Li     }
7685*67e74705SXin Li     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7686*67e74705SXin Li       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7687*67e74705SXin Li     }
7688*67e74705SXin Li     return QualType();
7689*67e74705SXin Li   }
7690*67e74705SXin Li 
7691*67e74705SXin Li   // Okay, qualifiers are equal.
7692*67e74705SXin Li 
7693*67e74705SXin Li   Type::TypeClass LHSClass = LHSCan->getTypeClass();
7694*67e74705SXin Li   Type::TypeClass RHSClass = RHSCan->getTypeClass();
7695*67e74705SXin Li 
7696*67e74705SXin Li   // We want to consider the two function types to be the same for these
7697*67e74705SXin Li   // comparisons, just force one to the other.
7698*67e74705SXin Li   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7699*67e74705SXin Li   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7700*67e74705SXin Li 
7701*67e74705SXin Li   // Same as above for arrays
7702*67e74705SXin Li   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7703*67e74705SXin Li     LHSClass = Type::ConstantArray;
7704*67e74705SXin Li   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7705*67e74705SXin Li     RHSClass = Type::ConstantArray;
7706*67e74705SXin Li 
7707*67e74705SXin Li   // ObjCInterfaces are just specialized ObjCObjects.
7708*67e74705SXin Li   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7709*67e74705SXin Li   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7710*67e74705SXin Li 
7711*67e74705SXin Li   // Canonicalize ExtVector -> Vector.
7712*67e74705SXin Li   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7713*67e74705SXin Li   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7714*67e74705SXin Li 
7715*67e74705SXin Li   // If the canonical type classes don't match.
7716*67e74705SXin Li   if (LHSClass != RHSClass) {
7717*67e74705SXin Li     // Note that we only have special rules for turning block enum
7718*67e74705SXin Li     // returns into block int returns, not vice-versa.
7719*67e74705SXin Li     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7720*67e74705SXin Li       return mergeEnumWithInteger(*this, ETy, RHS, false);
7721*67e74705SXin Li     }
7722*67e74705SXin Li     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7723*67e74705SXin Li       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7724*67e74705SXin Li     }
7725*67e74705SXin Li     // allow block pointer type to match an 'id' type.
7726*67e74705SXin Li     if (OfBlockPointer && !BlockReturnType) {
7727*67e74705SXin Li        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7728*67e74705SXin Li          return LHS;
7729*67e74705SXin Li       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7730*67e74705SXin Li         return RHS;
7731*67e74705SXin Li     }
7732*67e74705SXin Li 
7733*67e74705SXin Li     return QualType();
7734*67e74705SXin Li   }
7735*67e74705SXin Li 
7736*67e74705SXin Li   // The canonical type classes match.
7737*67e74705SXin Li   switch (LHSClass) {
7738*67e74705SXin Li #define TYPE(Class, Base)
7739*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
7740*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7741*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7742*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7743*67e74705SXin Li #include "clang/AST/TypeNodes.def"
7744*67e74705SXin Li     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7745*67e74705SXin Li 
7746*67e74705SXin Li   case Type::Auto:
7747*67e74705SXin Li   case Type::LValueReference:
7748*67e74705SXin Li   case Type::RValueReference:
7749*67e74705SXin Li   case Type::MemberPointer:
7750*67e74705SXin Li     llvm_unreachable("C++ should never be in mergeTypes");
7751*67e74705SXin Li 
7752*67e74705SXin Li   case Type::ObjCInterface:
7753*67e74705SXin Li   case Type::IncompleteArray:
7754*67e74705SXin Li   case Type::VariableArray:
7755*67e74705SXin Li   case Type::FunctionProto:
7756*67e74705SXin Li   case Type::ExtVector:
7757*67e74705SXin Li     llvm_unreachable("Types are eliminated above");
7758*67e74705SXin Li 
7759*67e74705SXin Li   case Type::Pointer:
7760*67e74705SXin Li   {
7761*67e74705SXin Li     // Merge two pointer types, while trying to preserve typedef info
7762*67e74705SXin Li     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7763*67e74705SXin Li     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7764*67e74705SXin Li     if (Unqualified) {
7765*67e74705SXin Li       LHSPointee = LHSPointee.getUnqualifiedType();
7766*67e74705SXin Li       RHSPointee = RHSPointee.getUnqualifiedType();
7767*67e74705SXin Li     }
7768*67e74705SXin Li     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7769*67e74705SXin Li                                      Unqualified);
7770*67e74705SXin Li     if (ResultType.isNull()) return QualType();
7771*67e74705SXin Li     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7772*67e74705SXin Li       return LHS;
7773*67e74705SXin Li     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7774*67e74705SXin Li       return RHS;
7775*67e74705SXin Li     return getPointerType(ResultType);
7776*67e74705SXin Li   }
7777*67e74705SXin Li   case Type::BlockPointer:
7778*67e74705SXin Li   {
7779*67e74705SXin Li     // Merge two block pointer types, while trying to preserve typedef info
7780*67e74705SXin Li     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7781*67e74705SXin Li     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7782*67e74705SXin Li     if (Unqualified) {
7783*67e74705SXin Li       LHSPointee = LHSPointee.getUnqualifiedType();
7784*67e74705SXin Li       RHSPointee = RHSPointee.getUnqualifiedType();
7785*67e74705SXin Li     }
7786*67e74705SXin Li     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7787*67e74705SXin Li                                      Unqualified);
7788*67e74705SXin Li     if (ResultType.isNull()) return QualType();
7789*67e74705SXin Li     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7790*67e74705SXin Li       return LHS;
7791*67e74705SXin Li     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7792*67e74705SXin Li       return RHS;
7793*67e74705SXin Li     return getBlockPointerType(ResultType);
7794*67e74705SXin Li   }
7795*67e74705SXin Li   case Type::Atomic:
7796*67e74705SXin Li   {
7797*67e74705SXin Li     // Merge two pointer types, while trying to preserve typedef info
7798*67e74705SXin Li     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7799*67e74705SXin Li     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7800*67e74705SXin Li     if (Unqualified) {
7801*67e74705SXin Li       LHSValue = LHSValue.getUnqualifiedType();
7802*67e74705SXin Li       RHSValue = RHSValue.getUnqualifiedType();
7803*67e74705SXin Li     }
7804*67e74705SXin Li     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7805*67e74705SXin Li                                      Unqualified);
7806*67e74705SXin Li     if (ResultType.isNull()) return QualType();
7807*67e74705SXin Li     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7808*67e74705SXin Li       return LHS;
7809*67e74705SXin Li     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7810*67e74705SXin Li       return RHS;
7811*67e74705SXin Li     return getAtomicType(ResultType);
7812*67e74705SXin Li   }
7813*67e74705SXin Li   case Type::ConstantArray:
7814*67e74705SXin Li   {
7815*67e74705SXin Li     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7816*67e74705SXin Li     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7817*67e74705SXin Li     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7818*67e74705SXin Li       return QualType();
7819*67e74705SXin Li 
7820*67e74705SXin Li     QualType LHSElem = getAsArrayType(LHS)->getElementType();
7821*67e74705SXin Li     QualType RHSElem = getAsArrayType(RHS)->getElementType();
7822*67e74705SXin Li     if (Unqualified) {
7823*67e74705SXin Li       LHSElem = LHSElem.getUnqualifiedType();
7824*67e74705SXin Li       RHSElem = RHSElem.getUnqualifiedType();
7825*67e74705SXin Li     }
7826*67e74705SXin Li 
7827*67e74705SXin Li     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7828*67e74705SXin Li     if (ResultType.isNull()) return QualType();
7829*67e74705SXin Li     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7830*67e74705SXin Li       return LHS;
7831*67e74705SXin Li     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7832*67e74705SXin Li       return RHS;
7833*67e74705SXin Li     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7834*67e74705SXin Li                                           ArrayType::ArraySizeModifier(), 0);
7835*67e74705SXin Li     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7836*67e74705SXin Li                                           ArrayType::ArraySizeModifier(), 0);
7837*67e74705SXin Li     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7838*67e74705SXin Li     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7839*67e74705SXin Li     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7840*67e74705SXin Li       return LHS;
7841*67e74705SXin Li     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7842*67e74705SXin Li       return RHS;
7843*67e74705SXin Li     if (LVAT) {
7844*67e74705SXin Li       // FIXME: This isn't correct! But tricky to implement because
7845*67e74705SXin Li       // the array's size has to be the size of LHS, but the type
7846*67e74705SXin Li       // has to be different.
7847*67e74705SXin Li       return LHS;
7848*67e74705SXin Li     }
7849*67e74705SXin Li     if (RVAT) {
7850*67e74705SXin Li       // FIXME: This isn't correct! But tricky to implement because
7851*67e74705SXin Li       // the array's size has to be the size of RHS, but the type
7852*67e74705SXin Li       // has to be different.
7853*67e74705SXin Li       return RHS;
7854*67e74705SXin Li     }
7855*67e74705SXin Li     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7856*67e74705SXin Li     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7857*67e74705SXin Li     return getIncompleteArrayType(ResultType,
7858*67e74705SXin Li                                   ArrayType::ArraySizeModifier(), 0);
7859*67e74705SXin Li   }
7860*67e74705SXin Li   case Type::FunctionNoProto:
7861*67e74705SXin Li     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7862*67e74705SXin Li   case Type::Record:
7863*67e74705SXin Li   case Type::Enum:
7864*67e74705SXin Li     return QualType();
7865*67e74705SXin Li   case Type::Builtin:
7866*67e74705SXin Li     // Only exactly equal builtin types are compatible, which is tested above.
7867*67e74705SXin Li     return QualType();
7868*67e74705SXin Li   case Type::Complex:
7869*67e74705SXin Li     // Distinct complex types are incompatible.
7870*67e74705SXin Li     return QualType();
7871*67e74705SXin Li   case Type::Vector:
7872*67e74705SXin Li     // FIXME: The merged type should be an ExtVector!
7873*67e74705SXin Li     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7874*67e74705SXin Li                              RHSCan->getAs<VectorType>()))
7875*67e74705SXin Li       return LHS;
7876*67e74705SXin Li     return QualType();
7877*67e74705SXin Li   case Type::ObjCObject: {
7878*67e74705SXin Li     // Check if the types are assignment compatible.
7879*67e74705SXin Li     // FIXME: This should be type compatibility, e.g. whether
7880*67e74705SXin Li     // "LHS x; RHS x;" at global scope is legal.
7881*67e74705SXin Li     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7882*67e74705SXin Li     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7883*67e74705SXin Li     if (canAssignObjCInterfaces(LHSIface, RHSIface))
7884*67e74705SXin Li       return LHS;
7885*67e74705SXin Li 
7886*67e74705SXin Li     return QualType();
7887*67e74705SXin Li   }
7888*67e74705SXin Li   case Type::ObjCObjectPointer: {
7889*67e74705SXin Li     if (OfBlockPointer) {
7890*67e74705SXin Li       if (canAssignObjCInterfacesInBlockPointer(
7891*67e74705SXin Li                                           LHS->getAs<ObjCObjectPointerType>(),
7892*67e74705SXin Li                                           RHS->getAs<ObjCObjectPointerType>(),
7893*67e74705SXin Li                                           BlockReturnType))
7894*67e74705SXin Li         return LHS;
7895*67e74705SXin Li       return QualType();
7896*67e74705SXin Li     }
7897*67e74705SXin Li     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7898*67e74705SXin Li                                 RHS->getAs<ObjCObjectPointerType>()))
7899*67e74705SXin Li       return LHS;
7900*67e74705SXin Li 
7901*67e74705SXin Li     return QualType();
7902*67e74705SXin Li   }
7903*67e74705SXin Li   case Type::Pipe:
7904*67e74705SXin Li   {
7905*67e74705SXin Li     // Merge two pointer types, while trying to preserve typedef info
7906*67e74705SXin Li     QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7907*67e74705SXin Li     QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7908*67e74705SXin Li     if (Unqualified) {
7909*67e74705SXin Li       LHSValue = LHSValue.getUnqualifiedType();
7910*67e74705SXin Li       RHSValue = RHSValue.getUnqualifiedType();
7911*67e74705SXin Li     }
7912*67e74705SXin Li     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7913*67e74705SXin Li                                      Unqualified);
7914*67e74705SXin Li     if (ResultType.isNull()) return QualType();
7915*67e74705SXin Li     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7916*67e74705SXin Li       return LHS;
7917*67e74705SXin Li     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7918*67e74705SXin Li       return RHS;
7919*67e74705SXin Li     return getPipeType(ResultType);
7920*67e74705SXin Li   }
7921*67e74705SXin Li   }
7922*67e74705SXin Li 
7923*67e74705SXin Li   llvm_unreachable("Invalid Type::Class!");
7924*67e74705SXin Li }
7925*67e74705SXin Li 
doFunctionTypesMatchOnExtParameterInfos(const FunctionProtoType * firstFnType,const FunctionProtoType * secondFnType)7926*67e74705SXin Li bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7927*67e74705SXin Li                    const FunctionProtoType *firstFnType,
7928*67e74705SXin Li                    const FunctionProtoType *secondFnType) {
7929*67e74705SXin Li   // Fast path: if the first type doesn't have ext parameter infos,
7930*67e74705SXin Li   // we match if and only if they second type also doesn't have them.
7931*67e74705SXin Li   if (!firstFnType->hasExtParameterInfos())
7932*67e74705SXin Li     return !secondFnType->hasExtParameterInfos();
7933*67e74705SXin Li 
7934*67e74705SXin Li   // Otherwise, we can only match if the second type has them.
7935*67e74705SXin Li   if (!secondFnType->hasExtParameterInfos())
7936*67e74705SXin Li     return false;
7937*67e74705SXin Li 
7938*67e74705SXin Li   auto firstEPI = firstFnType->getExtParameterInfos();
7939*67e74705SXin Li   auto secondEPI = secondFnType->getExtParameterInfos();
7940*67e74705SXin Li   assert(firstEPI.size() == secondEPI.size());
7941*67e74705SXin Li 
7942*67e74705SXin Li   for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7943*67e74705SXin Li     if (firstEPI[i] != secondEPI[i])
7944*67e74705SXin Li       return false;
7945*67e74705SXin Li   }
7946*67e74705SXin Li   return true;
7947*67e74705SXin Li }
7948*67e74705SXin Li 
ResetObjCLayout(const ObjCContainerDecl * CD)7949*67e74705SXin Li void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7950*67e74705SXin Li   ObjCLayouts[CD] = nullptr;
7951*67e74705SXin Li }
7952*67e74705SXin Li 
7953*67e74705SXin Li /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7954*67e74705SXin Li /// 'RHS' attributes and returns the merged version; including for function
7955*67e74705SXin Li /// return types.
mergeObjCGCQualifiers(QualType LHS,QualType RHS)7956*67e74705SXin Li QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7957*67e74705SXin Li   QualType LHSCan = getCanonicalType(LHS),
7958*67e74705SXin Li   RHSCan = getCanonicalType(RHS);
7959*67e74705SXin Li   // If two types are identical, they are compatible.
7960*67e74705SXin Li   if (LHSCan == RHSCan)
7961*67e74705SXin Li     return LHS;
7962*67e74705SXin Li   if (RHSCan->isFunctionType()) {
7963*67e74705SXin Li     if (!LHSCan->isFunctionType())
7964*67e74705SXin Li       return QualType();
7965*67e74705SXin Li     QualType OldReturnType =
7966*67e74705SXin Li         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7967*67e74705SXin Li     QualType NewReturnType =
7968*67e74705SXin Li         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7969*67e74705SXin Li     QualType ResReturnType =
7970*67e74705SXin Li       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7971*67e74705SXin Li     if (ResReturnType.isNull())
7972*67e74705SXin Li       return QualType();
7973*67e74705SXin Li     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7974*67e74705SXin Li       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7975*67e74705SXin Li       // In either case, use OldReturnType to build the new function type.
7976*67e74705SXin Li       const FunctionType *F = LHS->getAs<FunctionType>();
7977*67e74705SXin Li       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7978*67e74705SXin Li         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7979*67e74705SXin Li         EPI.ExtInfo = getFunctionExtInfo(LHS);
7980*67e74705SXin Li         QualType ResultType =
7981*67e74705SXin Li             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7982*67e74705SXin Li         return ResultType;
7983*67e74705SXin Li       }
7984*67e74705SXin Li     }
7985*67e74705SXin Li     return QualType();
7986*67e74705SXin Li   }
7987*67e74705SXin Li 
7988*67e74705SXin Li   // If the qualifiers are different, the types can still be merged.
7989*67e74705SXin Li   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7990*67e74705SXin Li   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7991*67e74705SXin Li   if (LQuals != RQuals) {
7992*67e74705SXin Li     // If any of these qualifiers are different, we have a type mismatch.
7993*67e74705SXin Li     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7994*67e74705SXin Li         LQuals.getAddressSpace() != RQuals.getAddressSpace())
7995*67e74705SXin Li       return QualType();
7996*67e74705SXin Li 
7997*67e74705SXin Li     // Exactly one GC qualifier difference is allowed: __strong is
7998*67e74705SXin Li     // okay if the other type has no GC qualifier but is an Objective
7999*67e74705SXin Li     // C object pointer (i.e. implicitly strong by default).  We fix
8000*67e74705SXin Li     // this by pretending that the unqualified type was actually
8001*67e74705SXin Li     // qualified __strong.
8002*67e74705SXin Li     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8003*67e74705SXin Li     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8004*67e74705SXin Li     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8005*67e74705SXin Li 
8006*67e74705SXin Li     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8007*67e74705SXin Li       return QualType();
8008*67e74705SXin Li 
8009*67e74705SXin Li     if (GC_L == Qualifiers::Strong)
8010*67e74705SXin Li       return LHS;
8011*67e74705SXin Li     if (GC_R == Qualifiers::Strong)
8012*67e74705SXin Li       return RHS;
8013*67e74705SXin Li     return QualType();
8014*67e74705SXin Li   }
8015*67e74705SXin Li 
8016*67e74705SXin Li   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8017*67e74705SXin Li     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8018*67e74705SXin Li     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8019*67e74705SXin Li     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8020*67e74705SXin Li     if (ResQT == LHSBaseQT)
8021*67e74705SXin Li       return LHS;
8022*67e74705SXin Li     if (ResQT == RHSBaseQT)
8023*67e74705SXin Li       return RHS;
8024*67e74705SXin Li   }
8025*67e74705SXin Li   return QualType();
8026*67e74705SXin Li }
8027*67e74705SXin Li 
8028*67e74705SXin Li //===----------------------------------------------------------------------===//
8029*67e74705SXin Li //                         Integer Predicates
8030*67e74705SXin Li //===----------------------------------------------------------------------===//
8031*67e74705SXin Li 
getIntWidth(QualType T) const8032*67e74705SXin Li unsigned ASTContext::getIntWidth(QualType T) const {
8033*67e74705SXin Li   if (const EnumType *ET = T->getAs<EnumType>())
8034*67e74705SXin Li     T = ET->getDecl()->getIntegerType();
8035*67e74705SXin Li   if (T->isBooleanType())
8036*67e74705SXin Li     return 1;
8037*67e74705SXin Li   // For builtin types, just use the standard type sizing method
8038*67e74705SXin Li   return (unsigned)getTypeSize(T);
8039*67e74705SXin Li }
8040*67e74705SXin Li 
getCorrespondingUnsignedType(QualType T) const8041*67e74705SXin Li QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8042*67e74705SXin Li   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8043*67e74705SXin Li 
8044*67e74705SXin Li   // Turn <4 x signed int> -> <4 x unsigned int>
8045*67e74705SXin Li   if (const VectorType *VTy = T->getAs<VectorType>())
8046*67e74705SXin Li     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8047*67e74705SXin Li                          VTy->getNumElements(), VTy->getVectorKind());
8048*67e74705SXin Li 
8049*67e74705SXin Li   // For enums, we return the unsigned version of the base type.
8050*67e74705SXin Li   if (const EnumType *ETy = T->getAs<EnumType>())
8051*67e74705SXin Li     T = ETy->getDecl()->getIntegerType();
8052*67e74705SXin Li 
8053*67e74705SXin Li   const BuiltinType *BTy = T->getAs<BuiltinType>();
8054*67e74705SXin Li   assert(BTy && "Unexpected signed integer type");
8055*67e74705SXin Li   switch (BTy->getKind()) {
8056*67e74705SXin Li   case BuiltinType::Char_S:
8057*67e74705SXin Li   case BuiltinType::SChar:
8058*67e74705SXin Li     return UnsignedCharTy;
8059*67e74705SXin Li   case BuiltinType::Short:
8060*67e74705SXin Li     return UnsignedShortTy;
8061*67e74705SXin Li   case BuiltinType::Int:
8062*67e74705SXin Li     return UnsignedIntTy;
8063*67e74705SXin Li   case BuiltinType::Long:
8064*67e74705SXin Li     return UnsignedLongTy;
8065*67e74705SXin Li   case BuiltinType::LongLong:
8066*67e74705SXin Li     return UnsignedLongLongTy;
8067*67e74705SXin Li   case BuiltinType::Int128:
8068*67e74705SXin Li     return UnsignedInt128Ty;
8069*67e74705SXin Li   default:
8070*67e74705SXin Li     llvm_unreachable("Unexpected signed integer type");
8071*67e74705SXin Li   }
8072*67e74705SXin Li }
8073*67e74705SXin Li 
~ASTMutationListener()8074*67e74705SXin Li ASTMutationListener::~ASTMutationListener() { }
8075*67e74705SXin Li 
DeducedReturnType(const FunctionDecl * FD,QualType ReturnType)8076*67e74705SXin Li void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8077*67e74705SXin Li                                             QualType ReturnType) {}
8078*67e74705SXin Li 
8079*67e74705SXin Li //===----------------------------------------------------------------------===//
8080*67e74705SXin Li //                          Builtin Type Computation
8081*67e74705SXin Li //===----------------------------------------------------------------------===//
8082*67e74705SXin Li 
8083*67e74705SXin Li /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8084*67e74705SXin Li /// pointer over the consumed characters.  This returns the resultant type.  If
8085*67e74705SXin Li /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8086*67e74705SXin Li /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
8087*67e74705SXin Li /// a vector of "i*".
8088*67e74705SXin Li ///
8089*67e74705SXin Li /// RequiresICE is filled in on return to indicate whether the value is required
8090*67e74705SXin Li /// to be an Integer Constant Expression.
DecodeTypeFromStr(const char * & Str,const ASTContext & Context,ASTContext::GetBuiltinTypeError & Error,bool & RequiresICE,bool AllowTypeModifiers)8091*67e74705SXin Li static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8092*67e74705SXin Li                                   ASTContext::GetBuiltinTypeError &Error,
8093*67e74705SXin Li                                   bool &RequiresICE,
8094*67e74705SXin Li                                   bool AllowTypeModifiers) {
8095*67e74705SXin Li   // Modifiers.
8096*67e74705SXin Li   int HowLong = 0;
8097*67e74705SXin Li   bool Signed = false, Unsigned = false;
8098*67e74705SXin Li   RequiresICE = false;
8099*67e74705SXin Li 
8100*67e74705SXin Li   // Read the prefixed modifiers first.
8101*67e74705SXin Li   bool Done = false;
8102*67e74705SXin Li   while (!Done) {
8103*67e74705SXin Li     switch (*Str++) {
8104*67e74705SXin Li     default: Done = true; --Str; break;
8105*67e74705SXin Li     case 'I':
8106*67e74705SXin Li       RequiresICE = true;
8107*67e74705SXin Li       break;
8108*67e74705SXin Li     case 'S':
8109*67e74705SXin Li       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8110*67e74705SXin Li       assert(!Signed && "Can't use 'S' modifier multiple times!");
8111*67e74705SXin Li       Signed = true;
8112*67e74705SXin Li       break;
8113*67e74705SXin Li     case 'U':
8114*67e74705SXin Li       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8115*67e74705SXin Li       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8116*67e74705SXin Li       Unsigned = true;
8117*67e74705SXin Li       break;
8118*67e74705SXin Li     case 'L':
8119*67e74705SXin Li       assert(HowLong <= 2 && "Can't have LLLL modifier");
8120*67e74705SXin Li       ++HowLong;
8121*67e74705SXin Li       break;
8122*67e74705SXin Li     case 'W':
8123*67e74705SXin Li       // This modifier represents int64 type.
8124*67e74705SXin Li       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8125*67e74705SXin Li       switch (Context.getTargetInfo().getInt64Type()) {
8126*67e74705SXin Li       default:
8127*67e74705SXin Li         llvm_unreachable("Unexpected integer type");
8128*67e74705SXin Li       case TargetInfo::SignedLong:
8129*67e74705SXin Li         HowLong = 1;
8130*67e74705SXin Li         break;
8131*67e74705SXin Li       case TargetInfo::SignedLongLong:
8132*67e74705SXin Li         HowLong = 2;
8133*67e74705SXin Li         break;
8134*67e74705SXin Li       }
8135*67e74705SXin Li     }
8136*67e74705SXin Li   }
8137*67e74705SXin Li 
8138*67e74705SXin Li   QualType Type;
8139*67e74705SXin Li 
8140*67e74705SXin Li   // Read the base type.
8141*67e74705SXin Li   switch (*Str++) {
8142*67e74705SXin Li   default: llvm_unreachable("Unknown builtin type letter!");
8143*67e74705SXin Li   case 'v':
8144*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned &&
8145*67e74705SXin Li            "Bad modifiers used with 'v'!");
8146*67e74705SXin Li     Type = Context.VoidTy;
8147*67e74705SXin Li     break;
8148*67e74705SXin Li   case 'h':
8149*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned &&
8150*67e74705SXin Li            "Bad modifiers used with 'h'!");
8151*67e74705SXin Li     Type = Context.HalfTy;
8152*67e74705SXin Li     break;
8153*67e74705SXin Li   case 'f':
8154*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned &&
8155*67e74705SXin Li            "Bad modifiers used with 'f'!");
8156*67e74705SXin Li     Type = Context.FloatTy;
8157*67e74705SXin Li     break;
8158*67e74705SXin Li   case 'd':
8159*67e74705SXin Li     assert(HowLong < 2 && !Signed && !Unsigned &&
8160*67e74705SXin Li            "Bad modifiers used with 'd'!");
8161*67e74705SXin Li     if (HowLong)
8162*67e74705SXin Li       Type = Context.LongDoubleTy;
8163*67e74705SXin Li     else
8164*67e74705SXin Li       Type = Context.DoubleTy;
8165*67e74705SXin Li     break;
8166*67e74705SXin Li   case 's':
8167*67e74705SXin Li     assert(HowLong == 0 && "Bad modifiers used with 's'!");
8168*67e74705SXin Li     if (Unsigned)
8169*67e74705SXin Li       Type = Context.UnsignedShortTy;
8170*67e74705SXin Li     else
8171*67e74705SXin Li       Type = Context.ShortTy;
8172*67e74705SXin Li     break;
8173*67e74705SXin Li   case 'i':
8174*67e74705SXin Li     if (HowLong == 3)
8175*67e74705SXin Li       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8176*67e74705SXin Li     else if (HowLong == 2)
8177*67e74705SXin Li       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8178*67e74705SXin Li     else if (HowLong == 1)
8179*67e74705SXin Li       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8180*67e74705SXin Li     else
8181*67e74705SXin Li       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8182*67e74705SXin Li     break;
8183*67e74705SXin Li   case 'c':
8184*67e74705SXin Li     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8185*67e74705SXin Li     if (Signed)
8186*67e74705SXin Li       Type = Context.SignedCharTy;
8187*67e74705SXin Li     else if (Unsigned)
8188*67e74705SXin Li       Type = Context.UnsignedCharTy;
8189*67e74705SXin Li     else
8190*67e74705SXin Li       Type = Context.CharTy;
8191*67e74705SXin Li     break;
8192*67e74705SXin Li   case 'b': // boolean
8193*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8194*67e74705SXin Li     Type = Context.BoolTy;
8195*67e74705SXin Li     break;
8196*67e74705SXin Li   case 'z':  // size_t.
8197*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8198*67e74705SXin Li     Type = Context.getSizeType();
8199*67e74705SXin Li     break;
8200*67e74705SXin Li   case 'F':
8201*67e74705SXin Li     Type = Context.getCFConstantStringType();
8202*67e74705SXin Li     break;
8203*67e74705SXin Li   case 'G':
8204*67e74705SXin Li     Type = Context.getObjCIdType();
8205*67e74705SXin Li     break;
8206*67e74705SXin Li   case 'H':
8207*67e74705SXin Li     Type = Context.getObjCSelType();
8208*67e74705SXin Li     break;
8209*67e74705SXin Li   case 'M':
8210*67e74705SXin Li     Type = Context.getObjCSuperType();
8211*67e74705SXin Li     break;
8212*67e74705SXin Li   case 'a':
8213*67e74705SXin Li     Type = Context.getBuiltinVaListType();
8214*67e74705SXin Li     assert(!Type.isNull() && "builtin va list type not initialized!");
8215*67e74705SXin Li     break;
8216*67e74705SXin Li   case 'A':
8217*67e74705SXin Li     // This is a "reference" to a va_list; however, what exactly
8218*67e74705SXin Li     // this means depends on how va_list is defined. There are two
8219*67e74705SXin Li     // different kinds of va_list: ones passed by value, and ones
8220*67e74705SXin Li     // passed by reference.  An example of a by-value va_list is
8221*67e74705SXin Li     // x86, where va_list is a char*. An example of by-ref va_list
8222*67e74705SXin Li     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8223*67e74705SXin Li     // we want this argument to be a char*&; for x86-64, we want
8224*67e74705SXin Li     // it to be a __va_list_tag*.
8225*67e74705SXin Li     Type = Context.getBuiltinVaListType();
8226*67e74705SXin Li     assert(!Type.isNull() && "builtin va list type not initialized!");
8227*67e74705SXin Li     if (Type->isArrayType())
8228*67e74705SXin Li       Type = Context.getArrayDecayedType(Type);
8229*67e74705SXin Li     else
8230*67e74705SXin Li       Type = Context.getLValueReferenceType(Type);
8231*67e74705SXin Li     break;
8232*67e74705SXin Li   case 'V': {
8233*67e74705SXin Li     char *End;
8234*67e74705SXin Li     unsigned NumElements = strtoul(Str, &End, 10);
8235*67e74705SXin Li     assert(End != Str && "Missing vector size");
8236*67e74705SXin Li     Str = End;
8237*67e74705SXin Li 
8238*67e74705SXin Li     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8239*67e74705SXin Li                                              RequiresICE, false);
8240*67e74705SXin Li     assert(!RequiresICE && "Can't require vector ICE");
8241*67e74705SXin Li 
8242*67e74705SXin Li     // TODO: No way to make AltiVec vectors in builtins yet.
8243*67e74705SXin Li     Type = Context.getVectorType(ElementType, NumElements,
8244*67e74705SXin Li                                  VectorType::GenericVector);
8245*67e74705SXin Li     break;
8246*67e74705SXin Li   }
8247*67e74705SXin Li   case 'E': {
8248*67e74705SXin Li     char *End;
8249*67e74705SXin Li 
8250*67e74705SXin Li     unsigned NumElements = strtoul(Str, &End, 10);
8251*67e74705SXin Li     assert(End != Str && "Missing vector size");
8252*67e74705SXin Li 
8253*67e74705SXin Li     Str = End;
8254*67e74705SXin Li 
8255*67e74705SXin Li     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8256*67e74705SXin Li                                              false);
8257*67e74705SXin Li     Type = Context.getExtVectorType(ElementType, NumElements);
8258*67e74705SXin Li     break;
8259*67e74705SXin Li   }
8260*67e74705SXin Li   case 'X': {
8261*67e74705SXin Li     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8262*67e74705SXin Li                                              false);
8263*67e74705SXin Li     assert(!RequiresICE && "Can't require complex ICE");
8264*67e74705SXin Li     Type = Context.getComplexType(ElementType);
8265*67e74705SXin Li     break;
8266*67e74705SXin Li   }
8267*67e74705SXin Li   case 'Y' : {
8268*67e74705SXin Li     Type = Context.getPointerDiffType();
8269*67e74705SXin Li     break;
8270*67e74705SXin Li   }
8271*67e74705SXin Li   case 'P':
8272*67e74705SXin Li     Type = Context.getFILEType();
8273*67e74705SXin Li     if (Type.isNull()) {
8274*67e74705SXin Li       Error = ASTContext::GE_Missing_stdio;
8275*67e74705SXin Li       return QualType();
8276*67e74705SXin Li     }
8277*67e74705SXin Li     break;
8278*67e74705SXin Li   case 'J':
8279*67e74705SXin Li     if (Signed)
8280*67e74705SXin Li       Type = Context.getsigjmp_bufType();
8281*67e74705SXin Li     else
8282*67e74705SXin Li       Type = Context.getjmp_bufType();
8283*67e74705SXin Li 
8284*67e74705SXin Li     if (Type.isNull()) {
8285*67e74705SXin Li       Error = ASTContext::GE_Missing_setjmp;
8286*67e74705SXin Li       return QualType();
8287*67e74705SXin Li     }
8288*67e74705SXin Li     break;
8289*67e74705SXin Li   case 'K':
8290*67e74705SXin Li     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8291*67e74705SXin Li     Type = Context.getucontext_tType();
8292*67e74705SXin Li 
8293*67e74705SXin Li     if (Type.isNull()) {
8294*67e74705SXin Li       Error = ASTContext::GE_Missing_ucontext;
8295*67e74705SXin Li       return QualType();
8296*67e74705SXin Li     }
8297*67e74705SXin Li     break;
8298*67e74705SXin Li   case 'p':
8299*67e74705SXin Li     Type = Context.getProcessIDType();
8300*67e74705SXin Li     break;
8301*67e74705SXin Li   }
8302*67e74705SXin Li 
8303*67e74705SXin Li   // If there are modifiers and if we're allowed to parse them, go for it.
8304*67e74705SXin Li   Done = !AllowTypeModifiers;
8305*67e74705SXin Li   while (!Done) {
8306*67e74705SXin Li     switch (char c = *Str++) {
8307*67e74705SXin Li     default: Done = true; --Str; break;
8308*67e74705SXin Li     case '*':
8309*67e74705SXin Li     case '&': {
8310*67e74705SXin Li       // Both pointers and references can have their pointee types
8311*67e74705SXin Li       // qualified with an address space.
8312*67e74705SXin Li       char *End;
8313*67e74705SXin Li       unsigned AddrSpace = strtoul(Str, &End, 10);
8314*67e74705SXin Li       if (End != Str && AddrSpace != 0) {
8315*67e74705SXin Li         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8316*67e74705SXin Li         Str = End;
8317*67e74705SXin Li       }
8318*67e74705SXin Li       if (c == '*')
8319*67e74705SXin Li         Type = Context.getPointerType(Type);
8320*67e74705SXin Li       else
8321*67e74705SXin Li         Type = Context.getLValueReferenceType(Type);
8322*67e74705SXin Li       break;
8323*67e74705SXin Li     }
8324*67e74705SXin Li     // FIXME: There's no way to have a built-in with an rvalue ref arg.
8325*67e74705SXin Li     case 'C':
8326*67e74705SXin Li       Type = Type.withConst();
8327*67e74705SXin Li       break;
8328*67e74705SXin Li     case 'D':
8329*67e74705SXin Li       Type = Context.getVolatileType(Type);
8330*67e74705SXin Li       break;
8331*67e74705SXin Li     case 'R':
8332*67e74705SXin Li       Type = Type.withRestrict();
8333*67e74705SXin Li       break;
8334*67e74705SXin Li     }
8335*67e74705SXin Li   }
8336*67e74705SXin Li 
8337*67e74705SXin Li   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8338*67e74705SXin Li          "Integer constant 'I' type must be an integer");
8339*67e74705SXin Li 
8340*67e74705SXin Li   return Type;
8341*67e74705SXin Li }
8342*67e74705SXin Li 
8343*67e74705SXin Li /// GetBuiltinType - Return the type for the specified builtin.
GetBuiltinType(unsigned Id,GetBuiltinTypeError & Error,unsigned * IntegerConstantArgs) const8344*67e74705SXin Li QualType ASTContext::GetBuiltinType(unsigned Id,
8345*67e74705SXin Li                                     GetBuiltinTypeError &Error,
8346*67e74705SXin Li                                     unsigned *IntegerConstantArgs) const {
8347*67e74705SXin Li   const char *TypeStr = BuiltinInfo.getTypeString(Id);
8348*67e74705SXin Li 
8349*67e74705SXin Li   SmallVector<QualType, 8> ArgTypes;
8350*67e74705SXin Li 
8351*67e74705SXin Li   bool RequiresICE = false;
8352*67e74705SXin Li   Error = GE_None;
8353*67e74705SXin Li   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8354*67e74705SXin Li                                        RequiresICE, true);
8355*67e74705SXin Li   if (Error != GE_None)
8356*67e74705SXin Li     return QualType();
8357*67e74705SXin Li 
8358*67e74705SXin Li   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8359*67e74705SXin Li 
8360*67e74705SXin Li   while (TypeStr[0] && TypeStr[0] != '.') {
8361*67e74705SXin Li     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8362*67e74705SXin Li     if (Error != GE_None)
8363*67e74705SXin Li       return QualType();
8364*67e74705SXin Li 
8365*67e74705SXin Li     // If this argument is required to be an IntegerConstantExpression and the
8366*67e74705SXin Li     // caller cares, fill in the bitmask we return.
8367*67e74705SXin Li     if (RequiresICE && IntegerConstantArgs)
8368*67e74705SXin Li       *IntegerConstantArgs |= 1 << ArgTypes.size();
8369*67e74705SXin Li 
8370*67e74705SXin Li     // Do array -> pointer decay.  The builtin should use the decayed type.
8371*67e74705SXin Li     if (Ty->isArrayType())
8372*67e74705SXin Li       Ty = getArrayDecayedType(Ty);
8373*67e74705SXin Li 
8374*67e74705SXin Li     ArgTypes.push_back(Ty);
8375*67e74705SXin Li   }
8376*67e74705SXin Li 
8377*67e74705SXin Li   if (Id == Builtin::BI__GetExceptionInfo)
8378*67e74705SXin Li     return QualType();
8379*67e74705SXin Li 
8380*67e74705SXin Li   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8381*67e74705SXin Li          "'.' should only occur at end of builtin type list!");
8382*67e74705SXin Li 
8383*67e74705SXin Li   FunctionType::ExtInfo EI(CC_C);
8384*67e74705SXin Li   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8385*67e74705SXin Li 
8386*67e74705SXin Li   bool Variadic = (TypeStr[0] == '.');
8387*67e74705SXin Li 
8388*67e74705SXin Li   // We really shouldn't be making a no-proto type here, especially in C++.
8389*67e74705SXin Li   if (ArgTypes.empty() && Variadic)
8390*67e74705SXin Li     return getFunctionNoProtoType(ResType, EI);
8391*67e74705SXin Li 
8392*67e74705SXin Li   FunctionProtoType::ExtProtoInfo EPI;
8393*67e74705SXin Li   EPI.ExtInfo = EI;
8394*67e74705SXin Li   EPI.Variadic = Variadic;
8395*67e74705SXin Li 
8396*67e74705SXin Li   return getFunctionType(ResType, ArgTypes, EPI);
8397*67e74705SXin Li }
8398*67e74705SXin Li 
basicGVALinkageForFunction(const ASTContext & Context,const FunctionDecl * FD)8399*67e74705SXin Li static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8400*67e74705SXin Li                                              const FunctionDecl *FD) {
8401*67e74705SXin Li   if (!FD->isExternallyVisible())
8402*67e74705SXin Li     return GVA_Internal;
8403*67e74705SXin Li 
8404*67e74705SXin Li   GVALinkage External = GVA_StrongExternal;
8405*67e74705SXin Li   switch (FD->getTemplateSpecializationKind()) {
8406*67e74705SXin Li   case TSK_Undeclared:
8407*67e74705SXin Li   case TSK_ExplicitSpecialization:
8408*67e74705SXin Li     External = GVA_StrongExternal;
8409*67e74705SXin Li     break;
8410*67e74705SXin Li 
8411*67e74705SXin Li   case TSK_ExplicitInstantiationDefinition:
8412*67e74705SXin Li     return GVA_StrongODR;
8413*67e74705SXin Li 
8414*67e74705SXin Li   // C++11 [temp.explicit]p10:
8415*67e74705SXin Li   //   [ Note: The intent is that an inline function that is the subject of
8416*67e74705SXin Li   //   an explicit instantiation declaration will still be implicitly
8417*67e74705SXin Li   //   instantiated when used so that the body can be considered for
8418*67e74705SXin Li   //   inlining, but that no out-of-line copy of the inline function would be
8419*67e74705SXin Li   //   generated in the translation unit. -- end note ]
8420*67e74705SXin Li   case TSK_ExplicitInstantiationDeclaration:
8421*67e74705SXin Li     return GVA_AvailableExternally;
8422*67e74705SXin Li 
8423*67e74705SXin Li   case TSK_ImplicitInstantiation:
8424*67e74705SXin Li     External = GVA_DiscardableODR;
8425*67e74705SXin Li     break;
8426*67e74705SXin Li   }
8427*67e74705SXin Li 
8428*67e74705SXin Li   if (!FD->isInlined())
8429*67e74705SXin Li     return External;
8430*67e74705SXin Li 
8431*67e74705SXin Li   if ((!Context.getLangOpts().CPlusPlus &&
8432*67e74705SXin Li        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8433*67e74705SXin Li        !FD->hasAttr<DLLExportAttr>()) ||
8434*67e74705SXin Li       FD->hasAttr<GNUInlineAttr>()) {
8435*67e74705SXin Li     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8436*67e74705SXin Li 
8437*67e74705SXin Li     // GNU or C99 inline semantics. Determine whether this symbol should be
8438*67e74705SXin Li     // externally visible.
8439*67e74705SXin Li     if (FD->isInlineDefinitionExternallyVisible())
8440*67e74705SXin Li       return External;
8441*67e74705SXin Li 
8442*67e74705SXin Li     // C99 inline semantics, where the symbol is not externally visible.
8443*67e74705SXin Li     return GVA_AvailableExternally;
8444*67e74705SXin Li   }
8445*67e74705SXin Li 
8446*67e74705SXin Li   // Functions specified with extern and inline in -fms-compatibility mode
8447*67e74705SXin Li   // forcibly get emitted.  While the body of the function cannot be later
8448*67e74705SXin Li   // replaced, the function definition cannot be discarded.
8449*67e74705SXin Li   if (FD->isMSExternInline())
8450*67e74705SXin Li     return GVA_StrongODR;
8451*67e74705SXin Li 
8452*67e74705SXin Li   return GVA_DiscardableODR;
8453*67e74705SXin Li }
8454*67e74705SXin Li 
adjustGVALinkageForAttributes(const ASTContext & Context,GVALinkage L,const Decl * D)8455*67e74705SXin Li static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8456*67e74705SXin Li                                                 GVALinkage L, const Decl *D) {
8457*67e74705SXin Li   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8458*67e74705SXin Li   // dllexport/dllimport on inline functions.
8459*67e74705SXin Li   if (D->hasAttr<DLLImportAttr>()) {
8460*67e74705SXin Li     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8461*67e74705SXin Li       return GVA_AvailableExternally;
8462*67e74705SXin Li   } else if (D->hasAttr<DLLExportAttr>()) {
8463*67e74705SXin Li     if (L == GVA_DiscardableODR)
8464*67e74705SXin Li       return GVA_StrongODR;
8465*67e74705SXin Li   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8466*67e74705SXin Li              D->hasAttr<CUDAGlobalAttr>()) {
8467*67e74705SXin Li     // Device-side functions with __global__ attribute must always be
8468*67e74705SXin Li     // visible externally so they can be launched from host.
8469*67e74705SXin Li     if (L == GVA_DiscardableODR || L == GVA_Internal)
8470*67e74705SXin Li       return GVA_StrongODR;
8471*67e74705SXin Li   }
8472*67e74705SXin Li   return L;
8473*67e74705SXin Li }
8474*67e74705SXin Li 
GetGVALinkageForFunction(const FunctionDecl * FD) const8475*67e74705SXin Li GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8476*67e74705SXin Li   return adjustGVALinkageForAttributes(
8477*67e74705SXin Li       *this, basicGVALinkageForFunction(*this, FD), FD);
8478*67e74705SXin Li }
8479*67e74705SXin Li 
basicGVALinkageForVariable(const ASTContext & Context,const VarDecl * VD)8480*67e74705SXin Li static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8481*67e74705SXin Li                                              const VarDecl *VD) {
8482*67e74705SXin Li   if (!VD->isExternallyVisible())
8483*67e74705SXin Li     return GVA_Internal;
8484*67e74705SXin Li 
8485*67e74705SXin Li   if (VD->isStaticLocal()) {
8486*67e74705SXin Li     GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8487*67e74705SXin Li     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8488*67e74705SXin Li     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8489*67e74705SXin Li       LexicalContext = LexicalContext->getLexicalParent();
8490*67e74705SXin Li 
8491*67e74705SXin Li     // Let the static local variable inherit its linkage from the nearest
8492*67e74705SXin Li     // enclosing function.
8493*67e74705SXin Li     if (LexicalContext)
8494*67e74705SXin Li       StaticLocalLinkage =
8495*67e74705SXin Li           Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8496*67e74705SXin Li 
8497*67e74705SXin Li     // GVA_StrongODR function linkage is stronger than what we need,
8498*67e74705SXin Li     // downgrade to GVA_DiscardableODR.
8499*67e74705SXin Li     // This allows us to discard the variable if we never end up needing it.
8500*67e74705SXin Li     return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8501*67e74705SXin Li                                                : StaticLocalLinkage;
8502*67e74705SXin Li   }
8503*67e74705SXin Li 
8504*67e74705SXin Li   // MSVC treats in-class initialized static data members as definitions.
8505*67e74705SXin Li   // By giving them non-strong linkage, out-of-line definitions won't
8506*67e74705SXin Li   // cause link errors.
8507*67e74705SXin Li   if (Context.isMSStaticDataMemberInlineDefinition(VD))
8508*67e74705SXin Li     return GVA_DiscardableODR;
8509*67e74705SXin Li 
8510*67e74705SXin Li   // Most non-template variables have strong linkage; inline variables are
8511*67e74705SXin Li   // linkonce_odr or (occasionally, for compatibility) weak_odr.
8512*67e74705SXin Li   GVALinkage StrongLinkage;
8513*67e74705SXin Li   switch (Context.getInlineVariableDefinitionKind(VD)) {
8514*67e74705SXin Li   case ASTContext::InlineVariableDefinitionKind::None:
8515*67e74705SXin Li     StrongLinkage = GVA_StrongExternal;
8516*67e74705SXin Li     break;
8517*67e74705SXin Li   case ASTContext::InlineVariableDefinitionKind::Weak:
8518*67e74705SXin Li   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8519*67e74705SXin Li     StrongLinkage = GVA_DiscardableODR;
8520*67e74705SXin Li     break;
8521*67e74705SXin Li   case ASTContext::InlineVariableDefinitionKind::Strong:
8522*67e74705SXin Li     StrongLinkage = GVA_StrongODR;
8523*67e74705SXin Li     break;
8524*67e74705SXin Li   }
8525*67e74705SXin Li 
8526*67e74705SXin Li   switch (VD->getTemplateSpecializationKind()) {
8527*67e74705SXin Li   case TSK_Undeclared:
8528*67e74705SXin Li     return StrongLinkage;
8529*67e74705SXin Li 
8530*67e74705SXin Li   case TSK_ExplicitSpecialization:
8531*67e74705SXin Li     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8532*67e74705SXin Li                    VD->isStaticDataMember()
8533*67e74705SXin Li                ? GVA_StrongODR
8534*67e74705SXin Li                : StrongLinkage;
8535*67e74705SXin Li 
8536*67e74705SXin Li   case TSK_ExplicitInstantiationDefinition:
8537*67e74705SXin Li     return GVA_StrongODR;
8538*67e74705SXin Li 
8539*67e74705SXin Li   case TSK_ExplicitInstantiationDeclaration:
8540*67e74705SXin Li     return GVA_AvailableExternally;
8541*67e74705SXin Li 
8542*67e74705SXin Li   case TSK_ImplicitInstantiation:
8543*67e74705SXin Li     return GVA_DiscardableODR;
8544*67e74705SXin Li   }
8545*67e74705SXin Li 
8546*67e74705SXin Li   llvm_unreachable("Invalid Linkage!");
8547*67e74705SXin Li }
8548*67e74705SXin Li 
GetGVALinkageForVariable(const VarDecl * VD)8549*67e74705SXin Li GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8550*67e74705SXin Li   return adjustGVALinkageForAttributes(
8551*67e74705SXin Li       *this, basicGVALinkageForVariable(*this, VD), VD);
8552*67e74705SXin Li }
8553*67e74705SXin Li 
DeclMustBeEmitted(const Decl * D)8554*67e74705SXin Li bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8555*67e74705SXin Li   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8556*67e74705SXin Li     if (!VD->isFileVarDecl())
8557*67e74705SXin Li       return false;
8558*67e74705SXin Li     // Global named register variables (GNU extension) are never emitted.
8559*67e74705SXin Li     if (VD->getStorageClass() == SC_Register)
8560*67e74705SXin Li       return false;
8561*67e74705SXin Li     if (VD->getDescribedVarTemplate() ||
8562*67e74705SXin Li         isa<VarTemplatePartialSpecializationDecl>(VD))
8563*67e74705SXin Li       return false;
8564*67e74705SXin Li   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8565*67e74705SXin Li     // We never need to emit an uninstantiated function template.
8566*67e74705SXin Li     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8567*67e74705SXin Li       return false;
8568*67e74705SXin Li   } else if (isa<PragmaCommentDecl>(D))
8569*67e74705SXin Li     return true;
8570*67e74705SXin Li   else if (isa<OMPThreadPrivateDecl>(D) ||
8571*67e74705SXin Li            D->hasAttr<OMPDeclareTargetDeclAttr>())
8572*67e74705SXin Li     return true;
8573*67e74705SXin Li   else if (isa<PragmaDetectMismatchDecl>(D))
8574*67e74705SXin Li     return true;
8575*67e74705SXin Li   else if (isa<OMPThreadPrivateDecl>(D))
8576*67e74705SXin Li     return !D->getDeclContext()->isDependentContext();
8577*67e74705SXin Li   else if (isa<OMPDeclareReductionDecl>(D))
8578*67e74705SXin Li     return !D->getDeclContext()->isDependentContext();
8579*67e74705SXin Li   else
8580*67e74705SXin Li     return false;
8581*67e74705SXin Li 
8582*67e74705SXin Li   // If this is a member of a class template, we do not need to emit it.
8583*67e74705SXin Li   if (D->getDeclContext()->isDependentContext())
8584*67e74705SXin Li     return false;
8585*67e74705SXin Li 
8586*67e74705SXin Li   // Weak references don't produce any output by themselves.
8587*67e74705SXin Li   if (D->hasAttr<WeakRefAttr>())
8588*67e74705SXin Li     return false;
8589*67e74705SXin Li 
8590*67e74705SXin Li   // Aliases and used decls are required.
8591*67e74705SXin Li   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8592*67e74705SXin Li     return true;
8593*67e74705SXin Li 
8594*67e74705SXin Li   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8595*67e74705SXin Li     // Forward declarations aren't required.
8596*67e74705SXin Li     if (!FD->doesThisDeclarationHaveABody())
8597*67e74705SXin Li       return FD->doesDeclarationForceExternallyVisibleDefinition();
8598*67e74705SXin Li 
8599*67e74705SXin Li     // Constructors and destructors are required.
8600*67e74705SXin Li     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8601*67e74705SXin Li       return true;
8602*67e74705SXin Li 
8603*67e74705SXin Li     // The key function for a class is required.  This rule only comes
8604*67e74705SXin Li     // into play when inline functions can be key functions, though.
8605*67e74705SXin Li     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8606*67e74705SXin Li       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8607*67e74705SXin Li         const CXXRecordDecl *RD = MD->getParent();
8608*67e74705SXin Li         if (MD->isOutOfLine() && RD->isDynamicClass()) {
8609*67e74705SXin Li           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8610*67e74705SXin Li           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8611*67e74705SXin Li             return true;
8612*67e74705SXin Li         }
8613*67e74705SXin Li       }
8614*67e74705SXin Li     }
8615*67e74705SXin Li 
8616*67e74705SXin Li     GVALinkage Linkage = GetGVALinkageForFunction(FD);
8617*67e74705SXin Li 
8618*67e74705SXin Li     // static, static inline, always_inline, and extern inline functions can
8619*67e74705SXin Li     // always be deferred.  Normal inline functions can be deferred in C99/C++.
8620*67e74705SXin Li     // Implicit template instantiations can also be deferred in C++.
8621*67e74705SXin Li     if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8622*67e74705SXin Li         Linkage == GVA_DiscardableODR)
8623*67e74705SXin Li       return false;
8624*67e74705SXin Li     return true;
8625*67e74705SXin Li   }
8626*67e74705SXin Li 
8627*67e74705SXin Li   const VarDecl *VD = cast<VarDecl>(D);
8628*67e74705SXin Li   assert(VD->isFileVarDecl() && "Expected file scoped var");
8629*67e74705SXin Li 
8630*67e74705SXin Li   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8631*67e74705SXin Li       !isMSStaticDataMemberInlineDefinition(VD))
8632*67e74705SXin Li     return false;
8633*67e74705SXin Li 
8634*67e74705SXin Li   // Variables that can be needed in other TUs are required.
8635*67e74705SXin Li   GVALinkage L = GetGVALinkageForVariable(VD);
8636*67e74705SXin Li   if (L != GVA_Internal && L != GVA_AvailableExternally &&
8637*67e74705SXin Li       L != GVA_DiscardableODR)
8638*67e74705SXin Li     return true;
8639*67e74705SXin Li 
8640*67e74705SXin Li   // Variables that have destruction with side-effects are required.
8641*67e74705SXin Li   if (VD->getType().isDestructedType())
8642*67e74705SXin Li     return true;
8643*67e74705SXin Li 
8644*67e74705SXin Li   // Variables that have initialization with side-effects are required.
8645*67e74705SXin Li   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8646*67e74705SXin Li       !VD->evaluateValue())
8647*67e74705SXin Li     return true;
8648*67e74705SXin Li 
8649*67e74705SXin Li   return false;
8650*67e74705SXin Li }
8651*67e74705SXin Li 
getDefaultCallingConvention(bool IsVariadic,bool IsCXXMethod) const8652*67e74705SXin Li CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8653*67e74705SXin Li                                                     bool IsCXXMethod) const {
8654*67e74705SXin Li   // Pass through to the C++ ABI object
8655*67e74705SXin Li   if (IsCXXMethod)
8656*67e74705SXin Li     return ABI->getDefaultMethodCallConv(IsVariadic);
8657*67e74705SXin Li 
8658*67e74705SXin Li   switch (LangOpts.getDefaultCallingConv()) {
8659*67e74705SXin Li   case LangOptions::DCC_None:
8660*67e74705SXin Li     break;
8661*67e74705SXin Li   case LangOptions::DCC_CDecl:
8662*67e74705SXin Li     return CC_C;
8663*67e74705SXin Li   case LangOptions::DCC_FastCall:
8664*67e74705SXin Li     if (getTargetInfo().hasFeature("sse2"))
8665*67e74705SXin Li       return CC_X86FastCall;
8666*67e74705SXin Li     break;
8667*67e74705SXin Li   case LangOptions::DCC_StdCall:
8668*67e74705SXin Li     if (!IsVariadic)
8669*67e74705SXin Li       return CC_X86StdCall;
8670*67e74705SXin Li     break;
8671*67e74705SXin Li   case LangOptions::DCC_VectorCall:
8672*67e74705SXin Li     // __vectorcall cannot be applied to variadic functions.
8673*67e74705SXin Li     if (!IsVariadic)
8674*67e74705SXin Li       return CC_X86VectorCall;
8675*67e74705SXin Li     break;
8676*67e74705SXin Li   }
8677*67e74705SXin Li   return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8678*67e74705SXin Li }
8679*67e74705SXin Li 
isNearlyEmpty(const CXXRecordDecl * RD) const8680*67e74705SXin Li bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8681*67e74705SXin Li   // Pass through to the C++ ABI object
8682*67e74705SXin Li   return ABI->isNearlyEmpty(RD);
8683*67e74705SXin Li }
8684*67e74705SXin Li 
getVTableContext()8685*67e74705SXin Li VTableContextBase *ASTContext::getVTableContext() {
8686*67e74705SXin Li   if (!VTContext.get()) {
8687*67e74705SXin Li     if (Target->getCXXABI().isMicrosoft())
8688*67e74705SXin Li       VTContext.reset(new MicrosoftVTableContext(*this));
8689*67e74705SXin Li     else
8690*67e74705SXin Li       VTContext.reset(new ItaniumVTableContext(*this));
8691*67e74705SXin Li   }
8692*67e74705SXin Li   return VTContext.get();
8693*67e74705SXin Li }
8694*67e74705SXin Li 
createMangleContext()8695*67e74705SXin Li MangleContext *ASTContext::createMangleContext() {
8696*67e74705SXin Li   switch (Target->getCXXABI().getKind()) {
8697*67e74705SXin Li   case TargetCXXABI::GenericAArch64:
8698*67e74705SXin Li   case TargetCXXABI::GenericItanium:
8699*67e74705SXin Li   case TargetCXXABI::GenericARM:
8700*67e74705SXin Li   case TargetCXXABI::GenericMIPS:
8701*67e74705SXin Li   case TargetCXXABI::iOS:
8702*67e74705SXin Li   case TargetCXXABI::iOS64:
8703*67e74705SXin Li   case TargetCXXABI::WebAssembly:
8704*67e74705SXin Li   case TargetCXXABI::WatchOS:
8705*67e74705SXin Li     return ItaniumMangleContext::create(*this, getDiagnostics());
8706*67e74705SXin Li   case TargetCXXABI::Microsoft:
8707*67e74705SXin Li     return MicrosoftMangleContext::create(*this, getDiagnostics());
8708*67e74705SXin Li   }
8709*67e74705SXin Li   llvm_unreachable("Unsupported ABI");
8710*67e74705SXin Li }
8711*67e74705SXin Li 
~CXXABI()8712*67e74705SXin Li CXXABI::~CXXABI() {}
8713*67e74705SXin Li 
getSideTableAllocatedMemory() const8714*67e74705SXin Li size_t ASTContext::getSideTableAllocatedMemory() const {
8715*67e74705SXin Li   return ASTRecordLayouts.getMemorySize() +
8716*67e74705SXin Li          llvm::capacity_in_bytes(ObjCLayouts) +
8717*67e74705SXin Li          llvm::capacity_in_bytes(KeyFunctions) +
8718*67e74705SXin Li          llvm::capacity_in_bytes(ObjCImpls) +
8719*67e74705SXin Li          llvm::capacity_in_bytes(BlockVarCopyInits) +
8720*67e74705SXin Li          llvm::capacity_in_bytes(DeclAttrs) +
8721*67e74705SXin Li          llvm::capacity_in_bytes(TemplateOrInstantiation) +
8722*67e74705SXin Li          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8723*67e74705SXin Li          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8724*67e74705SXin Li          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8725*67e74705SXin Li          llvm::capacity_in_bytes(OverriddenMethods) +
8726*67e74705SXin Li          llvm::capacity_in_bytes(Types) +
8727*67e74705SXin Li          llvm::capacity_in_bytes(VariableArrayTypes) +
8728*67e74705SXin Li          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8729*67e74705SXin Li }
8730*67e74705SXin Li 
8731*67e74705SXin Li /// getIntTypeForBitwidth -
8732*67e74705SXin Li /// sets integer QualTy according to specified details:
8733*67e74705SXin Li /// bitwidth, signed/unsigned.
8734*67e74705SXin Li /// Returns empty type if there is no appropriate target types.
getIntTypeForBitwidth(unsigned DestWidth,unsigned Signed) const8735*67e74705SXin Li QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8736*67e74705SXin Li                                            unsigned Signed) const {
8737*67e74705SXin Li   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8738*67e74705SXin Li   CanQualType QualTy = getFromTargetType(Ty);
8739*67e74705SXin Li   if (!QualTy && DestWidth == 128)
8740*67e74705SXin Li     return Signed ? Int128Ty : UnsignedInt128Ty;
8741*67e74705SXin Li   return QualTy;
8742*67e74705SXin Li }
8743*67e74705SXin Li 
8744*67e74705SXin Li /// getRealTypeForBitwidth -
8745*67e74705SXin Li /// sets floating point QualTy according to specified bitwidth.
8746*67e74705SXin Li /// Returns empty type if there is no appropriate target types.
getRealTypeForBitwidth(unsigned DestWidth) const8747*67e74705SXin Li QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8748*67e74705SXin Li   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8749*67e74705SXin Li   switch (Ty) {
8750*67e74705SXin Li   case TargetInfo::Float:
8751*67e74705SXin Li     return FloatTy;
8752*67e74705SXin Li   case TargetInfo::Double:
8753*67e74705SXin Li     return DoubleTy;
8754*67e74705SXin Li   case TargetInfo::LongDouble:
8755*67e74705SXin Li     return LongDoubleTy;
8756*67e74705SXin Li   case TargetInfo::Float128:
8757*67e74705SXin Li     return Float128Ty;
8758*67e74705SXin Li   case TargetInfo::NoFloat:
8759*67e74705SXin Li     return QualType();
8760*67e74705SXin Li   }
8761*67e74705SXin Li 
8762*67e74705SXin Li   llvm_unreachable("Unhandled TargetInfo::RealType value");
8763*67e74705SXin Li }
8764*67e74705SXin Li 
setManglingNumber(const NamedDecl * ND,unsigned Number)8765*67e74705SXin Li void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8766*67e74705SXin Li   if (Number > 1)
8767*67e74705SXin Li     MangleNumbers[ND] = Number;
8768*67e74705SXin Li }
8769*67e74705SXin Li 
getManglingNumber(const NamedDecl * ND) const8770*67e74705SXin Li unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8771*67e74705SXin Li   auto I = MangleNumbers.find(ND);
8772*67e74705SXin Li   return I != MangleNumbers.end() ? I->second : 1;
8773*67e74705SXin Li }
8774*67e74705SXin Li 
setStaticLocalNumber(const VarDecl * VD,unsigned Number)8775*67e74705SXin Li void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8776*67e74705SXin Li   if (Number > 1)
8777*67e74705SXin Li     StaticLocalNumbers[VD] = Number;
8778*67e74705SXin Li }
8779*67e74705SXin Li 
getStaticLocalNumber(const VarDecl * VD) const8780*67e74705SXin Li unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8781*67e74705SXin Li   auto I = StaticLocalNumbers.find(VD);
8782*67e74705SXin Li   return I != StaticLocalNumbers.end() ? I->second : 1;
8783*67e74705SXin Li }
8784*67e74705SXin Li 
8785*67e74705SXin Li MangleNumberingContext &
getManglingNumberContext(const DeclContext * DC)8786*67e74705SXin Li ASTContext::getManglingNumberContext(const DeclContext *DC) {
8787*67e74705SXin Li   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
8788*67e74705SXin Li   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8789*67e74705SXin Li   if (!MCtx)
8790*67e74705SXin Li     MCtx = createMangleNumberingContext();
8791*67e74705SXin Li   return *MCtx;
8792*67e74705SXin Li }
8793*67e74705SXin Li 
createMangleNumberingContext() const8794*67e74705SXin Li MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8795*67e74705SXin Li   return ABI->createMangleNumberingContext();
8796*67e74705SXin Li }
8797*67e74705SXin Li 
8798*67e74705SXin Li const CXXConstructorDecl *
getCopyConstructorForExceptionObject(CXXRecordDecl * RD)8799*67e74705SXin Li ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8800*67e74705SXin Li   return ABI->getCopyConstructorForExceptionObject(
8801*67e74705SXin Li       cast<CXXRecordDecl>(RD->getFirstDecl()));
8802*67e74705SXin Li }
8803*67e74705SXin Li 
addCopyConstructorForExceptionObject(CXXRecordDecl * RD,CXXConstructorDecl * CD)8804*67e74705SXin Li void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8805*67e74705SXin Li                                                       CXXConstructorDecl *CD) {
8806*67e74705SXin Li   return ABI->addCopyConstructorForExceptionObject(
8807*67e74705SXin Li       cast<CXXRecordDecl>(RD->getFirstDecl()),
8808*67e74705SXin Li       cast<CXXConstructorDecl>(CD->getFirstDecl()));
8809*67e74705SXin Li }
8810*67e74705SXin Li 
addDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx,Expr * DAE)8811*67e74705SXin Li void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8812*67e74705SXin Li                                                  unsigned ParmIdx, Expr *DAE) {
8813*67e74705SXin Li   ABI->addDefaultArgExprForConstructor(
8814*67e74705SXin Li       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8815*67e74705SXin Li }
8816*67e74705SXin Li 
getDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx)8817*67e74705SXin Li Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8818*67e74705SXin Li                                                   unsigned ParmIdx) {
8819*67e74705SXin Li   return ABI->getDefaultArgExprForConstructor(
8820*67e74705SXin Li       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8821*67e74705SXin Li }
8822*67e74705SXin Li 
addTypedefNameForUnnamedTagDecl(TagDecl * TD,TypedefNameDecl * DD)8823*67e74705SXin Li void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8824*67e74705SXin Li                                                  TypedefNameDecl *DD) {
8825*67e74705SXin Li   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8826*67e74705SXin Li }
8827*67e74705SXin Li 
8828*67e74705SXin Li TypedefNameDecl *
getTypedefNameForUnnamedTagDecl(const TagDecl * TD)8829*67e74705SXin Li ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8830*67e74705SXin Li   return ABI->getTypedefNameForUnnamedTagDecl(TD);
8831*67e74705SXin Li }
8832*67e74705SXin Li 
addDeclaratorForUnnamedTagDecl(TagDecl * TD,DeclaratorDecl * DD)8833*67e74705SXin Li void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8834*67e74705SXin Li                                                 DeclaratorDecl *DD) {
8835*67e74705SXin Li   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8836*67e74705SXin Li }
8837*67e74705SXin Li 
getDeclaratorForUnnamedTagDecl(const TagDecl * TD)8838*67e74705SXin Li DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8839*67e74705SXin Li   return ABI->getDeclaratorForUnnamedTagDecl(TD);
8840*67e74705SXin Li }
8841*67e74705SXin Li 
setParameterIndex(const ParmVarDecl * D,unsigned int index)8842*67e74705SXin Li void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8843*67e74705SXin Li   ParamIndices[D] = index;
8844*67e74705SXin Li }
8845*67e74705SXin Li 
getParameterIndex(const ParmVarDecl * D) const8846*67e74705SXin Li unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8847*67e74705SXin Li   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8848*67e74705SXin Li   assert(I != ParamIndices.end() &&
8849*67e74705SXin Li          "ParmIndices lacks entry set by ParmVarDecl");
8850*67e74705SXin Li   return I->second;
8851*67e74705SXin Li }
8852*67e74705SXin Li 
8853*67e74705SXin Li APValue *
getMaterializedTemporaryValue(const MaterializeTemporaryExpr * E,bool MayCreate)8854*67e74705SXin Li ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8855*67e74705SXin Li                                           bool MayCreate) {
8856*67e74705SXin Li   assert(E && E->getStorageDuration() == SD_Static &&
8857*67e74705SXin Li          "don't need to cache the computed value for this temporary");
8858*67e74705SXin Li   if (MayCreate) {
8859*67e74705SXin Li     APValue *&MTVI = MaterializedTemporaryValues[E];
8860*67e74705SXin Li     if (!MTVI)
8861*67e74705SXin Li       MTVI = new (*this) APValue;
8862*67e74705SXin Li     return MTVI;
8863*67e74705SXin Li   }
8864*67e74705SXin Li 
8865*67e74705SXin Li   return MaterializedTemporaryValues.lookup(E);
8866*67e74705SXin Li }
8867*67e74705SXin Li 
AtomicUsesUnsupportedLibcall(const AtomicExpr * E) const8868*67e74705SXin Li bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8869*67e74705SXin Li   const llvm::Triple &T = getTargetInfo().getTriple();
8870*67e74705SXin Li   if (!T.isOSDarwin())
8871*67e74705SXin Li     return false;
8872*67e74705SXin Li 
8873*67e74705SXin Li   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8874*67e74705SXin Li       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8875*67e74705SXin Li     return false;
8876*67e74705SXin Li 
8877*67e74705SXin Li   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8878*67e74705SXin Li   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8879*67e74705SXin Li   uint64_t Size = sizeChars.getQuantity();
8880*67e74705SXin Li   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8881*67e74705SXin Li   unsigned Align = alignChars.getQuantity();
8882*67e74705SXin Li   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8883*67e74705SXin Li   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8884*67e74705SXin Li }
8885*67e74705SXin Li 
8886*67e74705SXin Li namespace {
8887*67e74705SXin Li 
getSingleDynTypedNodeFromParentMap(ASTContext::ParentMapPointers::mapped_type U)8888*67e74705SXin Li ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8889*67e74705SXin Li     ASTContext::ParentMapPointers::mapped_type U) {
8890*67e74705SXin Li   if (const auto *D = U.dyn_cast<const Decl *>())
8891*67e74705SXin Li     return ast_type_traits::DynTypedNode::create(*D);
8892*67e74705SXin Li   if (const auto *S = U.dyn_cast<const Stmt *>())
8893*67e74705SXin Li     return ast_type_traits::DynTypedNode::create(*S);
8894*67e74705SXin Li   return *U.get<ast_type_traits::DynTypedNode *>();
8895*67e74705SXin Li }
8896*67e74705SXin Li 
8897*67e74705SXin Li /// Template specializations to abstract away from pointers and TypeLocs.
8898*67e74705SXin Li /// @{
8899*67e74705SXin Li template <typename T>
createDynTypedNode(const T & Node)8900*67e74705SXin Li ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8901*67e74705SXin Li   return ast_type_traits::DynTypedNode::create(*Node);
8902*67e74705SXin Li }
8903*67e74705SXin Li template <>
createDynTypedNode(const TypeLoc & Node)8904*67e74705SXin Li ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8905*67e74705SXin Li   return ast_type_traits::DynTypedNode::create(Node);
8906*67e74705SXin Li }
8907*67e74705SXin Li template <>
8908*67e74705SXin Li ast_type_traits::DynTypedNode
createDynTypedNode(const NestedNameSpecifierLoc & Node)8909*67e74705SXin Li createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8910*67e74705SXin Li   return ast_type_traits::DynTypedNode::create(Node);
8911*67e74705SXin Li }
8912*67e74705SXin Li /// @}
8913*67e74705SXin Li 
8914*67e74705SXin Li   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8915*67e74705SXin Li   /// parents as defined by the \c RecursiveASTVisitor.
8916*67e74705SXin Li   ///
8917*67e74705SXin Li   /// Note that the relationship described here is purely in terms of AST
8918*67e74705SXin Li   /// traversal - there are other relationships (for example declaration context)
8919*67e74705SXin Li   /// in the AST that are better modeled by special matchers.
8920*67e74705SXin Li   ///
8921*67e74705SXin Li   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8922*67e74705SXin Li   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8923*67e74705SXin Li   public:
8924*67e74705SXin Li     /// \brief Builds and returns the translation unit's parent map.
8925*67e74705SXin Li     ///
8926*67e74705SXin Li     ///  The caller takes ownership of the returned \c ParentMap.
8927*67e74705SXin Li     static std::pair<ASTContext::ParentMapPointers *,
8928*67e74705SXin Li                      ASTContext::ParentMapOtherNodes *>
buildMap(TranslationUnitDecl & TU)8929*67e74705SXin Li     buildMap(TranslationUnitDecl &TU) {
8930*67e74705SXin Li       ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8931*67e74705SXin Li                                   new ASTContext::ParentMapOtherNodes);
8932*67e74705SXin Li       Visitor.TraverseDecl(&TU);
8933*67e74705SXin Li       return std::make_pair(Visitor.Parents, Visitor.OtherParents);
8934*67e74705SXin Li     }
8935*67e74705SXin Li 
8936*67e74705SXin Li   private:
8937*67e74705SXin Li     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8938*67e74705SXin Li 
ParentMapASTVisitor(ASTContext::ParentMapPointers * Parents,ASTContext::ParentMapOtherNodes * OtherParents)8939*67e74705SXin Li     ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8940*67e74705SXin Li                         ASTContext::ParentMapOtherNodes *OtherParents)
8941*67e74705SXin Li         : Parents(Parents), OtherParents(OtherParents) {}
8942*67e74705SXin Li 
shouldVisitTemplateInstantiations() const8943*67e74705SXin Li     bool shouldVisitTemplateInstantiations() const {
8944*67e74705SXin Li       return true;
8945*67e74705SXin Li     }
shouldVisitImplicitCode() const8946*67e74705SXin Li     bool shouldVisitImplicitCode() const {
8947*67e74705SXin Li       return true;
8948*67e74705SXin Li     }
8949*67e74705SXin Li 
8950*67e74705SXin Li     template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8951*67e74705SXin Li               typename MapTy>
TraverseNode(T Node,MapNodeTy MapNode,BaseTraverseFn BaseTraverse,MapTy * Parents)8952*67e74705SXin Li     bool TraverseNode(T Node, MapNodeTy MapNode,
8953*67e74705SXin Li                       BaseTraverseFn BaseTraverse, MapTy *Parents) {
8954*67e74705SXin Li       if (!Node)
8955*67e74705SXin Li         return true;
8956*67e74705SXin Li       if (ParentStack.size() > 0) {
8957*67e74705SXin Li         // FIXME: Currently we add the same parent multiple times, but only
8958*67e74705SXin Li         // when no memoization data is available for the type.
8959*67e74705SXin Li         // For example when we visit all subexpressions of template
8960*67e74705SXin Li         // instantiations; this is suboptimal, but benign: the only way to
8961*67e74705SXin Li         // visit those is with hasAncestor / hasParent, and those do not create
8962*67e74705SXin Li         // new matches.
8963*67e74705SXin Li         // The plan is to enable DynTypedNode to be storable in a map or hash
8964*67e74705SXin Li         // map. The main problem there is to implement hash functions /
8965*67e74705SXin Li         // comparison operators for all types that DynTypedNode supports that
8966*67e74705SXin Li         // do not have pointer identity.
8967*67e74705SXin Li         auto &NodeOrVector = (*Parents)[MapNode];
8968*67e74705SXin Li         if (NodeOrVector.isNull()) {
8969*67e74705SXin Li           if (const auto *D = ParentStack.back().get<Decl>())
8970*67e74705SXin Li             NodeOrVector = D;
8971*67e74705SXin Li           else if (const auto *S = ParentStack.back().get<Stmt>())
8972*67e74705SXin Li             NodeOrVector = S;
8973*67e74705SXin Li           else
8974*67e74705SXin Li             NodeOrVector =
8975*67e74705SXin Li                 new ast_type_traits::DynTypedNode(ParentStack.back());
8976*67e74705SXin Li         } else {
8977*67e74705SXin Li           if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8978*67e74705SXin Li             auto *Vector = new ASTContext::ParentVector(
8979*67e74705SXin Li                 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
8980*67e74705SXin Li             if (auto *Node =
8981*67e74705SXin Li                     NodeOrVector
8982*67e74705SXin Li                         .template dyn_cast<ast_type_traits::DynTypedNode *>())
8983*67e74705SXin Li               delete Node;
8984*67e74705SXin Li             NodeOrVector = Vector;
8985*67e74705SXin Li           }
8986*67e74705SXin Li 
8987*67e74705SXin Li           auto *Vector =
8988*67e74705SXin Li               NodeOrVector.template get<ASTContext::ParentVector *>();
8989*67e74705SXin Li           // Skip duplicates for types that have memoization data.
8990*67e74705SXin Li           // We must check that the type has memoization data before calling
8991*67e74705SXin Li           // std::find() because DynTypedNode::operator== can't compare all
8992*67e74705SXin Li           // types.
8993*67e74705SXin Li           bool Found = ParentStack.back().getMemoizationData() &&
8994*67e74705SXin Li                        std::find(Vector->begin(), Vector->end(),
8995*67e74705SXin Li                                  ParentStack.back()) != Vector->end();
8996*67e74705SXin Li           if (!Found)
8997*67e74705SXin Li             Vector->push_back(ParentStack.back());
8998*67e74705SXin Li         }
8999*67e74705SXin Li       }
9000*67e74705SXin Li       ParentStack.push_back(createDynTypedNode(Node));
9001*67e74705SXin Li       bool Result = BaseTraverse();
9002*67e74705SXin Li       ParentStack.pop_back();
9003*67e74705SXin Li       return Result;
9004*67e74705SXin Li     }
9005*67e74705SXin Li 
TraverseDecl(Decl * DeclNode)9006*67e74705SXin Li     bool TraverseDecl(Decl *DeclNode) {
9007*67e74705SXin Li       return TraverseNode(DeclNode, DeclNode,
9008*67e74705SXin Li                           [&] { return VisitorBase::TraverseDecl(DeclNode); },
9009*67e74705SXin Li                           Parents);
9010*67e74705SXin Li     }
9011*67e74705SXin Li 
TraverseStmt(Stmt * StmtNode)9012*67e74705SXin Li     bool TraverseStmt(Stmt *StmtNode) {
9013*67e74705SXin Li       return TraverseNode(StmtNode, StmtNode,
9014*67e74705SXin Li                           [&] { return VisitorBase::TraverseStmt(StmtNode); },
9015*67e74705SXin Li                           Parents);
9016*67e74705SXin Li     }
9017*67e74705SXin Li 
TraverseTypeLoc(TypeLoc TypeLocNode)9018*67e74705SXin Li     bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9019*67e74705SXin Li       return TraverseNode(
9020*67e74705SXin Li           TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9021*67e74705SXin Li           [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9022*67e74705SXin Li           OtherParents);
9023*67e74705SXin Li     }
9024*67e74705SXin Li 
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode)9025*67e74705SXin Li     bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9026*67e74705SXin Li       return TraverseNode(
9027*67e74705SXin Li           NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9028*67e74705SXin Li           [&] {
9029*67e74705SXin Li             return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9030*67e74705SXin Li           },
9031*67e74705SXin Li           OtherParents);
9032*67e74705SXin Li     }
9033*67e74705SXin Li 
9034*67e74705SXin Li     ASTContext::ParentMapPointers *Parents;
9035*67e74705SXin Li     ASTContext::ParentMapOtherNodes *OtherParents;
9036*67e74705SXin Li     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9037*67e74705SXin Li 
9038*67e74705SXin Li     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9039*67e74705SXin Li   };
9040*67e74705SXin Li 
9041*67e74705SXin Li } // anonymous namespace
9042*67e74705SXin Li 
9043*67e74705SXin Li template <typename NodeTy, typename MapTy>
getDynNodeFromMap(const NodeTy & Node,const MapTy & Map)9044*67e74705SXin Li static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9045*67e74705SXin Li                                                       const MapTy &Map) {
9046*67e74705SXin Li   auto I = Map.find(Node);
9047*67e74705SXin Li   if (I == Map.end()) {
9048*67e74705SXin Li     return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9049*67e74705SXin Li   }
9050*67e74705SXin Li   if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9051*67e74705SXin Li     return llvm::makeArrayRef(*V);
9052*67e74705SXin Li   }
9053*67e74705SXin Li   return getSingleDynTypedNodeFromParentMap(I->second);
9054*67e74705SXin Li }
9055*67e74705SXin Li 
9056*67e74705SXin Li ASTContext::DynTypedNodeList
getParents(const ast_type_traits::DynTypedNode & Node)9057*67e74705SXin Li ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9058*67e74705SXin Li   if (!PointerParents) {
9059*67e74705SXin Li     // We always need to run over the whole translation unit, as
9060*67e74705SXin Li     // hasAncestor can escape any subtree.
9061*67e74705SXin Li     auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9062*67e74705SXin Li     PointerParents.reset(Maps.first);
9063*67e74705SXin Li     OtherParents.reset(Maps.second);
9064*67e74705SXin Li   }
9065*67e74705SXin Li   if (Node.getNodeKind().hasPointerIdentity())
9066*67e74705SXin Li     return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9067*67e74705SXin Li   return getDynNodeFromMap(Node, *OtherParents);
9068*67e74705SXin Li }
9069*67e74705SXin Li 
9070*67e74705SXin Li bool
ObjCMethodsAreEqual(const ObjCMethodDecl * MethodDecl,const ObjCMethodDecl * MethodImpl)9071*67e74705SXin Li ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9072*67e74705SXin Li                                 const ObjCMethodDecl *MethodImpl) {
9073*67e74705SXin Li   // No point trying to match an unavailable/deprecated mothod.
9074*67e74705SXin Li   if (MethodDecl->hasAttr<UnavailableAttr>()
9075*67e74705SXin Li       || MethodDecl->hasAttr<DeprecatedAttr>())
9076*67e74705SXin Li     return false;
9077*67e74705SXin Li   if (MethodDecl->getObjCDeclQualifier() !=
9078*67e74705SXin Li       MethodImpl->getObjCDeclQualifier())
9079*67e74705SXin Li     return false;
9080*67e74705SXin Li   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9081*67e74705SXin Li     return false;
9082*67e74705SXin Li 
9083*67e74705SXin Li   if (MethodDecl->param_size() != MethodImpl->param_size())
9084*67e74705SXin Li     return false;
9085*67e74705SXin Li 
9086*67e74705SXin Li   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9087*67e74705SXin Li        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9088*67e74705SXin Li        EF = MethodDecl->param_end();
9089*67e74705SXin Li        IM != EM && IF != EF; ++IM, ++IF) {
9090*67e74705SXin Li     const ParmVarDecl *DeclVar = (*IF);
9091*67e74705SXin Li     const ParmVarDecl *ImplVar = (*IM);
9092*67e74705SXin Li     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9093*67e74705SXin Li       return false;
9094*67e74705SXin Li     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9095*67e74705SXin Li       return false;
9096*67e74705SXin Li   }
9097*67e74705SXin Li   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9098*67e74705SXin Li 
9099*67e74705SXin Li }
9100*67e74705SXin Li 
9101*67e74705SXin Li // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9102*67e74705SXin Li // doesn't include ASTContext.h
9103*67e74705SXin Li template
9104*67e74705SXin Li clang::LazyGenerationalUpdatePtr<
9105*67e74705SXin Li     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9106*67e74705SXin Li clang::LazyGenerationalUpdatePtr<
9107*67e74705SXin Li     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9108*67e74705SXin Li         const clang::ASTContext &Ctx, Decl *Value);
9109