blob: 4d26748b07702884ae2171114237281055108c20 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000060 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000706 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000708 3, // opencl_local
709 2, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000710 4, // opencl_generic
711 5, // cuda_device
712 6, // cuda_constant
713 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000716 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000718 }
719}
720
David Tweed31d09b02013-09-13 12:04:22 +0000721static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
727 return true;
728 case LangOptions::ASMM_Off:
729 return false;
730 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000732}
733
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000734ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000735 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000736 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000759 TUDecl = TranslationUnitDecl::Create(*this);
760}
761
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000762ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000763 ReleaseParentMapEntries();
764
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000768
Manuel Klimeka7328992013-06-03 13:51:33 +0000769 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781
Ted Kremenek076baeb2010-06-08 23:00:58 +0000782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 R->Destroy(*this);
787 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000788
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
791 A != AEnd; ++A)
792 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000793
David Majnemere694f3e2015-08-14 14:43:50 +0000794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
797
Richard Smith423f46f2016-07-20 21:38:26 +0000798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000800}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000801
Manuel Klimek95403e62014-05-21 13:28:59 +0000802void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
809 }
810 }
811 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000814 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000815 delete Entry.second.get<ParentVector *>();
816 }
817 }
818}
819
Douglas Gregor1a809332010-05-23 18:26:36 +0000820void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000821 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000822}
823
Mike Stump11289f42009-09-09 15:08:12 +0000824void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000825ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000826 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000827}
828
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000832
Douglas Gregora30d0462009-05-26 14:40:08 +0000833 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000834#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000835#define ABSTRACT_TYPE(Name, Parent)
836#include "clang/AST/TypeNodes.def"
837 0 // Extra
838 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000839
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
841 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000843 }
844
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 unsigned Idx = 0;
846 unsigned TotalBytes = 0;
847#define TYPE(Name, Parent) \
848 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000849 llvm::errs() << " " << counts[Idx] << " " << #Name \
850 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
852 ++Idx;
853#define ABSTRACT_TYPE(Name, Parent)
854#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
857
Douglas Gregor7454c562010-07-02 20:37:36 +0000858 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
879
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000880 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000882 ExternalSource->PrintStats();
883 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000884
Douglas Gregor5b11d492010-07-25 17:53:33 +0000885 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886}
887
Richard Smith42413142015-05-15 20:05:43 +0000888void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
890 if (NotifyListeners)
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
893
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
896 else
Richard Smith90dc5252017-06-23 01:04:34 +0000897 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000898}
899
900void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
903 return;
904
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000905 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
909 M = nullptr;
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
911}
912
Richard Smithdc1f0422016-07-20 19:10:16 +0000913void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
915 return;
916
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source");
919
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
922
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
925
926 assert(LazyInitializers.empty() &&
927 "GetExternalDecl for lazy module initializer added more inits");
928}
929
930void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
935
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
938 return;
939
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
946 D = OnlyDecl;
947 }
948 }
949
950 auto *&Inits = ModuleInitializers[M];
951 if (!Inits)
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
954}
955
956void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
958 if (!Inits)
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
962}
963
964ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
967 return None;
968
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
972}
973
Richard Smithf19e1272015-03-07 00:04:49 +0000974ExternCContextDecl *ASTContext::getExternCContextDecl() const {
975 if (!ExternCContext)
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
977
978 return ExternCContext;
979}
980
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000981BuiltinTemplateDecl *
982ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
987
988 return BuiltinTemplate;
989}
990
991BuiltinTemplateDecl *
992ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
997}
998
Eric Fiselier6ad68552016-07-01 01:24:09 +0000999BuiltinTemplateDecl *
1000ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1005}
1006
Alp Toker2dea15b2013-12-17 01:22:38 +00001007RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001009 SourceLocation Loc;
1010 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1016 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001020 return NewDecl;
1021}
1022
1023TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1030 return NewDecl;
1031}
1032
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001034 if (!Int128Decl)
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001036 return Int128Decl;
1037}
1038
1039TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001040 if (!UInt128Decl)
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001042 return UInt128Decl;
1043}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001044
John McCall48f2d582009-10-23 23:03:21 +00001045void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001048 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001049}
1050
Artem Belevichb5bc9232015-09-22 17:23:22 +00001051void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 assert((!this->Target || this->Target == &Target) &&
1054 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001055 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001058 this->AuxTarget = AuxTarget;
1059
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner970e54e2006-11-12 00:37:36 +00001067 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001068 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001069 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001070 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1072 else
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001074 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner970e54e2006-11-12 00:37:36 +00001081 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001087
Chris Lattner970e54e2006-11-12 00:37:36 +00001088 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001092
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1095
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001096 // C11 extension ISO/IEC TS 18661-3
1097 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1098
Chris Lattnerf122cef2009-04-30 02:43:43 +00001099 // GNU extension, 128-bit integers.
1100 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1101 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1102
Hans Wennborg0d81e012013-05-10 10:08:40 +00001103 // C++ 3.9.1p5
1104 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1105 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1106 else // -fshort-wchar makes wchar_t be unsigned.
1107 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1108 if (LangOpts.CPlusPlus && LangOpts.WChar)
1109 WideCharTy = WCharTy;
1110 else {
1111 // C99 (or C++ using -fno-wchar).
1112 WideCharTy = getFromTargetType(Target.getWCharType());
1113 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001114
James Molloy36365542012-05-04 10:55:22 +00001115 WIntTy = getFromTargetType(Target.getWIntType());
1116
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001117 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1118 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1119 else // C99
1120 Char16Ty = getFromTargetType(Target.getChar16Type());
1121
1122 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1123 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1124 else // C99
1125 Char32Ty = getFromTargetType(Target.getChar32Type());
1126
Douglas Gregor4619e432008-12-05 23:32:09 +00001127 // Placeholder type for type-dependent expressions whose type is
1128 // completely unknown. No code should ever check a type against
1129 // DependentTy and users should never see it; however, it is here to
1130 // help diagnose failures to properly check for type-dependent
1131 // expressions.
1132 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133
John McCall36e7fe32010-10-12 00:20:44 +00001134 // Placeholder type for functions.
1135 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1136
John McCall0009fcc2011-04-26 20:42:42 +00001137 // Placeholder type for bound members.
1138 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1139
John McCall526ab472011-10-25 17:37:35 +00001140 // Placeholder type for pseudo-objects.
1141 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1142
John McCall31996342011-04-07 08:22:57 +00001143 // "any" type; useful for debugger-like clients.
1144 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1145
John McCall8a6b59a2011-10-17 18:09:15 +00001146 // Placeholder type for unbridged ARC casts.
1147 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1148
Eli Friedman34866c72012-08-31 00:14:07 +00001149 // Placeholder type for builtin functions.
1150 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1151
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001152 // Placeholder type for OMP array sections.
1153 if (LangOpts.OpenMP)
1154 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1155
Chris Lattner970e54e2006-11-12 00:37:36 +00001156 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001157 FloatComplexTy = getComplexType(FloatTy);
1158 DoubleComplexTy = getComplexType(DoubleTy);
1159 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001160 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001162 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001163 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1164 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001165 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001166
Alexey Bader954ba212016-04-08 13:40:33 +00001167 if (LangOpts.OpenCL) {
1168#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1169 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001170#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001171
Guy Benyei61054192013-02-07 10:55:47 +00001172 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001173 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001174 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1175 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001176 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001177 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001178
1179 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001180 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1181 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001182
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001183 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001184
1185 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001186
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001187 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001188 if (LangOpts.OpenCLVersion >= 200) {
1189 auto Q = VoidTy.getQualifiers();
1190 Q.setAddressSpace(LangAS::opencl_generic);
1191 VoidPtrTy = getPointerType(getCanonicalType(
1192 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1193 } else {
1194 VoidPtrTy = getPointerType(VoidTy);
1195 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001196
1197 // nullptr type (C++0x 2.14.7)
1198 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001199
1200 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1201 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001202
1203 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001204 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001205}
1206
David Blaikie9c902b52011-09-25 23:23:43 +00001207DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001208 return SourceMgr.getDiagnostics();
1209}
1210
Douglas Gregor561eceb2010-08-30 16:49:28 +00001211AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1212 AttrVec *&Result = DeclAttrs[D];
1213 if (!Result) {
1214 void *Mem = Allocate(sizeof(AttrVec));
1215 Result = new (Mem) AttrVec;
1216 }
1217
1218 return *Result;
1219}
1220
1221/// \brief Erase the attributes corresponding to the given declaration.
1222void ASTContext::eraseDeclAttrs(const Decl *D) {
1223 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1224 if (Pos != DeclAttrs.end()) {
1225 Pos->second->~AttrVec();
1226 DeclAttrs.erase(Pos);
1227 }
1228}
1229
Larisse Voufo39a1e502013-08-06 01:03:05 +00001230// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001231MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001232ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001233 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001234 return getTemplateOrSpecializationInfo(Var)
1235 .dyn_cast<MemberSpecializationInfo *>();
1236}
1237
1238ASTContext::TemplateOrSpecializationInfo
1239ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1240 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1241 TemplateOrInstantiation.find(Var);
1242 if (Pos == TemplateOrInstantiation.end())
1243 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001244
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001245 return Pos->second;
1246}
1247
Mike Stump11289f42009-09-09 15:08:12 +00001248void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001249ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001250 TemplateSpecializationKind TSK,
1251 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001252 assert(Inst->isStaticDataMember() && "Not a static data member");
1253 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001254 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1255 Tmpl, TSK, PointOfInstantiation));
1256}
1257
1258void
1259ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1260 TemplateOrSpecializationInfo TSI) {
1261 assert(!TemplateOrInstantiation[Inst] &&
1262 "Already noted what the variable was instantiated from");
1263 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001264}
1265
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001266FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1267 const FunctionDecl *FD){
1268 assert(FD && "Specialization is 0");
1269 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001270 = ClassScopeSpecializationPattern.find(FD);
1271 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001272 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001273
1274 return Pos->second;
1275}
1276
1277void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1278 FunctionDecl *Pattern) {
1279 assert(FD && "Specialization is 0");
1280 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001281 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001282}
1283
John McCalle61f2ba2009-11-18 02:36:19 +00001284NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001285ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1286 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001287 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001288 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001289
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001290 return Pos->second;
1291}
1292
1293void
Richard Smithd8a9e372016-12-18 21:39:37 +00001294ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001295 assert((isa<UsingDecl>(Pattern) ||
1296 isa<UnresolvedUsingValueDecl>(Pattern) ||
1297 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1298 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001299 assert((isa<UsingDecl>(Inst) ||
1300 isa<UnresolvedUsingValueDecl>(Inst) ||
1301 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1302 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001303 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1304 InstantiatedFromUsingDecl[Inst] = Pattern;
1305}
1306
1307UsingShadowDecl *
1308ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1309 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1310 = InstantiatedFromUsingShadowDecl.find(Inst);
1311 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001312 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001313
1314 return Pos->second;
1315}
1316
1317void
1318ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1319 UsingShadowDecl *Pattern) {
1320 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1321 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001322}
1323
Anders Carlsson5da84842009-09-01 04:26:58 +00001324FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1325 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1326 = InstantiatedFromUnnamedFieldDecl.find(Field);
1327 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001328 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Anders Carlsson5da84842009-09-01 04:26:58 +00001330 return Pos->second;
1331}
1332
1333void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1334 FieldDecl *Tmpl) {
1335 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1336 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1337 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1338 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001339
Anders Carlsson5da84842009-09-01 04:26:58 +00001340 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1341}
1342
Douglas Gregor832940b2010-03-02 23:58:15 +00001343ASTContext::overridden_cxx_method_iterator
1344ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001345 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1346 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001347 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001348 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001349 return Pos->second.begin();
1350}
1351
1352ASTContext::overridden_cxx_method_iterator
1353ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001354 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1355 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001356 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001357 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001358 return Pos->second.end();
1359}
1360
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001361unsigned
1362ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001363 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1364 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001365 if (Pos == OverriddenMethods.end())
1366 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001367 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001368}
1369
Clement Courbet6ecaec82016-07-05 07:49:31 +00001370ASTContext::overridden_method_range
1371ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1372 return overridden_method_range(overridden_methods_begin(Method),
1373 overridden_methods_end(Method));
1374}
1375
Douglas Gregor832940b2010-03-02 23:58:15 +00001376void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1377 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001378 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001379 OverriddenMethods[Method].push_back(Overridden);
1380}
1381
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001382void ASTContext::getOverriddenMethods(
1383 const NamedDecl *D,
1384 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001385 assert(D);
1386
1387 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001388 Overridden.append(overridden_methods_begin(CXXMethod),
1389 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001390 return;
1391 }
1392
1393 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1394 if (!Method)
1395 return;
1396
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001397 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1398 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001399 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001400}
1401
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001402void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1403 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1404 assert(!Import->isFromASTFile() && "Non-local import declaration");
1405 if (!FirstLocalImport) {
1406 FirstLocalImport = Import;
1407 LastLocalImport = Import;
1408 return;
1409 }
1410
1411 LastLocalImport->NextLocalImport = Import;
1412 LastLocalImport = Import;
1413}
1414
Chris Lattner53cfe802007-07-18 17:52:12 +00001415//===----------------------------------------------------------------------===//
1416// Type Sizing and Analysis
1417//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001418
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001419/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1420/// scalar floating point type.
1421const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001422 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001423 assert(BT && "Not a floating point type!");
1424 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001425 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001426 case BuiltinType::Float16:
1427 case BuiltinType::Half:
1428 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001429 case BuiltinType::Float: return Target->getFloatFormat();
1430 case BuiltinType::Double: return Target->getDoubleFormat();
1431 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001432 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001433 }
1434}
1435
Rafael Espindola71eccb32013-08-08 19:53:46 +00001436CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001437 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001438
John McCall94268702010-10-08 18:24:19 +00001439 bool UseAlignAttrOnly = false;
1440 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1441 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001442
John McCall94268702010-10-08 18:24:19 +00001443 // __attribute__((aligned)) can increase or decrease alignment
1444 // *except* on a struct or struct member, where it only increases
1445 // alignment unless 'packed' is also specified.
1446 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001447 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001448 // ignore that possibility; Sema should diagnose it.
1449 if (isa<FieldDecl>(D)) {
1450 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1451 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1452 } else {
1453 UseAlignAttrOnly = true;
1454 }
1455 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001456 else if (isa<FieldDecl>(D))
1457 UseAlignAttrOnly =
1458 D->hasAttr<PackedAttr>() ||
1459 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001460
John McCall4e819612011-01-20 07:57:12 +00001461 // If we're using the align attribute only, just ignore everything
1462 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001463 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001464 // do nothing
1465
John McCall94268702010-10-08 18:24:19 +00001466 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001467 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001468 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001469 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001470 T = RT->getPointeeType();
1471 else
1472 T = getPointerType(RT->getPointeeType());
1473 }
Richard Smithf6d70302014-06-10 23:34:28 +00001474 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001475 if (T->isFunctionType())
1476 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1477 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001478 // Adjust alignments of declarations with array type by the
1479 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001480 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001481 unsigned MinWidth = Target->getLargeArrayMinWidth();
1482 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001483 if (isa<VariableArrayType>(arrayType))
1484 Align = std::max(Align, Target->getLargeArrayAlign());
1485 else if (isa<ConstantArrayType>(arrayType) &&
1486 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1487 Align = std::max(Align, Target->getLargeArrayAlign());
1488 }
John McCall33ddac02011-01-19 10:06:00 +00001489 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001490 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001491 if (BaseT.getQualifiers().hasUnaligned())
1492 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001493 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001494 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001495 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1496 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001497 }
John McCall4e819612011-01-20 07:57:12 +00001498
1499 // Fields can be subject to extra alignment constraints, like if
1500 // the field is packed, the struct is packed, or the struct has a
1501 // a max-field-alignment constraint (#pragma pack). So calculate
1502 // the actual alignment of the field within the struct, and then
1503 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001504 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1505 const RecordDecl *Parent = Field->getParent();
1506 // We can only produce a sensible answer if the record is valid.
1507 if (!Parent->isInvalidDecl()) {
1508 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001509
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001510 // Start with the record's overall alignment.
1511 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001512
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001513 // Use the GCD of that and the offset within the record.
1514 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1515 if (Offset > 0) {
1516 // Alignment is always a power of 2, so the GCD will be a power of 2,
1517 // which means we get to do this crazy thing instead of Euclid's.
1518 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1519 if (LowBitOfOffset < FieldAlign)
1520 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1521 }
1522
1523 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001524 }
Charles Davis3fc51072010-02-23 04:52:00 +00001525 }
Chris Lattner68061312009-01-24 21:53:27 +00001526 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001527
Ken Dyckcc56c542011-01-15 18:38:59 +00001528 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001529}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001530
John McCallf1249922012-08-21 04:10:00 +00001531// getTypeInfoDataSizeInChars - Return the size of a type, in
1532// chars. If the type is a record, its data size is returned. This is
1533// the size of the memcpy that's performed when assigning this type
1534// using a trivial copy/move assignment operator.
1535std::pair<CharUnits, CharUnits>
1536ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1537 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1538
1539 // In C++, objects can sometimes be allocated into the tail padding
1540 // of a base-class subobject. We decide whether that's possible
1541 // during class layout, so here we can just trust the layout results.
1542 if (getLangOpts().CPlusPlus) {
1543 if (const RecordType *RT = T->getAs<RecordType>()) {
1544 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1545 sizeAndAlign.first = layout.getDataSize();
1546 }
1547 }
1548
1549 return sizeAndAlign;
1550}
1551
Richard Trieu04d2d942013-05-14 21:59:17 +00001552/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1553/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1554std::pair<CharUnits, CharUnits>
1555static getConstantArrayInfoInChars(const ASTContext &Context,
1556 const ConstantArrayType *CAT) {
1557 std::pair<CharUnits, CharUnits> EltInfo =
1558 Context.getTypeInfoInChars(CAT->getElementType());
1559 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001560 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1561 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001562 "Overflow in array type char size evaluation");
1563 uint64_t Width = EltInfo.first.getQuantity() * Size;
1564 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001565 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1566 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001567 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001568 return std::make_pair(CharUnits::fromQuantity(Width),
1569 CharUnits::fromQuantity(Align));
1570}
1571
John McCall87fe5d52010-05-20 01:18:31 +00001572std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001573ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001574 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1575 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001576 TypeInfo Info = getTypeInfo(T);
1577 return std::make_pair(toCharUnitsFromBits(Info.Width),
1578 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001579}
1580
1581std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001582ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001583 return getTypeInfoInChars(T.getTypePtr());
1584}
1585
David Majnemer34b57492014-07-30 01:30:47 +00001586bool ASTContext::isAlignmentRequired(const Type *T) const {
1587 return getTypeInfo(T).AlignIsRequired;
1588}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001589
David Majnemer34b57492014-07-30 01:30:47 +00001590bool ASTContext::isAlignmentRequired(QualType T) const {
1591 return isAlignmentRequired(T.getTypePtr());
1592}
1593
Richard Smithb2f0f052016-10-10 18:54:32 +00001594unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1595 // An alignment on a typedef overrides anything else.
1596 if (auto *TT = T->getAs<TypedefType>())
1597 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1598 return Align;
1599
1600 // If we have an (array of) complete type, we're done.
1601 T = getBaseElementType(T);
1602 if (!T->isIncompleteType())
1603 return getTypeAlign(T);
1604
1605 // If we had an array type, its element type might be a typedef
1606 // type with an alignment attribute.
1607 if (auto *TT = T->getAs<TypedefType>())
1608 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1609 return Align;
1610
1611 // Otherwise, see if the declaration of the type had an attribute.
1612 if (auto *TT = T->getAs<TagType>())
1613 return TT->getDecl()->getMaxAlignment();
1614
1615 return 0;
1616}
1617
David Majnemer34b57492014-07-30 01:30:47 +00001618TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001619 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1620 if (I != MemoizedTypeInfo.end())
1621 return I->second;
1622
1623 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1624 TypeInfo TI = getTypeInfoImpl(T);
1625 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001626 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001627}
1628
1629/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1630/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001631///
1632/// FIXME: Pointers into different addr spaces could have different sizes and
1633/// alignment requirements: getPointerInfo should take an AddrSpace, this
1634/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001635TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1636 uint64_t Width = 0;
1637 unsigned Align = 8;
1638 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001639 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001640 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001641#define TYPE(Class, Base)
1642#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001643#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001644#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001645#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1646 case Type::Class: \
1647 assert(!T->isDependentType() && "should not see dependent types here"); \
1648 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001649#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001650 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001651
Chris Lattner355332d2007-07-13 22:27:08 +00001652 case Type::FunctionNoProto:
1653 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001654 // GCC extension: alignof(function) = 32 bits
1655 Width = 0;
1656 Align = 32;
1657 break;
1658
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001659 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001660 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001661 Width = 0;
1662 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1663 break;
1664
Steve Naroff5c131802007-08-30 01:06:46 +00001665 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001666 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001667
David Majnemer34b57492014-07-30 01:30:47 +00001668 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001669 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001670 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001671 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001672 Width = EltInfo.Width * Size;
1673 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001674 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1675 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001676 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001677 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001678 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001679 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001680 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001681 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001682 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1683 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001684 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001685 // If the alignment is not a power of 2, round up to the next power of 2.
1686 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001687 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001688 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001689 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001690 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001691 // Adjust the alignment based on the target max.
1692 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1693 if (TargetVectorAlign && TargetVectorAlign < Align)
1694 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001695 break;
1696 }
Chris Lattner647fb222007-07-18 18:26:58 +00001697
Chris Lattner7570e9c2008-03-08 08:52:55 +00001698 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001699 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001700 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001701 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001702 // GCC extension: alignof(void) = 8 bits.
1703 Width = 0;
1704 Align = 8;
1705 break;
1706
Chris Lattner6a4f7452007-12-19 19:23:28 +00001707 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001708 Width = Target->getBoolWidth();
1709 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001710 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001711 case BuiltinType::Char_S:
1712 case BuiltinType::Char_U:
1713 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001714 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001715 Width = Target->getCharWidth();
1716 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001717 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001718 case BuiltinType::WChar_S:
1719 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001720 Width = Target->getWCharWidth();
1721 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001722 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001723 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001724 Width = Target->getChar16Width();
1725 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001726 break;
1727 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001728 Width = Target->getChar32Width();
1729 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001730 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001731 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001732 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001733 Width = Target->getShortWidth();
1734 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001735 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001736 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001737 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001738 Width = Target->getIntWidth();
1739 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001740 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001741 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001742 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001743 Width = Target->getLongWidth();
1744 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001745 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001746 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001747 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001748 Width = Target->getLongLongWidth();
1749 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001750 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001751 case BuiltinType::Int128:
1752 case BuiltinType::UInt128:
1753 Width = 128;
1754 Align = 128; // int128_t is 128-bit aligned on all targets.
1755 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001756 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001757 case BuiltinType::Half:
1758 Width = Target->getHalfWidth();
1759 Align = Target->getHalfAlign();
1760 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001761 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001762 Width = Target->getFloatWidth();
1763 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001764 break;
1765 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001766 Width = Target->getDoubleWidth();
1767 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001768 break;
1769 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001770 Width = Target->getLongDoubleWidth();
1771 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001772 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001773 case BuiltinType::Float128:
1774 Width = Target->getFloat128Width();
1775 Align = Target->getFloat128Align();
1776 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001777 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001778 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1779 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001780 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001781 case BuiltinType::ObjCId:
1782 case BuiltinType::ObjCClass:
1783 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001784 Width = Target->getPointerWidth(0);
1785 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001786 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001787 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001788 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001789 case BuiltinType::OCLClkEvent:
1790 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001791 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001792#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1793 case BuiltinType::Id:
1794#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001795 AS = getTargetAddressSpace(Target->getOpenCLTypeAddrSpace(T));
1796 Width = Target->getPointerWidth(AS);
1797 Align = Target->getPointerAlign(AS);
1798 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001799 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001800 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001801 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001802 Width = Target->getPointerWidth(0);
1803 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001804 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001805 case Type::BlockPointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001806 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001807 Width = Target->getPointerWidth(AS);
1808 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001809 break;
1810 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001811 case Type::LValueReference:
1812 case Type::RValueReference: {
1813 // alignof and sizeof should never enter this code path here, so we go
1814 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001815 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001816 Width = Target->getPointerWidth(AS);
1817 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001818 break;
1819 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001820 case Type::Pointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001821 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001822 Width = Target->getPointerWidth(AS);
1823 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001824 break;
1825 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001826 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001827 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001828 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001829 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001830 }
Chris Lattner647fb222007-07-18 18:26:58 +00001831 case Type::Complex: {
1832 // Complex types have the same alignment as their elements, but twice the
1833 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001834 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1835 Width = EltInfo.Width * 2;
1836 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001837 break;
1838 }
John McCall8b07ec22010-05-15 11:32:37 +00001839 case Type::ObjCObject:
1840 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001841 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001842 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001843 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001844 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001845 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001846 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001847 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001848 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001849 break;
1850 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001851 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001852 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001853 const TagType *TT = cast<TagType>(T);
1854
1855 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001856 Width = 8;
1857 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001858 break;
1859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
David Majnemer475b25e2015-01-21 10:54:38 +00001861 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1862 const EnumDecl *ED = ET->getDecl();
1863 TypeInfo Info =
1864 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1865 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1866 Info.Align = AttrAlign;
1867 Info.AlignIsRequired = true;
1868 }
1869 return Info;
1870 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001871
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001872 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001873 const RecordDecl *RD = RT->getDecl();
1874 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001875 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001876 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001877 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001878 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001879 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001880
Chris Lattner63d2b362009-10-22 05:17:15 +00001881 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001882 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1883 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001884
Richard Smith600b5262017-01-26 20:40:47 +00001885 case Type::Auto:
1886 case Type::DeducedTemplateSpecialization: {
1887 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001888 assert(!A->getDeducedType().isNull() &&
1889 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001890 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001891 }
1892
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001893 case Type::Paren:
1894 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1895
Manman Rene6be26c2016-09-13 17:25:08 +00001896 case Type::ObjCTypeParam:
1897 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1898
Douglas Gregoref462e62009-04-30 17:32:17 +00001899 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001900 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001901 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001902 // If the typedef has an aligned attribute on it, it overrides any computed
1903 // alignment we have. This violates the GCC documentation (which says that
1904 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001905 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001906 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001907 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001908 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001909 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001910 AlignIsRequired = Info.AlignIsRequired;
1911 }
David Majnemer34b57492014-07-30 01:30:47 +00001912 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001913 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001914 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001915
Abramo Bagnara6150c882010-05-11 21:36:43 +00001916 case Type::Elaborated:
1917 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001918
John McCall81904512011-01-06 01:58:22 +00001919 case Type::Attributed:
1920 return getTypeInfo(
1921 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1922
Eli Friedman0dfb8892011-10-06 23:00:33 +00001923 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001924 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001925 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1926 Width = Info.Width;
1927 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001928
1929 // If the size of the type doesn't exceed the platform's max
1930 // atomic promotion width, make the size and alignment more
1931 // favorable to atomic operations:
1932 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1933 // Round the size up to a power of 2.
1934 if (!llvm::isPowerOf2_64(Width))
1935 Width = llvm::NextPowerOf2(Width);
1936
1937 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001938 Align = static_cast<unsigned>(Width);
1939 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001940 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001941 break;
1942
1943 case Type::Pipe: {
Anastasia Stulovab3398932017-06-05 11:27:03 +00001944 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1945 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Xiuli Pan9c14e282016-01-09 12:53:17 +00001946 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001947
Douglas Gregoref462e62009-04-30 17:32:17 +00001948 }
Mike Stump11289f42009-09-09 15:08:12 +00001949
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001950 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001951 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001952}
1953
Alexey Bataev00396512015-07-02 03:40:19 +00001954unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1955 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1956 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1957 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1958 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1959 getTargetInfo().getABI() == "elfv1-qpx" &&
1960 T->isSpecificBuiltinType(BuiltinType::Double))
1961 SimdAlign = 256;
1962 return SimdAlign;
1963}
1964
Ken Dyckcc56c542011-01-15 18:38:59 +00001965/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1966CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1967 return CharUnits::fromQuantity(BitSize / getCharWidth());
1968}
1969
Ken Dyckb0fcc592011-02-11 01:54:29 +00001970/// toBits - Convert a size in characters to a size in characters.
1971int64_t ASTContext::toBits(CharUnits CharSize) const {
1972 return CharSize.getQuantity() * getCharWidth();
1973}
1974
Ken Dyck8c89d592009-12-22 14:23:30 +00001975/// getTypeSizeInChars - Return the size of the specified type, in characters.
1976/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001977CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001978 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001979}
Jay Foad39c79802011-01-12 09:06:06 +00001980CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001981 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001982}
1983
Ken Dycka6046ab2010-01-26 17:25:18 +00001984/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001985/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001986CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001987 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001988}
Jay Foad39c79802011-01-12 09:06:06 +00001989CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001990 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001991}
1992
Chris Lattnera3402cd2009-01-27 18:08:34 +00001993/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1994/// type for the current target in bits. This can be different than the ABI
1995/// alignment in cases where it is beneficial for performance to overalign
1996/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001997unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001998 TypeInfo TI = getTypeInfo(T);
1999 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002000
David Majnemere1544562015-04-24 01:25:05 +00002001 T = T->getBaseElementTypeUnsafe();
2002
2003 // The preferred alignment of member pointers is that of a pointer.
2004 if (T->isMemberPointerType())
2005 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2006
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002007 if (!Target->allowsLargerPreferedTypeAlignment())
2008 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002009
Eli Friedman7ab09572009-05-25 21:27:19 +00002010 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002011 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002012 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002013 if (const EnumType *ET = T->getAs<EnumType>())
2014 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002015 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002016 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2017 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002018 // Don't increase the alignment if an alignment attribute was specified on a
2019 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002020 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002021 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002022
Chris Lattnera3402cd2009-01-27 18:08:34 +00002023 return ABIAlign;
2024}
2025
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002026/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2027/// for __attribute__((aligned)) on this target, to be used if no alignment
2028/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002029unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002030 return getTargetInfo().getDefaultAlignForAttributeAligned();
2031}
2032
Ulrich Weigandfa806422013-05-06 16:23:57 +00002033/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2034/// to a global variable of the specified type.
2035unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2036 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2037}
2038
2039/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2040/// should be given to a global variable of the specified type.
2041CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2042 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2043}
2044
David Majnemer08ef2ba2015-06-23 20:34:18 +00002045CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2046 CharUnits Offset = CharUnits::Zero();
2047 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2048 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2049 Offset += Layout->getBaseClassOffset(Base);
2050 Layout = &getASTRecordLayout(Base);
2051 }
2052 return Offset;
2053}
2054
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002055/// DeepCollectObjCIvars -
2056/// This routine first collects all declared, but not synthesized, ivars in
2057/// super class and then collects all ivars, including those synthesized for
2058/// current class. This routine is used for implementation of current class
2059/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002060///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002061void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2062 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002063 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002064 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2065 DeepCollectObjCIvars(SuperClass, false, Ivars);
2066 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002067 for (const auto *I : OI->ivars())
2068 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002069 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002070 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002071 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002072 Iv= Iv->getNextIvar())
2073 Ivars.push_back(Iv);
2074 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002075}
2076
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002077/// CollectInheritedProtocols - Collect all protocols in current class and
2078/// those inherited by it.
2079void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002080 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002081 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002082 // We can use protocol_iterator here instead of
2083 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002084 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002085 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002086 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002087
2088 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002089 for (const auto *Cat : OI->visible_categories())
2090 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002091
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002092 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2093 while (SD) {
2094 CollectInheritedProtocols(SD, Protocols);
2095 SD = SD->getSuperClass();
2096 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002097 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002098 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002099 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002100 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002101 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002102 // Insert the protocol.
2103 if (!Protocols.insert(
2104 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2105 return;
2106
2107 for (auto *Proto : OP->protocols())
2108 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002109 }
2110}
2111
Jay Foad39c79802011-01-12 09:06:06 +00002112unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002113 unsigned count = 0;
2114 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002115 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002116 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002117
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002118 // Count ivar defined in this class's implementation. This
2119 // includes synthesized ivars.
2120 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002121 count += ImplDecl->ivar_size();
2122
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002123 return count;
2124}
2125
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002126bool ASTContext::isSentinelNullExpr(const Expr *E) {
2127 if (!E)
2128 return false;
2129
2130 // nullptr_t is always treated as null.
2131 if (E->getType()->isNullPtrType()) return true;
2132
2133 if (E->getType()->isAnyPointerType() &&
2134 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2135 Expr::NPC_ValueDependentIsNull))
2136 return true;
2137
2138 // Unfortunately, __null has type 'int'.
2139 if (isa<GNUNullExpr>(E)) return true;
2140
2141 return false;
2142}
2143
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002144/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2145ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2146 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2147 I = ObjCImpls.find(D);
2148 if (I != ObjCImpls.end())
2149 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002150 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002151}
2152/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2153ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2154 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2155 I = ObjCImpls.find(D);
2156 if (I != ObjCImpls.end())
2157 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002158 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002159}
2160
2161/// \brief Set the implementation of ObjCInterfaceDecl.
2162void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2163 ObjCImplementationDecl *ImplD) {
2164 assert(IFaceD && ImplD && "Passed null params");
2165 ObjCImpls[IFaceD] = ImplD;
2166}
2167/// \brief Set the implementation of ObjCCategoryDecl.
2168void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2169 ObjCCategoryImplDecl *ImplD) {
2170 assert(CatD && ImplD && "Passed null params");
2171 ObjCImpls[CatD] = ImplD;
2172}
2173
Chandler Carruth21c90602015-12-30 03:24:14 +00002174const ObjCMethodDecl *
2175ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2176 return ObjCMethodRedecls.lookup(MD);
2177}
2178
2179void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2180 const ObjCMethodDecl *Redecl) {
2181 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2182 ObjCMethodRedecls[MD] = Redecl;
2183}
2184
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002185const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2186 const NamedDecl *ND) const {
2187 if (const ObjCInterfaceDecl *ID =
2188 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002189 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002190 if (const ObjCCategoryDecl *CD =
2191 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002192 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002193 if (const ObjCImplDecl *IMD =
2194 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002195 return IMD->getClassInterface();
2196
Craig Topper36250ad2014-05-12 05:36:57 +00002197 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002198}
2199
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002200/// \brief Get the copy initialization expression of VarDecl,or NULL if
2201/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002202Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002203 assert(VD && "Passed null params");
2204 assert(VD->hasAttr<BlocksAttr>() &&
2205 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002206 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002207 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002208 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002209}
2210
2211/// \brief Set the copy inialization expression of a block var decl.
2212void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2213 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002214 assert(VD->hasAttr<BlocksAttr>() &&
2215 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002216 BlockVarCopyInits[VD] = Init;
2217}
2218
John McCallbcd03502009-12-07 02:54:59 +00002219TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002220 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002221 if (!DataSize)
2222 DataSize = TypeLoc::getFullDataSizeForType(T);
2223 else
2224 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002225 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002226
John McCallbcd03502009-12-07 02:54:59 +00002227 TypeSourceInfo *TInfo =
2228 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2229 new (TInfo) TypeSourceInfo(T);
2230 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002231}
2232
John McCallbcd03502009-12-07 02:54:59 +00002233TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002234 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002235 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002236 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002237 return DI;
2238}
2239
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002240const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002241ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002242 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002243}
2244
2245const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002246ASTContext::getASTObjCImplementationLayout(
2247 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002248 return getObjCLayout(D->getClassInterface(), D);
2249}
2250
Chris Lattner983a8bb2007-07-13 22:13:22 +00002251//===----------------------------------------------------------------------===//
2252// Type creation/memoization methods
2253//===----------------------------------------------------------------------===//
2254
Jay Foad39c79802011-01-12 09:06:06 +00002255QualType
John McCall33ddac02011-01-19 10:06:00 +00002256ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2257 unsigned fastQuals = quals.getFastQualifiers();
2258 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002259
2260 // Check if we've already instantiated this type.
2261 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002262 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002263 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002264 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2265 assert(eq->getQualifiers() == quals);
2266 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002267 }
2268
John McCall33ddac02011-01-19 10:06:00 +00002269 // If the base type is not canonical, make the appropriate canonical type.
2270 QualType canon;
2271 if (!baseType->isCanonicalUnqualified()) {
2272 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002273 canonSplit.Quals.addConsistentQualifiers(quals);
2274 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002275
2276 // Re-find the insert position.
2277 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2278 }
2279
2280 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2281 ExtQualNodes.InsertNode(eq, insertPos);
2282 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002283}
2284
Jay Foad39c79802011-01-12 09:06:06 +00002285QualType
2286ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002287 QualType CanT = getCanonicalType(T);
2288 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002289 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002290
John McCall8ccfcb52009-09-24 19:53:00 +00002291 // If we are composing extended qualifiers together, merge together
2292 // into one ExtQuals node.
2293 QualifierCollector Quals;
2294 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002295
John McCall8ccfcb52009-09-24 19:53:00 +00002296 // If this type already has an address space specified, it cannot get
2297 // another one.
2298 assert(!Quals.hasAddressSpace() &&
2299 "Type cannot be in multiple addr spaces!");
2300 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002301
John McCall8ccfcb52009-09-24 19:53:00 +00002302 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002303}
2304
Chris Lattnerd60183d2009-02-18 22:53:11 +00002305QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002306 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002307 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002308 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002309 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002310
John McCall53fa7142010-12-24 02:08:15 +00002311 if (const PointerType *ptr = T->getAs<PointerType>()) {
2312 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002313 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002314 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2315 return getPointerType(ResultType);
2316 }
2317 }
Mike Stump11289f42009-09-09 15:08:12 +00002318
John McCall8ccfcb52009-09-24 19:53:00 +00002319 // If we are composing extended qualifiers together, merge together
2320 // into one ExtQuals node.
2321 QualifierCollector Quals;
2322 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002323
John McCall8ccfcb52009-09-24 19:53:00 +00002324 // If this type already has an ObjCGC specified, it cannot get
2325 // another one.
2326 assert(!Quals.hasObjCGCAttr() &&
2327 "Type cannot have multiple ObjCGCs!");
2328 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002329
John McCall8ccfcb52009-09-24 19:53:00 +00002330 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002331}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002332
John McCall4f5019e2010-12-19 02:44:49 +00002333const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2334 FunctionType::ExtInfo Info) {
2335 if (T->getExtInfo() == Info)
2336 return T;
2337
2338 QualType Result;
2339 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002340 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002341 } else {
2342 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2343 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2344 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002345 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002346 }
2347
2348 return cast<FunctionType>(Result.getTypePtr());
2349}
2350
Richard Smith2a7d4812013-05-04 07:00:32 +00002351void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2352 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002353 FD = FD->getMostRecentDecl();
2354 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002355 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2356 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002357 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002358 if (FunctionDecl *Next = FD->getPreviousDecl())
2359 FD = Next;
2360 else
2361 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002362 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002363 if (ASTMutationListener *L = getASTMutationListener())
2364 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002365}
2366
Richard Smith0b3a4622014-11-13 20:01:57 +00002367/// Get a function type and produce the equivalent function type with the
2368/// specified exception specification. Type sugar that can be present on a
2369/// declaration of a function with an exception specification is permitted
2370/// and preserved. Other type sugar (for instance, typedefs) is not.
2371static QualType getFunctionTypeWithExceptionSpec(
2372 ASTContext &Context, QualType Orig,
2373 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2374 // Might have some parens.
2375 if (auto *PT = dyn_cast<ParenType>(Orig))
2376 return Context.getParenType(
2377 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2378
2379 // Might have a calling-convention attribute.
2380 if (auto *AT = dyn_cast<AttributedType>(Orig))
2381 return Context.getAttributedType(
2382 AT->getAttrKind(),
2383 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2384 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2385 ESI));
2386
2387 // Anything else must be a function type. Rebuild it with the new exception
2388 // specification.
2389 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2390 return Context.getFunctionType(
2391 Proto->getReturnType(), Proto->getParamTypes(),
2392 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2393}
2394
Richard Smithdfe85e22016-12-15 02:35:39 +00002395bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2396 QualType U) {
2397 return hasSameType(T, U) ||
2398 (getLangOpts().CPlusPlus1z &&
2399 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2400 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2401}
2402
Richard Smith0b3a4622014-11-13 20:01:57 +00002403void ASTContext::adjustExceptionSpec(
2404 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2405 bool AsWritten) {
2406 // Update the type.
2407 QualType Updated =
2408 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2409 FD->setType(Updated);
2410
2411 if (!AsWritten)
2412 return;
2413
2414 // Update the type in the type source information too.
2415 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2416 // If the type and the type-as-written differ, we may need to update
2417 // the type-as-written too.
2418 if (TSInfo->getType() != FD->getType())
2419 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2420
2421 // FIXME: When we get proper type location information for exceptions,
2422 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2423 // up the TypeSourceInfo;
2424 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2425 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2426 "TypeLoc size mismatch from updating exception specification");
2427 TSInfo->overrideType(Updated);
2428 }
2429}
2430
Chris Lattnerc6395932007-06-22 20:56:16 +00002431/// getComplexType - Return the uniqued reference to the type for a complex
2432/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002433QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002434 // Unique pointers, to guarantee there is only one pointer of a particular
2435 // structure.
2436 llvm::FoldingSetNodeID ID;
2437 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002438
Craig Topper36250ad2014-05-12 05:36:57 +00002439 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002440 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2441 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattnerc6395932007-06-22 20:56:16 +00002443 // If the pointee type isn't canonical, this won't be a canonical type either,
2444 // so fill in the canonical type field.
2445 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002446 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002447 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattnerc6395932007-06-22 20:56:16 +00002449 // Get the new insert position for the node we care about.
2450 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002451 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002452 }
John McCall90d1c2d2009-09-24 23:30:46 +00002453 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002454 Types.push_back(New);
2455 ComplexTypes.InsertNode(New, InsertPos);
2456 return QualType(New, 0);
2457}
2458
Chris Lattner970e54e2006-11-12 00:37:36 +00002459/// getPointerType - Return the uniqued reference to the type for a pointer to
2460/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002461QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002462 // Unique pointers, to guarantee there is only one pointer of a particular
2463 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002464 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002465 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Craig Topper36250ad2014-05-12 05:36:57 +00002467 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002468 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002469 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattner7ccecb92006-11-12 08:50:50 +00002471 // If the pointee type isn't canonical, this won't be a canonical type either,
2472 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002473 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002474 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002475 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002476
Bob Wilsonc8541f22013-03-15 17:12:43 +00002477 // Get the new insert position for the node we care about.
2478 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002479 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002480 }
John McCall90d1c2d2009-09-24 23:30:46 +00002481 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002482 Types.push_back(New);
2483 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002484 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002485}
2486
Reid Kleckner0503a872013-12-05 01:23:43 +00002487QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2488 llvm::FoldingSetNodeID ID;
2489 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002490 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002491 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 if (AT)
2493 return QualType(AT, 0);
2494
2495 QualType Canonical = getCanonicalType(New);
2496
2497 // Get the new insert position for the node we care about.
2498 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002499 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002500
2501 AT = new (*this, TypeAlignment)
2502 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2503 Types.push_back(AT);
2504 AdjustedTypes.InsertNode(AT, InsertPos);
2505 return QualType(AT, 0);
2506}
2507
Reid Kleckner8a365022013-06-24 17:51:48 +00002508QualType ASTContext::getDecayedType(QualType T) const {
2509 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2510
Reid Kleckner8a365022013-06-24 17:51:48 +00002511 QualType Decayed;
2512
2513 // C99 6.7.5.3p7:
2514 // A declaration of a parameter as "array of type" shall be
2515 // adjusted to "qualified pointer to type", where the type
2516 // qualifiers (if any) are those specified within the [ and ] of
2517 // the array type derivation.
2518 if (T->isArrayType())
2519 Decayed = getArrayDecayedType(T);
2520
2521 // C99 6.7.5.3p8:
2522 // A declaration of a parameter as "function returning type"
2523 // shall be adjusted to "pointer to function returning type", as
2524 // in 6.3.2.1.
2525 if (T->isFunctionType())
2526 Decayed = getPointerType(T);
2527
Reid Kleckner0503a872013-12-05 01:23:43 +00002528 llvm::FoldingSetNodeID ID;
2529 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002530 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002531 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 if (AT)
2533 return QualType(AT, 0);
2534
Reid Kleckner8a365022013-06-24 17:51:48 +00002535 QualType Canonical = getCanonicalType(Decayed);
2536
2537 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002538 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002539 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002540
Reid Kleckner0503a872013-12-05 01:23:43 +00002541 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2542 Types.push_back(AT);
2543 AdjustedTypes.InsertNode(AT, InsertPos);
2544 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002545}
2546
Mike Stump11289f42009-09-09 15:08:12 +00002547/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002548/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002549QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002550 assert(T->isFunctionType() && "block of function types only");
2551 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002552 // structure.
2553 llvm::FoldingSetNodeID ID;
2554 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Craig Topper36250ad2014-05-12 05:36:57 +00002556 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002557 if (BlockPointerType *PT =
2558 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2559 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002560
2561 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002562 // type either so fill in the canonical type field.
2563 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002564 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002565 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002566
Steve Naroffec33ed92008-08-27 16:04:49 +00002567 // Get the new insert position for the node we care about.
2568 BlockPointerType *NewIP =
2569 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002570 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002571 }
John McCall90d1c2d2009-09-24 23:30:46 +00002572 BlockPointerType *New
2573 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002574 Types.push_back(New);
2575 BlockPointerTypes.InsertNode(New, InsertPos);
2576 return QualType(New, 0);
2577}
2578
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002579/// getLValueReferenceType - Return the uniqued reference to the type for an
2580/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002581QualType
2582ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002583 assert(getCanonicalType(T) != OverloadTy &&
2584 "Unresolved overloaded function type");
2585
Bill Wendling3708c182007-05-27 10:15:43 +00002586 // Unique pointers, to guarantee there is only one pointer of a particular
2587 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002588 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002589 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002590
Craig Topper36250ad2014-05-12 05:36:57 +00002591 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002592 if (LValueReferenceType *RT =
2593 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002594 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002595
John McCallfc93cf92009-10-22 22:37:11 +00002596 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2597
Bill Wendling3708c182007-05-27 10:15:43 +00002598 // If the referencee type isn't canonical, this won't be a canonical type
2599 // either, so fill in the canonical type field.
2600 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002601 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2602 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2603 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002604
Bill Wendling3708c182007-05-27 10:15:43 +00002605 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002606 LValueReferenceType *NewIP =
2607 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002608 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002609 }
2610
John McCall90d1c2d2009-09-24 23:30:46 +00002611 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002612 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2613 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002614 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002615 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002616
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002617 return QualType(New, 0);
2618}
2619
2620/// getRValueReferenceType - Return the uniqued reference to the type for an
2621/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002622QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002623 // Unique pointers, to guarantee there is only one pointer of a particular
2624 // structure.
2625 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002626 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002627
Craig Topper36250ad2014-05-12 05:36:57 +00002628 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002629 if (RValueReferenceType *RT =
2630 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2631 return QualType(RT, 0);
2632
John McCallfc93cf92009-10-22 22:37:11 +00002633 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2634
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002635 // If the referencee type isn't canonical, this won't be a canonical type
2636 // either, so fill in the canonical type field.
2637 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002638 if (InnerRef || !T.isCanonical()) {
2639 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2640 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002641
2642 // Get the new insert position for the node we care about.
2643 RValueReferenceType *NewIP =
2644 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002645 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002646 }
2647
John McCall90d1c2d2009-09-24 23:30:46 +00002648 RValueReferenceType *New
2649 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002650 Types.push_back(New);
2651 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002652 return QualType(New, 0);
2653}
2654
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002655/// getMemberPointerType - Return the uniqued reference to the type for a
2656/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002657QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002658 // Unique pointers, to guarantee there is only one pointer of a particular
2659 // structure.
2660 llvm::FoldingSetNodeID ID;
2661 MemberPointerType::Profile(ID, T, Cls);
2662
Craig Topper36250ad2014-05-12 05:36:57 +00002663 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002664 if (MemberPointerType *PT =
2665 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2666 return QualType(PT, 0);
2667
2668 // If the pointee or class type isn't canonical, this won't be a canonical
2669 // type either, so fill in the canonical type field.
2670 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002671 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002672 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2673
2674 // Get the new insert position for the node we care about.
2675 MemberPointerType *NewIP =
2676 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002677 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002678 }
John McCall90d1c2d2009-09-24 23:30:46 +00002679 MemberPointerType *New
2680 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002681 Types.push_back(New);
2682 MemberPointerTypes.InsertNode(New, InsertPos);
2683 return QualType(New, 0);
2684}
2685
Mike Stump11289f42009-09-09 15:08:12 +00002686/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002687/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002688QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002689 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002690 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002691 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002692 assert((EltTy->isDependentType() ||
2693 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002694 "Constant array of VLAs is illegal!");
2695
Chris Lattnere2df3f92009-05-13 04:12:56 +00002696 // Convert the array size into a canonical width matching the pointer size for
2697 // the target.
2698 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002699 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002700
Chris Lattner23b7eb62007-06-15 23:05:46 +00002701 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002702 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002703
Craig Topper36250ad2014-05-12 05:36:57 +00002704 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002705 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002706 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002707 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002708
John McCall33ddac02011-01-19 10:06:00 +00002709 // If the element type isn't canonical or has qualifiers, this won't
2710 // be a canonical type either, so fill in the canonical type field.
2711 QualType Canon;
2712 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2713 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002714 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002715 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002716 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002717
Chris Lattner36f8e652007-01-27 08:31:04 +00002718 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002719 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002720 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002721 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
John McCall90d1c2d2009-09-24 23:30:46 +00002724 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002725 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002726 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002727 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002728 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002729}
2730
John McCall06549462011-01-18 08:40:38 +00002731/// getVariableArrayDecayedType - Turns the given type, which may be
2732/// variably-modified, into the corresponding type with all the known
2733/// sizes replaced with [*].
2734QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2735 // Vastly most common case.
2736 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002737
John McCall06549462011-01-18 08:40:38 +00002738 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002739
John McCall06549462011-01-18 08:40:38 +00002740 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002741 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002742 switch (ty->getTypeClass()) {
2743#define TYPE(Class, Base)
2744#define ABSTRACT_TYPE(Class, Base)
2745#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2746#include "clang/AST/TypeNodes.def"
2747 llvm_unreachable("didn't desugar past all non-canonical types?");
2748
2749 // These types should never be variably-modified.
2750 case Type::Builtin:
2751 case Type::Complex:
2752 case Type::Vector:
2753 case Type::ExtVector:
2754 case Type::DependentSizedExtVector:
2755 case Type::ObjCObject:
2756 case Type::ObjCInterface:
2757 case Type::ObjCObjectPointer:
2758 case Type::Record:
2759 case Type::Enum:
2760 case Type::UnresolvedUsing:
2761 case Type::TypeOfExpr:
2762 case Type::TypeOf:
2763 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002764 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002765 case Type::DependentName:
2766 case Type::InjectedClassName:
2767 case Type::TemplateSpecialization:
2768 case Type::DependentTemplateSpecialization:
2769 case Type::TemplateTypeParm:
2770 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002771 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002772 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002773 case Type::PackExpansion:
2774 llvm_unreachable("type should never be variably-modified");
2775
2776 // These types can be variably-modified but should never need to
2777 // further decay.
2778 case Type::FunctionNoProto:
2779 case Type::FunctionProto:
2780 case Type::BlockPointer:
2781 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002782 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002783 return type;
2784
2785 // These types can be variably-modified. All these modifications
2786 // preserve structure except as noted by comments.
2787 // TODO: if we ever care about optimizing VLAs, there are no-op
2788 // optimizations available here.
2789 case Type::Pointer:
2790 result = getPointerType(getVariableArrayDecayedType(
2791 cast<PointerType>(ty)->getPointeeType()));
2792 break;
2793
2794 case Type::LValueReference: {
2795 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2796 result = getLValueReferenceType(
2797 getVariableArrayDecayedType(lv->getPointeeType()),
2798 lv->isSpelledAsLValue());
2799 break;
2800 }
2801
2802 case Type::RValueReference: {
2803 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2804 result = getRValueReferenceType(
2805 getVariableArrayDecayedType(lv->getPointeeType()));
2806 break;
2807 }
2808
Eli Friedman0dfb8892011-10-06 23:00:33 +00002809 case Type::Atomic: {
2810 const AtomicType *at = cast<AtomicType>(ty);
2811 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2812 break;
2813 }
2814
John McCall06549462011-01-18 08:40:38 +00002815 case Type::ConstantArray: {
2816 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2817 result = getConstantArrayType(
2818 getVariableArrayDecayedType(cat->getElementType()),
2819 cat->getSize(),
2820 cat->getSizeModifier(),
2821 cat->getIndexTypeCVRQualifiers());
2822 break;
2823 }
2824
2825 case Type::DependentSizedArray: {
2826 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2827 result = getDependentSizedArrayType(
2828 getVariableArrayDecayedType(dat->getElementType()),
2829 dat->getSizeExpr(),
2830 dat->getSizeModifier(),
2831 dat->getIndexTypeCVRQualifiers(),
2832 dat->getBracketsRange());
2833 break;
2834 }
2835
2836 // Turn incomplete types into [*] types.
2837 case Type::IncompleteArray: {
2838 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2839 result = getVariableArrayType(
2840 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002841 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002842 ArrayType::Normal,
2843 iat->getIndexTypeCVRQualifiers(),
2844 SourceRange());
2845 break;
2846 }
2847
2848 // Turn VLA types into [*] types.
2849 case Type::VariableArray: {
2850 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2851 result = getVariableArrayType(
2852 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002853 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002854 ArrayType::Star,
2855 vat->getIndexTypeCVRQualifiers(),
2856 vat->getBracketsRange());
2857 break;
2858 }
2859 }
2860
2861 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002862 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002863}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002864
Steve Naroffcadebd02007-08-30 18:14:25 +00002865/// getVariableArrayType - Returns a non-unique reference to the type for a
2866/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002867QualType ASTContext::getVariableArrayType(QualType EltTy,
2868 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002869 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002870 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002871 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002872 // Since we don't unique expressions, it isn't possible to unique VLA's
2873 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002874 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002875
John McCall33ddac02011-01-19 10:06:00 +00002876 // Be sure to pull qualifiers off the element type.
2877 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2878 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002879 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002880 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002881 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002882 }
2883
John McCall90d1c2d2009-09-24 23:30:46 +00002884 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002885 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002886
2887 VariableArrayTypes.push_back(New);
2888 Types.push_back(New);
2889 return QualType(New, 0);
2890}
2891
Douglas Gregor4619e432008-12-05 23:32:09 +00002892/// getDependentSizedArrayType - Returns a non-unique reference to
2893/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002894/// type.
John McCall33ddac02011-01-19 10:06:00 +00002895QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2896 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002897 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002898 unsigned elementTypeQuals,
2899 SourceRange brackets) const {
2900 assert((!numElements || numElements->isTypeDependent() ||
2901 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002902 "Size must be type- or value-dependent!");
2903
John McCall33ddac02011-01-19 10:06:00 +00002904 // Dependently-sized array types that do not have a specified number
2905 // of elements will have their sizes deduced from a dependent
2906 // initializer. We do no canonicalization here at all, which is okay
2907 // because they can't be used in most locations.
2908 if (!numElements) {
2909 DependentSizedArrayType *newType
2910 = new (*this, TypeAlignment)
2911 DependentSizedArrayType(*this, elementType, QualType(),
2912 numElements, ASM, elementTypeQuals,
2913 brackets);
2914 Types.push_back(newType);
2915 return QualType(newType, 0);
2916 }
2917
2918 // Otherwise, we actually build a new type every time, but we
2919 // also build a canonical type.
2920
2921 SplitQualType canonElementType = getCanonicalType(elementType).split();
2922
Craig Topper36250ad2014-05-12 05:36:57 +00002923 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002924 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002925 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002926 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002927 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002928
John McCall33ddac02011-01-19 10:06:00 +00002929 // Look for an existing type with these properties.
2930 DependentSizedArrayType *canonTy =
2931 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002932
John McCall33ddac02011-01-19 10:06:00 +00002933 // If we don't have one, build one.
2934 if (!canonTy) {
2935 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002936 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002937 QualType(), numElements, ASM, elementTypeQuals,
2938 brackets);
2939 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2940 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002941 }
2942
John McCall33ddac02011-01-19 10:06:00 +00002943 // Apply qualifiers from the element type to the array.
2944 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002945 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002946
David Majnemer16a74702015-07-24 05:54:19 +00002947 // If we didn't need extra canonicalization for the element type or the size
2948 // expression, then just use that as our result.
2949 if (QualType(canonElementType.Ty, 0) == elementType &&
2950 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002951 return canon;
2952
2953 // Otherwise, we need to build a type which follows the spelling
2954 // of the element type.
2955 DependentSizedArrayType *sugaredType
2956 = new (*this, TypeAlignment)
2957 DependentSizedArrayType(*this, elementType, canon, numElements,
2958 ASM, elementTypeQuals, brackets);
2959 Types.push_back(sugaredType);
2960 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002961}
2962
John McCall33ddac02011-01-19 10:06:00 +00002963QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002964 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002965 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002966 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002967 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002968
Craig Topper36250ad2014-05-12 05:36:57 +00002969 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002970 if (IncompleteArrayType *iat =
2971 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2972 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002973
2974 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002975 // either, so fill in the canonical type field. We also have to pull
2976 // qualifiers off the element type.
2977 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002978
John McCall33ddac02011-01-19 10:06:00 +00002979 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2980 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002981 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002982 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002983 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002984
2985 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002986 IncompleteArrayType *existing =
2987 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2988 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002989 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002990
John McCall33ddac02011-01-19 10:06:00 +00002991 IncompleteArrayType *newType = new (*this, TypeAlignment)
2992 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002993
John McCall33ddac02011-01-19 10:06:00 +00002994 IncompleteArrayTypes.InsertNode(newType, insertPos);
2995 Types.push_back(newType);
2996 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002997}
2998
Steve Naroff91fcddb2007-07-18 18:00:27 +00002999/// getVectorType - Return the unique reference to a vector type of
3000/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003001QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003002 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003003 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003004
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003005 // Check if we've already instantiated a vector of this type.
3006 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003007 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003008
Craig Topper36250ad2014-05-12 05:36:57 +00003009 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003010 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3011 return QualType(VTP, 0);
3012
3013 // If the element type isn't canonical, this won't be a canonical type either,
3014 // so fill in the canonical type field.
3015 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003016 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003017 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003018
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003019 // Get the new insert position for the node we care about.
3020 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003021 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003022 }
John McCall90d1c2d2009-09-24 23:30:46 +00003023 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003024 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003025 VectorTypes.InsertNode(New, InsertPos);
3026 Types.push_back(New);
3027 return QualType(New, 0);
3028}
3029
Nate Begemance4d7fc2008-04-18 23:10:10 +00003030/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003031/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003032QualType
3033ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003034 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003035
Steve Naroff91fcddb2007-07-18 18:00:27 +00003036 // Check if we've already instantiated a vector of this type.
3037 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003038 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003039 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003040 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003041 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3042 return QualType(VTP, 0);
3043
3044 // If the element type isn't canonical, this won't be a canonical type either,
3045 // so fill in the canonical type field.
3046 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003047 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003048 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003049
Steve Naroff91fcddb2007-07-18 18:00:27 +00003050 // Get the new insert position for the node we care about.
3051 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003052 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003053 }
John McCall90d1c2d2009-09-24 23:30:46 +00003054 ExtVectorType *New = new (*this, TypeAlignment)
3055 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003056 VectorTypes.InsertNode(New, InsertPos);
3057 Types.push_back(New);
3058 return QualType(New, 0);
3059}
3060
Jay Foad39c79802011-01-12 09:06:06 +00003061QualType
3062ASTContext::getDependentSizedExtVectorType(QualType vecType,
3063 Expr *SizeExpr,
3064 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003065 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003066 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003067 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Craig Topper36250ad2014-05-12 05:36:57 +00003069 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003070 DependentSizedExtVectorType *Canon
3071 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3072 DependentSizedExtVectorType *New;
3073 if (Canon) {
3074 // We already have a canonical version of this array type; use it as
3075 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003076 New = new (*this, TypeAlignment)
3077 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3078 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003079 } else {
3080 QualType CanonVecTy = getCanonicalType(vecType);
3081 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003082 New = new (*this, TypeAlignment)
3083 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3084 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003085
3086 DependentSizedExtVectorType *CanonCheck
3087 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3088 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3089 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003090 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3091 } else {
3092 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3093 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003094 New = new (*this, TypeAlignment)
3095 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003096 }
3097 }
Mike Stump11289f42009-09-09 15:08:12 +00003098
Douglas Gregor758a8692009-06-17 21:51:59 +00003099 Types.push_back(New);
3100 return QualType(New, 0);
3101}
3102
John McCall18afab72016-03-01 00:49:02 +00003103/// \brief Determine whether \p T is canonical as the result type of a function.
3104static bool isCanonicalResultType(QualType T) {
3105 return T.isCanonical() &&
3106 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3107 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3108}
3109
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003110/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003111///
Jay Foad39c79802011-01-12 09:06:06 +00003112QualType
3113ASTContext::getFunctionNoProtoType(QualType ResultTy,
3114 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003115 // Unique functions, to guarantee there is only one function of a particular
3116 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003117 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003118 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003119
Craig Topper36250ad2014-05-12 05:36:57 +00003120 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003121 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003122 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003123 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003124
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003125 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003126 if (!isCanonicalResultType(ResultTy)) {
3127 Canonical =
3128 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003129
Chris Lattner47955de2007-01-27 08:37:20 +00003130 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003131 FunctionNoProtoType *NewIP =
3132 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003133 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
John McCall90d1c2d2009-09-24 23:30:46 +00003136 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003137 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003138 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003139 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003140 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003141}
3142
Douglas Gregora602a152015-10-01 20:20:47 +00003143CanQualType
3144ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3145 CanQualType CanResultType = getCanonicalType(ResultType);
3146
3147 // Canonical result types do not have ARC lifetime qualifiers.
3148 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3149 Qualifiers Qs = CanResultType.getQualifiers();
3150 Qs.removeObjCLifetime();
3151 return CanQualType::CreateUnsafe(
3152 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3153 }
3154
3155 return CanResultType;
3156}
3157
Richard Smith3c4f8d22016-10-16 17:54:23 +00003158static bool isCanonicalExceptionSpecification(
3159 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3160 if (ESI.Type == EST_None)
3161 return true;
3162 if (!NoexceptInType)
3163 return false;
3164
3165 // C++17 onwards: exception specification is part of the type, as a simple
3166 // boolean "can this function type throw".
3167 if (ESI.Type == EST_BasicNoexcept)
3168 return true;
3169
3170 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003171 // expansions (so we can't tell whether it's non-throwing) and all its
3172 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003173 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003174 bool AnyPackExpansions = false;
3175 for (QualType ET : ESI.Exceptions) {
3176 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003177 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003178 if (ET->getAs<PackExpansionType>())
3179 AnyPackExpansions = true;
3180 }
3181 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003182 }
3183
Richard Smith2a2cda52016-10-18 19:29:18 +00003184 // A noexcept(expr) specification is (possibly) canonical if expr is
3185 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003186 if (ESI.Type == EST_ComputedNoexcept)
3187 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3188
3189 return false;
3190}
3191
Richard Smith304b1242016-10-18 20:13:25 +00003192QualType ASTContext::getFunctionTypeInternal(
3193 QualType ResultTy, ArrayRef<QualType> ArgArray,
3194 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003195 size_t NumArgs = ArgArray.size();
3196
Richard Smith2a2cda52016-10-18 19:29:18 +00003197 // Unique functions, to guarantee there is only one function of a particular
3198 // structure.
3199 llvm::FoldingSetNodeID ID;
3200 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3201 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003202
Richard Smith2a2cda52016-10-18 19:29:18 +00003203 QualType Canonical;
3204 bool Unique = false;
3205
3206 void *InsertPos = nullptr;
3207 if (FunctionProtoType *FPT =
3208 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3209 QualType Existing = QualType(FPT, 0);
3210
3211 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3212 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003213 // noexcept expression, or we're just looking for a canonical type.
3214 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003215 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003216 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003217 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3218 return Existing;
3219
3220 // We need a new type sugar node for this one, to hold the new noexcept
3221 // expression. We do no canonicalization here, but that's OK since we don't
3222 // expect to see the same noexcept expression much more than once.
3223 Canonical = getCanonicalType(Existing);
3224 Unique = true;
3225 }
3226
3227 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003228 bool IsCanonicalExceptionSpec =
3229 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3230
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003231 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003232 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003233 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003234 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003235 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003236 isCanonical = false;
3237
Richard Smith304b1242016-10-18 20:13:25 +00003238 if (OnlyWantCanonical)
3239 assert(isCanonical &&
3240 "given non-canonical parameters constructing canonical type");
3241
Richard Smith2a2cda52016-10-18 19:29:18 +00003242 // If this type isn't canonical, get the canonical version of it if we don't
3243 // already have it. The exception spec is only partially part of the
3244 // canonical type, and only in C++17 onwards.
3245 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003246 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003247 CanonicalArgs.reserve(NumArgs);
3248 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003249 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003250
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003251 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003252 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003253 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003254
3255 if (IsCanonicalExceptionSpec) {
3256 // Exception spec is already OK.
3257 } else if (NoexceptInType) {
3258 switch (EPI.ExceptionSpec.Type) {
3259 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3260 // We don't know yet. It shouldn't matter what we pick here; no-one
3261 // should ever look at this.
3262 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003263 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003264 CanonicalEPI.ExceptionSpec.Type = EST_None;
3265 break;
3266
Richard Smith2a2cda52016-10-18 19:29:18 +00003267 // A dynamic exception specification is almost always "not noexcept",
3268 // with the exception that a pack expansion might expand to no types.
3269 case EST_Dynamic: {
3270 bool AnyPacks = false;
3271 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3272 if (ET->getAs<PackExpansionType>())
3273 AnyPacks = true;
3274 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3275 }
3276 if (!AnyPacks)
3277 CanonicalEPI.ExceptionSpec.Type = EST_None;
3278 else {
3279 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3280 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3281 }
3282 break;
3283 }
3284
Richard Smith3c4f8d22016-10-16 17:54:23 +00003285 case EST_DynamicNone: case EST_BasicNoexcept:
3286 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3287 break;
3288
3289 case EST_ComputedNoexcept:
3290 llvm::APSInt Value(1);
3291 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3292 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3293 /*IsEvaluated*/false)) {
3294 // This noexcept specification is invalid.
3295 // FIXME: Should this be able to happen?
3296 CanonicalEPI.ExceptionSpec.Type = EST_None;
3297 break;
3298 }
3299
3300 CanonicalEPI.ExceptionSpec.Type =
3301 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3302 break;
3303 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003304 } else {
3305 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3306 }
John McCalldb40c7f2010-12-14 08:05:40 +00003307
Douglas Gregora602a152015-10-01 20:20:47 +00003308 // Adjust the canonical function result type.
3309 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003310 Canonical =
3311 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003312
Chris Lattnerfd4de792007-01-27 01:15:32 +00003313 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003314 FunctionProtoType *NewIP =
3315 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003316 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003317 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003318
John McCall31168b02011-06-15 23:02:42 +00003319 // FunctionProtoType objects are allocated with extra bytes after
3320 // them for three variable size arrays at the end:
3321 // - parameter types
3322 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003323 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003324 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003325 // expression, or information used to resolve the exception
3326 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003327 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003328 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003329
Richard Smith8acb4282014-07-31 21:57:55 +00003330 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3331 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3332 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003333 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003334 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003335 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003336 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003337 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003338 }
John McCall18afab72016-03-01 00:49:02 +00003339
3340 // Put the ExtParameterInfos last. If all were equal, it would make
3341 // more sense to put these before the exception specification, because
3342 // it's much easier to skip past them compared to the elaborate switch
3343 // required to skip the exception specification. However, all is not
3344 // equal; ExtParameterInfos are used to model very uncommon features,
3345 // and it's better not to burden the more common paths.
3346 if (EPI.ExtParameterInfos) {
3347 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3348 }
John McCall31168b02011-06-15 23:02:42 +00003349
John McCalldb40c7f2010-12-14 08:05:40 +00003350 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003351 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003352 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003353 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003354 if (!Unique)
3355 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003356 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003357}
Chris Lattneref51c202006-11-10 07:17:23 +00003358
Joey Goulye3c85de2016-12-01 11:30:49 +00003359QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003360 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003361 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003362
3363 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003364 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003365 return QualType(PT, 0);
3366
3367 // If the pipe element type isn't canonical, this won't be a canonical type
3368 // either, so fill in the canonical type field.
3369 QualType Canonical;
3370 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003371 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003372
3373 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003374 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003375 assert(!NewIP && "Shouldn't be in the map!");
3376 (void)NewIP;
3377 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003378 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003379 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003380 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003381 return QualType(New, 0);
3382}
3383
Joey Goulye3c85de2016-12-01 11:30:49 +00003384QualType ASTContext::getReadPipeType(QualType T) const {
3385 return getPipeType(T, true);
3386}
3387
Joey Gouly5788b782016-11-18 14:10:54 +00003388QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003389 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003390}
3391
John McCalle78aac42010-03-10 03:28:59 +00003392#ifndef NDEBUG
3393static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3394 if (!isa<CXXRecordDecl>(D)) return false;
3395 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3396 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3397 return true;
3398 if (RD->getDescribedClassTemplate() &&
3399 !isa<ClassTemplateSpecializationDecl>(RD))
3400 return true;
3401 return false;
3402}
3403#endif
3404
3405/// getInjectedClassNameType - Return the unique reference to the
3406/// injected class name type for the specified templated declaration.
3407QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003408 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003409 assert(NeedsInjectedClassNameType(Decl));
3410 if (Decl->TypeForDecl) {
3411 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003412 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003413 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3414 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3415 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3416 } else {
John McCall424cec92011-01-19 06:33:43 +00003417 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003418 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003419 Decl->TypeForDecl = newType;
3420 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003421 }
3422 return QualType(Decl->TypeForDecl, 0);
3423}
3424
Douglas Gregor83a586e2008-04-13 21:07:44 +00003425/// getTypeDeclType - Return the unique reference to the type for the
3426/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003427QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003428 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003429 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003430
Richard Smithdda56e42011-04-15 14:24:37 +00003431 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003432 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003433
John McCall96f0b5f2010-03-10 06:48:02 +00003434 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3435 "Template type parameter types are always available.");
3436
John McCall81e38502010-02-16 03:57:14 +00003437 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003438 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003439 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003440 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003441 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003442 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003443 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003444 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003445 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003446 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3447 Decl->TypeForDecl = newType;
3448 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003449 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003450 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003451
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003452 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003453}
3454
Chris Lattner32d920b2007-01-26 02:01:53 +00003455/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003456/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003457QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003458ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3459 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003460 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003461
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003462 if (Canonical.isNull())
3463 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003464 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003465 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003466 Decl->TypeForDecl = newType;
3467 Types.push_back(newType);
3468 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003469}
3470
Jay Foad39c79802011-01-12 09:06:06 +00003471QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003472 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3473
Douglas Gregorec9fd132012-01-14 16:38:05 +00003474 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003475 if (PrevDecl->TypeForDecl)
3476 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3477
John McCall424cec92011-01-19 06:33:43 +00003478 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3479 Decl->TypeForDecl = newType;
3480 Types.push_back(newType);
3481 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003482}
3483
Jay Foad39c79802011-01-12 09:06:06 +00003484QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003485 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3486
Douglas Gregorec9fd132012-01-14 16:38:05 +00003487 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003488 if (PrevDecl->TypeForDecl)
3489 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3490
John McCall424cec92011-01-19 06:33:43 +00003491 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3492 Decl->TypeForDecl = newType;
3493 Types.push_back(newType);
3494 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003495}
3496
John McCall81904512011-01-06 01:58:22 +00003497QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3498 QualType modifiedType,
3499 QualType equivalentType) {
3500 llvm::FoldingSetNodeID id;
3501 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3502
Craig Topper36250ad2014-05-12 05:36:57 +00003503 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003504 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3505 if (type) return QualType(type, 0);
3506
3507 QualType canon = getCanonicalType(equivalentType);
3508 type = new (*this, TypeAlignment)
3509 AttributedType(canon, attrKind, modifiedType, equivalentType);
3510
3511 Types.push_back(type);
3512 AttributedTypes.InsertNode(type, insertPos);
3513
3514 return QualType(type, 0);
3515}
3516
John McCallcebee162009-10-18 09:09:24 +00003517/// \brief Retrieve a substitution-result type.
3518QualType
3519ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003520 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003521 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003522 && "replacement types must always be canonical");
3523
3524 llvm::FoldingSetNodeID ID;
3525 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003526 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003527 SubstTemplateTypeParmType *SubstParm
3528 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3529
3530 if (!SubstParm) {
3531 SubstParm = new (*this, TypeAlignment)
3532 SubstTemplateTypeParmType(Parm, Replacement);
3533 Types.push_back(SubstParm);
3534 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3535 }
3536
3537 return QualType(SubstParm, 0);
3538}
3539
Douglas Gregorada4b792011-01-14 02:55:32 +00003540/// \brief Retrieve a
3541QualType ASTContext::getSubstTemplateTypeParmPackType(
3542 const TemplateTypeParmType *Parm,
3543 const TemplateArgument &ArgPack) {
3544#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003545 for (const auto &P : ArgPack.pack_elements()) {
3546 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3547 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003548 }
3549#endif
3550
3551 llvm::FoldingSetNodeID ID;
3552 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003553 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003554 if (SubstTemplateTypeParmPackType *SubstParm
3555 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3556 return QualType(SubstParm, 0);
3557
3558 QualType Canon;
3559 if (!Parm->isCanonicalUnqualified()) {
3560 Canon = getCanonicalType(QualType(Parm, 0));
3561 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3562 ArgPack);
3563 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3564 }
3565
3566 SubstTemplateTypeParmPackType *SubstParm
3567 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3568 ArgPack);
3569 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003570 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003571 return QualType(SubstParm, 0);
3572}
3573
Douglas Gregoreff93e02009-02-05 23:33:38 +00003574/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003575/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003576/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003577QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003578 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003579 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003580 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003581 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003582 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003583 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003584 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3585
3586 if (TypeParm)
3587 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003588
Chandler Carruth08836322011-05-01 00:51:33 +00003589 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003590 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003591 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003592
3593 TemplateTypeParmType *TypeCheck
3594 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 assert(!TypeCheck && "Template type parameter canonical type broken");
3596 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003597 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003598 TypeParm = new (*this, TypeAlignment)
3599 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003600
3601 Types.push_back(TypeParm);
3602 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3603
3604 return QualType(TypeParm, 0);
3605}
3606
John McCalle78aac42010-03-10 03:28:59 +00003607TypeSourceInfo *
3608ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3609 SourceLocation NameLoc,
3610 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003611 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003612 assert(!Name.getAsDependentTemplateName() &&
3613 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003614 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003615
3616 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003617 TemplateSpecializationTypeLoc TL =
3618 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003619 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003620 TL.setTemplateNameLoc(NameLoc);
3621 TL.setLAngleLoc(Args.getLAngleLoc());
3622 TL.setRAngleLoc(Args.getRAngleLoc());
3623 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3624 TL.setArgLocInfo(i, Args[i].getLocInfo());
3625 return DI;
3626}
3627
Mike Stump11289f42009-09-09 15:08:12 +00003628QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003629ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003630 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003631 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003632 assert(!Template.getAsDependentTemplateName() &&
3633 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003634
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003635 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003636 ArgVec.reserve(Args.size());
3637 for (const TemplateArgumentLoc &Arg : Args.arguments())
3638 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003639
David Majnemer6fbeee32016-07-07 04:43:07 +00003640 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003641}
3642
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003643#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003644static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3645 for (const TemplateArgument &Arg : Args)
3646 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003647 return true;
3648
3649 return true;
3650}
3651#endif
3652
John McCall0ad16662009-10-29 08:12:44 +00003653QualType
3654ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003655 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003656 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003657 assert(!Template.getAsDependentTemplateName() &&
3658 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003659 // Look through qualified template names.
3660 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3661 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003662
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003663 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003664 Template.getAsTemplateDecl() &&
3665 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003666 QualType CanonType;
3667 if (!Underlying.isNull())
3668 CanonType = getCanonicalType(Underlying);
3669 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003670 // We can get here with an alias template when the specialization contains
3671 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003672 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003673 "Caller must compute aliased type");
3674 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003675 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003676 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003677
Douglas Gregora8e02e72009-07-28 23:00:59 +00003678 // Allocate the (non-canonical) template specialization type, but don't
3679 // try to unique it: these types typically have location information that
3680 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003681 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003682 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003683 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003684 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003685 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003686 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003687 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003688
Douglas Gregor8bf42052009-02-09 18:46:07 +00003689 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003690 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003691}
3692
David Majnemer6fbeee32016-07-07 04:43:07 +00003693QualType ASTContext::getCanonicalTemplateSpecializationType(
3694 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003695 assert(!Template.getAsDependentTemplateName() &&
3696 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003697
Douglas Gregore29139c2011-03-03 17:04:51 +00003698 // Look through qualified template names.
3699 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3700 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003701
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003702 // Build the canonical template specialization type.
3703 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003704 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003705 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003706 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003707 for (const TemplateArgument &Arg : Args)
3708 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003709
3710 // Determine whether this canonical template specialization type already
3711 // exists.
3712 llvm::FoldingSetNodeID ID;
3713 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003714 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003715
Craig Topper36250ad2014-05-12 05:36:57 +00003716 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003717 TemplateSpecializationType *Spec
3718 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3719
3720 if (!Spec) {
3721 // Allocate a new canonical template specialization type.
3722 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3723 sizeof(TemplateArgument) * NumArgs),
3724 TypeAlignment);
3725 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003726 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003727 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003728 Types.push_back(Spec);
3729 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3730 }
3731
3732 assert(Spec->isDependentType() &&
3733 "Non-dependent template-id type must have a canonical type");
3734 return QualType(Spec, 0);
3735}
3736
3737QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003738ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3739 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003740 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003741 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003742 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003743
Craig Topper36250ad2014-05-12 05:36:57 +00003744 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003745 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003746 if (T)
3747 return QualType(T, 0);
3748
Douglas Gregorc42075a2010-02-04 18:10:26 +00003749 QualType Canon = NamedType;
3750 if (!Canon.isCanonical()) {
3751 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003752 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3753 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003754 (void)CheckT;
3755 }
3756
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003757 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003758 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003759 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003760 return QualType(T, 0);
3761}
3762
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003763QualType
Jay Foad39c79802011-01-12 09:06:06 +00003764ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003765 llvm::FoldingSetNodeID ID;
3766 ParenType::Profile(ID, InnerType);
3767
Craig Topper36250ad2014-05-12 05:36:57 +00003768 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003769 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3770 if (T)
3771 return QualType(T, 0);
3772
3773 QualType Canon = InnerType;
3774 if (!Canon.isCanonical()) {
3775 Canon = getCanonicalType(InnerType);
3776 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3777 assert(!CheckT && "Paren canonical type broken");
3778 (void)CheckT;
3779 }
3780
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003781 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003782 Types.push_back(T);
3783 ParenTypes.InsertNode(T, InsertPos);
3784 return QualType(T, 0);
3785}
3786
Douglas Gregor02085352010-03-31 20:19:30 +00003787QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3788 NestedNameSpecifier *NNS,
3789 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003790 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003791 if (Canon.isNull()) {
3792 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003793 if (CanonNNS != NNS)
3794 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003795 }
3796
3797 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003798 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003799
Craig Topper36250ad2014-05-12 05:36:57 +00003800 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003801 DependentNameType *T
3802 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003803 if (T)
3804 return QualType(T, 0);
3805
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003806 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003807 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003808 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003809 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003810}
3811
Mike Stump11289f42009-09-09 15:08:12 +00003812QualType
John McCallc392f372010-06-11 00:33:02 +00003813ASTContext::getDependentTemplateSpecializationType(
3814 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003815 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003816 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003817 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003818 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003819 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003820 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3821 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003822 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003823}
3824
3825QualType
3826ASTContext::getDependentTemplateSpecializationType(
3827 ElaboratedTypeKeyword Keyword,
3828 NestedNameSpecifier *NNS,
3829 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003830 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003831 assert((!NNS || NNS->isDependent()) &&
3832 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003833
Douglas Gregorc42075a2010-02-04 18:10:26 +00003834 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003835 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003836 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003837
Craig Topper36250ad2014-05-12 05:36:57 +00003838 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003839 DependentTemplateSpecializationType *T
3840 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003841 if (T)
3842 return QualType(T, 0);
3843
John McCallc392f372010-06-11 00:33:02 +00003844 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003845
John McCallc392f372010-06-11 00:33:02 +00003846 ElaboratedTypeKeyword CanonKeyword = Keyword;
3847 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3848
3849 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003850 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003851 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003852 for (unsigned I = 0; I != NumArgs; ++I) {
3853 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3854 if (!CanonArgs[I].structurallyEquals(Args[I]))
3855 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003856 }
3857
John McCallc392f372010-06-11 00:33:02 +00003858 QualType Canon;
3859 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3860 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003861 Name,
3862 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003863
3864 // Find the insert position again.
3865 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3866 }
3867
3868 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3869 sizeof(TemplateArgument) * NumArgs),
3870 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003871 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003872 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003873 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003874 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003875 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003876}
3877
Richard Smith32918772017-02-14 00:25:28 +00003878TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3879 TemplateArgument Arg;
3880 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3881 QualType ArgType = getTypeDeclType(TTP);
3882 if (TTP->isParameterPack())
3883 ArgType = getPackExpansionType(ArgType, None);
3884
3885 Arg = TemplateArgument(ArgType);
3886 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3887 Expr *E = new (*this) DeclRefExpr(
3888 NTTP, /*enclosing*/false,
3889 NTTP->getType().getNonLValueExprType(*this),
3890 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3891
3892 if (NTTP->isParameterPack())
3893 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3894 None);
3895 Arg = TemplateArgument(E);
3896 } else {
3897 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3898 if (TTP->isParameterPack())
3899 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3900 else
3901 Arg = TemplateArgument(TemplateName(TTP));
3902 }
3903
3904 if (Param->isTemplateParameterPack())
3905 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3906
3907 return Arg;
3908}
3909
Richard Smith43e14d22016-12-23 02:10:11 +00003910void
3911ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3912 SmallVectorImpl<TemplateArgument> &Args) {
3913 Args.reserve(Args.size() + Params->size());
3914
Richard Smith32918772017-02-14 00:25:28 +00003915 for (NamedDecl *Param : *Params)
3916 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003917}
3918
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003919QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003920 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003921 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003922 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003923
3924 assert(Pattern->containsUnexpandedParameterPack() &&
3925 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003926 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003927 PackExpansionType *T
3928 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3929 if (T)
3930 return QualType(T, 0);
3931
3932 QualType Canon;
3933 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003934 Canon = getCanonicalType(Pattern);
3935 // The canonical type might not contain an unexpanded parameter pack, if it
3936 // contains an alias template specialization which ignores one of its
3937 // parameters.
3938 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003939 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003940
Richard Smith68eea502012-07-16 00:20:35 +00003941 // Find the insert position again, in case we inserted an element into
3942 // PackExpansionTypes and invalidated our insert position.
3943 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3944 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003945 }
3946
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003947 T = new (*this, TypeAlignment)
3948 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003949 Types.push_back(T);
3950 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003951 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003952}
3953
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003954/// CmpProtocolNames - Comparison predicate for sorting protocols
3955/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003956static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3957 ObjCProtocolDecl *const *RHS) {
3958 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003959}
3960
Craig Topper1f26d5b2016-01-03 19:43:23 +00003961static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3962 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003963
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003964 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3965 return false;
3966
Craig Topper1f26d5b2016-01-03 19:43:23 +00003967 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003968 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003969 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003970 return false;
3971 return true;
3972}
3973
Craig Topper6a8c1512015-10-22 01:56:18 +00003974static void
3975SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003976 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003977 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003978
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003979 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003980 for (ObjCProtocolDecl *&P : Protocols)
3981 P = P->getCanonicalDecl();
3982
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003983 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003984 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3985 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003986}
3987
John McCall8b07ec22010-05-15 11:32:37 +00003988QualType ASTContext::getObjCObjectType(QualType BaseType,
3989 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003990 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003991 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003992 llvm::makeArrayRef(Protocols, NumProtocols),
3993 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003994}
3995
3996QualType ASTContext::getObjCObjectType(
3997 QualType baseType,
3998 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003999 ArrayRef<ObjCProtocolDecl *> protocols,
4000 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004001 // If the base type is an interface and there aren't any protocols or
4002 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004003 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4004 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004005 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004006
4007 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004008 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004009 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004010 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004011 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4012 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004013
Douglas Gregore9d95f12015-07-07 03:57:35 +00004014 // Determine the type arguments to be used for canonicalization,
4015 // which may be explicitly specified here or written on the base
4016 // type.
4017 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4018 if (effectiveTypeArgs.empty()) {
4019 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4020 effectiveTypeArgs = baseObject->getTypeArgs();
4021 }
John McCallfc93cf92009-10-22 22:37:11 +00004022
Douglas Gregore9d95f12015-07-07 03:57:35 +00004023 // Build the canonical type, which has the canonical base type and a
4024 // sorted-and-uniqued list of protocols and the type arguments
4025 // canonicalized.
4026 QualType canonical;
4027 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4028 effectiveTypeArgs.end(),
4029 [&](QualType type) {
4030 return type.isCanonical();
4031 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004032 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004033 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4034 // Determine the canonical type arguments.
4035 ArrayRef<QualType> canonTypeArgs;
4036 SmallVector<QualType, 4> canonTypeArgsVec;
4037 if (!typeArgsAreCanonical) {
4038 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4039 for (auto typeArg : effectiveTypeArgs)
4040 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4041 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004042 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004043 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004044 }
4045
Douglas Gregore9d95f12015-07-07 03:57:35 +00004046 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4047 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4048 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004049 canonProtocolsVec.append(protocols.begin(), protocols.end());
4050 SortAndUniqueProtocols(canonProtocolsVec);
4051 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004052 } else {
4053 canonProtocols = protocols;
4054 }
4055
4056 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004057 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004058
John McCallfc93cf92009-10-22 22:37:11 +00004059 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004060 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4061 }
4062
Douglas Gregore9d95f12015-07-07 03:57:35 +00004063 unsigned size = sizeof(ObjCObjectTypeImpl);
4064 size += typeArgs.size() * sizeof(QualType);
4065 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4066 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004067 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004068 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4069 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004070
4071 Types.push_back(T);
4072 ObjCObjectTypes.InsertNode(T, InsertPos);
4073 return QualType(T, 0);
4074}
4075
Manman Ren3569eb52016-09-13 17:03:12 +00004076/// Apply Objective-C protocol qualifiers to the given type.
4077/// If this is for the canonical type of a type parameter, we can apply
4078/// protocol qualifiers on the ObjCObjectPointerType.
4079QualType
4080ASTContext::applyObjCProtocolQualifiers(QualType type,
4081 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4082 bool allowOnPointerType) const {
4083 hasError = false;
4084
Manman Renc5705ba2016-09-13 17:41:05 +00004085 if (const ObjCTypeParamType *objT =
4086 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4087 return getObjCTypeParamType(objT->getDecl(), protocols);
4088 }
4089
Manman Ren3569eb52016-09-13 17:03:12 +00004090 // Apply protocol qualifiers to ObjCObjectPointerType.
4091 if (allowOnPointerType) {
4092 if (const ObjCObjectPointerType *objPtr =
4093 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4094 const ObjCObjectType *objT = objPtr->getObjectType();
4095 // Merge protocol lists and construct ObjCObjectType.
4096 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4097 protocolsVec.append(objT->qual_begin(),
4098 objT->qual_end());
4099 protocolsVec.append(protocols.begin(), protocols.end());
4100 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4101 type = getObjCObjectType(
4102 objT->getBaseType(),
4103 objT->getTypeArgsAsWritten(),
4104 protocols,
4105 objT->isKindOfTypeAsWritten());
4106 return getObjCObjectPointerType(type);
4107 }
4108 }
4109
4110 // Apply protocol qualifiers to ObjCObjectType.
4111 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4112 // FIXME: Check for protocols to which the class type is already
4113 // known to conform.
4114
4115 return getObjCObjectType(objT->getBaseType(),
4116 objT->getTypeArgsAsWritten(),
4117 protocols,
4118 objT->isKindOfTypeAsWritten());
4119 }
4120
4121 // If the canonical type is ObjCObjectType, ...
4122 if (type->isObjCObjectType()) {
4123 // Silently overwrite any existing protocol qualifiers.
4124 // TODO: determine whether that's the right thing to do.
4125
4126 // FIXME: Check for protocols to which the class type is already
4127 // known to conform.
4128 return getObjCObjectType(type, { }, protocols, false);
4129 }
4130
4131 // id<protocol-list>
4132 if (type->isObjCIdType()) {
4133 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4134 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4135 objPtr->isKindOfType());
4136 return getObjCObjectPointerType(type);
4137 }
4138
4139 // Class<protocol-list>
4140 if (type->isObjCClassType()) {
4141 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4142 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4143 objPtr->isKindOfType());
4144 return getObjCObjectPointerType(type);
4145 }
4146
4147 hasError = true;
4148 return type;
4149}
4150
Manman Rene6be26c2016-09-13 17:25:08 +00004151QualType
4152ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4153 ArrayRef<ObjCProtocolDecl *> protocols,
4154 QualType Canonical) const {
4155 // Look in the folding set for an existing type.
4156 llvm::FoldingSetNodeID ID;
4157 ObjCTypeParamType::Profile(ID, Decl, protocols);
4158 void *InsertPos = nullptr;
4159 if (ObjCTypeParamType *TypeParam =
4160 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4161 return QualType(TypeParam, 0);
4162
4163 if (Canonical.isNull()) {
4164 // We canonicalize to the underlying type.
4165 Canonical = getCanonicalType(Decl->getUnderlyingType());
4166 if (!protocols.empty()) {
4167 // Apply the protocol qualifers.
4168 bool hasError;
4169 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4170 true/*allowOnPointerType*/);
4171 assert(!hasError && "Error when apply protocol qualifier to bound type");
4172 }
4173 }
4174
4175 unsigned size = sizeof(ObjCTypeParamType);
4176 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4177 void *mem = Allocate(size, TypeAlignment);
4178 ObjCTypeParamType *newType = new (mem)
4179 ObjCTypeParamType(Decl, Canonical, protocols);
4180
4181 Types.push_back(newType);
4182 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4183 return QualType(newType, 0);
4184}
4185
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004186/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4187/// protocol list adopt all protocols in QT's qualified-id protocol
4188/// list.
4189bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4190 ObjCInterfaceDecl *IC) {
4191 if (!QT->isObjCQualifiedIdType())
4192 return false;
4193
4194 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4195 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004196 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004197 if (!IC->ClassImplementsProtocol(Proto, false))
4198 return false;
4199 }
4200 return true;
4201 }
4202 return false;
4203}
4204
4205/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4206/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4207/// of protocols.
4208bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4209 ObjCInterfaceDecl *IDecl) {
4210 if (!QT->isObjCQualifiedIdType())
4211 return false;
4212 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4213 if (!OPT)
4214 return false;
4215 if (!IDecl->hasDefinition())
4216 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004217 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4218 CollectInheritedProtocols(IDecl, InheritedProtocols);
4219 if (InheritedProtocols.empty())
4220 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004221 // Check that if every protocol in list of id<plist> conforms to a protcol
4222 // of IDecl's, then bridge casting is ok.
4223 bool Conforms = false;
4224 for (auto *Proto : OPT->quals()) {
4225 Conforms = false;
4226 for (auto *PI : InheritedProtocols) {
4227 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4228 Conforms = true;
4229 break;
4230 }
4231 }
4232 if (!Conforms)
4233 break;
4234 }
4235 if (Conforms)
4236 return true;
4237
Aaron Ballman83731462014-03-17 16:14:00 +00004238 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004239 // If both the right and left sides have qualifiers.
4240 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004241 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004242 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004243 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004244 break;
4245 }
4246 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004247 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004248 }
4249 return true;
4250}
4251
John McCall8b07ec22010-05-15 11:32:37 +00004252/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4253/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004254QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004255 llvm::FoldingSetNodeID ID;
4256 ObjCObjectPointerType::Profile(ID, ObjectT);
4257
Craig Topper36250ad2014-05-12 05:36:57 +00004258 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004259 if (ObjCObjectPointerType *QT =
4260 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4261 return QualType(QT, 0);
4262
4263 // Find the canonical object type.
4264 QualType Canonical;
4265 if (!ObjectT.isCanonical()) {
4266 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4267
4268 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004269 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4270 }
4271
Douglas Gregorf85bee62010-02-08 22:59:26 +00004272 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004273 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4274 ObjCObjectPointerType *QType =
4275 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Narofffb4330f2009-06-17 22:40:22 +00004277 Types.push_back(QType);
4278 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004279 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004280}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004281
Douglas Gregor1c283312010-08-11 12:19:30 +00004282/// getObjCInterfaceType - Return the unique reference to the type for the
4283/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004284QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4285 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004286 if (Decl->TypeForDecl)
4287 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004288
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004289 if (PrevDecl) {
4290 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4291 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4292 return QualType(PrevDecl->TypeForDecl, 0);
4293 }
4294
Douglas Gregor7671e532011-12-16 16:34:57 +00004295 // Prefer the definition, if there is one.
4296 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4297 Decl = Def;
4298
Douglas Gregor1c283312010-08-11 12:19:30 +00004299 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4300 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4301 Decl->TypeForDecl = T;
4302 Types.push_back(T);
4303 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004304}
4305
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004306/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4307/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004308/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004309/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004310/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004311QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004312 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004313 if (tofExpr->isTypeDependent()) {
4314 llvm::FoldingSetNodeID ID;
4315 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004316
Craig Topper36250ad2014-05-12 05:36:57 +00004317 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004318 DependentTypeOfExprType *Canon
4319 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4320 if (Canon) {
4321 // We already have a "canonical" version of an identical, dependent
4322 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004323 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004324 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004325 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004326 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004327 Canon
4328 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004329 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4330 toe = Canon;
4331 }
4332 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004333 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004334 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004335 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004336 Types.push_back(toe);
4337 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004338}
4339
Steve Naroffa773cd52007-08-01 18:02:17 +00004340/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004341/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004342/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004343/// an issue. This doesn't affect the type checker, since it operates
4344/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004345QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004346 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004347 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004348 Types.push_back(tot);
4349 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004350}
4351
Richard Smith8eb1d322014-06-05 20:13:13 +00004352/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4353/// nodes. This would never be helpful, since each such type has its own
4354/// expression, and would not give a significant memory saving, since there
4355/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004356QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004357 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004358
4359 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004360 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004361 // unique dependent type. Two such decltype-specifiers refer to the same
4362 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004363 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004364 llvm::FoldingSetNodeID ID;
4365 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004366
Craig Topper36250ad2014-05-12 05:36:57 +00004367 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004368 DependentDecltypeType *Canon
4369 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004370 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004371 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004372 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004373 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004374 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004375 dt = new (*this, TypeAlignment)
4376 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004377 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004378 dt = new (*this, TypeAlignment)
4379 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004380 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004381 Types.push_back(dt);
4382 return QualType(dt, 0);
4383}
4384
Alexis Hunte852b102011-05-24 22:41:36 +00004385/// getUnaryTransformationType - We don't unique these, since the memory
4386/// savings are minimal and these are rare.
4387QualType ASTContext::getUnaryTransformType(QualType BaseType,
4388 QualType UnderlyingType,
4389 UnaryTransformType::UTTKind Kind)
4390 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004391 UnaryTransformType *ut = nullptr;
4392
4393 if (BaseType->isDependentType()) {
4394 // Look in the folding set for an existing type.
4395 llvm::FoldingSetNodeID ID;
4396 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4397
4398 void *InsertPos = nullptr;
4399 DependentUnaryTransformType *Canon
4400 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4401
4402 if (!Canon) {
4403 // Build a new, canonical __underlying_type(type) type.
4404 Canon = new (*this, TypeAlignment)
4405 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4406 Kind);
4407 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4408 }
4409 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4410 QualType(), Kind,
4411 QualType(Canon, 0));
4412 } else {
4413 QualType CanonType = getCanonicalType(UnderlyingType);
4414 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4415 UnderlyingType, Kind,
4416 CanonType);
4417 }
4418 Types.push_back(ut);
4419 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004420}
4421
Richard Smith2a7d4812013-05-04 07:00:32 +00004422/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4423/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4424/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004425QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004426 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004427 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004428 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004429
Richard Smith2a7d4812013-05-04 07:00:32 +00004430 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004431 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004432 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004433 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004434 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4435 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004436
Richard Smith74aeef52013-04-26 16:15:35 +00004437 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004438 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004439 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004440 Types.push_back(AT);
4441 if (InsertPos)
4442 AutoTypes.InsertNode(AT, InsertPos);
4443 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004444}
4445
Richard Smith600b5262017-01-26 20:40:47 +00004446/// Return the uniqued reference to the deduced template specialization type
4447/// which has been deduced to the given type, or to the canonical undeduced
4448/// such type, or the canonical deduced-but-dependent such type.
4449QualType ASTContext::getDeducedTemplateSpecializationType(
4450 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4451 // Look in the folding set for an existing type.
4452 void *InsertPos = nullptr;
4453 llvm::FoldingSetNodeID ID;
4454 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4455 IsDependent);
4456 if (DeducedTemplateSpecializationType *DTST =
4457 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4458 return QualType(DTST, 0);
4459
4460 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4461 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4462 Types.push_back(DTST);
4463 if (InsertPos)
4464 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4465 return QualType(DTST, 0);
4466}
4467
Eli Friedman0dfb8892011-10-06 23:00:33 +00004468/// getAtomicType - Return the uniqued reference to the atomic type for
4469/// the given value type.
4470QualType ASTContext::getAtomicType(QualType T) const {
4471 // Unique pointers, to guarantee there is only one pointer of a particular
4472 // structure.
4473 llvm::FoldingSetNodeID ID;
4474 AtomicType::Profile(ID, T);
4475
Craig Topper36250ad2014-05-12 05:36:57 +00004476 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004477 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4478 return QualType(AT, 0);
4479
4480 // If the atomic value type isn't canonical, this won't be a canonical type
4481 // either, so fill in the canonical type field.
4482 QualType Canonical;
4483 if (!T.isCanonical()) {
4484 Canonical = getAtomicType(getCanonicalType(T));
4485
4486 // Get the new insert position for the node we care about.
4487 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004488 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004489 }
4490 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4491 Types.push_back(New);
4492 AtomicTypes.InsertNode(New, InsertPos);
4493 return QualType(New, 0);
4494}
4495
Richard Smith02e85f32011-04-14 22:09:26 +00004496/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4497QualType ASTContext::getAutoDeductType() const {
4498 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004499 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004500 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004501 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004502 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004503 return AutoDeductTy;
4504}
4505
4506/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4507QualType ASTContext::getAutoRRefDeductType() const {
4508 if (AutoRRefDeductTy.isNull())
4509 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4510 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4511 return AutoRRefDeductTy;
4512}
4513
Chris Lattnerfb072462007-01-23 05:45:31 +00004514/// getTagDeclType - Return the unique reference to the type for the
4515/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004516QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004517 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004518 // FIXME: What is the design on getTagDeclType when it requires casting
4519 // away const? mutable?
4520 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004521}
4522
Mike Stump11289f42009-09-09 15:08:12 +00004523/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4524/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4525/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004526CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004527 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004528}
Chris Lattnerfb072462007-01-23 05:45:31 +00004529
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004530/// Return the unique signed counterpart of the integer type
4531/// corresponding to size_t.
4532CanQualType ASTContext::getSignedSizeType() const {
4533 return getFromTargetType(Target->getSignedSizeType());
4534}
4535
Hans Wennborg27541db2011-10-27 08:29:09 +00004536/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4537CanQualType ASTContext::getIntMaxType() const {
4538 return getFromTargetType(Target->getIntMaxType());
4539}
4540
4541/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4542CanQualType ASTContext::getUIntMaxType() const {
4543 return getFromTargetType(Target->getUIntMaxType());
4544}
4545
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004546/// getSignedWCharType - Return the type of "signed wchar_t".
4547/// Used when in C++, as a GCC extension.
4548QualType ASTContext::getSignedWCharType() const {
4549 // FIXME: derive from "Target" ?
4550 return WCharTy;
4551}
4552
4553/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4554/// Used when in C++, as a GCC extension.
4555QualType ASTContext::getUnsignedWCharType() const {
4556 // FIXME: derive from "Target" ?
4557 return UnsignedIntTy;
4558}
4559
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004560QualType ASTContext::getIntPtrType() const {
4561 return getFromTargetType(Target->getIntPtrType());
4562}
4563
4564QualType ASTContext::getUIntPtrType() const {
4565 return getCorrespondingUnsignedType(getIntPtrType());
4566}
4567
Hans Wennborg27541db2011-10-27 08:29:09 +00004568/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004569/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4570QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004571 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004572}
4573
Eli Friedman4e91899e2012-11-27 02:58:24 +00004574/// \brief Return the unique type for "pid_t" defined in
4575/// <sys/types.h>. We need this to compute the correct type for vfork().
4576QualType ASTContext::getProcessIDType() const {
4577 return getFromTargetType(Target->getProcessIDType());
4578}
4579
Chris Lattnera21ad802008-04-02 05:18:44 +00004580//===----------------------------------------------------------------------===//
4581// Type Operators
4582//===----------------------------------------------------------------------===//
4583
Jay Foad39c79802011-01-12 09:06:06 +00004584CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004585 // Push qualifiers into arrays, and then discard any remaining
4586 // qualifiers.
4587 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004588 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004589 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004590 QualType Result;
4591 if (isa<ArrayType>(Ty)) {
4592 Result = getArrayDecayedType(QualType(Ty,0));
4593 } else if (isa<FunctionType>(Ty)) {
4594 Result = getPointerType(QualType(Ty, 0));
4595 } else {
4596 Result = QualType(Ty, 0);
4597 }
4598
4599 return CanQualType::CreateUnsafe(Result);
4600}
4601
John McCall6c9dd522011-01-18 07:41:22 +00004602QualType ASTContext::getUnqualifiedArrayType(QualType type,
4603 Qualifiers &quals) {
4604 SplitQualType splitType = type.getSplitUnqualifiedType();
4605
4606 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4607 // the unqualified desugared type and then drops it on the floor.
4608 // We then have to strip that sugar back off with
4609 // getUnqualifiedDesugaredType(), which is silly.
4610 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004611 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004612
4613 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004614 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004615 quals = splitType.Quals;
4616 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004617 }
4618
John McCall6c9dd522011-01-18 07:41:22 +00004619 // Otherwise, recurse on the array's element type.
4620 QualType elementType = AT->getElementType();
4621 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4622
4623 // If that didn't change the element type, AT has no qualifiers, so we
4624 // can just use the results in splitType.
4625 if (elementType == unqualElementType) {
4626 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004627 quals = splitType.Quals;
4628 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004629 }
4630
4631 // Otherwise, add in the qualifiers from the outermost type, then
4632 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004633 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004634
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004635 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004636 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004637 CAT->getSizeModifier(), 0);
4638 }
4639
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004640 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004641 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004642 }
4643
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004644 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004645 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004646 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004647 VAT->getSizeModifier(),
4648 VAT->getIndexTypeCVRQualifiers(),
4649 VAT->getBracketsRange());
4650 }
4651
4652 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004653 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004654 DSAT->getSizeModifier(), 0,
4655 SourceRange());
4656}
4657
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004658/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4659/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4660/// they point to and return true. If T1 and T2 aren't pointer types
4661/// or pointer-to-member types, or if they are not similar at this
4662/// level, returns false and leaves T1 and T2 unchanged. Top-level
4663/// qualifiers on T1 and T2 are ignored. This function will typically
4664/// be called in a loop that successively "unwraps" pointer and
4665/// pointer-to-member types to compare them at each level.
4666bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4667 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4668 *T2PtrType = T2->getAs<PointerType>();
4669 if (T1PtrType && T2PtrType) {
4670 T1 = T1PtrType->getPointeeType();
4671 T2 = T2PtrType->getPointeeType();
4672 return true;
4673 }
4674
4675 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4676 *T2MPType = T2->getAs<MemberPointerType>();
4677 if (T1MPType && T2MPType &&
4678 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4679 QualType(T2MPType->getClass(), 0))) {
4680 T1 = T1MPType->getPointeeType();
4681 T2 = T2MPType->getPointeeType();
4682 return true;
4683 }
4684
David Blaikiebbafb8a2012-03-11 07:00:24 +00004685 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004686 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4687 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4688 if (T1OPType && T2OPType) {
4689 T1 = T1OPType->getPointeeType();
4690 T2 = T2OPType->getPointeeType();
4691 return true;
4692 }
4693 }
4694
4695 // FIXME: Block pointers, too?
4696
4697 return false;
4698}
4699
Jay Foad39c79802011-01-12 09:06:06 +00004700DeclarationNameInfo
4701ASTContext::getNameForTemplate(TemplateName Name,
4702 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004703 switch (Name.getKind()) {
4704 case TemplateName::QualifiedTemplate:
4705 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004706 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004707 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4708 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004709
John McCalld9dfe3a2011-06-30 08:33:18 +00004710 case TemplateName::OverloadedTemplate: {
4711 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4712 // DNInfo work in progress: CHECKME: what about DNLoc?
4713 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4714 }
4715
4716 case TemplateName::DependentTemplate: {
4717 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004718 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004719 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004720 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4721 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004722 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004723 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4724 // DNInfo work in progress: FIXME: source locations?
4725 DeclarationNameLoc DNLoc;
4726 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4727 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4728 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004729 }
4730 }
4731
John McCalld9dfe3a2011-06-30 08:33:18 +00004732 case TemplateName::SubstTemplateTemplateParm: {
4733 SubstTemplateTemplateParmStorage *subst
4734 = Name.getAsSubstTemplateTemplateParm();
4735 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4736 NameLoc);
4737 }
4738
4739 case TemplateName::SubstTemplateTemplateParmPack: {
4740 SubstTemplateTemplateParmPackStorage *subst
4741 = Name.getAsSubstTemplateTemplateParmPack();
4742 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4743 NameLoc);
4744 }
4745 }
4746
4747 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004748}
4749
Jay Foad39c79802011-01-12 09:06:06 +00004750TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004751 switch (Name.getKind()) {
4752 case TemplateName::QualifiedTemplate:
4753 case TemplateName::Template: {
4754 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004755 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004756 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004757 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4758
4759 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004760 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004761 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004762
John McCalld9dfe3a2011-06-30 08:33:18 +00004763 case TemplateName::OverloadedTemplate:
4764 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004765
John McCalld9dfe3a2011-06-30 08:33:18 +00004766 case TemplateName::DependentTemplate: {
4767 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4768 assert(DTN && "Non-dependent template names must refer to template decls.");
4769 return DTN->CanonicalTemplateName;
4770 }
4771
4772 case TemplateName::SubstTemplateTemplateParm: {
4773 SubstTemplateTemplateParmStorage *subst
4774 = Name.getAsSubstTemplateTemplateParm();
4775 return getCanonicalTemplateName(subst->getReplacement());
4776 }
4777
4778 case TemplateName::SubstTemplateTemplateParmPack: {
4779 SubstTemplateTemplateParmPackStorage *subst
4780 = Name.getAsSubstTemplateTemplateParmPack();
4781 TemplateTemplateParmDecl *canonParameter
4782 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4783 TemplateArgument canonArgPack
4784 = getCanonicalTemplateArgument(subst->getArgumentPack());
4785 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4786 }
4787 }
4788
4789 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004790}
4791
Douglas Gregoradee3e32009-11-11 23:06:43 +00004792bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4793 X = getCanonicalTemplateName(X);
4794 Y = getCanonicalTemplateName(Y);
4795 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4796}
4797
Mike Stump11289f42009-09-09 15:08:12 +00004798TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004799ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004800 switch (Arg.getKind()) {
4801 case TemplateArgument::Null:
4802 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004803
Douglas Gregora8e02e72009-07-28 23:00:59 +00004804 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004805 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004806
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004807 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004808 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004809 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Eli Friedmanb826a002012-09-26 02:36:12 +00004812 case TemplateArgument::NullPtr:
4813 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4814 /*isNullPtr*/true);
4815
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004816 case TemplateArgument::Template:
4817 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004818
4819 case TemplateArgument::TemplateExpansion:
4820 return TemplateArgument(getCanonicalTemplateName(
4821 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004822 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004823
Douglas Gregora8e02e72009-07-28 23:00:59 +00004824 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004825 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004826
Douglas Gregora8e02e72009-07-28 23:00:59 +00004827 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004828 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004829
Douglas Gregora8e02e72009-07-28 23:00:59 +00004830 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004831 if (Arg.pack_size() == 0)
4832 return Arg;
4833
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004834 TemplateArgument *CanonArgs
4835 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004836 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004837 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004838 AEnd = Arg.pack_end();
4839 A != AEnd; (void)++A, ++Idx)
4840 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004841
Benjamin Kramercce63472015-08-05 09:40:22 +00004842 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004843 }
4844 }
4845
4846 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004847 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004848}
4849
Douglas Gregor333489b2009-03-27 23:10:48 +00004850NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004851ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004852 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004853 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004854
4855 switch (NNS->getKind()) {
4856 case NestedNameSpecifier::Identifier:
4857 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004858 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004859 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4860 NNS->getAsIdentifier());
4861
4862 case NestedNameSpecifier::Namespace:
4863 // A namespace is canonical; build a nested-name-specifier with
4864 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004865 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004866 NNS->getAsNamespace()->getOriginalNamespace());
4867
4868 case NestedNameSpecifier::NamespaceAlias:
4869 // A namespace is canonical; build a nested-name-specifier with
4870 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004871 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004872 NNS->getAsNamespaceAlias()->getNamespace()
4873 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004874
4875 case NestedNameSpecifier::TypeSpec:
4876 case NestedNameSpecifier::TypeSpecWithTemplate: {
4877 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004878
4879 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4880 // break it apart into its prefix and identifier, then reconsititute those
4881 // as the canonical nested-name-specifier. This is required to canonicalize
4882 // a dependent nested-name-specifier involving typedefs of dependent-name
4883 // types, e.g.,
4884 // typedef typename T::type T1;
4885 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004886 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4887 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004888 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004889
Eli Friedman5358a0a2012-03-03 04:09:56 +00004890 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4891 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4892 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004893 return NestedNameSpecifier::Create(*this, nullptr, false,
4894 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004895 }
4896
4897 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004898 case NestedNameSpecifier::Super:
4899 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004900 return NNS;
4901 }
4902
David Blaikie8a40f702012-01-17 06:56:22 +00004903 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004904}
4905
Jay Foad39c79802011-01-12 09:06:06 +00004906const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004907 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004908 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004909 // Handle the common positive case fast.
4910 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4911 return AT;
4912 }
Mike Stump11289f42009-09-09 15:08:12 +00004913
John McCall8ccfcb52009-09-24 19:53:00 +00004914 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004915 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004916 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004917
John McCall8ccfcb52009-09-24 19:53:00 +00004918 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004919 // implements C99 6.7.3p8: "If the specification of an array type includes
4920 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004921
Chris Lattner7adf0762008-08-04 07:31:14 +00004922 // If we get here, we either have type qualifiers on the type, or we have
4923 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004924 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004925
John McCall33ddac02011-01-19 10:06:00 +00004926 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004927 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004928
Chris Lattner7adf0762008-08-04 07:31:14 +00004929 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004930 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004931 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004932 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004933
Chris Lattner7adf0762008-08-04 07:31:14 +00004934 // Otherwise, we have an array and we have qualifiers on it. Push the
4935 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004936 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004937
Chris Lattner7adf0762008-08-04 07:31:14 +00004938 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4939 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4940 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004941 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004942 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4943 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4944 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004945 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004946
Mike Stump11289f42009-09-09 15:08:12 +00004947 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004948 = dyn_cast<DependentSizedArrayType>(ATy))
4949 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004950 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004951 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004952 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004953 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004954 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004955
Chris Lattner7adf0762008-08-04 07:31:14 +00004956 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004957 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004958 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004959 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004960 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004961 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004962}
4963
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004964QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004965 if (T->isArrayType() || T->isFunctionType())
4966 return getDecayedType(T);
4967 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004968}
4969
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004970QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004971 T = getVariableArrayDecayedType(T);
4972 T = getAdjustedParameterType(T);
4973 return T.getUnqualifiedType();
4974}
4975
David Majnemerd09a51c2015-03-03 01:50:05 +00004976QualType ASTContext::getExceptionObjectType(QualType T) const {
4977 // C++ [except.throw]p3:
4978 // A throw-expression initializes a temporary object, called the exception
4979 // object, the type of which is determined by removing any top-level
4980 // cv-qualifiers from the static type of the operand of throw and adjusting
4981 // the type from "array of T" or "function returning T" to "pointer to T"
4982 // or "pointer to function returning T", [...]
4983 T = getVariableArrayDecayedType(T);
4984 if (T->isArrayType() || T->isFunctionType())
4985 T = getDecayedType(T);
4986 return T.getUnqualifiedType();
4987}
4988
Chris Lattnera21ad802008-04-02 05:18:44 +00004989/// getArrayDecayedType - Return the properly qualified result of decaying the
4990/// specified array type to a pointer. This operation is non-trivial when
4991/// handling typedefs etc. The canonical type of "T" must be an array type,
4992/// this returns a pointer to a properly qualified element of the array.
4993///
4994/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004995QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004996 // Get the element type with 'getAsArrayType' so that we don't lose any
4997 // typedefs in the element type of the array. This also handles propagation
4998 // of type qualifiers from the array type into the element type if present
4999 // (C99 6.7.3p8).
5000 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5001 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005002
Chris Lattner7adf0762008-08-04 07:31:14 +00005003 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005004
5005 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005006 QualType Result = getQualifiedType(PtrTy,
5007 PrettyArrayType->getIndexTypeQualifiers());
5008
5009 // int x[_Nullable] -> int * _Nullable
5010 if (auto Nullability = Ty->getNullability(*this)) {
5011 Result = const_cast<ASTContext *>(this)->getAttributedType(
5012 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5013 }
5014 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005015}
5016
John McCall33ddac02011-01-19 10:06:00 +00005017QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5018 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005019}
5020
John McCall33ddac02011-01-19 10:06:00 +00005021QualType ASTContext::getBaseElementType(QualType type) const {
5022 Qualifiers qs;
5023 while (true) {
5024 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005025 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005026 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005027
John McCall33ddac02011-01-19 10:06:00 +00005028 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005029 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005030 }
Mike Stump11289f42009-09-09 15:08:12 +00005031
John McCall33ddac02011-01-19 10:06:00 +00005032 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005033}
5034
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005035/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005036uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005037ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5038 uint64_t ElementCount = 1;
5039 do {
5040 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005041 CA = dyn_cast_or_null<ConstantArrayType>(
5042 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005043 } while (CA);
5044 return ElementCount;
5045}
5046
Steve Naroff0af91202007-04-27 21:51:21 +00005047/// getFloatingRank - Return a relative rank for floating point types.
5048/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005049static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005050 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005051 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005052
John McCall9dd450b2009-09-21 23:43:11 +00005053 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5054 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005055 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005056 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005057 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005058 case BuiltinType::Float: return FloatRank;
5059 case BuiltinType::Double: return DoubleRank;
5060 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005061 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005062 }
5063}
5064
Mike Stump11289f42009-09-09 15:08:12 +00005065/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5066/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005067/// 'typeDomain' is a real floating point or complex type.
5068/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005069QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5070 QualType Domain) const {
5071 FloatingRank EltRank = getFloatingRank(Size);
5072 if (Domain->isComplexType()) {
5073 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005074 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005075 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005076 case FloatRank: return FloatComplexTy;
5077 case DoubleRank: return DoubleComplexTy;
5078 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005079 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005080 }
Steve Naroff0af91202007-04-27 21:51:21 +00005081 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005082
5083 assert(Domain->isRealFloatingType() && "Unknown domain!");
5084 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005085 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005086 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005087 case FloatRank: return FloatTy;
5088 case DoubleRank: return DoubleTy;
5089 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005090 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005091 }
David Blaikief47fa302012-01-17 02:30:50 +00005092 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005093}
5094
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005095/// getFloatingTypeOrder - Compare the rank of the two specified floating
5096/// point types, ignoring the domain of the type (i.e. 'double' ==
5097/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005098/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005099int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005100 FloatingRank LHSR = getFloatingRank(LHS);
5101 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005102
Chris Lattnerb90739d2008-04-06 23:38:49 +00005103 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005104 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005105 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005106 return 1;
5107 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005108}
5109
Chris Lattner76a00cf2008-04-06 22:59:24 +00005110/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5111/// routine will assert if passed a built-in type that isn't an integer or enum,
5112/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005113unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005114 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005115
Chris Lattner76a00cf2008-04-06 22:59:24 +00005116 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005117 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005118 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005119 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005120 case BuiltinType::Char_S:
5121 case BuiltinType::Char_U:
5122 case BuiltinType::SChar:
5123 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005124 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005125 case BuiltinType::Short:
5126 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005127 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005128 case BuiltinType::Int:
5129 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005130 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005131 case BuiltinType::Long:
5132 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005133 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005134 case BuiltinType::LongLong:
5135 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005136 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005137 case BuiltinType::Int128:
5138 case BuiltinType::UInt128:
5139 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005140 }
5141}
5142
Eli Friedman629ffb92009-08-20 04:21:42 +00005143/// \brief Whether this is a promotable bitfield reference according
5144/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5145///
5146/// \returns the type this bit-field will promote to, or NULL if no
5147/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005148QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005149 if (E->isTypeDependent() || E->isValueDependent())
5150 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005151
5152 // FIXME: We should not do this unless E->refersToBitField() is true. This
5153 // matters in C where getSourceBitField() will find bit-fields for various
5154 // cases where the source expression is not a bit-field designator.
5155
John McCalld25db7e2013-05-06 21:39:12 +00005156 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005157 if (!Field)
5158 return QualType();
5159
5160 QualType FT = Field->getType();
5161
Richard Smithcaf33902011-10-10 18:28:20 +00005162 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005163 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005164 // C++ [conv.prom]p5:
5165 // A prvalue for an integral bit-field can be converted to a prvalue of type
5166 // int if int can represent all the values of the bit-field; otherwise, it
5167 // can be converted to unsigned int if unsigned int can represent all the
5168 // values of the bit-field. If the bit-field is larger yet, no integral
5169 // promotion applies to it.
5170 // C11 6.3.1.1/2:
5171 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5172 // If an int can represent all values of the original type (as restricted by
5173 // the width, for a bit-field), the value is converted to an int; otherwise,
5174 // it is converted to an unsigned int.
5175 //
5176 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5177 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005178 if (BitWidth < IntSize)
5179 return IntTy;
5180
5181 if (BitWidth == IntSize)
5182 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5183
5184 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005185 // like the base type. GCC has some weird bugs in this area that we
5186 // deliberately do not follow (GCC follows a pre-standard resolution to
5187 // C's DR315 which treats bit-width as being part of the type, and this leaks
5188 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005189 return QualType();
5190}
5191
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005192/// getPromotedIntegerType - Returns the type that Promotable will
5193/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5194/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005195QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005196 assert(!Promotable.isNull());
5197 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005198 if (const EnumType *ET = Promotable->getAs<EnumType>())
5199 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005200
5201 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5202 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5203 // (3.9.1) can be converted to a prvalue of the first of the following
5204 // types that can represent all the values of its underlying type:
5205 // int, unsigned int, long int, unsigned long int, long long int, or
5206 // unsigned long long int [...]
5207 // FIXME: Is there some better way to compute this?
5208 if (BT->getKind() == BuiltinType::WChar_S ||
5209 BT->getKind() == BuiltinType::WChar_U ||
5210 BT->getKind() == BuiltinType::Char16 ||
5211 BT->getKind() == BuiltinType::Char32) {
5212 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5213 uint64_t FromSize = getTypeSize(BT);
5214 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5215 LongLongTy, UnsignedLongLongTy };
5216 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5217 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5218 if (FromSize < ToSize ||
5219 (FromSize == ToSize &&
5220 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5221 return PromoteTypes[Idx];
5222 }
5223 llvm_unreachable("char type should fit into long long");
5224 }
5225 }
5226
5227 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005228 if (Promotable->isSignedIntegerType())
5229 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005230 uint64_t PromotableSize = getIntWidth(Promotable);
5231 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005232 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5233 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5234}
5235
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005236/// \brief Recurses in pointer/array types until it finds an objc retainable
5237/// type and returns its ownership.
5238Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5239 while (!T.isNull()) {
5240 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5241 return T.getObjCLifetime();
5242 if (T->isArrayType())
5243 T = getBaseElementType(T);
5244 else if (const PointerType *PT = T->getAs<PointerType>())
5245 T = PT->getPointeeType();
5246 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005247 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005248 else
5249 break;
5250 }
5251
5252 return Qualifiers::OCL_None;
5253}
5254
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005255static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5256 // Incomplete enum types are not treated as integer types.
5257 // FIXME: In C++, enum types are never integer types.
5258 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5259 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005260 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005261}
5262
Mike Stump11289f42009-09-09 15:08:12 +00005263/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005264/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005265/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005266int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005267 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5268 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005269
5270 // Unwrap enums to their underlying type.
5271 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5272 LHSC = getIntegerTypeForEnum(ET);
5273 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5274 RHSC = getIntegerTypeForEnum(ET);
5275
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005276 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005277
Chris Lattner76a00cf2008-04-06 22:59:24 +00005278 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5279 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005280
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005281 unsigned LHSRank = getIntegerRank(LHSC);
5282 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005283
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005284 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5285 if (LHSRank == RHSRank) return 0;
5286 return LHSRank > RHSRank ? 1 : -1;
5287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005289 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5290 if (LHSUnsigned) {
5291 // If the unsigned [LHS] type is larger, return it.
5292 if (LHSRank >= RHSRank)
5293 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005294
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005295 // If the signed type can represent all values of the unsigned type, it
5296 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005297 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005298 return -1;
5299 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005300
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005301 // If the unsigned [RHS] type is larger, return it.
5302 if (RHSRank >= LHSRank)
5303 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005304
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005305 // If the signed type can represent all values of the unsigned type, it
5306 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005307 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005308 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005309}
Anders Carlsson98f07902007-08-17 05:31:46 +00005310
Ben Langmuirf5416742016-02-04 00:55:24 +00005311TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005312 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005313 assert(!CFConstantStringTagDecl &&
5314 "tag and typedef should be initialized together");
5315 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5316 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005317
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005318 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005319 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005320
Anders Carlsson98f07902007-08-17 05:31:46 +00005321 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005322 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005323 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005324 // int flags;
5325 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005326 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005327 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005328 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005329 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005330 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005331 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005332 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005333
Anders Carlsson98f07902007-08-17 05:31:46 +00005334 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005335 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005336 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005337 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005338 SourceLocation(),
5339 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005340 FieldTypes[i], /*TInfo=*/nullptr,
5341 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005342 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005343 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005344 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005345 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005346 }
5347
Ben Langmuirf5416742016-02-04 00:55:24 +00005348 CFConstantStringTagDecl->completeDefinition();
5349 // This type is designed to be compatible with NSConstantString, but cannot
5350 // use the same name, since NSConstantString is an interface.
5351 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5352 CFConstantStringTypeDecl =
5353 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005354 }
Mike Stump11289f42009-09-09 15:08:12 +00005355
Quentin Colombet043406b2016-02-03 22:41:00 +00005356 return CFConstantStringTypeDecl;
5357}
5358
Ben Langmuirf5416742016-02-04 00:55:24 +00005359RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5360 if (!CFConstantStringTagDecl)
5361 getCFConstantStringDecl(); // Build the tag and the typedef.
5362 return CFConstantStringTagDecl;
5363}
5364
Quentin Colombet043406b2016-02-03 22:41:00 +00005365// getCFConstantStringType - Return the type used for constant CFStrings.
5366QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005367 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005368}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005369
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005370QualType ASTContext::getObjCSuperType() const {
5371 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005372 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005373 TUDecl->addDecl(ObjCSuperTypeDecl);
5374 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5375 }
5376 return ObjCSuperType;
5377}
5378
Douglas Gregor512b0772009-04-23 22:29:11 +00005379void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005380 const TypedefType *TD = T->getAs<TypedefType>();
5381 assert(TD && "Invalid CFConstantStringType");
5382 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5383 auto TagType =
5384 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5385 assert(TagType && "Invalid CFConstantStringType");
5386 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005387}
5388
Jay Foad39c79802011-01-12 09:06:06 +00005389QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005390 if (BlockDescriptorType)
5391 return getTagDeclType(BlockDescriptorType);
5392
Alp Toker2dea15b2013-12-17 01:22:38 +00005393 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005394 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005395 RD = buildImplicitRecord("__block_descriptor");
5396 RD->startDefinition();
5397
Mike Stumpd0153282009-10-20 02:12:22 +00005398 QualType FieldTypes[] = {
5399 UnsignedLongTy,
5400 UnsignedLongTy,
5401 };
5402
Craig Topperd6d31ac2013-07-15 08:24:27 +00005403 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005404 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005405 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005406 };
5407
5408 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005409 FieldDecl *Field = FieldDecl::Create(
5410 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005411 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5412 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005413 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005414 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005415 }
5416
Alp Toker2dea15b2013-12-17 01:22:38 +00005417 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005418
Alp Toker2dea15b2013-12-17 01:22:38 +00005419 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005420
5421 return getTagDeclType(BlockDescriptorType);
5422}
5423
Jay Foad39c79802011-01-12 09:06:06 +00005424QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005425 if (BlockDescriptorExtendedType)
5426 return getTagDeclType(BlockDescriptorExtendedType);
5427
Alp Toker2dea15b2013-12-17 01:22:38 +00005428 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005429 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005430 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5431 RD->startDefinition();
5432
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005433 QualType FieldTypes[] = {
5434 UnsignedLongTy,
5435 UnsignedLongTy,
5436 getPointerType(VoidPtrTy),
5437 getPointerType(VoidPtrTy)
5438 };
5439
Craig Topperd6d31ac2013-07-15 08:24:27 +00005440 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005441 "reserved",
5442 "Size",
5443 "CopyFuncPtr",
5444 "DestroyFuncPtr"
5445 };
5446
5447 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005448 FieldDecl *Field = FieldDecl::Create(
5449 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005450 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5451 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005452 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005453 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005454 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005455 }
5456
Alp Toker2dea15b2013-12-17 01:22:38 +00005457 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005458
Alp Toker2dea15b2013-12-17 01:22:38 +00005459 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005460 return getTagDeclType(BlockDescriptorExtendedType);
5461}
5462
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005463/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5464/// requires copy/dispose. Note that this must match the logic
5465/// in buildByrefHelpers.
5466bool ASTContext::BlockRequiresCopying(QualType Ty,
5467 const VarDecl *D) {
5468 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5469 const Expr *copyExpr = getBlockVarCopyInits(D);
5470 if (!copyExpr && record->hasTrivialDestructor()) return false;
5471
Mike Stump94967902009-10-21 18:16:27 +00005472 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005473 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005474
5475 if (!Ty->isObjCRetainableType()) return false;
5476
5477 Qualifiers qs = Ty.getQualifiers();
5478
5479 // If we have lifetime, that dominates.
5480 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005481 switch (lifetime) {
5482 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5483
5484 // These are just bits as far as the runtime is concerned.
5485 case Qualifiers::OCL_ExplicitNone:
5486 case Qualifiers::OCL_Autoreleasing:
5487 return false;
5488
5489 // Tell the runtime that this is ARC __weak, called by the
5490 // byref routines.
5491 case Qualifiers::OCL_Weak:
5492 // ARC __strong __block variables need to be retained.
5493 case Qualifiers::OCL_Strong:
5494 return true;
5495 }
5496 llvm_unreachable("fell out of lifetime switch!");
5497 }
5498 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5499 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005500}
5501
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005502bool ASTContext::getByrefLifetime(QualType Ty,
5503 Qualifiers::ObjCLifetime &LifeTime,
5504 bool &HasByrefExtendedLayout) const {
5505
5506 if (!getLangOpts().ObjC1 ||
5507 getLangOpts().getGC() != LangOptions::NonGC)
5508 return false;
5509
5510 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005511 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005512 HasByrefExtendedLayout = true;
5513 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005514 } else if ((LifeTime = Ty.getObjCLifetime())) {
5515 // Honor the ARC qualifiers.
5516 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5517 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005518 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005519 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005520 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005521 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005522 return true;
5523}
5524
Douglas Gregorbab8a962011-09-08 01:46:34 +00005525TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5526 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005527 ObjCInstanceTypeDecl =
5528 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005529 return ObjCInstanceTypeDecl;
5530}
5531
Anders Carlsson18acd442007-10-29 06:33:42 +00005532// This returns true if a type has been typedefed to BOOL:
5533// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005534static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005535 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005536 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5537 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005538
Anders Carlssond8499822007-10-29 05:01:08 +00005539 return false;
5540}
5541
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005542/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005543/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005544CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005545 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5546 return CharUnits::Zero();
5547
Ken Dyck40775002010-01-11 17:06:35 +00005548 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005549
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005550 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005551 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005552 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005553 // Treat arrays as pointers, since that's how they're passed in.
5554 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005555 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005556 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005557}
5558
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005559bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005560 return getTargetInfo().getCXXABI().isMicrosoft() &&
5561 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005562 VD->getType()->isIntegralOrEnumerationType() &&
5563 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005564}
5565
Richard Smithd9b90092016-07-02 01:32:16 +00005566ASTContext::InlineVariableDefinitionKind
5567ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5568 if (!VD->isInline())
5569 return InlineVariableDefinitionKind::None;
5570
5571 // In almost all cases, it's a weak definition.
5572 auto *First = VD->getFirstDecl();
5573 if (!First->isConstexpr() || First->isInlineSpecified() ||
5574 !VD->isStaticDataMember())
5575 return InlineVariableDefinitionKind::Weak;
5576
5577 // If there's a file-context declaration in this translation unit, it's a
5578 // non-discardable definition.
5579 for (auto *D : VD->redecls())
5580 if (D->getLexicalDeclContext()->isFileContext())
5581 return InlineVariableDefinitionKind::Strong;
5582
5583 // If we've not seen one yet, we don't know.
5584 return InlineVariableDefinitionKind::WeakUnknown;
5585}
5586
Ken Dyck40775002010-01-11 17:06:35 +00005587static inline
5588std::string charUnitsToString(const CharUnits &CU) {
5589 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005590}
5591
John McCall351762c2011-02-07 10:33:21 +00005592/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005593/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005594std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5595 std::string S;
5596
David Chisnall950a9512009-11-17 19:33:30 +00005597 const BlockDecl *Decl = Expr->getBlockDecl();
5598 QualType BlockTy =
5599 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5600 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005601 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005602 getObjCEncodingForMethodParameter(
5603 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5604 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005605 else
Alp Toker314cc812014-01-25 16:55:45 +00005606 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005607 // Compute size of all parameters.
5608 // Start with computing size of a pointer in number of bytes.
5609 // FIXME: There might(should) be a better way of doing this computation!
5610 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005611 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5612 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005613 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005614 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005615 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005616 if (sz.isZero())
5617 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005618 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005619 ParmOffset += sz;
5620 }
5621 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005622 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005623 // Block pointer and offset.
5624 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005625
5626 // Argument types.
5627 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005628 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005629 QualType PType = PVDecl->getOriginalType();
5630 if (const ArrayType *AT =
5631 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5632 // Use array's original type only if it has known number of
5633 // elements.
5634 if (!isa<ConstantArrayType>(AT))
5635 PType = PVDecl->getType();
5636 } else if (PType->isFunctionType())
5637 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005638 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005639 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5640 S, true /*Extended*/);
5641 else
5642 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005643 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005644 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005645 }
John McCall351762c2011-02-07 10:33:21 +00005646
5647 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005648}
5649
John McCall843dfcc2016-11-29 21:57:00 +00005650std::string
5651ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5652 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005653 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005654 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005655 CharUnits ParmOffset;
5656 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005657 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005658 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005659 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005660 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005661 continue;
5662
John McCall843dfcc2016-11-29 21:57:00 +00005663 assert(sz.isPositive() &&
5664 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005665 ParmOffset += sz;
5666 }
5667 S += charUnitsToString(ParmOffset);
5668 ParmOffset = CharUnits::Zero();
5669
5670 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005671 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005672 QualType PType = PVDecl->getOriginalType();
5673 if (const ArrayType *AT =
5674 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5675 // Use array's original type only if it has known number of
5676 // elements.
5677 if (!isa<ConstantArrayType>(AT))
5678 PType = PVDecl->getType();
5679 } else if (PType->isFunctionType())
5680 PType = PVDecl->getType();
5681 getObjCEncodingForType(PType, S);
5682 S += charUnitsToString(ParmOffset);
5683 ParmOffset += getObjCEncodingTypeSize(PType);
5684 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005685
John McCall843dfcc2016-11-29 21:57:00 +00005686 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005687}
5688
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005689/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5690/// method parameter or return type. If Extended, include class names and
5691/// block object types.
5692void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5693 QualType T, std::string& S,
5694 bool Extended) const {
5695 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5696 getObjCEncodingForTypeQualifier(QT, S);
5697 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005698 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005699 true /*OutermostType*/,
5700 false /*EncodingProperty*/,
5701 false /*StructField*/,
5702 Extended /*EncodeBlockParameters*/,
5703 Extended /*EncodeClassNames*/);
5704}
5705
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005706/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005707/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005708std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5709 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005710 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005711 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005712 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005713 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5714 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005715 // Compute size of all parameters.
5716 // Start with computing size of a pointer in number of bytes.
5717 // FIXME: There might(should) be a better way of doing this computation!
5718 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005719 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005720 // The first two arguments (self and _cmd) are pointers; account for
5721 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005722 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005723 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005724 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005725 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005726 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005727 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005728 continue;
5729
Ken Dyck40775002010-01-11 17:06:35 +00005730 assert (sz.isPositive() &&
5731 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005732 ParmOffset += sz;
5733 }
Ken Dyck40775002010-01-11 17:06:35 +00005734 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005735 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005736 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005737
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005738 // Argument types.
5739 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005740 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005741 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005742 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005743 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005744 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005745 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5746 // Use array's original type only if it has known number of
5747 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005748 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005749 PType = PVDecl->getType();
5750 } else if (PType->isFunctionType())
5751 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005752 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5753 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005754 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005755 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005756 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005757
John McCall843dfcc2016-11-29 21:57:00 +00005758 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005759}
5760
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005761ObjCPropertyImplDecl *
5762ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5763 const ObjCPropertyDecl *PD,
5764 const Decl *Container) const {
5765 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005766 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005767 if (const ObjCCategoryImplDecl *CID =
5768 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005769 for (auto *PID : CID->property_impls())
5770 if (PID->getPropertyDecl() == PD)
5771 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005772 } else {
5773 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5774 for (auto *PID : OID->property_impls())
5775 if (PID->getPropertyDecl() == PD)
5776 return PID;
5777 }
5778 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005779}
5780
Daniel Dunbar4932b362008-08-28 04:38:10 +00005781/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005782/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005783/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5784/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005785/// Property attributes are stored as a comma-delimited C string. The simple
5786/// attributes readonly and bycopy are encoded as single characters. The
5787/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5788/// encoded as single characters, followed by an identifier. Property types
5789/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005790/// these attributes are defined by the following enumeration:
5791/// @code
5792/// enum PropertyAttributes {
5793/// kPropertyReadOnly = 'R', // property is read-only.
5794/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5795/// kPropertyByref = '&', // property is a reference to the value last assigned
5796/// kPropertyDynamic = 'D', // property is dynamic
5797/// kPropertyGetter = 'G', // followed by getter selector name
5798/// kPropertySetter = 'S', // followed by setter selector name
5799/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005800/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005801/// kPropertyWeak = 'W' // 'weak' property
5802/// kPropertyStrong = 'P' // property GC'able
5803/// kPropertyNonAtomic = 'N' // property non-atomic
5804/// };
5805/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005806std::string
5807ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5808 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005809 // Collect information from the property implementation decl(s).
5810 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005811 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005812
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005813 if (ObjCPropertyImplDecl *PropertyImpDecl =
5814 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5815 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5816 Dynamic = true;
5817 else
5818 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005819 }
5820
5821 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005822 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005823
5824 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005825 // GCC has some special rules regarding encoding of properties which
5826 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005827 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005828
5829 if (PD->isReadOnly()) {
5830 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005831 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5832 S += ",C";
5833 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5834 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005835 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5836 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005837 } else {
5838 switch (PD->getSetterKind()) {
5839 case ObjCPropertyDecl::Assign: break;
5840 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005841 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005842 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005843 }
5844 }
5845
5846 // It really isn't clear at all what this means, since properties
5847 // are "dynamic by default".
5848 if (Dynamic)
5849 S += ",D";
5850
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005851 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5852 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005853
Daniel Dunbar4932b362008-08-28 04:38:10 +00005854 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5855 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005856 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005857 }
5858
5859 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5860 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005861 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005862 }
5863
5864 if (SynthesizePID) {
5865 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5866 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005867 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005868 }
5869
5870 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005871 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005872}
5873
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005874/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005875/// Another legacy compatibility encoding: 32-bit longs are encoded as
5876/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005877/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5878///
5879void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005880 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005881 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005882 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005883 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005884 else
Jay Foad39c79802011-01-12 09:06:06 +00005885 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005886 PointeeTy = IntTy;
5887 }
5888 }
5889}
5890
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005891void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005892 const FieldDecl *Field,
5893 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005894 // We follow the behavior of gcc, expanding structures which are
5895 // directly pointed to, and expanding embedded structures. Note that
5896 // these rules are sufficient to prevent recursive encoding of the
5897 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005898 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005899 true /* outermost type */, false, false,
5900 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005901}
5902
Joe Groff98ac7d22014-07-07 22:25:15 +00005903void ASTContext::getObjCEncodingForPropertyType(QualType T,
5904 std::string& S) const {
5905 // Encode result type.
5906 // GCC has some special rules regarding encoding of properties which
5907 // closely resembles encoding of ivars.
5908 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5909 true /* outermost type */,
5910 true /* encoding property */);
5911}
5912
John McCall393a78d2012-12-20 02:45:14 +00005913static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5914 BuiltinType::Kind kind) {
5915 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005916 case BuiltinType::Void: return 'v';
5917 case BuiltinType::Bool: return 'B';
5918 case BuiltinType::Char_U:
5919 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005920 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005921 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005922 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005923 case BuiltinType::UInt: return 'I';
5924 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005925 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005926 case BuiltinType::UInt128: return 'T';
5927 case BuiltinType::ULongLong: return 'Q';
5928 case BuiltinType::Char_S:
5929 case BuiltinType::SChar: return 'c';
5930 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005931 case BuiltinType::WChar_S:
5932 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005933 case BuiltinType::Int: return 'i';
5934 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005935 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005936 case BuiltinType::LongLong: return 'q';
5937 case BuiltinType::Int128: return 't';
5938 case BuiltinType::Float: return 'f';
5939 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005940 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005941 case BuiltinType::NullPtr: return '*'; // like char*
5942
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005943 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005944 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005945 case BuiltinType::Half:
5946 // FIXME: potentially need @encodes for these!
5947 return ' ';
5948
5949 case BuiltinType::ObjCId:
5950 case BuiltinType::ObjCClass:
5951 case BuiltinType::ObjCSel:
5952 llvm_unreachable("@encoding ObjC primitive type");
5953
5954 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005955#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5956 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005957#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005958 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005959 case BuiltinType::OCLClkEvent:
5960 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005961 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005962 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005963 case BuiltinType::Dependent:
5964#define BUILTIN_TYPE(KIND, ID)
5965#define PLACEHOLDER_TYPE(KIND, ID) \
5966 case BuiltinType::KIND:
5967#include "clang/AST/BuiltinTypes.def"
5968 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005969 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005970 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005971}
5972
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005973static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5974 EnumDecl *Enum = ET->getDecl();
5975
5976 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5977 if (!Enum->isFixed())
5978 return 'i';
5979
5980 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005981 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5982 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005983}
5984
Jay Foad39c79802011-01-12 09:06:06 +00005985static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005986 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005987 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005988 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005989 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5990 // The GNU runtime requires more information; bitfields are encoded as b,
5991 // then the offset (in bits) of the first element, then the type of the
5992 // bitfield, then the size in bits. For example, in this structure:
5993 //
5994 // struct
5995 // {
5996 // int integer;
5997 // int flags:2;
5998 // };
5999 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6000 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6001 // information is not especially sensible, but we're stuck with it for
6002 // compatibility with GCC, although providing it breaks anything that
6003 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006004 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006005 uint64_t Offset;
6006
6007 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6008 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6009 IVD);
6010 } else {
6011 const RecordDecl *RD = FD->getParent();
6012 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6013 Offset = RL.getFieldOffset(FD->getFieldIndex());
6014 }
6015
6016 S += llvm::utostr(Offset);
6017
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006018 if (const EnumType *ET = T->getAs<EnumType>())
6019 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006020 else {
6021 const BuiltinType *BT = T->castAs<BuiltinType>();
6022 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6023 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006024 }
Richard Smithcaf33902011-10-10 18:28:20 +00006025 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006026}
6027
Daniel Dunbar07d07852009-10-18 21:17:35 +00006028// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006029void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6030 bool ExpandPointedToStructures,
6031 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006032 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006033 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006034 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006035 bool StructField,
6036 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006037 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006038 bool EncodePointerToObjCTypedef,
6039 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006040 CanQualType CT = getCanonicalType(T);
6041 switch (CT->getTypeClass()) {
6042 case Type::Builtin:
6043 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006044 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006045 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006046 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6047 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6048 else
6049 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006050 return;
Mike Stump11289f42009-09-09 15:08:12 +00006051
John McCall393a78d2012-12-20 02:45:14 +00006052 case Type::Complex: {
6053 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006054 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006055 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006056 return;
6057 }
John McCall393a78d2012-12-20 02:45:14 +00006058
6059 case Type::Atomic: {
6060 const AtomicType *AT = T->castAs<AtomicType>();
6061 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006062 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006063 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006064 }
John McCall393a78d2012-12-20 02:45:14 +00006065
6066 // encoding for pointer or reference types.
6067 case Type::Pointer:
6068 case Type::LValueReference:
6069 case Type::RValueReference: {
6070 QualType PointeeTy;
6071 if (isa<PointerType>(CT)) {
6072 const PointerType *PT = T->castAs<PointerType>();
6073 if (PT->isObjCSelType()) {
6074 S += ':';
6075 return;
6076 }
6077 PointeeTy = PT->getPointeeType();
6078 } else {
6079 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6080 }
6081
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006082 bool isReadOnly = false;
6083 // For historical/compatibility reasons, the read-only qualifier of the
6084 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6085 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006086 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006087 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006088 if (OutermostType && T.isConstQualified()) {
6089 isReadOnly = true;
6090 S += 'r';
6091 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006092 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006093 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006094 while (P->getAs<PointerType>())
6095 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006096 if (P.isConstQualified()) {
6097 isReadOnly = true;
6098 S += 'r';
6099 }
6100 }
6101 if (isReadOnly) {
6102 // Another legacy compatibility encoding. Some ObjC qualifier and type
6103 // combinations need to be rearranged.
6104 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006105 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006106 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006107 }
Mike Stump11289f42009-09-09 15:08:12 +00006108
Anders Carlssond8499822007-10-29 05:01:08 +00006109 if (PointeeTy->isCharType()) {
6110 // char pointer types should be encoded as '*' unless it is a
6111 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006112 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006113 S += '*';
6114 return;
6115 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006116 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006117 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6118 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6119 S += '#';
6120 return;
6121 }
6122 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6123 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6124 S += '@';
6125 return;
6126 }
6127 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006128 }
Anders Carlssond8499822007-10-29 05:01:08 +00006129 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006130 getLegacyIntegralTypeEncoding(PointeeTy);
6131
Mike Stump11289f42009-09-09 15:08:12 +00006132 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006133 nullptr, false, false, false, false, false, false,
6134 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006135 return;
6136 }
John McCall393a78d2012-12-20 02:45:14 +00006137
6138 case Type::ConstantArray:
6139 case Type::IncompleteArray:
6140 case Type::VariableArray: {
6141 const ArrayType *AT = cast<ArrayType>(CT);
6142
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006143 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006144 // Incomplete arrays are encoded as a pointer to the array element.
6145 S += '^';
6146
Mike Stump11289f42009-09-09 15:08:12 +00006147 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006148 false, ExpandStructures, FD);
6149 } else {
6150 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006151
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6153 S += llvm::utostr(CAT->getSize().getZExtValue());
6154 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006155 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006156 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6157 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006158 S += '0';
6159 }
Mike Stump11289f42009-09-09 15:08:12 +00006160
6161 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006162 false, ExpandStructures, FD,
6163 false, false, false, false, false, false,
6164 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006165 S += ']';
6166 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006167 return;
6168 }
Mike Stump11289f42009-09-09 15:08:12 +00006169
John McCall393a78d2012-12-20 02:45:14 +00006170 case Type::FunctionNoProto:
6171 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006172 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006173 return;
Mike Stump11289f42009-09-09 15:08:12 +00006174
John McCall393a78d2012-12-20 02:45:14 +00006175 case Type::Record: {
6176 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006177 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006178 // Anonymous structures print as '?'
6179 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6180 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006181 if (ClassTemplateSpecializationDecl *Spec
6182 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6183 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006184 llvm::raw_string_ostream OS(S);
6185 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006186 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006187 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006188 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006189 } else {
6190 S += '?';
6191 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006192 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006193 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006194 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006195 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006196 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006197 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006198 if (FD) {
6199 S += '"';
6200 S += Field->getNameAsString();
6201 S += '"';
6202 }
Mike Stump11289f42009-09-09 15:08:12 +00006203
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006204 // Special case bit-fields.
6205 if (Field->isBitField()) {
6206 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006207 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006208 } else {
6209 QualType qt = Field->getType();
6210 getLegacyIntegralTypeEncoding(qt);
6211 getObjCEncodingForTypeImpl(qt, S, false, true,
6212 FD, /*OutermostType*/false,
6213 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006214 /*StructField*/true,
6215 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006216 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006217 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006218 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006219 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006220 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006221 return;
6222 }
Mike Stump11289f42009-09-09 15:08:12 +00006223
John McCall393a78d2012-12-20 02:45:14 +00006224 case Type::BlockPointer: {
6225 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006226 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006227 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006228 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006229
6230 S += '<';
6231 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006232 getObjCEncodingForTypeImpl(
6233 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6234 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006235 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6236 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006237 // Block self
6238 S += "@?";
6239 // Block parameters
6240 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006241 for (const auto &I : FPT->param_types())
6242 getObjCEncodingForTypeImpl(
6243 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6244 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006245 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6246 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006247 }
6248 S += '>';
6249 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006250 return;
6251 }
Mike Stump11289f42009-09-09 15:08:12 +00006252
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006253 case Type::ObjCObject: {
6254 // hack to match legacy encoding of *id and *Class
6255 QualType Ty = getObjCObjectPointerType(CT);
6256 if (Ty->isObjCIdType()) {
6257 S += "{objc_object=}";
6258 return;
6259 }
6260 else if (Ty->isObjCClassType()) {
6261 S += "{objc_class=}";
6262 return;
6263 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006264 // TODO: Double check to make sure this intentially falls through.
6265 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006266 }
6267
John McCall393a78d2012-12-20 02:45:14 +00006268 case Type::ObjCInterface: {
6269 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006270 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006271 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006272 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006273 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006274 if (ExpandStructures) {
6275 S += '=';
6276 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6277 DeepCollectObjCIvars(OI, true, Ivars);
6278 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6279 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6280 if (Field->isBitField())
6281 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6282 else
6283 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6284 false, false, false, false, false,
6285 EncodePointerToObjCTypedef,
6286 NotEncodedT);
6287 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006288 }
6289 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006290 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006291 }
Mike Stump11289f42009-09-09 15:08:12 +00006292
John McCall393a78d2012-12-20 02:45:14 +00006293 case Type::ObjCObjectPointer: {
6294 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006295 if (OPT->isObjCIdType()) {
6296 S += '@';
6297 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006298 }
Mike Stump11289f42009-09-09 15:08:12 +00006299
Steve Narofff0c86112009-10-28 22:03:49 +00006300 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6301 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6302 // Since this is a binary compatibility issue, need to consult with runtime
6303 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006304 S += '#';
6305 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006306 }
Mike Stump11289f42009-09-09 15:08:12 +00006307
Chris Lattnere7cabb92009-07-13 00:10:46 +00006308 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006309 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006310 ExpandPointedToStructures,
6311 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006312 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006313 // Note that we do extended encoding of protocol qualifer list
6314 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006315 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006316 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006317 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006318 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006319 S += '>';
6320 }
6321 S += '"';
6322 }
6323 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Chris Lattnere7cabb92009-07-13 00:10:46 +00006326 QualType PointeeTy = OPT->getPointeeType();
6327 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006328 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6329 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006330 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006331 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006332 // {...};
6333 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006334 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006335 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006336 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6337 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6338 DeepCollectObjCIvars(OI, true, Ivars);
6339 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6340 if (cast<FieldDecl>(Ivars[i]) == FD) {
6341 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006342 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006343 S += '}';
6344 return;
6345 }
6346 }
6347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348 getObjCEncodingForTypeImpl(PointeeTy, S,
6349 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006350 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006351 false, false, false, false, false,
6352 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006353 return;
6354 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006355
6356 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006357 if (OPT->getInterfaceDecl() &&
6358 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006359 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006360 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006361 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006362 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006363 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006364 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006365 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006366 S += '"';
6367 }
6368 return;
6369 }
Mike Stump11289f42009-09-09 15:08:12 +00006370
John McCalla9e6e8d2010-05-17 23:56:34 +00006371 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006372 // FIXME: we shoul do better than that. 'M' is available.
6373 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006374 // This matches gcc's encoding, even though technically it is insufficient.
6375 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006376 case Type::Vector:
6377 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006378 // Until we have a coherent encoding of these three types, issue warning.
6379 { if (NotEncodedT)
6380 *NotEncodedT = T;
6381 return;
6382 }
6383
6384 // We could see an undeduced auto type here during error recovery.
6385 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006386 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006387 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006388 return;
6389
Xiuli Pan9c14e282016-01-09 12:53:17 +00006390 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006391#define ABSTRACT_TYPE(KIND, BASE)
6392#define TYPE(KIND, BASE)
6393#define DEPENDENT_TYPE(KIND, BASE) \
6394 case Type::KIND:
6395#define NON_CANONICAL_TYPE(KIND, BASE) \
6396 case Type::KIND:
6397#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6398 case Type::KIND:
6399#include "clang/AST/TypeNodes.def"
6400 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006401 }
John McCall393a78d2012-12-20 02:45:14 +00006402 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006403}
6404
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006405void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6406 std::string &S,
6407 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006408 bool includeVBases,
6409 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006410 assert(RDecl && "Expected non-null RecordDecl");
6411 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006412 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006413 return;
6414
6415 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6416 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6417 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6418
6419 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006420 for (const auto &BI : CXXRec->bases()) {
6421 if (!BI.isVirtual()) {
6422 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006423 if (base->isEmpty())
6424 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006425 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006426 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6427 std::make_pair(offs, base));
6428 }
6429 }
6430 }
6431
6432 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006433 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006434 uint64_t offs = layout.getFieldOffset(i);
6435 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006436 std::make_pair(offs, Field));
6437 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006438 }
6439
6440 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006441 for (const auto &BI : CXXRec->vbases()) {
6442 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006443 if (base->isEmpty())
6444 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006445 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006446 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6447 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006448 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6449 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006450 }
6451 }
6452
6453 CharUnits size;
6454 if (CXXRec) {
6455 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6456 } else {
6457 size = layout.getSize();
6458 }
6459
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006460#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006461 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006462#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006463 std::multimap<uint64_t, NamedDecl *>::iterator
6464 CurLayObj = FieldOrBaseOffsets.begin();
6465
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006466 if (CXXRec && CXXRec->isDynamicClass() &&
6467 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006468 if (FD) {
6469 S += "\"_vptr$";
6470 std::string recname = CXXRec->getNameAsString();
6471 if (recname.empty()) recname = "?";
6472 S += recname;
6473 S += '"';
6474 }
6475 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006476#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006477 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006478#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006479 }
6480
6481 if (!RDecl->hasFlexibleArrayMember()) {
6482 // Mark the end of the structure.
6483 uint64_t offs = toBits(size);
6484 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006485 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006486 }
6487
6488 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006489#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006490 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006491 if (CurOffs < CurLayObj->first) {
6492 uint64_t padding = CurLayObj->first - CurOffs;
6493 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6494 // packing/alignment of members is different that normal, in which case
6495 // the encoding will be out-of-sync with the real layout.
6496 // If the runtime switches to just consider the size of types without
6497 // taking into account alignment, we could make padding explicit in the
6498 // encoding (e.g. using arrays of chars). The encoding strings would be
6499 // longer then though.
6500 CurOffs += padding;
6501 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006502#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006503
6504 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006505 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006506 break; // reached end of structure.
6507
6508 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6509 // We expand the bases without their virtual bases since those are going
6510 // in the initial structure. Note that this differs from gcc which
6511 // expands virtual bases each time one is encountered in the hierarchy,
6512 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006513 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6514 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006515 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006516#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006517 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006518#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006519 } else {
6520 FieldDecl *field = cast<FieldDecl>(dcl);
6521 if (FD) {
6522 S += '"';
6523 S += field->getNameAsString();
6524 S += '"';
6525 }
6526
6527 if (field->isBitField()) {
6528 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006529#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006530 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006531#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006532 } else {
6533 QualType qt = field->getType();
6534 getLegacyIntegralTypeEncoding(qt);
6535 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6536 /*OutermostType*/false,
6537 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006538 /*StructField*/true,
6539 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006540#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006541 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006542#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006543 }
6544 }
6545 }
6546}
6547
Mike Stump11289f42009-09-09 15:08:12 +00006548void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006549 std::string& S) const {
6550 if (QT & Decl::OBJC_TQ_In)
6551 S += 'n';
6552 if (QT & Decl::OBJC_TQ_Inout)
6553 S += 'N';
6554 if (QT & Decl::OBJC_TQ_Out)
6555 S += 'o';
6556 if (QT & Decl::OBJC_TQ_Bycopy)
6557 S += 'O';
6558 if (QT & Decl::OBJC_TQ_Byref)
6559 S += 'R';
6560 if (QT & Decl::OBJC_TQ_Oneway)
6561 S += 'V';
6562}
6563
Douglas Gregor3ea72692011-08-12 05:46:01 +00006564TypedefDecl *ASTContext::getObjCIdDecl() const {
6565 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006566 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006567 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006568 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006569 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006570 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006571}
6572
Douglas Gregor52e02802011-08-12 06:17:30 +00006573TypedefDecl *ASTContext::getObjCSelDecl() const {
6574 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006575 QualType T = getPointerType(ObjCBuiltinSelTy);
6576 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006577 }
6578 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006579}
6580
Douglas Gregor0a586182011-08-12 05:59:41 +00006581TypedefDecl *ASTContext::getObjCClassDecl() const {
6582 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006583 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006584 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006585 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006586 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006587 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006588}
6589
Douglas Gregord53ae832012-01-17 18:09:05 +00006590ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6591 if (!ObjCProtocolClassDecl) {
6592 ObjCProtocolClassDecl
6593 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6594 SourceLocation(),
6595 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006596 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006597 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006598 SourceLocation(), true);
6599 }
6600
6601 return ObjCProtocolClassDecl;
6602}
6603
Meador Inge5d3fb222012-06-16 03:34:49 +00006604//===----------------------------------------------------------------------===//
6605// __builtin_va_list Construction Functions
6606//===----------------------------------------------------------------------===//
6607
Charles Davisc7d5c942015-09-17 20:55:33 +00006608static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6609 StringRef Name) {
6610 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006611 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006612 return Context->buildImplicitTypedef(T, Name);
6613}
6614
6615static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6616 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6617}
6618
6619static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6620 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006621}
6622
6623static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6624 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006625 QualType T = Context->getPointerType(Context->VoidTy);
6626 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006627}
6628
Tim Northover9bb857a2013-01-31 12:13:10 +00006629static TypedefDecl *
6630CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006631 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006632 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006633 if (Context->getLangOpts().CPlusPlus) {
6634 // namespace std { struct __va_list {
6635 NamespaceDecl *NS;
6636 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6637 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006638 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006639 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006640 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006641 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006642 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006643 }
6644
6645 VaListTagDecl->startDefinition();
6646
6647 const size_t NumFields = 5;
6648 QualType FieldTypes[NumFields];
6649 const char *FieldNames[NumFields];
6650
6651 // void *__stack;
6652 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6653 FieldNames[0] = "__stack";
6654
6655 // void *__gr_top;
6656 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6657 FieldNames[1] = "__gr_top";
6658
6659 // void *__vr_top;
6660 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6661 FieldNames[2] = "__vr_top";
6662
6663 // int __gr_offs;
6664 FieldTypes[3] = Context->IntTy;
6665 FieldNames[3] = "__gr_offs";
6666
6667 // int __vr_offs;
6668 FieldTypes[4] = Context->IntTy;
6669 FieldNames[4] = "__vr_offs";
6670
6671 // Create fields
6672 for (unsigned i = 0; i < NumFields; ++i) {
6673 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6674 VaListTagDecl,
6675 SourceLocation(),
6676 SourceLocation(),
6677 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006678 FieldTypes[i], /*TInfo=*/nullptr,
6679 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006680 /*Mutable=*/false,
6681 ICIS_NoInit);
6682 Field->setAccess(AS_public);
6683 VaListTagDecl->addDecl(Field);
6684 }
6685 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006686 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006687 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006688
6689 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006690 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006691}
6692
Meador Inge5d3fb222012-06-16 03:34:49 +00006693static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6694 // typedef struct __va_list_tag {
6695 RecordDecl *VaListTagDecl;
6696
Alp Toker2dea15b2013-12-17 01:22:38 +00006697 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006698 VaListTagDecl->startDefinition();
6699
6700 const size_t NumFields = 5;
6701 QualType FieldTypes[NumFields];
6702 const char *FieldNames[NumFields];
6703
6704 // unsigned char gpr;
6705 FieldTypes[0] = Context->UnsignedCharTy;
6706 FieldNames[0] = "gpr";
6707
6708 // unsigned char fpr;
6709 FieldTypes[1] = Context->UnsignedCharTy;
6710 FieldNames[1] = "fpr";
6711
6712 // unsigned short reserved;
6713 FieldTypes[2] = Context->UnsignedShortTy;
6714 FieldNames[2] = "reserved";
6715
6716 // void* overflow_arg_area;
6717 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6718 FieldNames[3] = "overflow_arg_area";
6719
6720 // void* reg_save_area;
6721 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6722 FieldNames[4] = "reg_save_area";
6723
6724 // Create fields
6725 for (unsigned i = 0; i < NumFields; ++i) {
6726 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6727 SourceLocation(),
6728 SourceLocation(),
6729 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006730 FieldTypes[i], /*TInfo=*/nullptr,
6731 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006732 /*Mutable=*/false,
6733 ICIS_NoInit);
6734 Field->setAccess(AS_public);
6735 VaListTagDecl->addDecl(Field);
6736 }
6737 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006738 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006739 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6740
6741 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006742 TypedefDecl *VaListTagTypedefDecl =
6743 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6744
Meador Inge5d3fb222012-06-16 03:34:49 +00006745 QualType VaListTagTypedefType =
6746 Context->getTypedefType(VaListTagTypedefDecl);
6747
6748 // typedef __va_list_tag __builtin_va_list[1];
6749 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6750 QualType VaListTagArrayType
6751 = Context->getConstantArrayType(VaListTagTypedefType,
6752 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006753 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006754}
6755
6756static TypedefDecl *
6757CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006758 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006759 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006760 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006761 VaListTagDecl->startDefinition();
6762
6763 const size_t NumFields = 4;
6764 QualType FieldTypes[NumFields];
6765 const char *FieldNames[NumFields];
6766
6767 // unsigned gp_offset;
6768 FieldTypes[0] = Context->UnsignedIntTy;
6769 FieldNames[0] = "gp_offset";
6770
6771 // unsigned fp_offset;
6772 FieldTypes[1] = Context->UnsignedIntTy;
6773 FieldNames[1] = "fp_offset";
6774
6775 // void* overflow_arg_area;
6776 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6777 FieldNames[2] = "overflow_arg_area";
6778
6779 // void* reg_save_area;
6780 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6781 FieldNames[3] = "reg_save_area";
6782
6783 // Create fields
6784 for (unsigned i = 0; i < NumFields; ++i) {
6785 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6786 VaListTagDecl,
6787 SourceLocation(),
6788 SourceLocation(),
6789 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006790 FieldTypes[i], /*TInfo=*/nullptr,
6791 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006792 /*Mutable=*/false,
6793 ICIS_NoInit);
6794 Field->setAccess(AS_public);
6795 VaListTagDecl->addDecl(Field);
6796 }
6797 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006798 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006799 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6800
Richard Smith9b88a4c2015-07-27 05:40:23 +00006801 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006802
Richard Smith9b88a4c2015-07-27 05:40:23 +00006803 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006804 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006805 QualType VaListTagArrayType =
6806 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006807 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006808}
6809
6810static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6811 // typedef int __builtin_va_list[4];
6812 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006813 QualType IntArrayType =
6814 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006815 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006816}
6817
Logan Chien57086ce2012-10-10 06:56:20 +00006818static TypedefDecl *
6819CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006820 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006821 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006822 if (Context->getLangOpts().CPlusPlus) {
6823 // namespace std { struct __va_list {
6824 NamespaceDecl *NS;
6825 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6826 Context->getTranslationUnitDecl(),
6827 /*Inline*/false, SourceLocation(),
6828 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006829 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006830 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006831 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006832 }
6833
6834 VaListDecl->startDefinition();
6835
6836 // void * __ap;
6837 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6838 VaListDecl,
6839 SourceLocation(),
6840 SourceLocation(),
6841 &Context->Idents.get("__ap"),
6842 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006843 /*TInfo=*/nullptr,
6844 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006845 /*Mutable=*/false,
6846 ICIS_NoInit);
6847 Field->setAccess(AS_public);
6848 VaListDecl->addDecl(Field);
6849
6850 // };
6851 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006852 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006853
6854 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006855 QualType T = Context->getRecordType(VaListDecl);
6856 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006857}
6858
Ulrich Weigand47445072013-05-06 16:26:41 +00006859static TypedefDecl *
6860CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006861 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006862 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006863 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006864 VaListTagDecl->startDefinition();
6865
6866 const size_t NumFields = 4;
6867 QualType FieldTypes[NumFields];
6868 const char *FieldNames[NumFields];
6869
6870 // long __gpr;
6871 FieldTypes[0] = Context->LongTy;
6872 FieldNames[0] = "__gpr";
6873
6874 // long __fpr;
6875 FieldTypes[1] = Context->LongTy;
6876 FieldNames[1] = "__fpr";
6877
6878 // void *__overflow_arg_area;
6879 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6880 FieldNames[2] = "__overflow_arg_area";
6881
6882 // void *__reg_save_area;
6883 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6884 FieldNames[3] = "__reg_save_area";
6885
6886 // Create fields
6887 for (unsigned i = 0; i < NumFields; ++i) {
6888 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6889 VaListTagDecl,
6890 SourceLocation(),
6891 SourceLocation(),
6892 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006893 FieldTypes[i], /*TInfo=*/nullptr,
6894 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006895 /*Mutable=*/false,
6896 ICIS_NoInit);
6897 Field->setAccess(AS_public);
6898 VaListTagDecl->addDecl(Field);
6899 }
6900 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006901 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006902 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006903
Richard Smith9b88a4c2015-07-27 05:40:23 +00006904 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006905
6906 // typedef __va_list_tag __builtin_va_list[1];
6907 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006908 QualType VaListTagArrayType =
6909 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006910
Alp Toker56b5cc92013-12-15 10:36:26 +00006911 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006912}
6913
Meador Inge5d3fb222012-06-16 03:34:49 +00006914static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6915 TargetInfo::BuiltinVaListKind Kind) {
6916 switch (Kind) {
6917 case TargetInfo::CharPtrBuiltinVaList:
6918 return CreateCharPtrBuiltinVaListDecl(Context);
6919 case TargetInfo::VoidPtrBuiltinVaList:
6920 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006921 case TargetInfo::AArch64ABIBuiltinVaList:
6922 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006923 case TargetInfo::PowerABIBuiltinVaList:
6924 return CreatePowerABIBuiltinVaListDecl(Context);
6925 case TargetInfo::X86_64ABIBuiltinVaList:
6926 return CreateX86_64ABIBuiltinVaListDecl(Context);
6927 case TargetInfo::PNaClABIBuiltinVaList:
6928 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006929 case TargetInfo::AAPCSABIBuiltinVaList:
6930 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006931 case TargetInfo::SystemZBuiltinVaList:
6932 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006933 }
6934
6935 llvm_unreachable("Unhandled __builtin_va_list type kind");
6936}
6937
6938TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006939 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006940 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006941 assert(BuiltinVaListDecl->isImplicit());
6942 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006943
6944 return BuiltinVaListDecl;
6945}
6946
Richard Smith9b88a4c2015-07-27 05:40:23 +00006947Decl *ASTContext::getVaListTagDecl() const {
6948 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006949 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006950 if (!VaListTagDecl)
6951 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006952
Richard Smith9b88a4c2015-07-27 05:40:23 +00006953 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006954}
6955
Charles Davisc7d5c942015-09-17 20:55:33 +00006956TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6957 if (!BuiltinMSVaListDecl)
6958 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6959
6960 return BuiltinMSVaListDecl;
6961}
6962
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006963void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006964 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006965 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006966
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006967 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006968}
6969
John McCalld28ae272009-12-02 08:04:21 +00006970/// \brief Retrieve the template name that corresponds to a non-empty
6971/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006972TemplateName
6973ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6974 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006975 unsigned size = End - Begin;
6976 assert(size > 1 && "set is not overloaded!");
6977
6978 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6979 size * sizeof(FunctionTemplateDecl*));
6980 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6981
6982 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006983 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006984 NamedDecl *D = *I;
6985 assert(isa<FunctionTemplateDecl>(D) ||
6986 (isa<UsingShadowDecl>(D) &&
6987 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6988 *Storage++ = D;
6989 }
6990
6991 return TemplateName(OT);
6992}
6993
Douglas Gregordc572a32009-03-30 22:58:21 +00006994/// \brief Retrieve the template name that represents a qualified
6995/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006996TemplateName
6997ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6998 bool TemplateKeyword,
6999 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007000 assert(NNS && "Missing nested-name-specifier in qualified template name");
7001
Douglas Gregorc42075a2010-02-04 18:10:26 +00007002 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007003 llvm::FoldingSetNodeID ID;
7004 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7005
Craig Topper36250ad2014-05-12 05:36:57 +00007006 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007007 QualifiedTemplateName *QTN =
7008 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7009 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007010 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007011 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007012 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7013 }
7014
7015 return TemplateName(QTN);
7016}
7017
7018/// \brief Retrieve the template name that represents a dependent
7019/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007020TemplateName
7021ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7022 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007023 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007024 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007025
7026 llvm::FoldingSetNodeID ID;
7027 DependentTemplateName::Profile(ID, NNS, Name);
7028
Craig Topper36250ad2014-05-12 05:36:57 +00007029 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007030 DependentTemplateName *QTN =
7031 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7032
7033 if (QTN)
7034 return TemplateName(QTN);
7035
7036 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7037 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007038 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007039 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007040 } else {
7041 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007042 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007043 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007044 DependentTemplateName *CheckQTN =
7045 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7046 assert(!CheckQTN && "Dependent type name canonicalization broken");
7047 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007048 }
7049
7050 DependentTemplateNames.InsertNode(QTN, InsertPos);
7051 return TemplateName(QTN);
7052}
7053
Douglas Gregor71395fa2009-11-04 00:56:37 +00007054/// \brief Retrieve the template name that represents a dependent
7055/// template name such as \c MetaFun::template operator+.
7056TemplateName
7057ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007058 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007059 assert((!NNS || NNS->isDependent()) &&
7060 "Nested name specifier must be dependent");
7061
7062 llvm::FoldingSetNodeID ID;
7063 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007064
7065 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007066 DependentTemplateName *QTN
7067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007068
7069 if (QTN)
7070 return TemplateName(QTN);
7071
7072 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7073 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007074 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007075 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007076 } else {
7077 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007078 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007079 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007080
Douglas Gregorc42075a2010-02-04 18:10:26 +00007081 DependentTemplateName *CheckQTN
7082 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7083 assert(!CheckQTN && "Dependent template name canonicalization broken");
7084 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007085 }
7086
7087 DependentTemplateNames.InsertNode(QTN, InsertPos);
7088 return TemplateName(QTN);
7089}
7090
Douglas Gregor5590be02011-01-15 06:45:20 +00007091TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007092ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7093 TemplateName replacement) const {
7094 llvm::FoldingSetNodeID ID;
7095 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007096
7097 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007098 SubstTemplateTemplateParmStorage *subst
7099 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7100
7101 if (!subst) {
7102 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7103 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7104 }
7105
7106 return TemplateName(subst);
7107}
7108
7109TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007110ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7111 const TemplateArgument &ArgPack) const {
7112 ASTContext &Self = const_cast<ASTContext &>(*this);
7113 llvm::FoldingSetNodeID ID;
7114 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007115
7116 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007117 SubstTemplateTemplateParmPackStorage *Subst
7118 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7119
7120 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007121 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007122 ArgPack.pack_size(),
7123 ArgPack.pack_begin());
7124 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7125 }
7126
7127 return TemplateName(Subst);
7128}
7129
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007130/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007131/// TargetInfo, produce the corresponding type. The unsigned @p Type
7132/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007133CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007134 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007135 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007136 case TargetInfo::SignedChar: return SignedCharTy;
7137 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007138 case TargetInfo::SignedShort: return ShortTy;
7139 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7140 case TargetInfo::SignedInt: return IntTy;
7141 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7142 case TargetInfo::SignedLong: return LongTy;
7143 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7144 case TargetInfo::SignedLongLong: return LongLongTy;
7145 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7146 }
7147
David Blaikie83d382b2011-09-23 05:06:16 +00007148 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007149}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007150
7151//===----------------------------------------------------------------------===//
7152// Type Predicates.
7153//===----------------------------------------------------------------------===//
7154
Fariborz Jahanian96207692009-02-18 21:49:28 +00007155/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7156/// garbage collection attribute.
7157///
John McCall553d45a2011-01-12 00:34:59 +00007158Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007159 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007160 return Qualifiers::GCNone;
7161
David Blaikiebbafb8a2012-03-11 07:00:24 +00007162 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007163 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7164
7165 // Default behaviour under objective-C's gc is for ObjC pointers
7166 // (or pointers to them) be treated as though they were declared
7167 // as __strong.
7168 if (GCAttrs == Qualifiers::GCNone) {
7169 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7170 return Qualifiers::Strong;
7171 else if (Ty->isPointerType())
7172 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7173 } else {
7174 // It's not valid to set GC attributes on anything that isn't a
7175 // pointer.
7176#ifndef NDEBUG
7177 QualType CT = Ty->getCanonicalTypeInternal();
7178 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7179 CT = AT->getElementType();
7180 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7181#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007182 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007183 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007184}
7185
Chris Lattner49af6a42008-04-07 06:51:04 +00007186//===----------------------------------------------------------------------===//
7187// Type Compatibility Testing
7188//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007189
Mike Stump11289f42009-09-09 15:08:12 +00007190/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007191/// compatible.
7192static bool areCompatVectorTypes(const VectorType *LHS,
7193 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007194 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007195 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007196 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007197}
7198
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007199bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7200 QualType SecondVec) {
7201 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7202 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7203
7204 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7205 return true;
7206
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007207 // Treat Neon vector types and most AltiVec vector types as if they are the
7208 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007209 const VectorType *First = FirstVec->getAs<VectorType>();
7210 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007211 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007212 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007213 First->getVectorKind() != VectorType::AltiVecPixel &&
7214 First->getVectorKind() != VectorType::AltiVecBool &&
7215 Second->getVectorKind() != VectorType::AltiVecPixel &&
7216 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007217 return true;
7218
7219 return false;
7220}
7221
Steve Naroff8e6aee52009-07-23 01:01:38 +00007222//===----------------------------------------------------------------------===//
7223// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7224//===----------------------------------------------------------------------===//
7225
7226/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7227/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007228bool
7229ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7230 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007231 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007232 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007233 for (auto *PI : rProto->protocols())
7234 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007235 return true;
7236 return false;
7237}
7238
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007239/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7240/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007241bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7242 QualType rhs) {
7243 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7244 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7245 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7246
Aaron Ballman83731462014-03-17 16:14:00 +00007247 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007248 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007249 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007250 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7251 match = true;
7252 break;
7253 }
7254 }
7255 if (!match)
7256 return false;
7257 }
7258 return true;
7259}
7260
Steve Naroff8e6aee52009-07-23 01:01:38 +00007261/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7262/// ObjCQualifiedIDType.
7263bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7264 bool compare) {
7265 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007266 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007267 lhs->isObjCIdType() || lhs->isObjCClassType())
7268 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007269 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007270 rhs->isObjCIdType() || rhs->isObjCClassType())
7271 return true;
7272
7273 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007274 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007275
Steve Naroff8e6aee52009-07-23 01:01:38 +00007276 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007277
Steve Naroff8e6aee52009-07-23 01:01:38 +00007278 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007279 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007280 // make sure we check the class hierarchy.
7281 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007282 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007283 // when comparing an id<P> on lhs with a static type on rhs,
7284 // see if static class implements all of id's protocols, directly or
7285 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007286 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007287 return false;
7288 }
7289 }
7290 // If there are no qualifiers and no interface, we have an 'id'.
7291 return true;
7292 }
Mike Stump11289f42009-09-09 15:08:12 +00007293 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007294 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007295 bool match = false;
7296
7297 // when comparing an id<P> on lhs with a static type on rhs,
7298 // see if static class implements all of id's protocols, directly or
7299 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007300 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007301 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7302 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7303 match = true;
7304 break;
7305 }
7306 }
Mike Stump11289f42009-09-09 15:08:12 +00007307 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007308 // make sure we check the class hierarchy.
7309 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007310 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007311 // when comparing an id<P> on lhs with a static type on rhs,
7312 // see if static class implements all of id's protocols, directly or
7313 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007314 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007315 match = true;
7316 break;
7317 }
7318 }
7319 }
7320 if (!match)
7321 return false;
7322 }
Mike Stump11289f42009-09-09 15:08:12 +00007323
Steve Naroff8e6aee52009-07-23 01:01:38 +00007324 return true;
7325 }
Mike Stump11289f42009-09-09 15:08:12 +00007326
Steve Naroff8e6aee52009-07-23 01:01:38 +00007327 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7328 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7329
Mike Stump11289f42009-09-09 15:08:12 +00007330 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007331 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007332 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007333 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007334 bool match = false;
7335
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007336 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007337 // see if static class implements all of id's protocols, directly or
7338 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007339 // First, lhs protocols in the qualifier list must be found, direct
7340 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007341 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007342 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7343 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7344 match = true;
7345 break;
7346 }
7347 }
7348 if (!match)
7349 return false;
7350 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007351
7352 // Static class's protocols, or its super class or category protocols
7353 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7354 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7355 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7356 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7357 // This is rather dubious but matches gcc's behavior. If lhs has
7358 // no type qualifier and its class has no static protocol(s)
7359 // assume that it is mismatch.
7360 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7361 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007362 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007363 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007364 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007365 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7366 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7367 match = true;
7368 break;
7369 }
7370 }
7371 if (!match)
7372 return false;
7373 }
7374 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007375 return true;
7376 }
7377 return false;
7378}
7379
Eli Friedman47f77112008-08-22 00:56:42 +00007380/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007381/// compatible for assignment from RHS to LHS. This handles validation of any
7382/// protocol qualifiers on the LHS or RHS.
7383///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007384bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7385 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007386 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7387 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7388
Steve Naroff1329fa02009-07-15 18:40:39 +00007389 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007390 if (LHS->isObjCUnqualifiedIdOrClass() ||
7391 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007392 return true;
7393
Douglas Gregorab209d82015-07-07 03:58:42 +00007394 // Function object that propagates a successful result or handles
7395 // __kindof types.
7396 auto finish = [&](bool succeeded) -> bool {
7397 if (succeeded)
7398 return true;
7399
7400 if (!RHS->isKindOfType())
7401 return false;
7402
7403 // Strip off __kindof and protocol qualifiers, then check whether
7404 // we can assign the other way.
7405 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7406 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7407 };
7408
7409 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7410 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7411 QualType(RHSOPT,0),
7412 false));
7413 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007414
Douglas Gregorab209d82015-07-07 03:58:42 +00007415 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7416 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7417 QualType(RHSOPT,0)));
7418 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007419
John McCall8b07ec22010-05-15 11:32:37 +00007420 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007421 if (LHS->getInterface() && RHS->getInterface()) {
7422 return finish(canAssignObjCInterfaces(LHS, RHS));
7423 }
Mike Stump11289f42009-09-09 15:08:12 +00007424
Steve Naroff8e6aee52009-07-23 01:01:38 +00007425 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007426}
7427
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007428/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007429/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007430/// arguments in block literals. When passed as arguments, passing 'A*' where
7431/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7432/// not OK. For the return type, the opposite is not OK.
7433bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7434 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007435 const ObjCObjectPointerType *RHSOPT,
7436 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007437
7438 // Function object that propagates a successful result or handles
7439 // __kindof types.
7440 auto finish = [&](bool succeeded) -> bool {
7441 if (succeeded)
7442 return true;
7443
7444 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7445 if (!Expected->isKindOfType())
7446 return false;
7447
7448 // Strip off __kindof and protocol qualifiers, then check whether
7449 // we can assign the other way.
7450 return canAssignObjCInterfacesInBlockPointer(
7451 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7452 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7453 BlockReturnType);
7454 };
7455
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007456 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007457 return true;
7458
7459 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007460 return finish(RHSOPT->isObjCBuiltinType() ||
7461 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007462 }
7463
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007464 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007465 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7466 QualType(RHSOPT,0),
7467 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007468
7469 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7470 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7471 if (LHS && RHS) { // We have 2 user-defined types.
7472 if (LHS != RHS) {
7473 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007474 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007475 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007476 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007477 }
7478 else
7479 return true;
7480 }
7481 return false;
7482}
7483
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007484/// Comparison routine for Objective-C protocols to be used with
7485/// llvm::array_pod_sort.
7486static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7487 ObjCProtocolDecl * const *rhs) {
7488 return (*lhs)->getName().compare((*rhs)->getName());
7489
7490}
7491
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007492/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007493/// of protocols inherited from two distinct objective-c pointer objects with
7494/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007495/// It is used to build composite qualifier list of the composite type of
7496/// the conditional expression involving two objective-c pointer objects.
7497static
7498void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007499 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007500 const ObjCObjectPointerType *LHSOPT,
7501 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007502 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007503
John McCall8b07ec22010-05-15 11:32:37 +00007504 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7505 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7506 assert(LHS->getInterface() && "LHS must have an interface base");
7507 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007508
7509 // Add all of the protocols for the LHS.
7510 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7511
7512 // Start with the protocol qualifiers.
7513 for (auto proto : LHS->quals()) {
7514 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007515 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007516
7517 // Also add the protocols associated with the LHS interface.
7518 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7519
7520 // Add all of the protocls for the RHS.
7521 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7522
7523 // Start with the protocol qualifiers.
7524 for (auto proto : RHS->quals()) {
7525 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007526 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007527
7528 // Also add the protocols associated with the RHS interface.
7529 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7530
7531 // Compute the intersection of the collected protocol sets.
7532 for (auto proto : LHSProtocolSet) {
7533 if (RHSProtocolSet.count(proto))
7534 IntersectionSet.push_back(proto);
7535 }
7536
7537 // Compute the set of protocols that is implied by either the common type or
7538 // the protocols within the intersection.
7539 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7540 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7541
7542 // Remove any implied protocols from the list of inherited protocols.
7543 if (!ImpliedProtocols.empty()) {
7544 IntersectionSet.erase(
7545 std::remove_if(IntersectionSet.begin(),
7546 IntersectionSet.end(),
7547 [&](ObjCProtocolDecl *proto) -> bool {
7548 return ImpliedProtocols.count(proto) > 0;
7549 }),
7550 IntersectionSet.end());
7551 }
7552
7553 // Sort the remaining protocols by name.
7554 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7555 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007556}
7557
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007558/// Determine whether the first type is a subtype of the second.
7559static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7560 QualType rhs) {
7561 // Common case: two object pointers.
7562 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7563 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7564 if (lhsOPT && rhsOPT)
7565 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7566
7567 // Two block pointers.
7568 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7569 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7570 if (lhsBlock && rhsBlock)
7571 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7572
7573 // If either is an unqualified 'id' and the other is a block, it's
7574 // acceptable.
7575 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7576 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7577 return true;
7578
7579 return false;
7580}
7581
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007582// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007583static bool sameObjCTypeArgs(ASTContext &ctx,
7584 const ObjCInterfaceDecl *iface,
7585 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007586 ArrayRef<QualType> rhsArgs,
7587 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007588 if (lhsArgs.size() != rhsArgs.size())
7589 return false;
7590
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007591 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007592 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007593 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7594 continue;
7595
7596 switch (typeParams->begin()[i]->getVariance()) {
7597 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007598 if (!stripKindOf ||
7599 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7600 rhsArgs[i].stripObjCKindOfType(ctx))) {
7601 return false;
7602 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007603 break;
7604
7605 case ObjCTypeParamVariance::Covariant:
7606 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7607 return false;
7608 break;
7609
7610 case ObjCTypeParamVariance::Contravariant:
7611 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7612 return false;
7613 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007614 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007615 }
7616
7617 return true;
7618}
7619
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007620QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007621 const ObjCObjectPointerType *Lptr,
7622 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007623 const ObjCObjectType *LHS = Lptr->getObjectType();
7624 const ObjCObjectType *RHS = Rptr->getObjectType();
7625 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7626 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007627
7628 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007629 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007630
Manman Renc46f7d12016-05-06 19:35:02 +00007631 // When either LHS or RHS is a kindof type, we should return a kindof type.
7632 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7633 // kindof(A).
7634 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7635
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007636 // Follow the left-hand side up the class hierarchy until we either hit a
7637 // root or find the RHS. Record the ancestors in case we don't find it.
7638 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7639 LHSAncestors;
7640 while (true) {
7641 // Record this ancestor. We'll need this if the common type isn't in the
7642 // path from the LHS to the root.
7643 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007644
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007645 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7646 // Get the type arguments.
7647 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7648 bool anyChanges = false;
7649 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7650 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007651 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7652 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007653 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007654 return QualType();
7655 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7656 // If only one has type arguments, the result will not have type
7657 // arguments.
7658 LHSTypeArgs = { };
7659 anyChanges = true;
7660 }
7661
7662 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007663 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007664 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7665 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007666 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007667 anyChanges = true;
7668
7669 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007670 // If we need to return a kindof type but LHS is not a kindof type, we
7671 // build a new result type.
7672 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007673 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007674 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007675 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007676 return getObjCObjectPointerType(Result);
7677 }
7678
7679 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007680 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007681
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007682 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007683 QualType LHSSuperType = LHS->getSuperClassType();
7684 if (LHSSuperType.isNull())
7685 break;
7686
7687 LHS = LHSSuperType->castAs<ObjCObjectType>();
7688 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007689
7690 // We didn't find anything by following the LHS to its root; now check
7691 // the RHS against the cached set of ancestors.
7692 while (true) {
7693 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7694 if (KnownLHS != LHSAncestors.end()) {
7695 LHS = KnownLHS->second;
7696
7697 // Get the type arguments.
7698 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7699 bool anyChanges = false;
7700 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7701 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007702 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7703 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007704 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007705 return QualType();
7706 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7707 // If only one has type arguments, the result will not have type
7708 // arguments.
7709 RHSTypeArgs = { };
7710 anyChanges = true;
7711 }
7712
7713 // Compute the intersection of protocols.
7714 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7715 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7716 Protocols);
7717 if (!Protocols.empty())
7718 anyChanges = true;
7719
Manman Renc46f7d12016-05-06 19:35:02 +00007720 // If we need to return a kindof type but RHS is not a kindof type, we
7721 // build a new result type.
7722 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007723 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007724 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007725 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007726 return getObjCObjectPointerType(Result);
7727 }
7728
7729 return getObjCObjectPointerType(QualType(RHS, 0));
7730 }
7731
7732 // Find the superclass of the RHS.
7733 QualType RHSSuperType = RHS->getSuperClassType();
7734 if (RHSSuperType.isNull())
7735 break;
7736
7737 RHS = RHSSuperType->castAs<ObjCObjectType>();
7738 }
7739
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007740 return QualType();
7741}
7742
John McCall8b07ec22010-05-15 11:32:37 +00007743bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7744 const ObjCObjectType *RHS) {
7745 assert(LHS->getInterface() && "LHS is not an interface type");
7746 assert(RHS->getInterface() && "RHS is not an interface type");
7747
Chris Lattner49af6a42008-04-07 06:51:04 +00007748 // Verify that the base decls are compatible: the RHS must be a subclass of
7749 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007750 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7751 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7752 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007753 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007754
Douglas Gregore83b9562015-07-07 03:57:53 +00007755 // If the LHS has protocol qualifiers, determine whether all of them are
7756 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7757 // LHS).
7758 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007759 // OK if conversion of LHS to SuperClass results in narrowing of types
7760 // ; i.e., SuperClass may implement at least one of the protocols
7761 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7762 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7763 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7764 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7765 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7766 // qualifiers.
7767 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007768 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007769 // If there is no protocols associated with RHS, it is not a match.
7770 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007771 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007772
7773 for (const auto *LHSProto : LHS->quals()) {
7774 bool SuperImplementsProtocol = false;
7775 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7776 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7777 SuperImplementsProtocol = true;
7778 break;
7779 }
7780 if (!SuperImplementsProtocol)
7781 return false;
7782 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007783 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007784
7785 // If the LHS is specialized, we may need to check type arguments.
7786 if (LHS->isSpecialized()) {
7787 // Follow the superclass chain until we've matched the LHS class in the
7788 // hierarchy. This substitutes type arguments through.
7789 const ObjCObjectType *RHSSuper = RHS;
7790 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7791 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7792
7793 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007794 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007795 !sameObjCTypeArgs(*this, LHS->getInterface(),
7796 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007797 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007798 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007799 }
7800 }
7801
7802 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007803}
7804
Steve Naroffb7605152009-02-12 17:52:19 +00007805bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7806 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007807 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7808 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007809
Steve Naroff7cae42b2009-07-10 23:34:53 +00007810 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007811 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007812
7813 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7814 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007815}
7816
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007817bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7818 return canAssignObjCInterfaces(
7819 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7820 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7821}
7822
Mike Stump11289f42009-09-09 15:08:12 +00007823/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007824/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007825/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007826/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007827bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7828 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007829 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007830 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007831
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007832 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007833}
7834
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007835bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007836 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007837}
7838
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007839bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7840 return !mergeTypes(LHS, RHS, true).isNull();
7841}
7842
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007843/// mergeTransparentUnionType - if T is a transparent union type and a member
7844/// of T is compatible with SubType, return the merged type, else return
7845/// QualType()
7846QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7847 bool OfBlockPointer,
7848 bool Unqualified) {
7849 if (const RecordType *UT = T->getAsUnionType()) {
7850 RecordDecl *UD = UT->getDecl();
7851 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007852 for (const auto *I : UD->fields()) {
7853 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007854 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7855 if (!MT.isNull())
7856 return MT;
7857 }
7858 }
7859 }
7860
7861 return QualType();
7862}
7863
Alp Toker9cacbab2014-01-20 20:26:09 +00007864/// mergeFunctionParameterTypes - merge two types which appear as function
7865/// parameter types
7866QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7867 bool OfBlockPointer,
7868 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007869 // GNU extension: two types are compatible if they appear as a function
7870 // argument, one of the types is a transparent union type and the other
7871 // type is compatible with a union member
7872 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7873 Unqualified);
7874 if (!lmerge.isNull())
7875 return lmerge;
7876
7877 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7878 Unqualified);
7879 if (!rmerge.isNull())
7880 return rmerge;
7881
7882 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7883}
7884
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007885QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007886 bool OfBlockPointer,
7887 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007888 const FunctionType *lbase = lhs->getAs<FunctionType>();
7889 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007890 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7891 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007892 bool allLTypes = true;
7893 bool allRTypes = true;
7894
7895 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007896 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007897 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007898 QualType RHS = rbase->getReturnType();
7899 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007900 bool UnqualifiedResult = Unqualified;
7901 if (!UnqualifiedResult)
7902 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007903 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007904 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007905 else
Alp Toker314cc812014-01-25 16:55:45 +00007906 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007907 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007908 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007909
7910 if (Unqualified)
7911 retType = retType.getUnqualifiedType();
7912
Alp Toker314cc812014-01-25 16:55:45 +00007913 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7914 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007915 if (Unqualified) {
7916 LRetType = LRetType.getUnqualifiedType();
7917 RRetType = RRetType.getUnqualifiedType();
7918 }
7919
7920 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007921 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007922 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007923 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007924
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007925 // FIXME: double check this
7926 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7927 // rbase->getRegParmAttr() != 0 &&
7928 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007929 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7930 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007931
Douglas Gregor8c940862010-01-18 17:14:39 +00007932 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007933 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007934 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007935
John McCall8c6b56f2010-12-15 01:06:38 +00007936 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007937 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7938 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007939 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7940 return QualType();
7941
John McCall31168b02011-06-15 23:02:42 +00007942 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7943 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00007944 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
7945 return QualType();
John McCall31168b02011-06-15 23:02:42 +00007946
John McCall8c6b56f2010-12-15 01:06:38 +00007947 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7948 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007949
Rafael Espindola8778c282012-11-29 16:09:03 +00007950 if (lbaseInfo.getNoReturn() != NoReturn)
7951 allLTypes = false;
7952 if (rbaseInfo.getNoReturn() != NoReturn)
7953 allRTypes = false;
7954
John McCall31168b02011-06-15 23:02:42 +00007955 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007956
Eli Friedman47f77112008-08-22 00:56:42 +00007957 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007958 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7959 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007960 // Compatible functions must have the same number of parameters
7961 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007962 return QualType();
7963
7964 // Variadic and non-variadic functions aren't compatible
7965 if (lproto->isVariadic() != rproto->isVariadic())
7966 return QualType();
7967
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007968 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7969 return QualType();
7970
John McCall18afab72016-03-01 00:49:02 +00007971 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007972 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007973
7974 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007975 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007976 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7977 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7978 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7979 QualType paramType = mergeFunctionParameterTypes(
7980 lParamType, rParamType, OfBlockPointer, Unqualified);
7981 if (paramType.isNull())
7982 return QualType();
7983
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007984 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007985 paramType = paramType.getUnqualifiedType();
7986
7987 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007988 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007989 lParamType = lParamType.getUnqualifiedType();
7990 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007991 }
Alp Toker601b22c2014-01-21 23:35:24 +00007992
7993 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007994 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007995 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007996 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007997 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007998
Eli Friedman47f77112008-08-22 00:56:42 +00007999 if (allLTypes) return lhs;
8000 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008001
8002 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8003 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00008004 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008005 }
8006
8007 if (lproto) allRTypes = false;
8008 if (rproto) allLTypes = false;
8009
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008010 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008011 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008012 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008013 if (proto->isVariadic()) return QualType();
8014 // Check that the types are compatible with the types that
8015 // would result from default argument promotions (C99 6.7.5.3p15).
8016 // The only types actually affected are promotable integer
8017 // types and floats, which would be passed as a different
8018 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008019 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8020 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008021
Eli Friedman448ce402012-08-30 00:44:15 +00008022 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008023 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008024 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8025 paramTy = Enum->getDecl()->getIntegerType();
8026 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008027 return QualType();
8028 }
Alp Toker601b22c2014-01-21 23:35:24 +00008029
8030 if (paramTy->isPromotableIntegerType() ||
8031 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008032 return QualType();
8033 }
8034
8035 if (allLTypes) return lhs;
8036 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008037
8038 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8039 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008040 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008041 }
8042
8043 if (allLTypes) return lhs;
8044 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008045 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008046}
8047
John McCall433c2e62013-03-21 00:10:07 +00008048/// Given that we have an enum type and a non-enum type, try to merge them.
8049static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8050 QualType other, bool isBlockReturnType) {
8051 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8052 // a signed integer type, or an unsigned integer type.
8053 // Compatibility is based on the underlying type, not the promotion
8054 // type.
8055 QualType underlyingType = ET->getDecl()->getIntegerType();
8056 if (underlyingType.isNull()) return QualType();
8057 if (Context.hasSameType(underlyingType, other))
8058 return other;
8059
8060 // In block return types, we're more permissive and accept any
8061 // integral type of the same size.
8062 if (isBlockReturnType && other->isIntegerType() &&
8063 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8064 return other;
8065
8066 return QualType();
8067}
8068
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008069QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008070 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008071 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008072 // C++ [expr]: If an expression initially has the type "reference to T", the
8073 // type is adjusted to "T" prior to any further analysis, the expression
8074 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008075 // expression is an lvalue unless the reference is an rvalue reference and
8076 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008077 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8078 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008079
8080 if (Unqualified) {
8081 LHS = LHS.getUnqualifiedType();
8082 RHS = RHS.getUnqualifiedType();
8083 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008084
Eli Friedman47f77112008-08-22 00:56:42 +00008085 QualType LHSCan = getCanonicalType(LHS),
8086 RHSCan = getCanonicalType(RHS);
8087
8088 // If two types are identical, they are compatible.
8089 if (LHSCan == RHSCan)
8090 return LHS;
8091
John McCall8ccfcb52009-09-24 19:53:00 +00008092 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008093 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8094 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008095 if (LQuals != RQuals) {
8096 // If any of these qualifiers are different, we have a type
8097 // mismatch.
8098 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008099 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008100 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8101 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008102 return QualType();
8103
8104 // Exactly one GC qualifier difference is allowed: __strong is
8105 // okay if the other type has no GC qualifier but is an Objective
8106 // C object pointer (i.e. implicitly strong by default). We fix
8107 // this by pretending that the unqualified type was actually
8108 // qualified __strong.
8109 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8110 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8111 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8112
8113 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8114 return QualType();
8115
8116 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8117 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8118 }
8119 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8120 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8121 }
Eli Friedman47f77112008-08-22 00:56:42 +00008122 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008123 }
8124
8125 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008126
Eli Friedmandcca6332009-06-01 01:22:52 +00008127 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8128 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008129
Chris Lattnerfd652912008-01-14 05:45:46 +00008130 // We want to consider the two function types to be the same for these
8131 // comparisons, just force one to the other.
8132 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8133 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008134
8135 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008136 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8137 LHSClass = Type::ConstantArray;
8138 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8139 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008140
John McCall8b07ec22010-05-15 11:32:37 +00008141 // ObjCInterfaces are just specialized ObjCObjects.
8142 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8143 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8144
Nate Begemance4d7fc2008-04-18 23:10:10 +00008145 // Canonicalize ExtVector -> Vector.
8146 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8147 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008148
Chris Lattner95554662008-04-07 05:43:21 +00008149 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008150 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008151 // Note that we only have special rules for turning block enum
8152 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008153 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008154 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008155 }
John McCall9dd450b2009-09-21 23:43:11 +00008156 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008157 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008158 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008159 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008160 if (OfBlockPointer && !BlockReturnType) {
8161 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8162 return LHS;
8163 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8164 return RHS;
8165 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008166
Eli Friedman47f77112008-08-22 00:56:42 +00008167 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008168 }
Eli Friedman47f77112008-08-22 00:56:42 +00008169
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008170 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008171 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008172#define TYPE(Class, Base)
8173#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008174#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008175#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8176#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8177#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008178 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008179
Richard Smith27d807c2013-04-30 13:56:41 +00008180 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008181 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008182 case Type::LValueReference:
8183 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008184 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008185 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008186
John McCall8b07ec22010-05-15 11:32:37 +00008187 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008188 case Type::IncompleteArray:
8189 case Type::VariableArray:
8190 case Type::FunctionProto:
8191 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008192 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008193
Chris Lattnerfd652912008-01-14 05:45:46 +00008194 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008195 {
8196 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008197 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8198 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008199 if (Unqualified) {
8200 LHSPointee = LHSPointee.getUnqualifiedType();
8201 RHSPointee = RHSPointee.getUnqualifiedType();
8202 }
8203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8204 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008205 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008207 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008209 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008210 return getPointerType(ResultType);
8211 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008212 case Type::BlockPointer:
8213 {
8214 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008215 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8216 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008217 if (Unqualified) {
8218 LHSPointee = LHSPointee.getUnqualifiedType();
8219 RHSPointee = RHSPointee.getUnqualifiedType();
8220 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008221 if (getLangOpts().OpenCL) {
8222 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8223 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8224 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8225 // 6.12.5) thus the following check is asymmetric.
8226 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8227 return QualType();
8228 LHSPteeQual.removeAddressSpace();
8229 RHSPteeQual.removeAddressSpace();
8230 LHSPointee =
8231 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8232 RHSPointee =
8233 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8234 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008235 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8236 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008237 if (ResultType.isNull()) return QualType();
8238 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8239 return LHS;
8240 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8241 return RHS;
8242 return getBlockPointerType(ResultType);
8243 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008244 case Type::Atomic:
8245 {
8246 // Merge two pointer types, while trying to preserve typedef info
8247 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8248 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8249 if (Unqualified) {
8250 LHSValue = LHSValue.getUnqualifiedType();
8251 RHSValue = RHSValue.getUnqualifiedType();
8252 }
8253 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8254 Unqualified);
8255 if (ResultType.isNull()) return QualType();
8256 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8257 return LHS;
8258 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8259 return RHS;
8260 return getAtomicType(ResultType);
8261 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008262 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008263 {
8264 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8265 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8266 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8267 return QualType();
8268
8269 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8270 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008271 if (Unqualified) {
8272 LHSElem = LHSElem.getUnqualifiedType();
8273 RHSElem = RHSElem.getUnqualifiedType();
8274 }
8275
8276 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008277 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008278 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8279 return LHS;
8280 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8281 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008282 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8283 ArrayType::ArraySizeModifier(), 0);
8284 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8285 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008286 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8287 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008288 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8289 return LHS;
8290 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8291 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008292 if (LVAT) {
8293 // FIXME: This isn't correct! But tricky to implement because
8294 // the array's size has to be the size of LHS, but the type
8295 // has to be different.
8296 return LHS;
8297 }
8298 if (RVAT) {
8299 // FIXME: This isn't correct! But tricky to implement because
8300 // the array's size has to be the size of RHS, but the type
8301 // has to be different.
8302 return RHS;
8303 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008304 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8305 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008306 return getIncompleteArrayType(ResultType,
8307 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008308 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008309 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008310 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008311 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008312 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008313 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008314 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008315 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008316 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008317 case Type::Complex:
8318 // Distinct complex types are incompatible.
8319 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008320 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008321 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008322 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8323 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008324 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008325 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008326 case Type::ObjCObject: {
8327 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008328 // FIXME: This should be type compatibility, e.g. whether
8329 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008330 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8331 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8332 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008333 return LHS;
8334
Eli Friedman47f77112008-08-22 00:56:42 +00008335 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008336 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008337 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008338 if (OfBlockPointer) {
8339 if (canAssignObjCInterfacesInBlockPointer(
8340 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008341 RHS->getAs<ObjCObjectPointerType>(),
8342 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008343 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008344 return QualType();
8345 }
John McCall9dd450b2009-09-21 23:43:11 +00008346 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8347 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008348 return LHS;
8349
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008350 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008351 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008352 case Type::Pipe:
8353 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008354 assert(LHS != RHS &&
8355 "Equivalent pipe types should have already been handled!");
8356 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008357 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008358 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008359
David Blaikie8a40f702012-01-17 06:56:22 +00008360 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008361}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008362
John McCall18afab72016-03-01 00:49:02 +00008363bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8364 const FunctionProtoType *firstFnType,
8365 const FunctionProtoType *secondFnType) {
8366 // Fast path: if the first type doesn't have ext parameter infos,
8367 // we match if and only if they second type also doesn't have them.
8368 if (!firstFnType->hasExtParameterInfos())
8369 return !secondFnType->hasExtParameterInfos();
8370
8371 // Otherwise, we can only match if the second type has them.
8372 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008373 return false;
John McCall18afab72016-03-01 00:49:02 +00008374
8375 auto firstEPI = firstFnType->getExtParameterInfos();
8376 auto secondEPI = secondFnType->getExtParameterInfos();
8377 assert(firstEPI.size() == secondEPI.size());
8378
8379 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8380 if (firstEPI[i] != secondEPI[i])
8381 return false;
8382 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008383 return true;
8384}
8385
Chandler Carruth21c90602015-12-30 03:24:14 +00008386void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8387 ObjCLayouts[CD] = nullptr;
8388}
8389
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008390/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8391/// 'RHS' attributes and returns the merged version; including for function
8392/// return types.
8393QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8394 QualType LHSCan = getCanonicalType(LHS),
8395 RHSCan = getCanonicalType(RHS);
8396 // If two types are identical, they are compatible.
8397 if (LHSCan == RHSCan)
8398 return LHS;
8399 if (RHSCan->isFunctionType()) {
8400 if (!LHSCan->isFunctionType())
8401 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008402 QualType OldReturnType =
8403 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008404 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008405 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008406 QualType ResReturnType =
8407 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8408 if (ResReturnType.isNull())
8409 return QualType();
8410 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8411 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8412 // In either case, use OldReturnType to build the new function type.
8413 const FunctionType *F = LHS->getAs<FunctionType>();
8414 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8416 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008417 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008418 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008419 return ResultType;
8420 }
8421 }
8422 return QualType();
8423 }
8424
8425 // If the qualifiers are different, the types can still be merged.
8426 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8427 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8428 if (LQuals != RQuals) {
8429 // If any of these qualifiers are different, we have a type mismatch.
8430 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8431 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8432 return QualType();
8433
8434 // Exactly one GC qualifier difference is allowed: __strong is
8435 // okay if the other type has no GC qualifier but is an Objective
8436 // C object pointer (i.e. implicitly strong by default). We fix
8437 // this by pretending that the unqualified type was actually
8438 // qualified __strong.
8439 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8440 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8441 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8442
8443 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8444 return QualType();
8445
8446 if (GC_L == Qualifiers::Strong)
8447 return LHS;
8448 if (GC_R == Qualifiers::Strong)
8449 return RHS;
8450 return QualType();
8451 }
8452
8453 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8454 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8455 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8456 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8457 if (ResQT == LHSBaseQT)
8458 return LHS;
8459 if (ResQT == RHSBaseQT)
8460 return RHS;
8461 }
8462 return QualType();
8463}
8464
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008465//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008466// Integer Predicates
8467//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008468
Jay Foad39c79802011-01-12 09:06:06 +00008469unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008470 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008471 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008472 if (T->isBooleanType())
8473 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008474 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008475 return (unsigned)getTypeSize(T);
8476}
8477
Abramo Bagnara13640492012-09-09 10:21:24 +00008478QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008479 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008480
8481 // Turn <4 x signed int> -> <4 x unsigned int>
8482 if (const VectorType *VTy = T->getAs<VectorType>())
8483 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008484 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008485
8486 // For enums, we return the unsigned version of the base type.
8487 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008488 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008489
8490 const BuiltinType *BTy = T->getAs<BuiltinType>();
8491 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008492 switch (BTy->getKind()) {
8493 case BuiltinType::Char_S:
8494 case BuiltinType::SChar:
8495 return UnsignedCharTy;
8496 case BuiltinType::Short:
8497 return UnsignedShortTy;
8498 case BuiltinType::Int:
8499 return UnsignedIntTy;
8500 case BuiltinType::Long:
8501 return UnsignedLongTy;
8502 case BuiltinType::LongLong:
8503 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008504 case BuiltinType::Int128:
8505 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008506 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008507 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008508 }
8509}
8510
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008511ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008512
Richard Smith1fa5d642013-05-11 05:45:24 +00008513void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8514 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008515
8516//===----------------------------------------------------------------------===//
8517// Builtin Type Computation
8518//===----------------------------------------------------------------------===//
8519
8520/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008521/// pointer over the consumed characters. This returns the resultant type. If
8522/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8523/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8524/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008525///
8526/// RequiresICE is filled in on return to indicate whether the value is required
8527/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008528static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008529 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008530 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008531 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008532 // Modifiers.
8533 int HowLong = 0;
8534 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008535 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008536
Chris Lattnerdc226c22010-10-01 22:42:38 +00008537 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008538 bool Done = false;
8539 #ifndef NDEBUG
8540 bool IsSpecialLong = false;
8541 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008542 while (!Done) {
8543 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008544 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008545 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008546 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008547 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008548 case 'S':
8549 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8550 assert(!Signed && "Can't use 'S' modifier multiple times!");
8551 Signed = true;
8552 break;
8553 case 'U':
8554 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008555 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008556 Unsigned = true;
8557 break;
8558 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008559 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008560 assert(HowLong <= 2 && "Can't have LLLL modifier");
8561 ++HowLong;
8562 break;
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008563 case 'N': {
8564 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8565 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8566 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008567 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008568 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008569 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008570 if (Context.getTargetInfo().getLongWidth() == 32)
8571 ++HowLong;
8572 break;
8573 }
Kevin Qinad64f6d2014-02-24 02:45:03 +00008574 case 'W':
8575 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008576 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008577 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008578 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008579 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008580 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008581 switch (Context.getTargetInfo().getInt64Type()) {
8582 default:
8583 llvm_unreachable("Unexpected integer type");
8584 case TargetInfo::SignedLong:
8585 HowLong = 1;
8586 break;
8587 case TargetInfo::SignedLongLong:
8588 HowLong = 2;
8589 break;
8590 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008591 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008592 }
8593 }
8594
8595 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008596
Chris Lattnerecd79c62009-06-14 00:45:47 +00008597 // Read the base type.
8598 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008599 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008600 case 'v':
8601 assert(HowLong == 0 && !Signed && !Unsigned &&
8602 "Bad modifiers used with 'v'!");
8603 Type = Context.VoidTy;
8604 break;
Jack Carter24bef982013-08-15 15:16:57 +00008605 case 'h':
8606 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008607 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008608 Type = Context.HalfTy;
8609 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008610 case 'f':
8611 assert(HowLong == 0 && !Signed && !Unsigned &&
8612 "Bad modifiers used with 'f'!");
8613 Type = Context.FloatTy;
8614 break;
8615 case 'd':
8616 assert(HowLong < 2 && !Signed && !Unsigned &&
8617 "Bad modifiers used with 'd'!");
8618 if (HowLong)
8619 Type = Context.LongDoubleTy;
8620 else
8621 Type = Context.DoubleTy;
8622 break;
8623 case 's':
8624 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8625 if (Unsigned)
8626 Type = Context.UnsignedShortTy;
8627 else
8628 Type = Context.ShortTy;
8629 break;
8630 case 'i':
8631 if (HowLong == 3)
8632 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8633 else if (HowLong == 2)
8634 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8635 else if (HowLong == 1)
8636 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8637 else
8638 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8639 break;
8640 case 'c':
8641 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8642 if (Signed)
8643 Type = Context.SignedCharTy;
8644 else if (Unsigned)
8645 Type = Context.UnsignedCharTy;
8646 else
8647 Type = Context.CharTy;
8648 break;
8649 case 'b': // boolean
8650 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8651 Type = Context.BoolTy;
8652 break;
8653 case 'z': // size_t.
8654 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8655 Type = Context.getSizeType();
8656 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008657 case 'w': // wchar_t.
8658 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8659 Type = Context.getWideCharType();
8660 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008661 case 'F':
8662 Type = Context.getCFConstantStringType();
8663 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008664 case 'G':
8665 Type = Context.getObjCIdType();
8666 break;
8667 case 'H':
8668 Type = Context.getObjCSelType();
8669 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008670 case 'M':
8671 Type = Context.getObjCSuperType();
8672 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008673 case 'a':
8674 Type = Context.getBuiltinVaListType();
8675 assert(!Type.isNull() && "builtin va list type not initialized!");
8676 break;
8677 case 'A':
8678 // This is a "reference" to a va_list; however, what exactly
8679 // this means depends on how va_list is defined. There are two
8680 // different kinds of va_list: ones passed by value, and ones
8681 // passed by reference. An example of a by-value va_list is
8682 // x86, where va_list is a char*. An example of by-ref va_list
8683 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8684 // we want this argument to be a char*&; for x86-64, we want
8685 // it to be a __va_list_tag*.
8686 Type = Context.getBuiltinVaListType();
8687 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008688 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008689 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008690 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008691 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008692 break;
8693 case 'V': {
8694 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008695 unsigned NumElements = strtoul(Str, &End, 10);
8696 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008697 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008698
Chandler Carruth45bbe012017-03-24 09:11:57 +00008699 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8700 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008701 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008702
8703 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008704 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008705 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008706 break;
8707 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008708 case 'E': {
8709 char *End;
8710
8711 unsigned NumElements = strtoul(Str, &End, 10);
8712 assert(End != Str && "Missing vector size");
8713
8714 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008715
Douglas Gregorfed66992012-06-07 18:08:25 +00008716 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008717 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00008718 Type = Context.getExtVectorType(ElementType, NumElements);
8719 break;
8720 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008721 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008722 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008723 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008724 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008725 Type = Context.getComplexType(ElementType);
8726 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008727 }
8728 case 'Y' : {
8729 Type = Context.getPointerDiffType();
8730 break;
8731 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008732 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008733 Type = Context.getFILEType();
8734 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008735 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008736 return QualType();
8737 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008738 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008739 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008740 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008741 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008742 else
8743 Type = Context.getjmp_bufType();
8744
Mike Stump2adb4da2009-07-28 23:47:15 +00008745 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008746 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008747 return QualType();
8748 }
8749 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008750 case 'K':
8751 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8752 Type = Context.getucontext_tType();
8753
8754 if (Type.isNull()) {
8755 Error = ASTContext::GE_Missing_ucontext;
8756 return QualType();
8757 }
8758 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008759 case 'p':
8760 Type = Context.getProcessIDType();
8761 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008762 }
Mike Stump11289f42009-09-09 15:08:12 +00008763
Chris Lattnerdc226c22010-10-01 22:42:38 +00008764 // If there are modifiers and if we're allowed to parse them, go for it.
8765 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008766 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008767 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008768 default: Done = true; --Str; break;
8769 case '*':
8770 case '&': {
8771 // Both pointers and references can have their pointee types
8772 // qualified with an address space.
8773 char *End;
8774 unsigned AddrSpace = strtoul(Str, &End, 10);
8775 if (End != Str && AddrSpace != 0) {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00008776 Type = Context.getAddrSpaceQualType(
8777 Type, AddrSpace + LangAS::FirstTargetAddressSpace);
Chris Lattnerdc226c22010-10-01 22:42:38 +00008778 Str = End;
8779 }
8780 if (c == '*')
8781 Type = Context.getPointerType(Type);
8782 else
8783 Type = Context.getLValueReferenceType(Type);
8784 break;
8785 }
8786 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8787 case 'C':
8788 Type = Type.withConst();
8789 break;
8790 case 'D':
8791 Type = Context.getVolatileType(Type);
8792 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008793 case 'R':
8794 Type = Type.withRestrict();
8795 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008796 }
8797 }
Chris Lattner84733392010-10-01 07:13:18 +00008798
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008799 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008800 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008801
Chris Lattnerecd79c62009-06-14 00:45:47 +00008802 return Type;
8803}
8804
8805/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00008806QualType ASTContext::GetBuiltinType(unsigned Id,
8807 GetBuiltinTypeError &Error,
8808 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008809 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008810
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008811 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008812
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008813 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008814 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008815 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8816 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008817 if (Error != GE_None)
8818 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00008819
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008820 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00008821
Chris Lattnerecd79c62009-06-14 00:45:47 +00008822 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00008823 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008824 if (Error != GE_None)
8825 return QualType();
8826
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008827 // If this argument is required to be an IntegerConstantExpression and the
8828 // caller cares, fill in the bitmask we return.
8829 if (RequiresICE && IntegerConstantArgs)
8830 *IntegerConstantArgs |= 1 << ArgTypes.size();
8831
Chris Lattnerecd79c62009-06-14 00:45:47 +00008832 // Do array -> pointer decay. The builtin should use the decayed type.
8833 if (Ty->isArrayType())
8834 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008835
Chris Lattnerecd79c62009-06-14 00:45:47 +00008836 ArgTypes.push_back(Ty);
8837 }
8838
David Majnemerba3e5ec2015-03-13 18:26:17 +00008839 if (Id == Builtin::BI__GetExceptionInfo)
8840 return QualType();
8841
Chris Lattnerecd79c62009-06-14 00:45:47 +00008842 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8843 "'.' should only occur at end of builtin type list!");
8844
Reid Kleckner78af0702013-08-27 23:08:25 +00008845 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008846 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8847
8848 bool Variadic = (TypeStr[0] == '.');
8849
Richard Smith836de6b2016-12-19 23:59:34 +00008850 // We really shouldn't be making a no-proto type here.
8851 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008852 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008853
John McCalldb40c7f2010-12-14 08:05:40 +00008854 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008855 EPI.ExtInfo = EI;
8856 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008857 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8858 EPI.ExceptionSpec.Type =
8859 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008860
Jordan Rose5c382722013-03-08 21:51:21 +00008861 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008862}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008863
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008864static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8865 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008866 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008867 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008868
Yaron Keren4cd211b2017-02-22 14:32:39 +00008869 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008870 switch (FD->getTemplateSpecializationKind()) {
8871 case TSK_Undeclared:
8872 case TSK_ExplicitSpecialization:
8873 External = GVA_StrongExternal;
8874 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008875
Rafael Espindola3ae00052013-05-13 00:12:11 +00008876 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008877 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008878
David Majnemerc3d07332014-05-15 06:25:57 +00008879 // C++11 [temp.explicit]p10:
8880 // [ Note: The intent is that an inline function that is the subject of
8881 // an explicit instantiation declaration will still be implicitly
8882 // instantiated when used so that the body can be considered for
8883 // inlining, but that no out-of-line copy of the inline function would be
8884 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008885 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008886 return GVA_AvailableExternally;
8887
Rafael Espindola3ae00052013-05-13 00:12:11 +00008888 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008889 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008890 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008891 }
8892
8893 if (!FD->isInlined())
8894 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008895
David Majnemer3f021502015-10-08 04:53:31 +00008896 if ((!Context.getLangOpts().CPlusPlus &&
8897 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008898 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008899 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008900 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8901
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008902 // GNU or C99 inline semantics. Determine whether this symbol should be
8903 // externally visible.
8904 if (FD->isInlineDefinitionExternallyVisible())
8905 return External;
8906
8907 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008908 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008909 }
8910
David Majnemer54e3ba52014-04-02 23:17:29 +00008911 // Functions specified with extern and inline in -fms-compatibility mode
8912 // forcibly get emitted. While the body of the function cannot be later
8913 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008914 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008915 return GVA_StrongODR;
8916
David Majnemer27d69db2014-04-28 22:17:59 +00008917 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008918}
8919
Artem Belevichca2b9512016-05-02 20:30:03 +00008920static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00008921 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008922 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8923 // dllexport/dllimport on inline functions.
8924 if (D->hasAttr<DLLImportAttr>()) {
8925 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8926 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008927 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008928 if (L == GVA_DiscardableODR)
8929 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008930 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8931 D->hasAttr<CUDAGlobalAttr>()) {
8932 // Device-side functions with __global__ attribute must always be
8933 // visible externally so they can be launched from host.
8934 if (L == GVA_DiscardableODR || L == GVA_Internal)
8935 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008936 }
8937 return L;
8938}
8939
Richard Smitha4653622017-09-06 20:01:14 +00008940/// Adjust the GVALinkage for a declaration based on what an external AST source
8941/// knows about whether there can be other definitions of this declaration.
8942static GVALinkage
8943adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
8944 GVALinkage L) {
8945 ExternalASTSource *Source = Ctx.getExternalSource();
8946 if (!Source)
8947 return L;
8948
8949 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008950 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00008951 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00008952 if (L == GVA_DiscardableODR)
8953 return GVA_StrongODR;
8954 break;
Richard Smitha4653622017-09-06 20:01:14 +00008955
David Blaikie9ffe5a32017-01-30 05:00:26 +00008956 case ExternalASTSource::EK_Always:
8957 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00008958
David Blaikie9ffe5a32017-01-30 05:00:26 +00008959 case ExternalASTSource::EK_ReplyHazy:
8960 break;
8961 }
8962 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008963}
8964
Richard Smitha4653622017-09-06 20:01:14 +00008965GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8966 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
8967 adjustGVALinkageForAttributes(*this, FD,
8968 basicGVALinkageForFunction(*this, FD)));
8969}
8970
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008971static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8972 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008973 if (!VD->isExternallyVisible())
8974 return GVA_Internal;
8975
David Majnemer27d69db2014-04-28 22:17:59 +00008976 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008977 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8978 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8979 LexicalContext = LexicalContext->getLexicalParent();
8980
David Blaikieeb210012017-01-27 23:11:10 +00008981 // ObjC Blocks can create local variables that don't have a FunctionDecl
8982 // LexicalContext.
8983 if (!LexicalContext)
8984 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008985
David Blaikieeb210012017-01-27 23:11:10 +00008986 // Otherwise, let the static local variable inherit its linkage from the
8987 // nearest enclosing function.
8988 auto StaticLocalLinkage =
8989 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8990
8991 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8992 // be emitted in any object with references to the symbol for the object it
8993 // contains, whether inline or out-of-line."
8994 // Similar behavior is observed with MSVC. An alternative ABI could use
8995 // StrongODR/AvailableExternally to match the function, but none are
8996 // known/supported currently.
8997 if (StaticLocalLinkage == GVA_StrongODR ||
8998 StaticLocalLinkage == GVA_AvailableExternally)
8999 return GVA_DiscardableODR;
9000 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009001 }
9002
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009003 // MSVC treats in-class initialized static data members as definitions.
9004 // By giving them non-strong linkage, out-of-line definitions won't
9005 // cause link errors.
9006 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9007 return GVA_DiscardableODR;
9008
Richard Smithd9b90092016-07-02 01:32:16 +00009009 // Most non-template variables have strong linkage; inline variables are
9010 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9011 GVALinkage StrongLinkage;
9012 switch (Context.getInlineVariableDefinitionKind(VD)) {
9013 case ASTContext::InlineVariableDefinitionKind::None:
9014 StrongLinkage = GVA_StrongExternal;
9015 break;
9016 case ASTContext::InlineVariableDefinitionKind::Weak:
9017 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009018 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009019 break;
9020 case ASTContext::InlineVariableDefinitionKind::Strong:
9021 StrongLinkage = GVA_StrongODR;
9022 break;
9023 }
Richard Smith62f19e72016-06-25 00:15:56 +00009024
Richard Smith8809a0c2013-09-27 20:14:12 +00009025 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009026 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009027 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009028
David Majnemer6d1780c2015-07-17 23:36:49 +00009029 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009030 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9031 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009032 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009033 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009034
Rafael Espindola3ae00052013-05-13 00:12:11 +00009035 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009036 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009037
David Majnemer27d69db2014-04-28 22:17:59 +00009038 case TSK_ExplicitInstantiationDeclaration:
9039 return GVA_AvailableExternally;
9040
Rafael Espindola3ae00052013-05-13 00:12:11 +00009041 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009042 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009043 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009044
9045 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009046}
9047
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009048GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009049 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9050 adjustGVALinkageForAttributes(*this, VD,
9051 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009052}
9053
David Blaikiee6b7c282017-04-11 20:46:34 +00009054bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009055 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9056 if (!VD->isFileVarDecl())
9057 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009058 // Global named register variables (GNU extension) are never emitted.
9059 if (VD->getStorageClass() == SC_Register)
9060 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009061 if (VD->getDescribedVarTemplate() ||
9062 isa<VarTemplatePartialSpecializationDecl>(VD))
9063 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009064 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9065 // We never need to emit an uninstantiated function template.
9066 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9067 return false;
Nico Weber66220292016-03-02 17:28:48 +00009068 } else if (isa<PragmaCommentDecl>(D))
9069 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009070 else if (isa<OMPThreadPrivateDecl>(D) ||
9071 D->hasAttr<OMPDeclareTargetDeclAttr>())
9072 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009073 else if (isa<PragmaDetectMismatchDecl>(D))
9074 return true;
Nico Weber66220292016-03-02 17:28:48 +00009075 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009076 return !D->getDeclContext()->isDependentContext();
9077 else if (isa<OMPDeclareReductionDecl>(D))
9078 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009079 else if (isa<ImportDecl>(D))
9080 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009081 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009082 return false;
9083
9084 // If this is a member of a class template, we do not need to emit it.
9085 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009086 return false;
9087
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009088 // Weak references don't produce any output by themselves.
9089 if (D->hasAttr<WeakRefAttr>())
9090 return false;
9091
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009092 // Aliases and used decls are required.
9093 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9094 return true;
9095
9096 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9097 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009098 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009099 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009100
9101 // Constructors and destructors are required.
9102 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9103 return true;
9104
John McCall6bd2a892013-01-25 22:31:03 +00009105 // The key function for a class is required. This rule only comes
9106 // into play when inline functions can be key functions, though.
9107 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9109 const CXXRecordDecl *RD = MD->getParent();
9110 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9111 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9112 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9113 return true;
9114 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009115 }
9116 }
9117
David Blaikie9ffe5a32017-01-30 05:00:26 +00009118 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9119
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009120 // static, static inline, always_inline, and extern inline functions can
9121 // always be deferred. Normal inline functions can be deferred in C99/C++.
9122 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009123 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009124 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009125
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009126 const VarDecl *VD = cast<VarDecl>(D);
9127 assert(VD->isFileVarDecl() && "Expected file scoped var");
9128
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009129 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9130 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009131 return false;
9132
Richard Smitha0e5e542012-11-12 21:38:00 +00009133 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009134 auto Linkage = GetGVALinkageForVariable(VD);
9135 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009136 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009137
Richard Smitha4653622017-09-06 20:01:14 +00009138 // We never need to emit a variable that is available in another TU.
9139 if (Linkage == GVA_AvailableExternally)
9140 return false;
9141
Richard Smitha0e5e542012-11-12 21:38:00 +00009142 // Variables that have destruction with side-effects are required.
9143 if (VD->getType().isDestructedType())
9144 return true;
9145
9146 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009147 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009148 // We can get a value-dependent initializer during error recovery.
9149 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009150 return true;
9151
Richard Smithda383632016-08-15 01:33:41 +00009152 // Likewise, variables with tuple-like bindings are required if their
9153 // bindings have side-effects.
9154 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9155 for (auto *BD : DD->bindings())
9156 if (auto *BindingVD = BD->getHoldingVar())
9157 if (DeclMustBeEmitted(BindingVD))
9158 return true;
9159
Richard Smitha0e5e542012-11-12 21:38:00 +00009160 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009161}
Charles Davis53c59df2010-08-16 03:33:14 +00009162
Reid Kleckner78af0702013-08-27 23:08:25 +00009163CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9164 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009165 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009166 if (IsCXXMethod)
9167 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009168
Alexey Bataeva7547182016-05-18 09:06:38 +00009169 switch (LangOpts.getDefaultCallingConv()) {
9170 case LangOptions::DCC_None:
9171 break;
9172 case LangOptions::DCC_CDecl:
9173 return CC_C;
9174 case LangOptions::DCC_FastCall:
9175 if (getTargetInfo().hasFeature("sse2"))
9176 return CC_X86FastCall;
9177 break;
9178 case LangOptions::DCC_StdCall:
9179 if (!IsVariadic)
9180 return CC_X86StdCall;
9181 break;
9182 case LangOptions::DCC_VectorCall:
9183 // __vectorcall cannot be applied to variadic functions.
9184 if (!IsVariadic)
9185 return CC_X86VectorCall;
9186 break;
9187 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009188 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009189}
9190
Jay Foad39c79802011-01-12 09:06:06 +00009191bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009192 // Pass through to the C++ ABI object
9193 return ABI->isNearlyEmpty(RD);
9194}
9195
Reid Kleckner96f8f932014-02-05 17:27:08 +00009196VTableContextBase *ASTContext::getVTableContext() {
9197 if (!VTContext.get()) {
9198 if (Target->getCXXABI().isMicrosoft())
9199 VTContext.reset(new MicrosoftVTableContext(*this));
9200 else
9201 VTContext.reset(new ItaniumVTableContext(*this));
9202 }
9203 return VTContext.get();
9204}
9205
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009206MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009207 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009208 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009209 case TargetCXXABI::GenericItanium:
9210 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009211 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009212 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009213 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009214 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009215 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009216 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009217 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009218 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009219 }
David Blaikie83d382b2011-09-23 05:06:16 +00009220 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009221}
9222
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009223CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009224
9225size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009226 return ASTRecordLayouts.getMemorySize() +
9227 llvm::capacity_in_bytes(ObjCLayouts) +
9228 llvm::capacity_in_bytes(KeyFunctions) +
9229 llvm::capacity_in_bytes(ObjCImpls) +
9230 llvm::capacity_in_bytes(BlockVarCopyInits) +
9231 llvm::capacity_in_bytes(DeclAttrs) +
9232 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9233 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9234 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9235 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9236 llvm::capacity_in_bytes(OverriddenMethods) +
9237 llvm::capacity_in_bytes(Types) +
9238 llvm::capacity_in_bytes(VariableArrayTypes) +
9239 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009240}
Ted Kremenek540017e2011-10-06 05:00:56 +00009241
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009242/// getIntTypeForBitwidth -
9243/// sets integer QualTy according to specified details:
9244/// bitwidth, signed/unsigned.
9245/// Returns empty type if there is no appropriate target types.
9246QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9247 unsigned Signed) const {
9248 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9249 CanQualType QualTy = getFromTargetType(Ty);
9250 if (!QualTy && DestWidth == 128)
9251 return Signed ? Int128Ty : UnsignedInt128Ty;
9252 return QualTy;
9253}
9254
9255/// getRealTypeForBitwidth -
9256/// sets floating point QualTy according to specified bitwidth.
9257/// Returns empty type if there is no appropriate target types.
9258QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9259 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9260 switch (Ty) {
9261 case TargetInfo::Float:
9262 return FloatTy;
9263 case TargetInfo::Double:
9264 return DoubleTy;
9265 case TargetInfo::LongDouble:
9266 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009267 case TargetInfo::Float128:
9268 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009269 case TargetInfo::NoFloat:
9270 return QualType();
9271 }
9272
9273 llvm_unreachable("Unhandled TargetInfo::RealType value");
9274}
9275
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009276void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9277 if (Number > 1)
9278 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009279}
9280
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009281unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009282 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009283 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009284}
9285
David Majnemer2206bf52014-03-05 08:57:59 +00009286void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9287 if (Number > 1)
9288 StaticLocalNumbers[VD] = Number;
9289}
9290
9291unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009292 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009293 return I != StaticLocalNumbers.end() ? I->second : 1;
9294}
9295
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009296MangleNumberingContext &
9297ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009298 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009299 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009300 if (!MCtx)
9301 MCtx = createMangleNumberingContext();
9302 return *MCtx;
9303}
9304
Justin Lebar20ebffc2016-10-10 16:26:19 +00009305std::unique_ptr<MangleNumberingContext>
9306ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009307 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009308}
9309
David Majnemere7a818f2015-03-06 18:53:55 +00009310const CXXConstructorDecl *
9311ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9312 return ABI->getCopyConstructorForExceptionObject(
9313 cast<CXXRecordDecl>(RD->getFirstDecl()));
9314}
9315
9316void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9317 CXXConstructorDecl *CD) {
9318 return ABI->addCopyConstructorForExceptionObject(
9319 cast<CXXRecordDecl>(RD->getFirstDecl()),
9320 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9321}
9322
David Majnemer00350522015-08-31 18:48:39 +00009323void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9324 TypedefNameDecl *DD) {
9325 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9326}
9327
9328TypedefNameDecl *
9329ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9330 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9331}
9332
9333void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9334 DeclaratorDecl *DD) {
9335 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9336}
9337
9338DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9339 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9340}
9341
Ted Kremenek540017e2011-10-06 05:00:56 +00009342void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9343 ParamIndices[D] = index;
9344}
9345
9346unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9347 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9348 assert(I != ParamIndices.end() &&
9349 "ParmIndices lacks entry set by ParmVarDecl");
9350 return I->second;
9351}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009352
Richard Smithe6c01442013-06-05 00:46:14 +00009353APValue *
9354ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9355 bool MayCreate) {
9356 assert(E && E->getStorageDuration() == SD_Static &&
9357 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009358 if (MayCreate) {
9359 APValue *&MTVI = MaterializedTemporaryValues[E];
9360 if (!MTVI)
9361 MTVI = new (*this) APValue;
9362 return MTVI;
9363 }
Richard Smithe6c01442013-06-05 00:46:14 +00009364
David Majnemer2dcef9e2015-08-13 23:50:15 +00009365 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009366}
9367
Fariborz Jahanian615de762013-05-28 17:37:39 +00009368bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9369 const llvm::Triple &T = getTargetInfo().getTriple();
9370 if (!T.isOSDarwin())
9371 return false;
9372
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009373 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9374 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9375 return false;
9376
Fariborz Jahanian615de762013-05-28 17:37:39 +00009377 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9378 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9379 uint64_t Size = sizeChars.getQuantity();
9380 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9381 unsigned Align = alignChars.getQuantity();
9382 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9383 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9384}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009385
9386namespace {
9387
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009388ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9389 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009390 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009391 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009392 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009393 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009394 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009395}
9396
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009397/// Template specializations to abstract away from pointers and TypeLocs.
9398/// @{
9399template <typename T>
9400ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9401 return ast_type_traits::DynTypedNode::create(*Node);
9402}
9403template <>
9404ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9405 return ast_type_traits::DynTypedNode::create(Node);
9406}
9407template <>
9408ast_type_traits::DynTypedNode
9409createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9410 return ast_type_traits::DynTypedNode::create(Node);
9411}
9412/// @}
9413
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009414 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9415 /// parents as defined by the \c RecursiveASTVisitor.
9416 ///
9417 /// Note that the relationship described here is purely in terms of AST
9418 /// traversal - there are other relationships (for example declaration context)
9419 /// in the AST that are better modeled by special matchers.
9420 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009421 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009422 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009423 public:
9424 /// \brief Builds and returns the translation unit's parent map.
9425 ///
9426 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009427 static std::pair<ASTContext::ParentMapPointers *,
9428 ASTContext::ParentMapOtherNodes *>
9429 buildMap(TranslationUnitDecl &TU) {
9430 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9431 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009432 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009433 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009434 }
9435
9436 private:
9437 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9438
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009439 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9440 ASTContext::ParentMapOtherNodes *OtherParents)
9441 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009442
9443 bool shouldVisitTemplateInstantiations() const {
9444 return true;
9445 }
9446 bool shouldVisitImplicitCode() const {
9447 return true;
9448 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009449
Richard Smith85838722015-11-24 03:09:01 +00009450 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9451 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009452 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009453 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009454 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009455 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009456 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009457 // FIXME: Currently we add the same parent multiple times, but only
9458 // when no memoization data is available for the type.
9459 // For example when we visit all subexpressions of template
9460 // instantiations; this is suboptimal, but benign: the only way to
9461 // visit those is with hasAncestor / hasParent, and those do not create
9462 // new matches.
9463 // The plan is to enable DynTypedNode to be storable in a map or hash
9464 // map. The main problem there is to implement hash functions /
9465 // comparison operators for all types that DynTypedNode supports that
9466 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009467 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009468 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009469 if (const auto *D = ParentStack.back().get<Decl>())
9470 NodeOrVector = D;
9471 else if (const auto *S = ParentStack.back().get<Stmt>())
9472 NodeOrVector = S;
9473 else
9474 NodeOrVector =
9475 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009476 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009477 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9478 auto *Vector = new ASTContext::ParentVector(
9479 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009480 delete NodeOrVector
9481 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009482 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009483 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009484
9485 auto *Vector =
9486 NodeOrVector.template get<ASTContext::ParentVector *>();
9487 // Skip duplicates for types that have memoization data.
9488 // We must check that the type has memoization data before calling
9489 // std::find() because DynTypedNode::operator== can't compare all
9490 // types.
9491 bool Found = ParentStack.back().getMemoizationData() &&
9492 std::find(Vector->begin(), Vector->end(),
9493 ParentStack.back()) != Vector->end();
9494 if (!Found)
9495 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009496 }
9497 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009498 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009499 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009500 ParentStack.pop_back();
9501 return Result;
9502 }
9503
9504 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009505 return TraverseNode(DeclNode, DeclNode,
9506 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009507 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009508 }
9509
9510 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009511 return TraverseNode(StmtNode, StmtNode,
9512 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009513 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009514 }
9515
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009516 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009517 return TraverseNode(
9518 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9519 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9520 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009521 }
9522
9523 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9524 return TraverseNode(
9525 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009526 [&] {
9527 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9528 },
9529 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009530 }
9531
9532 ASTContext::ParentMapPointers *Parents;
9533 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009534 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9535
9536 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9537 };
9538
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009539} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009540
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009541template <typename NodeTy, typename MapTy>
9542static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9543 const MapTy &Map) {
9544 auto I = Map.find(Node);
9545 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009546 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009547 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009548 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009549 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009550 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009551 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009552}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009553
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009554ASTContext::DynTypedNodeList
9555ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9556 if (!PointerParents) {
9557 // We always need to run over the whole translation unit, as
9558 // hasAncestor can escape any subtree.
9559 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9560 PointerParents.reset(Maps.first);
9561 OtherParents.reset(Maps.second);
9562 }
9563 if (Node.getNodeKind().hasPointerIdentity())
9564 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9565 return getDynNodeFromMap(Node, *OtherParents);
9566}
9567
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009568bool
9569ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9570 const ObjCMethodDecl *MethodImpl) {
9571 // No point trying to match an unavailable/deprecated mothod.
9572 if (MethodDecl->hasAttr<UnavailableAttr>()
9573 || MethodDecl->hasAttr<DeprecatedAttr>())
9574 return false;
9575 if (MethodDecl->getObjCDeclQualifier() !=
9576 MethodImpl->getObjCDeclQualifier())
9577 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009578 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009579 return false;
9580
9581 if (MethodDecl->param_size() != MethodImpl->param_size())
9582 return false;
9583
9584 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9585 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9586 EF = MethodDecl->param_end();
9587 IM != EM && IF != EF; ++IM, ++IF) {
9588 const ParmVarDecl *DeclVar = (*IF);
9589 const ParmVarDecl *ImplVar = (*IM);
9590 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9591 return false;
9592 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9593 return false;
9594 }
9595 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9596
9597}
Richard Smith053f6c62014-05-16 23:01:30 +00009598
Yaxun Liu402804b2016-12-15 08:09:08 +00009599uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9600 unsigned AS;
9601 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9602 AS = 0;
9603 else
9604 AS = QT->getPointeeType().getAddressSpace();
9605
9606 return getTargetInfo().getNullPointerValue(AS);
9607}
9608
Yaxun Liub34ec822017-04-11 17:24:23 +00009609unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00009610 if (AS >= LangAS::FirstTargetAddressSpace)
9611 return AS - LangAS::FirstTargetAddressSpace;
Yaxun Liub34ec822017-04-11 17:24:23 +00009612 else
9613 return (*AddrSpaceMap)[AS];
9614}
9615
Richard Smith053f6c62014-05-16 23:01:30 +00009616// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9617// doesn't include ASTContext.h
9618template
9619clang::LazyGenerationalUpdatePtr<
9620 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9621clang::LazyGenerationalUpdatePtr<
9622 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9623 const clang::ASTContext &Ctx, Decl *Value);