blob: 9a25c6d6605829d36a68a123531e193e58872ef6 [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 {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 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[] = {
706 1, // opencl_global
707 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000708 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000709 4, // opencl_generic
710 5, // cuda_device
711 6, // cuda_constant
712 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000717 }
718}
719
David Tweed31d09b02013-09-13 12:04:22 +0000720static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
721 const LangOptions &LangOpts) {
722 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000723 case LangOptions::ASMM_Target:
724 return TI.useAddressSpaceMapMangling();
725 case LangOptions::ASMM_On:
726 return true;
727 case LangOptions::ASMM_Off:
728 return false;
729 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000731}
732
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000734 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000735 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
737 DependentTemplateSpecializationTypes(this_()),
738 SubstTemplateTemplateParmPacks(this_()),
739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
754 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000756 TUDecl = TranslationUnitDecl::Create(*this);
757}
758
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000759ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000760 ReleaseParentMapEntries();
761
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000765
Manuel Klimeka7328992013-06-03 13:51:33 +0000766 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Richard Smith423f46f2016-07-20 21:38:26 +0000795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000797}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000798
Manuel Klimek95403e62014-05-21 13:28:59 +0000799void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000800 if (!PointerParents) return;
801 for (const auto &Entry : *PointerParents) {
802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
803 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
804 } else if (Entry.second.is<ParentVector *>()) {
805 delete Entry.second.get<ParentVector *>();
806 }
807 }
808 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
810 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000811 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 delete Entry.second.get<ParentVector *>();
813 }
814 }
815}
816
Douglas Gregor1a809332010-05-23 18:26:36 +0000817void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000818 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000819}
820
Mike Stump11289f42009-09-09 15:08:12 +0000821void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000822ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000823 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000824}
825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000829
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000831#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000832#define ABSTRACT_TYPE(Name, Parent)
833#include "clang/AST/TypeNodes.def"
834 0 // Extra
835 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000836
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
838 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 }
841
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 unsigned Idx = 0;
843 unsigned TotalBytes = 0;
844#define TYPE(Name, Parent) \
845 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << " " << counts[Idx] << " " << #Name \
847 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
849 ++Idx;
850#define ABSTRACT_TYPE(Name, Parent)
851#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
854
Douglas Gregor7454c562010-07-02 20:37:36 +0000855 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
857 << NumImplicitDefaultConstructors
858 << " implicit default constructors created\n";
859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
860 << NumImplicitCopyConstructors
861 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
864 << NumImplicitMoveConstructors
865 << " implicit move constructors created\n";
866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
867 << NumImplicitCopyAssignmentOperators
868 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
871 << NumImplicitMoveAssignmentOperators
872 << " implicit move assignment operators created\n";
873 llvm::errs() << NumImplicitDestructorsDeclared << "/"
874 << NumImplicitDestructors
875 << " implicit destructors created\n";
876
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000877 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000879 ExternalSource->PrintStats();
880 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881
Douglas Gregor5b11d492010-07-25 17:53:33 +0000882 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883}
884
Richard Smith42413142015-05-15 20:05:43 +0000885void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
887 if (NotifyListeners)
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
890
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
893 else
Richard Smith42413142015-05-15 20:05:43 +0000894 ND->setHidden(false);
895}
896
897void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
900 return;
901
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000902 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
906 M = nullptr;
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
908}
909
Richard Smithdc1f0422016-07-20 19:10:16 +0000910void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
912 return;
913
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
916
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
919
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
922
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
925}
926
927void ASTContext::addModuleInitializer(Module *M, Decl *D) {
928 // One special case: if we add a module initializer that imports another
929 // module, and that module's only initializer is an ImportDecl, simplify.
930 if (auto *ID = dyn_cast<ImportDecl>(D)) {
931 auto It = ModuleInitializers.find(ID->getImportedModule());
932
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
935 return;
936
937 // Maybe the ImportDecl only imports another ImportDecl.
938 auto &Imported = *It->second;
939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
940 Imported.resolve(*this);
941 auto *OnlyDecl = Imported.Initializers.front();
942 if (isa<ImportDecl>(OnlyDecl))
943 D = OnlyDecl;
944 }
945 }
946
947 auto *&Inits = ModuleInitializers[M];
948 if (!Inits)
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
951}
952
953void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
955 if (!Inits)
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
959}
960
961ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
964 return None;
965
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
969}
970
Richard Smithf19e1272015-03-07 00:04:49 +0000971ExternCContextDecl *ASTContext::getExternCContextDecl() const {
972 if (!ExternCContext)
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
974
975 return ExternCContext;
976}
977
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000978BuiltinTemplateDecl *
979ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
980 const IdentifierInfo *II) const {
981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
982 BuiltinTemplate->setImplicit();
983 TUDecl->addDecl(BuiltinTemplate);
984
985 return BuiltinTemplate;
986}
987
988BuiltinTemplateDecl *
989ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
994}
995
Eric Fiselier6ad68552016-07-01 01:24:09 +0000996BuiltinTemplateDecl *
997ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1002}
1003
Alp Toker2dea15b2013-12-17 01:22:38 +00001004RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001006 SourceLocation Loc;
1007 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1013 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 return NewDecl;
1018}
1019
1020TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1021 StringRef Name) const {
1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1023 TypedefDecl *NewDecl = TypedefDecl::Create(
1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1026 NewDecl->setImplicit();
1027 return NewDecl;
1028}
1029
Douglas Gregor801c99d2011-08-12 06:49:56 +00001030TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001031 if (!Int128Decl)
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033 return Int128Decl;
1034}
1035
1036TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001037 if (!UInt128Decl)
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001039 return UInt128Decl;
1040}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001041
John McCall48f2d582009-10-23 23:03:21 +00001042void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001044 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001045 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001046}
1047
Artem Belevichb5bc9232015-09-22 17:23:22 +00001048void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1049 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001050 assert((!this->Target || this->Target == &Target) &&
1051 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001052 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001055 this->AuxTarget = AuxTarget;
1056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060
Chris Lattner970e54e2006-11-12 00:37:36 +00001061 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001062 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001066 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001067 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1069 else
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001071 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001072 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1073 InitBuiltinType(ShortTy, BuiltinType::Short);
1074 InitBuiltinType(IntTy, BuiltinType::Int);
1075 InitBuiltinType(LongTy, BuiltinType::Long);
1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattner970e54e2006-11-12 00:37:36 +00001078 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001089
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1092
Chris Lattnerf122cef2009-04-30 02:43:43 +00001093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1096
Hans Wennborg0d81e012013-05-10 10:08:40 +00001097 // C++ 3.9.1p5
1098 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1100 else // -fshort-wchar makes wchar_t be unsigned.
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1102 if (LangOpts.CPlusPlus && LangOpts.WChar)
1103 WideCharTy = WCharTy;
1104 else {
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1107 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001108
James Molloy36365542012-05-04 10:55:22 +00001109 WIntTy = getFromTargetType(Target.getWIntType());
1110
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1113 else // C99
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1115
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1118 else // C99
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
1120
Douglas Gregor4619e432008-12-05 23:32:09 +00001121 // Placeholder type for type-dependent expressions whose type is
1122 // completely unknown. No code should ever check a type against
1123 // DependentTy and users should never see it; however, it is here to
1124 // help diagnose failures to properly check for type-dependent
1125 // expressions.
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127
John McCall36e7fe32010-10-12 00:20:44 +00001128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1130
John McCall0009fcc2011-04-26 20:42:42 +00001131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1133
John McCall526ab472011-10-25 17:37:35 +00001134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1136
John McCall31996342011-04-07 08:22:57 +00001137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1139
John McCall8a6b59a2011-10-17 18:09:15 +00001140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1142
Eli Friedman34866c72012-08-31 00:14:07 +00001143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1145
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1149
Chris Lattner970e54e2006-11-12 00:37:36 +00001150 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001154 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001156 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001160
Alexey Bader954ba212016-04-08 13:40:33 +00001161 if (LangOpts.OpenCL) {
1162#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001164#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001165
Guy Benyei61054192013-02-07 10:55:47 +00001166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001172 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001173
1174 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001177
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001178 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001179
1180 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001182 // void * type
1183 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001184
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001187
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001190
1191 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001192 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001193}
1194
David Blaikie9c902b52011-09-25 23:23:43 +00001195DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001196 return SourceMgr.getDiagnostics();
1197}
1198
Douglas Gregor561eceb2010-08-30 16:49:28 +00001199AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1201 if (!Result) {
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
1204 }
1205
1206 return *Result;
1207}
1208
1209/// \brief Erase the attributes corresponding to the given declaration.
1210void ASTContext::eraseDeclAttrs(const Decl *D) {
1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1212 if (Pos != DeclAttrs.end()) {
1213 Pos->second->~AttrVec();
1214 DeclAttrs.erase(Pos);
1215 }
1216}
1217
Larisse Voufo39a1e502013-08-06 01:03:05 +00001218// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001219MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001220ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001221 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001222 return getTemplateOrSpecializationInfo(Var)
1223 .dyn_cast<MemberSpecializationInfo *>();
1224}
1225
1226ASTContext::TemplateOrSpecializationInfo
1227ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1229 TemplateOrInstantiation.find(Var);
1230 if (Pos == TemplateOrInstantiation.end())
1231 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001233 return Pos->second;
1234}
1235
Mike Stump11289f42009-09-09 15:08:12 +00001236void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001238 TemplateSpecializationKind TSK,
1239 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001240 assert(Inst->isStaticDataMember() && "Not a static data member");
1241 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1243 Tmpl, TSK, PointOfInstantiation));
1244}
1245
1246void
1247ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1248 TemplateOrSpecializationInfo TSI) {
1249 assert(!TemplateOrInstantiation[Inst] &&
1250 "Already noted what the variable was instantiated from");
1251 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001252}
1253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001254FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1255 const FunctionDecl *FD){
1256 assert(FD && "Specialization is 0");
1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001258 = ClassScopeSpecializationPattern.find(FD);
1259 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001261
1262 return Pos->second;
1263}
1264
1265void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1266 FunctionDecl *Pattern) {
1267 assert(FD && "Specialization is 0");
1268 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001269 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270}
1271
John McCalle61f2ba2009-11-18 02:36:19 +00001272NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001273ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1274 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001275 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001276 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001278 return Pos->second;
1279}
1280
1281void
Richard Smithd8a9e372016-12-18 21:39:37 +00001282ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001283 assert((isa<UsingDecl>(Pattern) ||
1284 isa<UnresolvedUsingValueDecl>(Pattern) ||
1285 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1286 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001287 assert((isa<UsingDecl>(Inst) ||
1288 isa<UnresolvedUsingValueDecl>(Inst) ||
1289 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1290 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1292 InstantiatedFromUsingDecl[Inst] = Pattern;
1293}
1294
1295UsingShadowDecl *
1296ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1298 = InstantiatedFromUsingShadowDecl.find(Inst);
1299 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001300 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001301
1302 return Pos->second;
1303}
1304
1305void
1306ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1307 UsingShadowDecl *Pattern) {
1308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001310}
1311
Anders Carlsson5da84842009-09-01 04:26:58 +00001312FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1314 = InstantiatedFromUnnamedFieldDecl.find(Field);
1315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001316 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Anders Carlsson5da84842009-09-01 04:26:58 +00001318 return Pos->second;
1319}
1320
1321void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1322 FieldDecl *Tmpl) {
1323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1326 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001327
Anders Carlsson5da84842009-09-01 04:26:58 +00001328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1329}
1330
Douglas Gregor832940b2010-03-02 23:58:15 +00001331ASTContext::overridden_cxx_method_iterator
1332ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001335 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001336 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001337 return Pos->second.begin();
1338}
1339
1340ASTContext::overridden_cxx_method_iterator
1341ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001344 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001345 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 return Pos->second.end();
1347}
1348
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001349unsigned
1350ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001353 if (Pos == OverriddenMethods.end())
1354 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001355 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001356}
1357
Clement Courbet6ecaec82016-07-05 07:49:31 +00001358ASTContext::overridden_method_range
1359ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1360 return overridden_method_range(overridden_methods_begin(Method),
1361 overridden_methods_end(Method));
1362}
1363
Douglas Gregor832940b2010-03-02 23:58:15 +00001364void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1365 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001366 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001367 OverriddenMethods[Method].push_back(Overridden);
1368}
1369
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001370void ASTContext::getOverriddenMethods(
1371 const NamedDecl *D,
1372 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001373 assert(D);
1374
1375 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001376 Overridden.append(overridden_methods_begin(CXXMethod),
1377 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001378 return;
1379 }
1380
1381 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1382 if (!Method)
1383 return;
1384
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001385 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1386 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001387 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001388}
1389
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001390void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1391 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1392 assert(!Import->isFromASTFile() && "Non-local import declaration");
1393 if (!FirstLocalImport) {
1394 FirstLocalImport = Import;
1395 LastLocalImport = Import;
1396 return;
1397 }
1398
1399 LastLocalImport->NextLocalImport = Import;
1400 LastLocalImport = Import;
1401}
1402
Chris Lattner53cfe802007-07-18 17:52:12 +00001403//===----------------------------------------------------------------------===//
1404// Type Sizing and Analysis
1405//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001406
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001407/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1408/// scalar floating point type.
1409const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001410 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001411 assert(BT && "Not a floating point type!");
1412 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001413 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001414 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001415 case BuiltinType::Float: return Target->getFloatFormat();
1416 case BuiltinType::Double: return Target->getDoubleFormat();
1417 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001418 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001419 }
1420}
1421
Rafael Espindola71eccb32013-08-08 19:53:46 +00001422CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001423 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001424
John McCall94268702010-10-08 18:24:19 +00001425 bool UseAlignAttrOnly = false;
1426 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1427 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001428
John McCall94268702010-10-08 18:24:19 +00001429 // __attribute__((aligned)) can increase or decrease alignment
1430 // *except* on a struct or struct member, where it only increases
1431 // alignment unless 'packed' is also specified.
1432 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001433 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001434 // ignore that possibility; Sema should diagnose it.
1435 if (isa<FieldDecl>(D)) {
1436 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1437 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1438 } else {
1439 UseAlignAttrOnly = true;
1440 }
1441 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001442 else if (isa<FieldDecl>(D))
1443 UseAlignAttrOnly =
1444 D->hasAttr<PackedAttr>() ||
1445 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001446
John McCall4e819612011-01-20 07:57:12 +00001447 // If we're using the align attribute only, just ignore everything
1448 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001449 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001450 // do nothing
1451
John McCall94268702010-10-08 18:24:19 +00001452 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001453 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001454 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001455 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001456 T = RT->getPointeeType();
1457 else
1458 T = getPointerType(RT->getPointeeType());
1459 }
Richard Smithf6d70302014-06-10 23:34:28 +00001460 QualType BaseT = getBaseElementType(T);
1461 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001462 // Adjust alignments of declarations with array type by the
1463 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001464 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001465 unsigned MinWidth = Target->getLargeArrayMinWidth();
1466 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001467 if (isa<VariableArrayType>(arrayType))
1468 Align = std::max(Align, Target->getLargeArrayAlign());
1469 else if (isa<ConstantArrayType>(arrayType) &&
1470 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1471 Align = std::max(Align, Target->getLargeArrayAlign());
1472 }
John McCall33ddac02011-01-19 10:06:00 +00001473 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001474 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001475 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001476 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001477 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1478 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001479 }
John McCall4e819612011-01-20 07:57:12 +00001480
1481 // Fields can be subject to extra alignment constraints, like if
1482 // the field is packed, the struct is packed, or the struct has a
1483 // a max-field-alignment constraint (#pragma pack). So calculate
1484 // the actual alignment of the field within the struct, and then
1485 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001486 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1487 const RecordDecl *Parent = Field->getParent();
1488 // We can only produce a sensible answer if the record is valid.
1489 if (!Parent->isInvalidDecl()) {
1490 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001491
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001492 // Start with the record's overall alignment.
1493 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001494
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001495 // Use the GCD of that and the offset within the record.
1496 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1497 if (Offset > 0) {
1498 // Alignment is always a power of 2, so the GCD will be a power of 2,
1499 // which means we get to do this crazy thing instead of Euclid's.
1500 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1501 if (LowBitOfOffset < FieldAlign)
1502 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1503 }
1504
1505 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001506 }
Charles Davis3fc51072010-02-23 04:52:00 +00001507 }
Chris Lattner68061312009-01-24 21:53:27 +00001508 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001509
Ken Dyckcc56c542011-01-15 18:38:59 +00001510 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001511}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001512
John McCallf1249922012-08-21 04:10:00 +00001513// getTypeInfoDataSizeInChars - Return the size of a type, in
1514// chars. If the type is a record, its data size is returned. This is
1515// the size of the memcpy that's performed when assigning this type
1516// using a trivial copy/move assignment operator.
1517std::pair<CharUnits, CharUnits>
1518ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1519 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1520
1521 // In C++, objects can sometimes be allocated into the tail padding
1522 // of a base-class subobject. We decide whether that's possible
1523 // during class layout, so here we can just trust the layout results.
1524 if (getLangOpts().CPlusPlus) {
1525 if (const RecordType *RT = T->getAs<RecordType>()) {
1526 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1527 sizeAndAlign.first = layout.getDataSize();
1528 }
1529 }
1530
1531 return sizeAndAlign;
1532}
1533
Richard Trieu04d2d942013-05-14 21:59:17 +00001534/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1535/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1536std::pair<CharUnits, CharUnits>
1537static getConstantArrayInfoInChars(const ASTContext &Context,
1538 const ConstantArrayType *CAT) {
1539 std::pair<CharUnits, CharUnits> EltInfo =
1540 Context.getTypeInfoInChars(CAT->getElementType());
1541 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001542 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1543 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001544 "Overflow in array type char size evaluation");
1545 uint64_t Width = EltInfo.first.getQuantity() * Size;
1546 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001547 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1548 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001549 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001550 return std::make_pair(CharUnits::fromQuantity(Width),
1551 CharUnits::fromQuantity(Align));
1552}
1553
John McCall87fe5d52010-05-20 01:18:31 +00001554std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001555ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001556 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1557 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001558 TypeInfo Info = getTypeInfo(T);
1559 return std::make_pair(toCharUnitsFromBits(Info.Width),
1560 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001561}
1562
1563std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001564ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001565 return getTypeInfoInChars(T.getTypePtr());
1566}
1567
David Majnemer34b57492014-07-30 01:30:47 +00001568bool ASTContext::isAlignmentRequired(const Type *T) const {
1569 return getTypeInfo(T).AlignIsRequired;
1570}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001571
David Majnemer34b57492014-07-30 01:30:47 +00001572bool ASTContext::isAlignmentRequired(QualType T) const {
1573 return isAlignmentRequired(T.getTypePtr());
1574}
1575
Richard Smithb2f0f052016-10-10 18:54:32 +00001576unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1577 // An alignment on a typedef overrides anything else.
1578 if (auto *TT = T->getAs<TypedefType>())
1579 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1580 return Align;
1581
1582 // If we have an (array of) complete type, we're done.
1583 T = getBaseElementType(T);
1584 if (!T->isIncompleteType())
1585 return getTypeAlign(T);
1586
1587 // If we had an array type, its element type might be a typedef
1588 // type with an alignment attribute.
1589 if (auto *TT = T->getAs<TypedefType>())
1590 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1591 return Align;
1592
1593 // Otherwise, see if the declaration of the type had an attribute.
1594 if (auto *TT = T->getAs<TagType>())
1595 return TT->getDecl()->getMaxAlignment();
1596
1597 return 0;
1598}
1599
David Majnemer34b57492014-07-30 01:30:47 +00001600TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001601 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1602 if (I != MemoizedTypeInfo.end())
1603 return I->second;
1604
1605 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1606 TypeInfo TI = getTypeInfoImpl(T);
1607 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001608 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001609}
1610
1611/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1612/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001613///
1614/// FIXME: Pointers into different addr spaces could have different sizes and
1615/// alignment requirements: getPointerInfo should take an AddrSpace, this
1616/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001617TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1618 uint64_t Width = 0;
1619 unsigned Align = 8;
1620 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001621 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001622#define TYPE(Class, Base)
1623#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001624#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001625#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001626#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1627 case Type::Class: \
1628 assert(!T->isDependentType() && "should not see dependent types here"); \
1629 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001630#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001631 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001632
Chris Lattner355332d2007-07-13 22:27:08 +00001633 case Type::FunctionNoProto:
1634 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001635 // GCC extension: alignof(function) = 32 bits
1636 Width = 0;
1637 Align = 32;
1638 break;
1639
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001640 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001641 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001642 Width = 0;
1643 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1644 break;
1645
Steve Naroff5c131802007-08-30 01:06:46 +00001646 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001647 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001648
David Majnemer34b57492014-07-30 01:30:47 +00001649 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001650 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001651 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001652 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001653 Width = EltInfo.Width * Size;
1654 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001655 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1656 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001657 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001658 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001659 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001660 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001661 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001662 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001663 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1664 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001665 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001666 // If the alignment is not a power of 2, round up to the next power of 2.
1667 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001668 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001669 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001670 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001671 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001672 // Adjust the alignment based on the target max.
1673 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1674 if (TargetVectorAlign && TargetVectorAlign < Align)
1675 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001676 break;
1677 }
Chris Lattner647fb222007-07-18 18:26:58 +00001678
Chris Lattner7570e9c2008-03-08 08:52:55 +00001679 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001680 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001681 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001682 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001683 // GCC extension: alignof(void) = 8 bits.
1684 Width = 0;
1685 Align = 8;
1686 break;
1687
Chris Lattner6a4f7452007-12-19 19:23:28 +00001688 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001689 Width = Target->getBoolWidth();
1690 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001691 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001692 case BuiltinType::Char_S:
1693 case BuiltinType::Char_U:
1694 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001695 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001696 Width = Target->getCharWidth();
1697 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001698 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001699 case BuiltinType::WChar_S:
1700 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001701 Width = Target->getWCharWidth();
1702 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001703 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001704 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001705 Width = Target->getChar16Width();
1706 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001707 break;
1708 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getChar32Width();
1710 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001711 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001712 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001713 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001714 Width = Target->getShortWidth();
1715 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001716 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001717 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001719 Width = Target->getIntWidth();
1720 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001721 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001722 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001723 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001724 Width = Target->getLongWidth();
1725 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001726 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001727 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001728 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001729 Width = Target->getLongLongWidth();
1730 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001731 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001732 case BuiltinType::Int128:
1733 case BuiltinType::UInt128:
1734 Width = 128;
1735 Align = 128; // int128_t is 128-bit aligned on all targets.
1736 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001737 case BuiltinType::Half:
1738 Width = Target->getHalfWidth();
1739 Align = Target->getHalfAlign();
1740 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001742 Width = Target->getFloatWidth();
1743 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001744 break;
1745 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001746 Width = Target->getDoubleWidth();
1747 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001748 break;
1749 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001750 Width = Target->getLongDoubleWidth();
1751 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001752 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001753 case BuiltinType::Float128:
1754 Width = Target->getFloat128Width();
1755 Align = Target->getFloat128Align();
1756 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001757 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001758 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1759 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001760 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001761 case BuiltinType::ObjCId:
1762 case BuiltinType::ObjCClass:
1763 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getPointerWidth(0);
1765 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001766 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001767 case BuiltinType::OCLSampler: {
1768 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1769 Width = Target->getPointerWidth(AS);
1770 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001771 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001772 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001773 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001774 case BuiltinType::OCLClkEvent:
1775 case BuiltinType::OCLQueue:
1776 case BuiltinType::OCLNDRange:
1777 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001778 // Currently these types are pointers to opaque types.
1779 Width = Target->getPointerWidth(0);
1780 Align = Target->getPointerAlign(0);
1781 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001782#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1783 case BuiltinType::Id:
1784#include "clang/Basic/OpenCLImageTypes.def"
1785 {
1786 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1787 Width = Target->getPointerWidth(AS);
1788 Align = Target->getPointerAlign(AS);
1789 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001790 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001791 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001792 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001793 Width = Target->getPointerWidth(0);
1794 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001795 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001796 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001797 unsigned AS = getTargetAddressSpace(
1798 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001799 Width = Target->getPointerWidth(AS);
1800 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001801 break;
1802 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001803 case Type::LValueReference:
1804 case Type::RValueReference: {
1805 // alignof and sizeof should never enter this code path here, so we go
1806 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001807 unsigned AS = getTargetAddressSpace(
1808 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001809 Width = Target->getPointerWidth(AS);
1810 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001811 break;
1812 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001813 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001814 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001815 Width = Target->getPointerWidth(AS);
1816 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001817 break;
1818 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001819 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001820 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001821 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001822 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001823 }
Chris Lattner647fb222007-07-18 18:26:58 +00001824 case Type::Complex: {
1825 // Complex types have the same alignment as their elements, but twice the
1826 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001827 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1828 Width = EltInfo.Width * 2;
1829 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001830 break;
1831 }
John McCall8b07ec22010-05-15 11:32:37 +00001832 case Type::ObjCObject:
1833 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001834 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001835 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001836 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001837 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001838 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001839 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001840 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001841 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001842 break;
1843 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001844 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001845 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001846 const TagType *TT = cast<TagType>(T);
1847
1848 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001849 Width = 8;
1850 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001851 break;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
David Majnemer475b25e2015-01-21 10:54:38 +00001854 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1855 const EnumDecl *ED = ET->getDecl();
1856 TypeInfo Info =
1857 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1858 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1859 Info.Align = AttrAlign;
1860 Info.AlignIsRequired = true;
1861 }
1862 return Info;
1863 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001864
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001865 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001866 const RecordDecl *RD = RT->getDecl();
1867 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001868 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001869 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001870 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001871 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001872 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001873
Chris Lattner63d2b362009-10-22 05:17:15 +00001874 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001875 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1876 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001877
Richard Smith30482bc2011-02-20 03:19:35 +00001878 case Type::Auto: {
1879 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001880 assert(!A->getDeducedType().isNull() &&
1881 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001882 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001883 }
1884
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001885 case Type::Paren:
1886 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1887
Manman Rene6be26c2016-09-13 17:25:08 +00001888 case Type::ObjCTypeParam:
1889 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1890
Douglas Gregoref462e62009-04-30 17:32:17 +00001891 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001892 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001893 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001894 // If the typedef has an aligned attribute on it, it overrides any computed
1895 // alignment we have. This violates the GCC documentation (which says that
1896 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001897 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001898 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001899 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001900 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001901 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001902 AlignIsRequired = Info.AlignIsRequired;
1903 }
David Majnemer34b57492014-07-30 01:30:47 +00001904 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001905 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001906 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001907
Abramo Bagnara6150c882010-05-11 21:36:43 +00001908 case Type::Elaborated:
1909 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001910
John McCall81904512011-01-06 01:58:22 +00001911 case Type::Attributed:
1912 return getTypeInfo(
1913 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1914
Eli Friedman0dfb8892011-10-06 23:00:33 +00001915 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001916 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001917 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1918 Width = Info.Width;
1919 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001920
1921 // If the size of the type doesn't exceed the platform's max
1922 // atomic promotion width, make the size and alignment more
1923 // favorable to atomic operations:
1924 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1925 // Round the size up to a power of 2.
1926 if (!llvm::isPowerOf2_64(Width))
1927 Width = llvm::NextPowerOf2(Width);
1928
1929 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001930 Align = static_cast<unsigned>(Width);
1931 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001932 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001933 break;
1934
1935 case Type::Pipe: {
1936 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1937 Width = Info.Width;
1938 Align = Info.Align;
1939 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001940
Douglas Gregoref462e62009-04-30 17:32:17 +00001941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001943 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001944 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001945}
1946
Alexey Bataev00396512015-07-02 03:40:19 +00001947unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1948 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1949 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1950 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1951 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1952 getTargetInfo().getABI() == "elfv1-qpx" &&
1953 T->isSpecificBuiltinType(BuiltinType::Double))
1954 SimdAlign = 256;
1955 return SimdAlign;
1956}
1957
Ken Dyckcc56c542011-01-15 18:38:59 +00001958/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1959CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1960 return CharUnits::fromQuantity(BitSize / getCharWidth());
1961}
1962
Ken Dyckb0fcc592011-02-11 01:54:29 +00001963/// toBits - Convert a size in characters to a size in characters.
1964int64_t ASTContext::toBits(CharUnits CharSize) const {
1965 return CharSize.getQuantity() * getCharWidth();
1966}
1967
Ken Dyck8c89d592009-12-22 14:23:30 +00001968/// getTypeSizeInChars - Return the size of the specified type, in characters.
1969/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001970CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001971 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001972}
Jay Foad39c79802011-01-12 09:06:06 +00001973CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001974 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001975}
1976
Ken Dycka6046ab2010-01-26 17:25:18 +00001977/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001978/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001979CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001980 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001981}
Jay Foad39c79802011-01-12 09:06:06 +00001982CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001983 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001984}
1985
Chris Lattnera3402cd2009-01-27 18:08:34 +00001986/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1987/// type for the current target in bits. This can be different than the ABI
1988/// alignment in cases where it is beneficial for performance to overalign
1989/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001990unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001991 TypeInfo TI = getTypeInfo(T);
1992 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001993
David Majnemere1544562015-04-24 01:25:05 +00001994 T = T->getBaseElementTypeUnsafe();
1995
1996 // The preferred alignment of member pointers is that of a pointer.
1997 if (T->isMemberPointerType())
1998 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1999
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002000 if (!Target->allowsLargerPreferedTypeAlignment())
2001 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002002
Eli Friedman7ab09572009-05-25 21:27:19 +00002003 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002004 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002005 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002006 if (const EnumType *ET = T->getAs<EnumType>())
2007 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002008 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002009 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2010 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002011 // Don't increase the alignment if an alignment attribute was specified on a
2012 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002013 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002014 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002015
Chris Lattnera3402cd2009-01-27 18:08:34 +00002016 return ABIAlign;
2017}
2018
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002019/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2020/// for __attribute__((aligned)) on this target, to be used if no alignment
2021/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002022unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002023 return getTargetInfo().getDefaultAlignForAttributeAligned();
2024}
2025
Ulrich Weigandfa806422013-05-06 16:23:57 +00002026/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2027/// to a global variable of the specified type.
2028unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2029 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2030}
2031
2032/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2033/// should be given to a global variable of the specified type.
2034CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2035 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2036}
2037
David Majnemer08ef2ba2015-06-23 20:34:18 +00002038CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2039 CharUnits Offset = CharUnits::Zero();
2040 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2041 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2042 Offset += Layout->getBaseClassOffset(Base);
2043 Layout = &getASTRecordLayout(Base);
2044 }
2045 return Offset;
2046}
2047
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002048/// DeepCollectObjCIvars -
2049/// This routine first collects all declared, but not synthesized, ivars in
2050/// super class and then collects all ivars, including those synthesized for
2051/// current class. This routine is used for implementation of current class
2052/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002053///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002054void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2055 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002056 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002057 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2058 DeepCollectObjCIvars(SuperClass, false, Ivars);
2059 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002060 for (const auto *I : OI->ivars())
2061 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002062 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002063 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002064 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002065 Iv= Iv->getNextIvar())
2066 Ivars.push_back(Iv);
2067 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002068}
2069
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002070/// CollectInheritedProtocols - Collect all protocols in current class and
2071/// those inherited by it.
2072void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002074 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002075 // We can use protocol_iterator here instead of
2076 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002077 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002078 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002079 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002080
2081 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002082 for (const auto *Cat : OI->visible_categories())
2083 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002084
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002085 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2086 while (SD) {
2087 CollectInheritedProtocols(SD, Protocols);
2088 SD = SD->getSuperClass();
2089 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002090 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002091 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002092 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002093 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002094 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002095 // Insert the protocol.
2096 if (!Protocols.insert(
2097 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2098 return;
2099
2100 for (auto *Proto : OP->protocols())
2101 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002102 }
2103}
2104
Jay Foad39c79802011-01-12 09:06:06 +00002105unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002106 unsigned count = 0;
2107 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002108 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002109 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002110
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002111 // Count ivar defined in this class's implementation. This
2112 // includes synthesized ivars.
2113 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002114 count += ImplDecl->ivar_size();
2115
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002116 return count;
2117}
2118
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002119bool ASTContext::isSentinelNullExpr(const Expr *E) {
2120 if (!E)
2121 return false;
2122
2123 // nullptr_t is always treated as null.
2124 if (E->getType()->isNullPtrType()) return true;
2125
2126 if (E->getType()->isAnyPointerType() &&
2127 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2128 Expr::NPC_ValueDependentIsNull))
2129 return true;
2130
2131 // Unfortunately, __null has type 'int'.
2132 if (isa<GNUNullExpr>(E)) return true;
2133
2134 return false;
2135}
2136
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002137/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2138ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2139 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2140 I = ObjCImpls.find(D);
2141 if (I != ObjCImpls.end())
2142 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002143 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002144}
2145/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2146ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2147 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2148 I = ObjCImpls.find(D);
2149 if (I != ObjCImpls.end())
2150 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002151 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002152}
2153
2154/// \brief Set the implementation of ObjCInterfaceDecl.
2155void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2156 ObjCImplementationDecl *ImplD) {
2157 assert(IFaceD && ImplD && "Passed null params");
2158 ObjCImpls[IFaceD] = ImplD;
2159}
2160/// \brief Set the implementation of ObjCCategoryDecl.
2161void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2162 ObjCCategoryImplDecl *ImplD) {
2163 assert(CatD && ImplD && "Passed null params");
2164 ObjCImpls[CatD] = ImplD;
2165}
2166
Chandler Carruth21c90602015-12-30 03:24:14 +00002167const ObjCMethodDecl *
2168ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2169 return ObjCMethodRedecls.lookup(MD);
2170}
2171
2172void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2173 const ObjCMethodDecl *Redecl) {
2174 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2175 ObjCMethodRedecls[MD] = Redecl;
2176}
2177
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002178const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2179 const NamedDecl *ND) const {
2180 if (const ObjCInterfaceDecl *ID =
2181 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002182 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002183 if (const ObjCCategoryDecl *CD =
2184 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002185 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002186 if (const ObjCImplDecl *IMD =
2187 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002188 return IMD->getClassInterface();
2189
Craig Topper36250ad2014-05-12 05:36:57 +00002190 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002191}
2192
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002193/// \brief Get the copy initialization expression of VarDecl,or NULL if
2194/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002195Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002196 assert(VD && "Passed null params");
2197 assert(VD->hasAttr<BlocksAttr>() &&
2198 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002199 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002200 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002201 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002202}
2203
2204/// \brief Set the copy inialization expression of a block var decl.
2205void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2206 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002207 assert(VD->hasAttr<BlocksAttr>() &&
2208 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002209 BlockVarCopyInits[VD] = Init;
2210}
2211
John McCallbcd03502009-12-07 02:54:59 +00002212TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002213 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002214 if (!DataSize)
2215 DataSize = TypeLoc::getFullDataSizeForType(T);
2216 else
2217 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002218 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002219
John McCallbcd03502009-12-07 02:54:59 +00002220 TypeSourceInfo *TInfo =
2221 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2222 new (TInfo) TypeSourceInfo(T);
2223 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002224}
2225
John McCallbcd03502009-12-07 02:54:59 +00002226TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002227 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002228 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002229 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002230 return DI;
2231}
2232
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002233const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002234ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002235 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002236}
2237
2238const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002239ASTContext::getASTObjCImplementationLayout(
2240 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002241 return getObjCLayout(D->getClassInterface(), D);
2242}
2243
Chris Lattner983a8bb2007-07-13 22:13:22 +00002244//===----------------------------------------------------------------------===//
2245// Type creation/memoization methods
2246//===----------------------------------------------------------------------===//
2247
Jay Foad39c79802011-01-12 09:06:06 +00002248QualType
John McCall33ddac02011-01-19 10:06:00 +00002249ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2250 unsigned fastQuals = quals.getFastQualifiers();
2251 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002252
2253 // Check if we've already instantiated this type.
2254 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002255 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002256 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002257 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2258 assert(eq->getQualifiers() == quals);
2259 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002260 }
2261
John McCall33ddac02011-01-19 10:06:00 +00002262 // If the base type is not canonical, make the appropriate canonical type.
2263 QualType canon;
2264 if (!baseType->isCanonicalUnqualified()) {
2265 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002266 canonSplit.Quals.addConsistentQualifiers(quals);
2267 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002268
2269 // Re-find the insert position.
2270 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2271 }
2272
2273 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2274 ExtQualNodes.InsertNode(eq, insertPos);
2275 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002276}
2277
Jay Foad39c79802011-01-12 09:06:06 +00002278QualType
2279ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002280 QualType CanT = getCanonicalType(T);
2281 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002282 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002283
John McCall8ccfcb52009-09-24 19:53:00 +00002284 // If we are composing extended qualifiers together, merge together
2285 // into one ExtQuals node.
2286 QualifierCollector Quals;
2287 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002288
John McCall8ccfcb52009-09-24 19:53:00 +00002289 // If this type already has an address space specified, it cannot get
2290 // another one.
2291 assert(!Quals.hasAddressSpace() &&
2292 "Type cannot be in multiple addr spaces!");
2293 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002294
John McCall8ccfcb52009-09-24 19:53:00 +00002295 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002296}
2297
Chris Lattnerd60183d2009-02-18 22:53:11 +00002298QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002299 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002300 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002301 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002302 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002303
John McCall53fa7142010-12-24 02:08:15 +00002304 if (const PointerType *ptr = T->getAs<PointerType>()) {
2305 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002306 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002307 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2308 return getPointerType(ResultType);
2309 }
2310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
John McCall8ccfcb52009-09-24 19:53:00 +00002312 // If we are composing extended qualifiers together, merge together
2313 // into one ExtQuals node.
2314 QualifierCollector Quals;
2315 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002316
John McCall8ccfcb52009-09-24 19:53:00 +00002317 // If this type already has an ObjCGC specified, it cannot get
2318 // another one.
2319 assert(!Quals.hasObjCGCAttr() &&
2320 "Type cannot have multiple ObjCGCs!");
2321 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002322
John McCall8ccfcb52009-09-24 19:53:00 +00002323 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002324}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002325
John McCall4f5019e2010-12-19 02:44:49 +00002326const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2327 FunctionType::ExtInfo Info) {
2328 if (T->getExtInfo() == Info)
2329 return T;
2330
2331 QualType Result;
2332 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002333 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002334 } else {
2335 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2336 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2337 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002338 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002339 }
2340
2341 return cast<FunctionType>(Result.getTypePtr());
2342}
2343
Richard Smith2a7d4812013-05-04 07:00:32 +00002344void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2345 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002346 FD = FD->getMostRecentDecl();
2347 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002348 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2349 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002350 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002351 if (FunctionDecl *Next = FD->getPreviousDecl())
2352 FD = Next;
2353 else
2354 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002355 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002356 if (ASTMutationListener *L = getASTMutationListener())
2357 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002358}
2359
Richard Smith0b3a4622014-11-13 20:01:57 +00002360/// Get a function type and produce the equivalent function type with the
2361/// specified exception specification. Type sugar that can be present on a
2362/// declaration of a function with an exception specification is permitted
2363/// and preserved. Other type sugar (for instance, typedefs) is not.
2364static QualType getFunctionTypeWithExceptionSpec(
2365 ASTContext &Context, QualType Orig,
2366 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2367 // Might have some parens.
2368 if (auto *PT = dyn_cast<ParenType>(Orig))
2369 return Context.getParenType(
2370 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2371
2372 // Might have a calling-convention attribute.
2373 if (auto *AT = dyn_cast<AttributedType>(Orig))
2374 return Context.getAttributedType(
2375 AT->getAttrKind(),
2376 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2377 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2378 ESI));
2379
2380 // Anything else must be a function type. Rebuild it with the new exception
2381 // specification.
2382 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2383 return Context.getFunctionType(
2384 Proto->getReturnType(), Proto->getParamTypes(),
2385 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2386}
2387
Richard Smithdfe85e22016-12-15 02:35:39 +00002388bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2389 QualType U) {
2390 return hasSameType(T, U) ||
2391 (getLangOpts().CPlusPlus1z &&
2392 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2393 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2394}
2395
Richard Smith0b3a4622014-11-13 20:01:57 +00002396void ASTContext::adjustExceptionSpec(
2397 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2398 bool AsWritten) {
2399 // Update the type.
2400 QualType Updated =
2401 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2402 FD->setType(Updated);
2403
2404 if (!AsWritten)
2405 return;
2406
2407 // Update the type in the type source information too.
2408 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2409 // If the type and the type-as-written differ, we may need to update
2410 // the type-as-written too.
2411 if (TSInfo->getType() != FD->getType())
2412 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2413
2414 // FIXME: When we get proper type location information for exceptions,
2415 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2416 // up the TypeSourceInfo;
2417 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2418 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2419 "TypeLoc size mismatch from updating exception specification");
2420 TSInfo->overrideType(Updated);
2421 }
2422}
2423
Chris Lattnerc6395932007-06-22 20:56:16 +00002424/// getComplexType - Return the uniqued reference to the type for a complex
2425/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002426QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002427 // Unique pointers, to guarantee there is only one pointer of a particular
2428 // structure.
2429 llvm::FoldingSetNodeID ID;
2430 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002431
Craig Topper36250ad2014-05-12 05:36:57 +00002432 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002433 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2434 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Chris Lattnerc6395932007-06-22 20:56:16 +00002436 // If the pointee type isn't canonical, this won't be a canonical type either,
2437 // so fill in the canonical type field.
2438 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002439 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002440 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002441
Chris Lattnerc6395932007-06-22 20:56:16 +00002442 // Get the new insert position for the node we care about.
2443 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002444 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002445 }
John McCall90d1c2d2009-09-24 23:30:46 +00002446 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002447 Types.push_back(New);
2448 ComplexTypes.InsertNode(New, InsertPos);
2449 return QualType(New, 0);
2450}
2451
Chris Lattner970e54e2006-11-12 00:37:36 +00002452/// getPointerType - Return the uniqued reference to the type for a pointer to
2453/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002454QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002455 // Unique pointers, to guarantee there is only one pointer of a particular
2456 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002457 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002458 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002459
Craig Topper36250ad2014-05-12 05:36:57 +00002460 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002461 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002462 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002463
Chris Lattner7ccecb92006-11-12 08:50:50 +00002464 // If the pointee type isn't canonical, this won't be a canonical type either,
2465 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002466 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002467 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002468 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002469
Bob Wilsonc8541f22013-03-15 17:12:43 +00002470 // Get the new insert position for the node we care about.
2471 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002472 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002473 }
John McCall90d1c2d2009-09-24 23:30:46 +00002474 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002475 Types.push_back(New);
2476 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002477 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002478}
2479
Reid Kleckner0503a872013-12-05 01:23:43 +00002480QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2481 llvm::FoldingSetNodeID ID;
2482 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002483 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002484 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2485 if (AT)
2486 return QualType(AT, 0);
2487
2488 QualType Canonical = getCanonicalType(New);
2489
2490 // Get the new insert position for the node we care about.
2491 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002492 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002493
2494 AT = new (*this, TypeAlignment)
2495 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2496 Types.push_back(AT);
2497 AdjustedTypes.InsertNode(AT, InsertPos);
2498 return QualType(AT, 0);
2499}
2500
Reid Kleckner8a365022013-06-24 17:51:48 +00002501QualType ASTContext::getDecayedType(QualType T) const {
2502 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2503
Reid Kleckner8a365022013-06-24 17:51:48 +00002504 QualType Decayed;
2505
2506 // C99 6.7.5.3p7:
2507 // A declaration of a parameter as "array of type" shall be
2508 // adjusted to "qualified pointer to type", where the type
2509 // qualifiers (if any) are those specified within the [ and ] of
2510 // the array type derivation.
2511 if (T->isArrayType())
2512 Decayed = getArrayDecayedType(T);
2513
2514 // C99 6.7.5.3p8:
2515 // A declaration of a parameter as "function returning type"
2516 // shall be adjusted to "pointer to function returning type", as
2517 // in 6.3.2.1.
2518 if (T->isFunctionType())
2519 Decayed = getPointerType(T);
2520
Reid Kleckner0503a872013-12-05 01:23:43 +00002521 llvm::FoldingSetNodeID ID;
2522 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002523 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002524 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2525 if (AT)
2526 return QualType(AT, 0);
2527
Reid Kleckner8a365022013-06-24 17:51:48 +00002528 QualType Canonical = getCanonicalType(Decayed);
2529
2530 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002531 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002532 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002533
Reid Kleckner0503a872013-12-05 01:23:43 +00002534 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2535 Types.push_back(AT);
2536 AdjustedTypes.InsertNode(AT, InsertPos);
2537 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002538}
2539
Mike Stump11289f42009-09-09 15:08:12 +00002540/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002541/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002542QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002543 assert(T->isFunctionType() && "block of function types only");
2544 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002545 // structure.
2546 llvm::FoldingSetNodeID ID;
2547 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002548
Craig Topper36250ad2014-05-12 05:36:57 +00002549 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002550 if (BlockPointerType *PT =
2551 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2552 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002553
2554 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002555 // type either so fill in the canonical type field.
2556 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002557 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002558 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002559
Steve Naroffec33ed92008-08-27 16:04:49 +00002560 // Get the new insert position for the node we care about.
2561 BlockPointerType *NewIP =
2562 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002563 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002564 }
John McCall90d1c2d2009-09-24 23:30:46 +00002565 BlockPointerType *New
2566 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002567 Types.push_back(New);
2568 BlockPointerTypes.InsertNode(New, InsertPos);
2569 return QualType(New, 0);
2570}
2571
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002572/// getLValueReferenceType - Return the uniqued reference to the type for an
2573/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002574QualType
2575ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002576 assert(getCanonicalType(T) != OverloadTy &&
2577 "Unresolved overloaded function type");
2578
Bill Wendling3708c182007-05-27 10:15:43 +00002579 // Unique pointers, to guarantee there is only one pointer of a particular
2580 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002581 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002582 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002583
Craig Topper36250ad2014-05-12 05:36:57 +00002584 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002585 if (LValueReferenceType *RT =
2586 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002587 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002588
John McCallfc93cf92009-10-22 22:37:11 +00002589 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2590
Bill Wendling3708c182007-05-27 10:15:43 +00002591 // If the referencee type isn't canonical, this won't be a canonical type
2592 // either, so fill in the canonical type field.
2593 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002594 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2595 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2596 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002597
Bill Wendling3708c182007-05-27 10:15:43 +00002598 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002599 LValueReferenceType *NewIP =
2600 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002601 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002602 }
2603
John McCall90d1c2d2009-09-24 23:30:46 +00002604 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002605 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2606 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002607 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002608 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002609
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002610 return QualType(New, 0);
2611}
2612
2613/// getRValueReferenceType - Return the uniqued reference to the type for an
2614/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002615QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002616 // Unique pointers, to guarantee there is only one pointer of a particular
2617 // structure.
2618 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002619 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002620
Craig Topper36250ad2014-05-12 05:36:57 +00002621 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002622 if (RValueReferenceType *RT =
2623 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2624 return QualType(RT, 0);
2625
John McCallfc93cf92009-10-22 22:37:11 +00002626 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2627
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002628 // If the referencee type isn't canonical, this won't be a canonical type
2629 // either, so fill in the canonical type field.
2630 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002631 if (InnerRef || !T.isCanonical()) {
2632 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2633 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002634
2635 // Get the new insert position for the node we care about.
2636 RValueReferenceType *NewIP =
2637 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002638 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002639 }
2640
John McCall90d1c2d2009-09-24 23:30:46 +00002641 RValueReferenceType *New
2642 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002643 Types.push_back(New);
2644 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002645 return QualType(New, 0);
2646}
2647
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002648/// getMemberPointerType - Return the uniqued reference to the type for a
2649/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002650QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002651 // Unique pointers, to guarantee there is only one pointer of a particular
2652 // structure.
2653 llvm::FoldingSetNodeID ID;
2654 MemberPointerType::Profile(ID, T, Cls);
2655
Craig Topper36250ad2014-05-12 05:36:57 +00002656 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002657 if (MemberPointerType *PT =
2658 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2659 return QualType(PT, 0);
2660
2661 // If the pointee or class type isn't canonical, this won't be a canonical
2662 // type either, so fill in the canonical type field.
2663 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002664 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002665 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2666
2667 // Get the new insert position for the node we care about.
2668 MemberPointerType *NewIP =
2669 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002670 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002671 }
John McCall90d1c2d2009-09-24 23:30:46 +00002672 MemberPointerType *New
2673 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002674 Types.push_back(New);
2675 MemberPointerTypes.InsertNode(New, InsertPos);
2676 return QualType(New, 0);
2677}
2678
Mike Stump11289f42009-09-09 15:08:12 +00002679/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002680/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002681QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002682 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002683 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002684 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002685 assert((EltTy->isDependentType() ||
2686 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002687 "Constant array of VLAs is illegal!");
2688
Chris Lattnere2df3f92009-05-13 04:12:56 +00002689 // Convert the array size into a canonical width matching the pointer size for
2690 // the target.
2691 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002692 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002693 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattner23b7eb62007-06-15 23:05:46 +00002695 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002696 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002697
Craig Topper36250ad2014-05-12 05:36:57 +00002698 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002699 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002700 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002701 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002702
John McCall33ddac02011-01-19 10:06:00 +00002703 // If the element type isn't canonical or has qualifiers, this won't
2704 // be a canonical type either, so fill in the canonical type field.
2705 QualType Canon;
2706 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2707 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002708 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002709 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002710 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002711
Chris Lattner36f8e652007-01-27 08:31:04 +00002712 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002713 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002714 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
John McCall90d1c2d2009-09-24 23:30:46 +00002718 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002719 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002720 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002721 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002722 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002723}
2724
John McCall06549462011-01-18 08:40:38 +00002725/// getVariableArrayDecayedType - Turns the given type, which may be
2726/// variably-modified, into the corresponding type with all the known
2727/// sizes replaced with [*].
2728QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2729 // Vastly most common case.
2730 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002731
John McCall06549462011-01-18 08:40:38 +00002732 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002733
John McCall06549462011-01-18 08:40:38 +00002734 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002735 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002736 switch (ty->getTypeClass()) {
2737#define TYPE(Class, Base)
2738#define ABSTRACT_TYPE(Class, Base)
2739#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2740#include "clang/AST/TypeNodes.def"
2741 llvm_unreachable("didn't desugar past all non-canonical types?");
2742
2743 // These types should never be variably-modified.
2744 case Type::Builtin:
2745 case Type::Complex:
2746 case Type::Vector:
2747 case Type::ExtVector:
2748 case Type::DependentSizedExtVector:
2749 case Type::ObjCObject:
2750 case Type::ObjCInterface:
2751 case Type::ObjCObjectPointer:
2752 case Type::Record:
2753 case Type::Enum:
2754 case Type::UnresolvedUsing:
2755 case Type::TypeOfExpr:
2756 case Type::TypeOf:
2757 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002758 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002759 case Type::DependentName:
2760 case Type::InjectedClassName:
2761 case Type::TemplateSpecialization:
2762 case Type::DependentTemplateSpecialization:
2763 case Type::TemplateTypeParm:
2764 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002765 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002766 case Type::PackExpansion:
2767 llvm_unreachable("type should never be variably-modified");
2768
2769 // These types can be variably-modified but should never need to
2770 // further decay.
2771 case Type::FunctionNoProto:
2772 case Type::FunctionProto:
2773 case Type::BlockPointer:
2774 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002775 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002776 return type;
2777
2778 // These types can be variably-modified. All these modifications
2779 // preserve structure except as noted by comments.
2780 // TODO: if we ever care about optimizing VLAs, there are no-op
2781 // optimizations available here.
2782 case Type::Pointer:
2783 result = getPointerType(getVariableArrayDecayedType(
2784 cast<PointerType>(ty)->getPointeeType()));
2785 break;
2786
2787 case Type::LValueReference: {
2788 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2789 result = getLValueReferenceType(
2790 getVariableArrayDecayedType(lv->getPointeeType()),
2791 lv->isSpelledAsLValue());
2792 break;
2793 }
2794
2795 case Type::RValueReference: {
2796 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2797 result = getRValueReferenceType(
2798 getVariableArrayDecayedType(lv->getPointeeType()));
2799 break;
2800 }
2801
Eli Friedman0dfb8892011-10-06 23:00:33 +00002802 case Type::Atomic: {
2803 const AtomicType *at = cast<AtomicType>(ty);
2804 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2805 break;
2806 }
2807
John McCall06549462011-01-18 08:40:38 +00002808 case Type::ConstantArray: {
2809 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2810 result = getConstantArrayType(
2811 getVariableArrayDecayedType(cat->getElementType()),
2812 cat->getSize(),
2813 cat->getSizeModifier(),
2814 cat->getIndexTypeCVRQualifiers());
2815 break;
2816 }
2817
2818 case Type::DependentSizedArray: {
2819 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2820 result = getDependentSizedArrayType(
2821 getVariableArrayDecayedType(dat->getElementType()),
2822 dat->getSizeExpr(),
2823 dat->getSizeModifier(),
2824 dat->getIndexTypeCVRQualifiers(),
2825 dat->getBracketsRange());
2826 break;
2827 }
2828
2829 // Turn incomplete types into [*] types.
2830 case Type::IncompleteArray: {
2831 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2832 result = getVariableArrayType(
2833 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002834 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002835 ArrayType::Normal,
2836 iat->getIndexTypeCVRQualifiers(),
2837 SourceRange());
2838 break;
2839 }
2840
2841 // Turn VLA types into [*] types.
2842 case Type::VariableArray: {
2843 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2844 result = getVariableArrayType(
2845 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002846 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002847 ArrayType::Star,
2848 vat->getIndexTypeCVRQualifiers(),
2849 vat->getBracketsRange());
2850 break;
2851 }
2852 }
2853
2854 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002855 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002856}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002857
Steve Naroffcadebd02007-08-30 18:14:25 +00002858/// getVariableArrayType - Returns a non-unique reference to the type for a
2859/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002860QualType ASTContext::getVariableArrayType(QualType EltTy,
2861 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002862 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002863 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002864 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002865 // Since we don't unique expressions, it isn't possible to unique VLA's
2866 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002867 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002868
John McCall33ddac02011-01-19 10:06:00 +00002869 // Be sure to pull qualifiers off the element type.
2870 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2871 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002872 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002873 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002874 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002875 }
2876
John McCall90d1c2d2009-09-24 23:30:46 +00002877 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002878 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002879
2880 VariableArrayTypes.push_back(New);
2881 Types.push_back(New);
2882 return QualType(New, 0);
2883}
2884
Douglas Gregor4619e432008-12-05 23:32:09 +00002885/// getDependentSizedArrayType - Returns a non-unique reference to
2886/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002887/// type.
John McCall33ddac02011-01-19 10:06:00 +00002888QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2889 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002890 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002891 unsigned elementTypeQuals,
2892 SourceRange brackets) const {
2893 assert((!numElements || numElements->isTypeDependent() ||
2894 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002895 "Size must be type- or value-dependent!");
2896
John McCall33ddac02011-01-19 10:06:00 +00002897 // Dependently-sized array types that do not have a specified number
2898 // of elements will have their sizes deduced from a dependent
2899 // initializer. We do no canonicalization here at all, which is okay
2900 // because they can't be used in most locations.
2901 if (!numElements) {
2902 DependentSizedArrayType *newType
2903 = new (*this, TypeAlignment)
2904 DependentSizedArrayType(*this, elementType, QualType(),
2905 numElements, ASM, elementTypeQuals,
2906 brackets);
2907 Types.push_back(newType);
2908 return QualType(newType, 0);
2909 }
2910
2911 // Otherwise, we actually build a new type every time, but we
2912 // also build a canonical type.
2913
2914 SplitQualType canonElementType = getCanonicalType(elementType).split();
2915
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002917 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002918 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002919 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002920 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002921
John McCall33ddac02011-01-19 10:06:00 +00002922 // Look for an existing type with these properties.
2923 DependentSizedArrayType *canonTy =
2924 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002925
John McCall33ddac02011-01-19 10:06:00 +00002926 // If we don't have one, build one.
2927 if (!canonTy) {
2928 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002929 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002930 QualType(), numElements, ASM, elementTypeQuals,
2931 brackets);
2932 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2933 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002934 }
2935
John McCall33ddac02011-01-19 10:06:00 +00002936 // Apply qualifiers from the element type to the array.
2937 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002938 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002939
David Majnemer16a74702015-07-24 05:54:19 +00002940 // If we didn't need extra canonicalization for the element type or the size
2941 // expression, then just use that as our result.
2942 if (QualType(canonElementType.Ty, 0) == elementType &&
2943 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002944 return canon;
2945
2946 // Otherwise, we need to build a type which follows the spelling
2947 // of the element type.
2948 DependentSizedArrayType *sugaredType
2949 = new (*this, TypeAlignment)
2950 DependentSizedArrayType(*this, elementType, canon, numElements,
2951 ASM, elementTypeQuals, brackets);
2952 Types.push_back(sugaredType);
2953 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002954}
2955
John McCall33ddac02011-01-19 10:06:00 +00002956QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002957 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002958 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002959 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002960 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002961
Craig Topper36250ad2014-05-12 05:36:57 +00002962 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002963 if (IncompleteArrayType *iat =
2964 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2965 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002966
2967 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002968 // either, so fill in the canonical type field. We also have to pull
2969 // qualifiers off the element type.
2970 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002971
John McCall33ddac02011-01-19 10:06:00 +00002972 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2973 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002974 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002975 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002976 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002977
2978 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002979 IncompleteArrayType *existing =
2980 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2981 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002982 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002983
John McCall33ddac02011-01-19 10:06:00 +00002984 IncompleteArrayType *newType = new (*this, TypeAlignment)
2985 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002986
John McCall33ddac02011-01-19 10:06:00 +00002987 IncompleteArrayTypes.InsertNode(newType, insertPos);
2988 Types.push_back(newType);
2989 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002990}
2991
Steve Naroff91fcddb2007-07-18 18:00:27 +00002992/// getVectorType - Return the unique reference to a vector type of
2993/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002994QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002995 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002996 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002997
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002998 // Check if we've already instantiated a vector of this type.
2999 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003000 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003001
Craig Topper36250ad2014-05-12 05:36:57 +00003002 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003003 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3004 return QualType(VTP, 0);
3005
3006 // If the element type isn't canonical, this won't be a canonical type either,
3007 // so fill in the canonical type field.
3008 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003009 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003010 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003012 // Get the new insert position for the node we care about.
3013 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003014 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003015 }
John McCall90d1c2d2009-09-24 23:30:46 +00003016 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003017 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003018 VectorTypes.InsertNode(New, InsertPos);
3019 Types.push_back(New);
3020 return QualType(New, 0);
3021}
3022
Nate Begemance4d7fc2008-04-18 23:10:10 +00003023/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003024/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003025QualType
3026ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003027 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003028
Steve Naroff91fcddb2007-07-18 18:00:27 +00003029 // Check if we've already instantiated a vector of this type.
3030 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003031 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003032 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003033 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003034 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3035 return QualType(VTP, 0);
3036
3037 // If the element type isn't canonical, this won't be a canonical type either,
3038 // so fill in the canonical type field.
3039 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003040 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003041 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003042
Steve Naroff91fcddb2007-07-18 18:00:27 +00003043 // Get the new insert position for the node we care about.
3044 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003045 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003046 }
John McCall90d1c2d2009-09-24 23:30:46 +00003047 ExtVectorType *New = new (*this, TypeAlignment)
3048 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003049 VectorTypes.InsertNode(New, InsertPos);
3050 Types.push_back(New);
3051 return QualType(New, 0);
3052}
3053
Jay Foad39c79802011-01-12 09:06:06 +00003054QualType
3055ASTContext::getDependentSizedExtVectorType(QualType vecType,
3056 Expr *SizeExpr,
3057 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003058 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003059 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003060 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003061
Craig Topper36250ad2014-05-12 05:36:57 +00003062 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003063 DependentSizedExtVectorType *Canon
3064 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3065 DependentSizedExtVectorType *New;
3066 if (Canon) {
3067 // We already have a canonical version of this array type; use it as
3068 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003069 New = new (*this, TypeAlignment)
3070 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3071 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003072 } else {
3073 QualType CanonVecTy = getCanonicalType(vecType);
3074 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003075 New = new (*this, TypeAlignment)
3076 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3077 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003078
3079 DependentSizedExtVectorType *CanonCheck
3080 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3082 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003083 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3084 } else {
3085 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3086 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003087 New = new (*this, TypeAlignment)
3088 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003089 }
3090 }
Mike Stump11289f42009-09-09 15:08:12 +00003091
Douglas Gregor758a8692009-06-17 21:51:59 +00003092 Types.push_back(New);
3093 return QualType(New, 0);
3094}
3095
John McCall18afab72016-03-01 00:49:02 +00003096/// \brief Determine whether \p T is canonical as the result type of a function.
3097static bool isCanonicalResultType(QualType T) {
3098 return T.isCanonical() &&
3099 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3100 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3101}
3102
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003103/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003104///
Jay Foad39c79802011-01-12 09:06:06 +00003105QualType
3106ASTContext::getFunctionNoProtoType(QualType ResultTy,
3107 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003108 // Unique functions, to guarantee there is only one function of a particular
3109 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003110 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003111 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003112
Craig Topper36250ad2014-05-12 05:36:57 +00003113 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003114 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003115 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003116 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003117
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003118 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003119 if (!isCanonicalResultType(ResultTy)) {
3120 Canonical =
3121 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003122
Chris Lattner47955de2007-01-27 08:37:20 +00003123 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003124 FunctionNoProtoType *NewIP =
3125 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003126 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003127 }
Mike Stump11289f42009-09-09 15:08:12 +00003128
John McCall90d1c2d2009-09-24 23:30:46 +00003129 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003130 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003131 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003132 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003133 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003134}
3135
Douglas Gregora602a152015-10-01 20:20:47 +00003136CanQualType
3137ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3138 CanQualType CanResultType = getCanonicalType(ResultType);
3139
3140 // Canonical result types do not have ARC lifetime qualifiers.
3141 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3142 Qualifiers Qs = CanResultType.getQualifiers();
3143 Qs.removeObjCLifetime();
3144 return CanQualType::CreateUnsafe(
3145 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3146 }
3147
3148 return CanResultType;
3149}
3150
Richard Smith3c4f8d22016-10-16 17:54:23 +00003151static bool isCanonicalExceptionSpecification(
3152 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3153 if (ESI.Type == EST_None)
3154 return true;
3155 if (!NoexceptInType)
3156 return false;
3157
3158 // C++17 onwards: exception specification is part of the type, as a simple
3159 // boolean "can this function type throw".
3160 if (ESI.Type == EST_BasicNoexcept)
3161 return true;
3162
3163 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003164 // expansions (so we can't tell whether it's non-throwing) and all its
3165 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003166 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003167 bool AnyPackExpansions = false;
3168 for (QualType ET : ESI.Exceptions) {
3169 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003170 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003171 if (ET->getAs<PackExpansionType>())
3172 AnyPackExpansions = true;
3173 }
3174 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003175 }
3176
Richard Smith2a2cda52016-10-18 19:29:18 +00003177 // A noexcept(expr) specification is (possibly) canonical if expr is
3178 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003179 if (ESI.Type == EST_ComputedNoexcept)
3180 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3181
3182 return false;
3183}
3184
Richard Smith304b1242016-10-18 20:13:25 +00003185QualType ASTContext::getFunctionTypeInternal(
3186 QualType ResultTy, ArrayRef<QualType> ArgArray,
3187 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003188 size_t NumArgs = ArgArray.size();
3189
Richard Smith2a2cda52016-10-18 19:29:18 +00003190 // Unique functions, to guarantee there is only one function of a particular
3191 // structure.
3192 llvm::FoldingSetNodeID ID;
3193 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3194 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003195
Richard Smith2a2cda52016-10-18 19:29:18 +00003196 QualType Canonical;
3197 bool Unique = false;
3198
3199 void *InsertPos = nullptr;
3200 if (FunctionProtoType *FPT =
3201 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3202 QualType Existing = QualType(FPT, 0);
3203
3204 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3205 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003206 // noexcept expression, or we're just looking for a canonical type.
3207 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003208 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003209 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003210 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3211 return Existing;
3212
3213 // We need a new type sugar node for this one, to hold the new noexcept
3214 // expression. We do no canonicalization here, but that's OK since we don't
3215 // expect to see the same noexcept expression much more than once.
3216 Canonical = getCanonicalType(Existing);
3217 Unique = true;
3218 }
3219
3220 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003221 bool IsCanonicalExceptionSpec =
3222 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3223
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003224 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003225 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003226 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003227 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003228 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003229 isCanonical = false;
3230
Richard Smith304b1242016-10-18 20:13:25 +00003231 if (OnlyWantCanonical)
3232 assert(isCanonical &&
3233 "given non-canonical parameters constructing canonical type");
3234
Richard Smith2a2cda52016-10-18 19:29:18 +00003235 // If this type isn't canonical, get the canonical version of it if we don't
3236 // already have it. The exception spec is only partially part of the
3237 // canonical type, and only in C++17 onwards.
3238 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003240 CanonicalArgs.reserve(NumArgs);
3241 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003242 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003243
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003244 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003245 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003246 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003247
3248 if (IsCanonicalExceptionSpec) {
3249 // Exception spec is already OK.
3250 } else if (NoexceptInType) {
3251 switch (EPI.ExceptionSpec.Type) {
3252 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3253 // We don't know yet. It shouldn't matter what we pick here; no-one
3254 // should ever look at this.
3255 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003256 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003257 CanonicalEPI.ExceptionSpec.Type = EST_None;
3258 break;
3259
Richard Smith2a2cda52016-10-18 19:29:18 +00003260 // A dynamic exception specification is almost always "not noexcept",
3261 // with the exception that a pack expansion might expand to no types.
3262 case EST_Dynamic: {
3263 bool AnyPacks = false;
3264 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3265 if (ET->getAs<PackExpansionType>())
3266 AnyPacks = true;
3267 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3268 }
3269 if (!AnyPacks)
3270 CanonicalEPI.ExceptionSpec.Type = EST_None;
3271 else {
3272 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3273 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3274 }
3275 break;
3276 }
3277
Richard Smith3c4f8d22016-10-16 17:54:23 +00003278 case EST_DynamicNone: case EST_BasicNoexcept:
3279 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3280 break;
3281
3282 case EST_ComputedNoexcept:
3283 llvm::APSInt Value(1);
3284 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3285 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3286 /*IsEvaluated*/false)) {
3287 // This noexcept specification is invalid.
3288 // FIXME: Should this be able to happen?
3289 CanonicalEPI.ExceptionSpec.Type = EST_None;
3290 break;
3291 }
3292
3293 CanonicalEPI.ExceptionSpec.Type =
3294 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3295 break;
3296 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003297 } else {
3298 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3299 }
John McCalldb40c7f2010-12-14 08:05:40 +00003300
Douglas Gregora602a152015-10-01 20:20:47 +00003301 // Adjust the canonical function result type.
3302 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003303 Canonical =
3304 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003305
Chris Lattnerfd4de792007-01-27 01:15:32 +00003306 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003307 FunctionProtoType *NewIP =
3308 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003309 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003310 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003311
John McCall31168b02011-06-15 23:02:42 +00003312 // FunctionProtoType objects are allocated with extra bytes after
3313 // them for three variable size arrays at the end:
3314 // - parameter types
3315 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003316 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003317 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003318 // expression, or information used to resolve the exception
3319 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003320 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003321 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003322
Richard Smith8acb4282014-07-31 21:57:55 +00003323 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3324 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3325 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003326 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003327 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003328 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003329 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003330 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003331 }
John McCall18afab72016-03-01 00:49:02 +00003332
3333 // Put the ExtParameterInfos last. If all were equal, it would make
3334 // more sense to put these before the exception specification, because
3335 // it's much easier to skip past them compared to the elaborate switch
3336 // required to skip the exception specification. However, all is not
3337 // equal; ExtParameterInfos are used to model very uncommon features,
3338 // and it's better not to burden the more common paths.
3339 if (EPI.ExtParameterInfos) {
3340 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3341 }
John McCall31168b02011-06-15 23:02:42 +00003342
John McCalldb40c7f2010-12-14 08:05:40 +00003343 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003344 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003345 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003346 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003347 if (!Unique)
3348 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003349 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003350}
Chris Lattneref51c202006-11-10 07:17:23 +00003351
Joey Goulye3c85de2016-12-01 11:30:49 +00003352QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003353 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003354 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003355
3356 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003357 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003358 return QualType(PT, 0);
3359
3360 // If the pipe element type isn't canonical, this won't be a canonical type
3361 // either, so fill in the canonical type field.
3362 QualType Canonical;
3363 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003364 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003365
3366 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003367 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003368 assert(!NewIP && "Shouldn't be in the map!");
3369 (void)NewIP;
3370 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003371 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003372 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003373 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003374 return QualType(New, 0);
3375}
3376
Joey Goulye3c85de2016-12-01 11:30:49 +00003377QualType ASTContext::getReadPipeType(QualType T) const {
3378 return getPipeType(T, true);
3379}
3380
Joey Gouly5788b782016-11-18 14:10:54 +00003381QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003382 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003383}
3384
John McCalle78aac42010-03-10 03:28:59 +00003385#ifndef NDEBUG
3386static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3387 if (!isa<CXXRecordDecl>(D)) return false;
3388 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3389 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3390 return true;
3391 if (RD->getDescribedClassTemplate() &&
3392 !isa<ClassTemplateSpecializationDecl>(RD))
3393 return true;
3394 return false;
3395}
3396#endif
3397
3398/// getInjectedClassNameType - Return the unique reference to the
3399/// injected class name type for the specified templated declaration.
3400QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003401 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003402 assert(NeedsInjectedClassNameType(Decl));
3403 if (Decl->TypeForDecl) {
3404 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003405 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003406 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3407 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3408 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3409 } else {
John McCall424cec92011-01-19 06:33:43 +00003410 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003411 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003412 Decl->TypeForDecl = newType;
3413 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003414 }
3415 return QualType(Decl->TypeForDecl, 0);
3416}
3417
Douglas Gregor83a586e2008-04-13 21:07:44 +00003418/// getTypeDeclType - Return the unique reference to the type for the
3419/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003420QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003421 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003422 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003423
Richard Smithdda56e42011-04-15 14:24:37 +00003424 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003425 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003426
John McCall96f0b5f2010-03-10 06:48:02 +00003427 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3428 "Template type parameter types are always available.");
3429
John McCall81e38502010-02-16 03:57:14 +00003430 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003431 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003432 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003433 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003434 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003435 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003436 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003437 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003438 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003439 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3440 Decl->TypeForDecl = newType;
3441 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003442 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003443 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003444
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003445 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003446}
3447
Chris Lattner32d920b2007-01-26 02:01:53 +00003448/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003449/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003450QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003451ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3452 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003453 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003454
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003455 if (Canonical.isNull())
3456 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003457 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003458 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003459 Decl->TypeForDecl = newType;
3460 Types.push_back(newType);
3461 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003462}
3463
Jay Foad39c79802011-01-12 09:06:06 +00003464QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003465 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3466
Douglas Gregorec9fd132012-01-14 16:38:05 +00003467 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003468 if (PrevDecl->TypeForDecl)
3469 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3470
John McCall424cec92011-01-19 06:33:43 +00003471 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3472 Decl->TypeForDecl = newType;
3473 Types.push_back(newType);
3474 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003475}
3476
Jay Foad39c79802011-01-12 09:06:06 +00003477QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003478 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3479
Douglas Gregorec9fd132012-01-14 16:38:05 +00003480 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003481 if (PrevDecl->TypeForDecl)
3482 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3483
John McCall424cec92011-01-19 06:33:43 +00003484 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3485 Decl->TypeForDecl = newType;
3486 Types.push_back(newType);
3487 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003488}
3489
John McCall81904512011-01-06 01:58:22 +00003490QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3491 QualType modifiedType,
3492 QualType equivalentType) {
3493 llvm::FoldingSetNodeID id;
3494 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3495
Craig Topper36250ad2014-05-12 05:36:57 +00003496 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003497 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3498 if (type) return QualType(type, 0);
3499
3500 QualType canon = getCanonicalType(equivalentType);
3501 type = new (*this, TypeAlignment)
3502 AttributedType(canon, attrKind, modifiedType, equivalentType);
3503
3504 Types.push_back(type);
3505 AttributedTypes.InsertNode(type, insertPos);
3506
3507 return QualType(type, 0);
3508}
3509
John McCallcebee162009-10-18 09:09:24 +00003510/// \brief Retrieve a substitution-result type.
3511QualType
3512ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003513 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003514 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003515 && "replacement types must always be canonical");
3516
3517 llvm::FoldingSetNodeID ID;
3518 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003519 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003520 SubstTemplateTypeParmType *SubstParm
3521 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3522
3523 if (!SubstParm) {
3524 SubstParm = new (*this, TypeAlignment)
3525 SubstTemplateTypeParmType(Parm, Replacement);
3526 Types.push_back(SubstParm);
3527 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3528 }
3529
3530 return QualType(SubstParm, 0);
3531}
3532
Douglas Gregorada4b792011-01-14 02:55:32 +00003533/// \brief Retrieve a
3534QualType ASTContext::getSubstTemplateTypeParmPackType(
3535 const TemplateTypeParmType *Parm,
3536 const TemplateArgument &ArgPack) {
3537#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003538 for (const auto &P : ArgPack.pack_elements()) {
3539 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3540 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003541 }
3542#endif
3543
3544 llvm::FoldingSetNodeID ID;
3545 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003546 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003547 if (SubstTemplateTypeParmPackType *SubstParm
3548 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3549 return QualType(SubstParm, 0);
3550
3551 QualType Canon;
3552 if (!Parm->isCanonicalUnqualified()) {
3553 Canon = getCanonicalType(QualType(Parm, 0));
3554 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3555 ArgPack);
3556 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3557 }
3558
3559 SubstTemplateTypeParmPackType *SubstParm
3560 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3561 ArgPack);
3562 Types.push_back(SubstParm);
3563 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3564 return QualType(SubstParm, 0);
3565}
3566
Douglas Gregoreff93e02009-02-05 23:33:38 +00003567/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003568/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003569/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003570QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003571 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003572 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003573 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003574 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003575 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003576 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003577 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3578
3579 if (TypeParm)
3580 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Chandler Carruth08836322011-05-01 00:51:33 +00003582 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003583 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003584 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003585
3586 TemplateTypeParmType *TypeCheck
3587 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3588 assert(!TypeCheck && "Template type parameter canonical type broken");
3589 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003590 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003591 TypeParm = new (*this, TypeAlignment)
3592 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003593
3594 Types.push_back(TypeParm);
3595 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3596
3597 return QualType(TypeParm, 0);
3598}
3599
John McCalle78aac42010-03-10 03:28:59 +00003600TypeSourceInfo *
3601ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3602 SourceLocation NameLoc,
3603 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003604 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003605 assert(!Name.getAsDependentTemplateName() &&
3606 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003607 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003608
3609 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003610 TemplateSpecializationTypeLoc TL =
3611 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003612 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003613 TL.setTemplateNameLoc(NameLoc);
3614 TL.setLAngleLoc(Args.getLAngleLoc());
3615 TL.setRAngleLoc(Args.getRAngleLoc());
3616 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3617 TL.setArgLocInfo(i, Args[i].getLocInfo());
3618 return DI;
3619}
3620
Mike Stump11289f42009-09-09 15:08:12 +00003621QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003622ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003623 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003624 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003625 assert(!Template.getAsDependentTemplateName() &&
3626 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003627
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003628 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003629 ArgVec.reserve(Args.size());
3630 for (const TemplateArgumentLoc &Arg : Args.arguments())
3631 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003632
David Majnemer6fbeee32016-07-07 04:43:07 +00003633 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003634}
3635
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003636#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003637static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3638 for (const TemplateArgument &Arg : Args)
3639 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003640 return true;
3641
3642 return true;
3643}
3644#endif
3645
John McCall0ad16662009-10-29 08:12:44 +00003646QualType
3647ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003648 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003649 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003650 assert(!Template.getAsDependentTemplateName() &&
3651 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003652 // Look through qualified template names.
3653 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3654 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003655
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003656 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003657 Template.getAsTemplateDecl() &&
3658 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003659 QualType CanonType;
3660 if (!Underlying.isNull())
3661 CanonType = getCanonicalType(Underlying);
3662 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003663 // We can get here with an alias template when the specialization contains
3664 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003665 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003666 "Caller must compute aliased type");
3667 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003668 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003669 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003670
Douglas Gregora8e02e72009-07-28 23:00:59 +00003671 // Allocate the (non-canonical) template specialization type, but don't
3672 // try to unique it: these types typically have location information that
3673 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003674 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003675 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003676 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003677 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003678 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003679 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003680 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregor8bf42052009-02-09 18:46:07 +00003682 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003683 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003684}
3685
David Majnemer6fbeee32016-07-07 04:43:07 +00003686QualType ASTContext::getCanonicalTemplateSpecializationType(
3687 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003688 assert(!Template.getAsDependentTemplateName() &&
3689 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003690
Douglas Gregore29139c2011-03-03 17:04:51 +00003691 // Look through qualified template names.
3692 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3693 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003694
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003695 // Build the canonical template specialization type.
3696 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003697 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003698 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003699 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003700 for (const TemplateArgument &Arg : Args)
3701 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003702
3703 // Determine whether this canonical template specialization type already
3704 // exists.
3705 llvm::FoldingSetNodeID ID;
3706 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003707 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003708
Craig Topper36250ad2014-05-12 05:36:57 +00003709 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003710 TemplateSpecializationType *Spec
3711 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3712
3713 if (!Spec) {
3714 // Allocate a new canonical template specialization type.
3715 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3716 sizeof(TemplateArgument) * NumArgs),
3717 TypeAlignment);
3718 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003719 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003720 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003721 Types.push_back(Spec);
3722 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3723 }
3724
3725 assert(Spec->isDependentType() &&
3726 "Non-dependent template-id type must have a canonical type");
3727 return QualType(Spec, 0);
3728}
3729
3730QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003731ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3732 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003733 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003734 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003735 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003736
Craig Topper36250ad2014-05-12 05:36:57 +00003737 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003738 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003739 if (T)
3740 return QualType(T, 0);
3741
Douglas Gregorc42075a2010-02-04 18:10:26 +00003742 QualType Canon = NamedType;
3743 if (!Canon.isCanonical()) {
3744 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003745 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3746 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003747 (void)CheckT;
3748 }
3749
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003750 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003751 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003752 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003753 return QualType(T, 0);
3754}
3755
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003756QualType
Jay Foad39c79802011-01-12 09:06:06 +00003757ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003758 llvm::FoldingSetNodeID ID;
3759 ParenType::Profile(ID, InnerType);
3760
Craig Topper36250ad2014-05-12 05:36:57 +00003761 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003762 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3763 if (T)
3764 return QualType(T, 0);
3765
3766 QualType Canon = InnerType;
3767 if (!Canon.isCanonical()) {
3768 Canon = getCanonicalType(InnerType);
3769 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3770 assert(!CheckT && "Paren canonical type broken");
3771 (void)CheckT;
3772 }
3773
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003774 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003775 Types.push_back(T);
3776 ParenTypes.InsertNode(T, InsertPos);
3777 return QualType(T, 0);
3778}
3779
Douglas Gregor02085352010-03-31 20:19:30 +00003780QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3781 NestedNameSpecifier *NNS,
3782 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003783 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003784 if (Canon.isNull()) {
3785 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003786 ElaboratedTypeKeyword CanonKeyword = Keyword;
3787 if (Keyword == ETK_None)
3788 CanonKeyword = ETK_Typename;
3789
3790 if (CanonNNS != NNS || CanonKeyword != Keyword)
3791 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003792 }
3793
3794 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003795 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003796
Craig Topper36250ad2014-05-12 05:36:57 +00003797 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003798 DependentNameType *T
3799 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003800 if (T)
3801 return QualType(T, 0);
3802
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003803 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003804 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003805 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003806 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003807}
3808
Mike Stump11289f42009-09-09 15:08:12 +00003809QualType
John McCallc392f372010-06-11 00:33:02 +00003810ASTContext::getDependentTemplateSpecializationType(
3811 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003812 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003813 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003814 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003815 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003816 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003817 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3818 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003819 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003820}
3821
3822QualType
3823ASTContext::getDependentTemplateSpecializationType(
3824 ElaboratedTypeKeyword Keyword,
3825 NestedNameSpecifier *NNS,
3826 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003827 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003828 assert((!NNS || NNS->isDependent()) &&
3829 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003830
Douglas Gregorc42075a2010-02-04 18:10:26 +00003831 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003832 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003833 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003834
Craig Topper36250ad2014-05-12 05:36:57 +00003835 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003836 DependentTemplateSpecializationType *T
3837 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003838 if (T)
3839 return QualType(T, 0);
3840
John McCallc392f372010-06-11 00:33:02 +00003841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003842
John McCallc392f372010-06-11 00:33:02 +00003843 ElaboratedTypeKeyword CanonKeyword = Keyword;
3844 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3845
3846 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003847 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003848 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003849 for (unsigned I = 0; I != NumArgs; ++I) {
3850 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3851 if (!CanonArgs[I].structurallyEquals(Args[I]))
3852 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003853 }
3854
John McCallc392f372010-06-11 00:33:02 +00003855 QualType Canon;
3856 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3857 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003858 Name,
3859 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003860
3861 // Find the insert position again.
3862 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3863 }
3864
3865 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3866 sizeof(TemplateArgument) * NumArgs),
3867 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003868 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003869 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003870 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003871 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003872 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003873}
3874
Richard Smith43e14d22016-12-23 02:10:11 +00003875void
3876ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3877 SmallVectorImpl<TemplateArgument> &Args) {
3878 Args.reserve(Args.size() + Params->size());
3879
3880 for (NamedDecl *Param : *Params) {
3881 TemplateArgument Arg;
3882 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3883 QualType ArgType = getTypeDeclType(TTP);
3884 if (TTP->isParameterPack())
3885 ArgType = getPackExpansionType(ArgType, None);
3886
3887 Arg = TemplateArgument(ArgType);
3888 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3889 Expr *E = new (*this) DeclRefExpr(
3890 NTTP, /*enclosing*/false,
3891 NTTP->getType().getNonLValueExprType(*this),
3892 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3893
3894 if (NTTP->isParameterPack())
3895 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3896 None);
3897 Arg = TemplateArgument(E);
3898 } else {
3899 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3900 if (TTP->isParameterPack())
3901 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3902 else
3903 Arg = TemplateArgument(TemplateName(TTP));
3904 }
3905
3906 if (Param->isTemplateParameterPack())
3907 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3908
3909 Args.push_back(Arg);
3910 }
3911}
3912
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003913QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003914 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003915 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003916 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003917
3918 assert(Pattern->containsUnexpandedParameterPack() &&
3919 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003920 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003921 PackExpansionType *T
3922 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3923 if (T)
3924 return QualType(T, 0);
3925
3926 QualType Canon;
3927 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003928 Canon = getCanonicalType(Pattern);
3929 // The canonical type might not contain an unexpanded parameter pack, if it
3930 // contains an alias template specialization which ignores one of its
3931 // parameters.
3932 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003933 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003934
Richard Smith68eea502012-07-16 00:20:35 +00003935 // Find the insert position again, in case we inserted an element into
3936 // PackExpansionTypes and invalidated our insert position.
3937 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3938 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003939 }
3940
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003941 T = new (*this, TypeAlignment)
3942 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003943 Types.push_back(T);
3944 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003945 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003946}
3947
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003948/// CmpProtocolNames - Comparison predicate for sorting protocols
3949/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003950static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3951 ObjCProtocolDecl *const *RHS) {
3952 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003953}
3954
Craig Topper1f26d5b2016-01-03 19:43:23 +00003955static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3956 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003957
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003958 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3959 return false;
3960
Craig Topper1f26d5b2016-01-03 19:43:23 +00003961 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003962 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003963 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003964 return false;
3965 return true;
3966}
3967
Craig Topper6a8c1512015-10-22 01:56:18 +00003968static void
3969SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003970 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003971 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003972
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003973 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003974 for (ObjCProtocolDecl *&P : Protocols)
3975 P = P->getCanonicalDecl();
3976
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003977 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003978 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3979 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003980}
3981
John McCall8b07ec22010-05-15 11:32:37 +00003982QualType ASTContext::getObjCObjectType(QualType BaseType,
3983 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003984 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003985 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003986 llvm::makeArrayRef(Protocols, NumProtocols),
3987 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003988}
3989
3990QualType ASTContext::getObjCObjectType(
3991 QualType baseType,
3992 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003993 ArrayRef<ObjCProtocolDecl *> protocols,
3994 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003995 // If the base type is an interface and there aren't any protocols or
3996 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003997 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3998 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003999 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004000
4001 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004002 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004003 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004004 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004005 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4006 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004007
Douglas Gregore9d95f12015-07-07 03:57:35 +00004008 // Determine the type arguments to be used for canonicalization,
4009 // which may be explicitly specified here or written on the base
4010 // type.
4011 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4012 if (effectiveTypeArgs.empty()) {
4013 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4014 effectiveTypeArgs = baseObject->getTypeArgs();
4015 }
John McCallfc93cf92009-10-22 22:37:11 +00004016
Douglas Gregore9d95f12015-07-07 03:57:35 +00004017 // Build the canonical type, which has the canonical base type and a
4018 // sorted-and-uniqued list of protocols and the type arguments
4019 // canonicalized.
4020 QualType canonical;
4021 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4022 effectiveTypeArgs.end(),
4023 [&](QualType type) {
4024 return type.isCanonical();
4025 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004026 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004027 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4028 // Determine the canonical type arguments.
4029 ArrayRef<QualType> canonTypeArgs;
4030 SmallVector<QualType, 4> canonTypeArgsVec;
4031 if (!typeArgsAreCanonical) {
4032 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4033 for (auto typeArg : effectiveTypeArgs)
4034 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4035 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004036 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004037 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004038 }
4039
Douglas Gregore9d95f12015-07-07 03:57:35 +00004040 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4041 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4042 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004043 canonProtocolsVec.append(protocols.begin(), protocols.end());
4044 SortAndUniqueProtocols(canonProtocolsVec);
4045 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004046 } else {
4047 canonProtocols = protocols;
4048 }
4049
4050 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004051 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004052
John McCallfc93cf92009-10-22 22:37:11 +00004053 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004054 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4055 }
4056
Douglas Gregore9d95f12015-07-07 03:57:35 +00004057 unsigned size = sizeof(ObjCObjectTypeImpl);
4058 size += typeArgs.size() * sizeof(QualType);
4059 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4060 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004061 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004062 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4063 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004064
4065 Types.push_back(T);
4066 ObjCObjectTypes.InsertNode(T, InsertPos);
4067 return QualType(T, 0);
4068}
4069
Manman Ren3569eb52016-09-13 17:03:12 +00004070/// Apply Objective-C protocol qualifiers to the given type.
4071/// If this is for the canonical type of a type parameter, we can apply
4072/// protocol qualifiers on the ObjCObjectPointerType.
4073QualType
4074ASTContext::applyObjCProtocolQualifiers(QualType type,
4075 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4076 bool allowOnPointerType) const {
4077 hasError = false;
4078
Manman Renc5705ba2016-09-13 17:41:05 +00004079 if (const ObjCTypeParamType *objT =
4080 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4081 return getObjCTypeParamType(objT->getDecl(), protocols);
4082 }
4083
Manman Ren3569eb52016-09-13 17:03:12 +00004084 // Apply protocol qualifiers to ObjCObjectPointerType.
4085 if (allowOnPointerType) {
4086 if (const ObjCObjectPointerType *objPtr =
4087 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4088 const ObjCObjectType *objT = objPtr->getObjectType();
4089 // Merge protocol lists and construct ObjCObjectType.
4090 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4091 protocolsVec.append(objT->qual_begin(),
4092 objT->qual_end());
4093 protocolsVec.append(protocols.begin(), protocols.end());
4094 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4095 type = getObjCObjectType(
4096 objT->getBaseType(),
4097 objT->getTypeArgsAsWritten(),
4098 protocols,
4099 objT->isKindOfTypeAsWritten());
4100 return getObjCObjectPointerType(type);
4101 }
4102 }
4103
4104 // Apply protocol qualifiers to ObjCObjectType.
4105 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4106 // FIXME: Check for protocols to which the class type is already
4107 // known to conform.
4108
4109 return getObjCObjectType(objT->getBaseType(),
4110 objT->getTypeArgsAsWritten(),
4111 protocols,
4112 objT->isKindOfTypeAsWritten());
4113 }
4114
4115 // If the canonical type is ObjCObjectType, ...
4116 if (type->isObjCObjectType()) {
4117 // Silently overwrite any existing protocol qualifiers.
4118 // TODO: determine whether that's the right thing to do.
4119
4120 // FIXME: Check for protocols to which the class type is already
4121 // known to conform.
4122 return getObjCObjectType(type, { }, protocols, false);
4123 }
4124
4125 // id<protocol-list>
4126 if (type->isObjCIdType()) {
4127 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4128 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4129 objPtr->isKindOfType());
4130 return getObjCObjectPointerType(type);
4131 }
4132
4133 // Class<protocol-list>
4134 if (type->isObjCClassType()) {
4135 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4136 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4137 objPtr->isKindOfType());
4138 return getObjCObjectPointerType(type);
4139 }
4140
4141 hasError = true;
4142 return type;
4143}
4144
Manman Rene6be26c2016-09-13 17:25:08 +00004145QualType
4146ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4147 ArrayRef<ObjCProtocolDecl *> protocols,
4148 QualType Canonical) const {
4149 // Look in the folding set for an existing type.
4150 llvm::FoldingSetNodeID ID;
4151 ObjCTypeParamType::Profile(ID, Decl, protocols);
4152 void *InsertPos = nullptr;
4153 if (ObjCTypeParamType *TypeParam =
4154 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4155 return QualType(TypeParam, 0);
4156
4157 if (Canonical.isNull()) {
4158 // We canonicalize to the underlying type.
4159 Canonical = getCanonicalType(Decl->getUnderlyingType());
4160 if (!protocols.empty()) {
4161 // Apply the protocol qualifers.
4162 bool hasError;
4163 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4164 true/*allowOnPointerType*/);
4165 assert(!hasError && "Error when apply protocol qualifier to bound type");
4166 }
4167 }
4168
4169 unsigned size = sizeof(ObjCTypeParamType);
4170 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4171 void *mem = Allocate(size, TypeAlignment);
4172 ObjCTypeParamType *newType = new (mem)
4173 ObjCTypeParamType(Decl, Canonical, protocols);
4174
4175 Types.push_back(newType);
4176 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4177 return QualType(newType, 0);
4178}
4179
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004180/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4181/// protocol list adopt all protocols in QT's qualified-id protocol
4182/// list.
4183bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4184 ObjCInterfaceDecl *IC) {
4185 if (!QT->isObjCQualifiedIdType())
4186 return false;
4187
4188 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4189 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004190 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004191 if (!IC->ClassImplementsProtocol(Proto, false))
4192 return false;
4193 }
4194 return true;
4195 }
4196 return false;
4197}
4198
4199/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4200/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4201/// of protocols.
4202bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4203 ObjCInterfaceDecl *IDecl) {
4204 if (!QT->isObjCQualifiedIdType())
4205 return false;
4206 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4207 if (!OPT)
4208 return false;
4209 if (!IDecl->hasDefinition())
4210 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004211 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4212 CollectInheritedProtocols(IDecl, InheritedProtocols);
4213 if (InheritedProtocols.empty())
4214 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004215 // Check that if every protocol in list of id<plist> conforms to a protcol
4216 // of IDecl's, then bridge casting is ok.
4217 bool Conforms = false;
4218 for (auto *Proto : OPT->quals()) {
4219 Conforms = false;
4220 for (auto *PI : InheritedProtocols) {
4221 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4222 Conforms = true;
4223 break;
4224 }
4225 }
4226 if (!Conforms)
4227 break;
4228 }
4229 if (Conforms)
4230 return true;
4231
Aaron Ballman83731462014-03-17 16:14:00 +00004232 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004233 // If both the right and left sides have qualifiers.
4234 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004235 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004236 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004237 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004238 break;
4239 }
4240 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004241 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004242 }
4243 return true;
4244}
4245
John McCall8b07ec22010-05-15 11:32:37 +00004246/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4247/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004248QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004249 llvm::FoldingSetNodeID ID;
4250 ObjCObjectPointerType::Profile(ID, ObjectT);
4251
Craig Topper36250ad2014-05-12 05:36:57 +00004252 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004253 if (ObjCObjectPointerType *QT =
4254 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4255 return QualType(QT, 0);
4256
4257 // Find the canonical object type.
4258 QualType Canonical;
4259 if (!ObjectT.isCanonical()) {
4260 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4261
4262 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004263 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4264 }
4265
Douglas Gregorf85bee62010-02-08 22:59:26 +00004266 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004267 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4268 ObjCObjectPointerType *QType =
4269 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004270
Steve Narofffb4330f2009-06-17 22:40:22 +00004271 Types.push_back(QType);
4272 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004273 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004274}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004275
Douglas Gregor1c283312010-08-11 12:19:30 +00004276/// getObjCInterfaceType - Return the unique reference to the type for the
4277/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004278QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4279 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004280 if (Decl->TypeForDecl)
4281 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004282
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004283 if (PrevDecl) {
4284 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4285 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4286 return QualType(PrevDecl->TypeForDecl, 0);
4287 }
4288
Douglas Gregor7671e532011-12-16 16:34:57 +00004289 // Prefer the definition, if there is one.
4290 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4291 Decl = Def;
4292
Douglas Gregor1c283312010-08-11 12:19:30 +00004293 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4294 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4295 Decl->TypeForDecl = T;
4296 Types.push_back(T);
4297 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004298}
4299
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004300/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4301/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004302/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004303/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004304/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004305QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004306 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004307 if (tofExpr->isTypeDependent()) {
4308 llvm::FoldingSetNodeID ID;
4309 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004310
Craig Topper36250ad2014-05-12 05:36:57 +00004311 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004312 DependentTypeOfExprType *Canon
4313 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4314 if (Canon) {
4315 // We already have a "canonical" version of an identical, dependent
4316 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004317 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004318 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004319 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004320 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004321 Canon
4322 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004323 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4324 toe = Canon;
4325 }
4326 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004327 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004328 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004329 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004330 Types.push_back(toe);
4331 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004332}
4333
Steve Naroffa773cd52007-08-01 18:02:17 +00004334/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004335/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004336/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004337/// an issue. This doesn't affect the type checker, since it operates
4338/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004339QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004340 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004341 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004342 Types.push_back(tot);
4343 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004344}
4345
Richard Smith8eb1d322014-06-05 20:13:13 +00004346/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4347/// nodes. This would never be helpful, since each such type has its own
4348/// expression, and would not give a significant memory saving, since there
4349/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004350QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004351 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004352
4353 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004354 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004355 // unique dependent type. Two such decltype-specifiers refer to the same
4356 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004357 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004358 llvm::FoldingSetNodeID ID;
4359 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004360
Craig Topper36250ad2014-05-12 05:36:57 +00004361 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004362 DependentDecltypeType *Canon
4363 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004364 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004365 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004366 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004367 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004368 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004369 dt = new (*this, TypeAlignment)
4370 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004371 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004372 dt = new (*this, TypeAlignment)
4373 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004374 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004375 Types.push_back(dt);
4376 return QualType(dt, 0);
4377}
4378
Alexis Hunte852b102011-05-24 22:41:36 +00004379/// getUnaryTransformationType - We don't unique these, since the memory
4380/// savings are minimal and these are rare.
4381QualType ASTContext::getUnaryTransformType(QualType BaseType,
4382 QualType UnderlyingType,
4383 UnaryTransformType::UTTKind Kind)
4384 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004385 UnaryTransformType *ut = nullptr;
4386
4387 if (BaseType->isDependentType()) {
4388 // Look in the folding set for an existing type.
4389 llvm::FoldingSetNodeID ID;
4390 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4391
4392 void *InsertPos = nullptr;
4393 DependentUnaryTransformType *Canon
4394 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4395
4396 if (!Canon) {
4397 // Build a new, canonical __underlying_type(type) type.
4398 Canon = new (*this, TypeAlignment)
4399 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4400 Kind);
4401 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4402 }
4403 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4404 QualType(), Kind,
4405 QualType(Canon, 0));
4406 } else {
4407 QualType CanonType = getCanonicalType(UnderlyingType);
4408 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4409 UnderlyingType, Kind,
4410 CanonType);
4411 }
4412 Types.push_back(ut);
4413 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004414}
4415
Richard Smith2a7d4812013-05-04 07:00:32 +00004416/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4417/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4418/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004419QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004420 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004421 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004422 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004423
Richard Smith2a7d4812013-05-04 07:00:32 +00004424 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004425 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004426 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004427 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004428 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4429 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004430
Richard Smith74aeef52013-04-26 16:15:35 +00004431 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004432 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004433 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004434 Types.push_back(AT);
4435 if (InsertPos)
4436 AutoTypes.InsertNode(AT, InsertPos);
4437 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004438}
4439
Eli Friedman0dfb8892011-10-06 23:00:33 +00004440/// getAtomicType - Return the uniqued reference to the atomic type for
4441/// the given value type.
4442QualType ASTContext::getAtomicType(QualType T) const {
4443 // Unique pointers, to guarantee there is only one pointer of a particular
4444 // structure.
4445 llvm::FoldingSetNodeID ID;
4446 AtomicType::Profile(ID, T);
4447
Craig Topper36250ad2014-05-12 05:36:57 +00004448 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004449 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4450 return QualType(AT, 0);
4451
4452 // If the atomic value type isn't canonical, this won't be a canonical type
4453 // either, so fill in the canonical type field.
4454 QualType Canonical;
4455 if (!T.isCanonical()) {
4456 Canonical = getAtomicType(getCanonicalType(T));
4457
4458 // Get the new insert position for the node we care about.
4459 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004460 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004461 }
4462 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4463 Types.push_back(New);
4464 AtomicTypes.InsertNode(New, InsertPos);
4465 return QualType(New, 0);
4466}
4467
Richard Smith02e85f32011-04-14 22:09:26 +00004468/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4469QualType ASTContext::getAutoDeductType() const {
4470 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004471 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004472 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004473 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004474 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004475 return AutoDeductTy;
4476}
4477
4478/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4479QualType ASTContext::getAutoRRefDeductType() const {
4480 if (AutoRRefDeductTy.isNull())
4481 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4482 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4483 return AutoRRefDeductTy;
4484}
4485
Chris Lattnerfb072462007-01-23 05:45:31 +00004486/// getTagDeclType - Return the unique reference to the type for the
4487/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004488QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004489 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004490 // FIXME: What is the design on getTagDeclType when it requires casting
4491 // away const? mutable?
4492 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004493}
4494
Mike Stump11289f42009-09-09 15:08:12 +00004495/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4496/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4497/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004498CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004499 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004500}
Chris Lattnerfb072462007-01-23 05:45:31 +00004501
Hans Wennborg27541db2011-10-27 08:29:09 +00004502/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4503CanQualType ASTContext::getIntMaxType() const {
4504 return getFromTargetType(Target->getIntMaxType());
4505}
4506
4507/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4508CanQualType ASTContext::getUIntMaxType() const {
4509 return getFromTargetType(Target->getUIntMaxType());
4510}
4511
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004512/// getSignedWCharType - Return the type of "signed wchar_t".
4513/// Used when in C++, as a GCC extension.
4514QualType ASTContext::getSignedWCharType() const {
4515 // FIXME: derive from "Target" ?
4516 return WCharTy;
4517}
4518
4519/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4520/// Used when in C++, as a GCC extension.
4521QualType ASTContext::getUnsignedWCharType() const {
4522 // FIXME: derive from "Target" ?
4523 return UnsignedIntTy;
4524}
4525
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004526QualType ASTContext::getIntPtrType() const {
4527 return getFromTargetType(Target->getIntPtrType());
4528}
4529
4530QualType ASTContext::getUIntPtrType() const {
4531 return getCorrespondingUnsignedType(getIntPtrType());
4532}
4533
Hans Wennborg27541db2011-10-27 08:29:09 +00004534/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004535/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4536QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004537 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004538}
4539
Eli Friedman4e91899e2012-11-27 02:58:24 +00004540/// \brief Return the unique type for "pid_t" defined in
4541/// <sys/types.h>. We need this to compute the correct type for vfork().
4542QualType ASTContext::getProcessIDType() const {
4543 return getFromTargetType(Target->getProcessIDType());
4544}
4545
Chris Lattnera21ad802008-04-02 05:18:44 +00004546//===----------------------------------------------------------------------===//
4547// Type Operators
4548//===----------------------------------------------------------------------===//
4549
Jay Foad39c79802011-01-12 09:06:06 +00004550CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004551 // Push qualifiers into arrays, and then discard any remaining
4552 // qualifiers.
4553 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004554 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004555 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004556 QualType Result;
4557 if (isa<ArrayType>(Ty)) {
4558 Result = getArrayDecayedType(QualType(Ty,0));
4559 } else if (isa<FunctionType>(Ty)) {
4560 Result = getPointerType(QualType(Ty, 0));
4561 } else {
4562 Result = QualType(Ty, 0);
4563 }
4564
4565 return CanQualType::CreateUnsafe(Result);
4566}
4567
John McCall6c9dd522011-01-18 07:41:22 +00004568QualType ASTContext::getUnqualifiedArrayType(QualType type,
4569 Qualifiers &quals) {
4570 SplitQualType splitType = type.getSplitUnqualifiedType();
4571
4572 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4573 // the unqualified desugared type and then drops it on the floor.
4574 // We then have to strip that sugar back off with
4575 // getUnqualifiedDesugaredType(), which is silly.
4576 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004577 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004578
4579 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004580 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004581 quals = splitType.Quals;
4582 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004583 }
4584
John McCall6c9dd522011-01-18 07:41:22 +00004585 // Otherwise, recurse on the array's element type.
4586 QualType elementType = AT->getElementType();
4587 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4588
4589 // If that didn't change the element type, AT has no qualifiers, so we
4590 // can just use the results in splitType.
4591 if (elementType == unqualElementType) {
4592 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004593 quals = splitType.Quals;
4594 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004595 }
4596
4597 // Otherwise, add in the qualifiers from the outermost type, then
4598 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004599 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004600
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004601 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004602 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004603 CAT->getSizeModifier(), 0);
4604 }
4605
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004606 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004607 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004608 }
4609
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004610 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004611 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004612 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004613 VAT->getSizeModifier(),
4614 VAT->getIndexTypeCVRQualifiers(),
4615 VAT->getBracketsRange());
4616 }
4617
4618 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004619 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004620 DSAT->getSizeModifier(), 0,
4621 SourceRange());
4622}
4623
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004624/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4625/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4626/// they point to and return true. If T1 and T2 aren't pointer types
4627/// or pointer-to-member types, or if they are not similar at this
4628/// level, returns false and leaves T1 and T2 unchanged. Top-level
4629/// qualifiers on T1 and T2 are ignored. This function will typically
4630/// be called in a loop that successively "unwraps" pointer and
4631/// pointer-to-member types to compare them at each level.
4632bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4633 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4634 *T2PtrType = T2->getAs<PointerType>();
4635 if (T1PtrType && T2PtrType) {
4636 T1 = T1PtrType->getPointeeType();
4637 T2 = T2PtrType->getPointeeType();
4638 return true;
4639 }
4640
4641 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4642 *T2MPType = T2->getAs<MemberPointerType>();
4643 if (T1MPType && T2MPType &&
4644 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4645 QualType(T2MPType->getClass(), 0))) {
4646 T1 = T1MPType->getPointeeType();
4647 T2 = T2MPType->getPointeeType();
4648 return true;
4649 }
4650
David Blaikiebbafb8a2012-03-11 07:00:24 +00004651 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004652 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4653 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4654 if (T1OPType && T2OPType) {
4655 T1 = T1OPType->getPointeeType();
4656 T2 = T2OPType->getPointeeType();
4657 return true;
4658 }
4659 }
4660
4661 // FIXME: Block pointers, too?
4662
4663 return false;
4664}
4665
Jay Foad39c79802011-01-12 09:06:06 +00004666DeclarationNameInfo
4667ASTContext::getNameForTemplate(TemplateName Name,
4668 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004669 switch (Name.getKind()) {
4670 case TemplateName::QualifiedTemplate:
4671 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004672 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004673 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4674 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004675
John McCalld9dfe3a2011-06-30 08:33:18 +00004676 case TemplateName::OverloadedTemplate: {
4677 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4678 // DNInfo work in progress: CHECKME: what about DNLoc?
4679 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4680 }
4681
4682 case TemplateName::DependentTemplate: {
4683 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004684 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004685 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004686 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4687 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004688 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004689 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4690 // DNInfo work in progress: FIXME: source locations?
4691 DeclarationNameLoc DNLoc;
4692 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4693 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4694 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004695 }
4696 }
4697
John McCalld9dfe3a2011-06-30 08:33:18 +00004698 case TemplateName::SubstTemplateTemplateParm: {
4699 SubstTemplateTemplateParmStorage *subst
4700 = Name.getAsSubstTemplateTemplateParm();
4701 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4702 NameLoc);
4703 }
4704
4705 case TemplateName::SubstTemplateTemplateParmPack: {
4706 SubstTemplateTemplateParmPackStorage *subst
4707 = Name.getAsSubstTemplateTemplateParmPack();
4708 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4709 NameLoc);
4710 }
4711 }
4712
4713 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004714}
4715
Jay Foad39c79802011-01-12 09:06:06 +00004716TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004717 switch (Name.getKind()) {
4718 case TemplateName::QualifiedTemplate:
4719 case TemplateName::Template: {
4720 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004721 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004722 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004723 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4724
4725 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004726 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004727 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004728
John McCalld9dfe3a2011-06-30 08:33:18 +00004729 case TemplateName::OverloadedTemplate:
4730 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004731
John McCalld9dfe3a2011-06-30 08:33:18 +00004732 case TemplateName::DependentTemplate: {
4733 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4734 assert(DTN && "Non-dependent template names must refer to template decls.");
4735 return DTN->CanonicalTemplateName;
4736 }
4737
4738 case TemplateName::SubstTemplateTemplateParm: {
4739 SubstTemplateTemplateParmStorage *subst
4740 = Name.getAsSubstTemplateTemplateParm();
4741 return getCanonicalTemplateName(subst->getReplacement());
4742 }
4743
4744 case TemplateName::SubstTemplateTemplateParmPack: {
4745 SubstTemplateTemplateParmPackStorage *subst
4746 = Name.getAsSubstTemplateTemplateParmPack();
4747 TemplateTemplateParmDecl *canonParameter
4748 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4749 TemplateArgument canonArgPack
4750 = getCanonicalTemplateArgument(subst->getArgumentPack());
4751 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4752 }
4753 }
4754
4755 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004756}
4757
Douglas Gregoradee3e32009-11-11 23:06:43 +00004758bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4759 X = getCanonicalTemplateName(X);
4760 Y = getCanonicalTemplateName(Y);
4761 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4762}
4763
Mike Stump11289f42009-09-09 15:08:12 +00004764TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004765ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004766 switch (Arg.getKind()) {
4767 case TemplateArgument::Null:
4768 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004769
Douglas Gregora8e02e72009-07-28 23:00:59 +00004770 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004771 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004772
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004773 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004774 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004775 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004776 }
Mike Stump11289f42009-09-09 15:08:12 +00004777
Eli Friedmanb826a002012-09-26 02:36:12 +00004778 case TemplateArgument::NullPtr:
4779 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4780 /*isNullPtr*/true);
4781
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004782 case TemplateArgument::Template:
4783 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004784
4785 case TemplateArgument::TemplateExpansion:
4786 return TemplateArgument(getCanonicalTemplateName(
4787 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004788 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004789
Douglas Gregora8e02e72009-07-28 23:00:59 +00004790 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004791 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004792
Douglas Gregora8e02e72009-07-28 23:00:59 +00004793 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004794 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004795
Douglas Gregora8e02e72009-07-28 23:00:59 +00004796 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004797 if (Arg.pack_size() == 0)
4798 return Arg;
4799
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004800 TemplateArgument *CanonArgs
4801 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004802 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004803 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004804 AEnd = Arg.pack_end();
4805 A != AEnd; (void)++A, ++Idx)
4806 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004807
Benjamin Kramercce63472015-08-05 09:40:22 +00004808 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004809 }
4810 }
4811
4812 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004813 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004814}
4815
Douglas Gregor333489b2009-03-27 23:10:48 +00004816NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004817ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004818 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004819 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004820
4821 switch (NNS->getKind()) {
4822 case NestedNameSpecifier::Identifier:
4823 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004824 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004825 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4826 NNS->getAsIdentifier());
4827
4828 case NestedNameSpecifier::Namespace:
4829 // A namespace is canonical; build a nested-name-specifier with
4830 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004831 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004832 NNS->getAsNamespace()->getOriginalNamespace());
4833
4834 case NestedNameSpecifier::NamespaceAlias:
4835 // A namespace is canonical; build a nested-name-specifier with
4836 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004837 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004838 NNS->getAsNamespaceAlias()->getNamespace()
4839 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004840
4841 case NestedNameSpecifier::TypeSpec:
4842 case NestedNameSpecifier::TypeSpecWithTemplate: {
4843 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004844
4845 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4846 // break it apart into its prefix and identifier, then reconsititute those
4847 // as the canonical nested-name-specifier. This is required to canonicalize
4848 // a dependent nested-name-specifier involving typedefs of dependent-name
4849 // types, e.g.,
4850 // typedef typename T::type T1;
4851 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004852 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4853 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004854 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004855
Eli Friedman5358a0a2012-03-03 04:09:56 +00004856 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4857 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4858 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004859 return NestedNameSpecifier::Create(*this, nullptr, false,
4860 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004861 }
4862
4863 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004864 case NestedNameSpecifier::Super:
4865 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004866 return NNS;
4867 }
4868
David Blaikie8a40f702012-01-17 06:56:22 +00004869 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004870}
4871
Jay Foad39c79802011-01-12 09:06:06 +00004872const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004873 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004874 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004875 // Handle the common positive case fast.
4876 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4877 return AT;
4878 }
Mike Stump11289f42009-09-09 15:08:12 +00004879
John McCall8ccfcb52009-09-24 19:53:00 +00004880 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004881 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004882 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004883
John McCall8ccfcb52009-09-24 19:53:00 +00004884 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004885 // implements C99 6.7.3p8: "If the specification of an array type includes
4886 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004887
Chris Lattner7adf0762008-08-04 07:31:14 +00004888 // If we get here, we either have type qualifiers on the type, or we have
4889 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004890 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004891
John McCall33ddac02011-01-19 10:06:00 +00004892 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004893 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004894
Chris Lattner7adf0762008-08-04 07:31:14 +00004895 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004896 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004897 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004898 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004899
Chris Lattner7adf0762008-08-04 07:31:14 +00004900 // Otherwise, we have an array and we have qualifiers on it. Push the
4901 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004902 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004903
Chris Lattner7adf0762008-08-04 07:31:14 +00004904 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4905 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4906 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004907 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004908 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4909 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4910 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004911 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004912
Mike Stump11289f42009-09-09 15:08:12 +00004913 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004914 = dyn_cast<DependentSizedArrayType>(ATy))
4915 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004916 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004917 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004918 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004919 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004920 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004921
Chris Lattner7adf0762008-08-04 07:31:14 +00004922 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004923 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004924 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004925 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004926 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004927 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004928}
4929
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004930QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004931 if (T->isArrayType() || T->isFunctionType())
4932 return getDecayedType(T);
4933 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004934}
4935
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004936QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004937 T = getVariableArrayDecayedType(T);
4938 T = getAdjustedParameterType(T);
4939 return T.getUnqualifiedType();
4940}
4941
David Majnemerd09a51c2015-03-03 01:50:05 +00004942QualType ASTContext::getExceptionObjectType(QualType T) const {
4943 // C++ [except.throw]p3:
4944 // A throw-expression initializes a temporary object, called the exception
4945 // object, the type of which is determined by removing any top-level
4946 // cv-qualifiers from the static type of the operand of throw and adjusting
4947 // the type from "array of T" or "function returning T" to "pointer to T"
4948 // or "pointer to function returning T", [...]
4949 T = getVariableArrayDecayedType(T);
4950 if (T->isArrayType() || T->isFunctionType())
4951 T = getDecayedType(T);
4952 return T.getUnqualifiedType();
4953}
4954
Chris Lattnera21ad802008-04-02 05:18:44 +00004955/// getArrayDecayedType - Return the properly qualified result of decaying the
4956/// specified array type to a pointer. This operation is non-trivial when
4957/// handling typedefs etc. The canonical type of "T" must be an array type,
4958/// this returns a pointer to a properly qualified element of the array.
4959///
4960/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004961QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004962 // Get the element type with 'getAsArrayType' so that we don't lose any
4963 // typedefs in the element type of the array. This also handles propagation
4964 // of type qualifiers from the array type into the element type if present
4965 // (C99 6.7.3p8).
4966 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4967 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004968
Chris Lattner7adf0762008-08-04 07:31:14 +00004969 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004970
4971 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00004972 QualType Result = getQualifiedType(PtrTy,
4973 PrettyArrayType->getIndexTypeQualifiers());
4974
4975 // int x[_Nullable] -> int * _Nullable
4976 if (auto Nullability = Ty->getNullability(*this)) {
4977 Result = const_cast<ASTContext *>(this)->getAttributedType(
4978 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
4979 }
4980 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00004981}
4982
John McCall33ddac02011-01-19 10:06:00 +00004983QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4984 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004985}
4986
John McCall33ddac02011-01-19 10:06:00 +00004987QualType ASTContext::getBaseElementType(QualType type) const {
4988 Qualifiers qs;
4989 while (true) {
4990 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004991 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004992 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004993
John McCall33ddac02011-01-19 10:06:00 +00004994 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004995 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004996 }
Mike Stump11289f42009-09-09 15:08:12 +00004997
John McCall33ddac02011-01-19 10:06:00 +00004998 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004999}
5000
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005001/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005002uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005003ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5004 uint64_t ElementCount = 1;
5005 do {
5006 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005007 CA = dyn_cast_or_null<ConstantArrayType>(
5008 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005009 } while (CA);
5010 return ElementCount;
5011}
5012
Steve Naroff0af91202007-04-27 21:51:21 +00005013/// getFloatingRank - Return a relative rank for floating point types.
5014/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005015static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005016 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005017 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005018
John McCall9dd450b2009-09-21 23:43:11 +00005019 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5020 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005021 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005022 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005023 case BuiltinType::Float: return FloatRank;
5024 case BuiltinType::Double: return DoubleRank;
5025 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005026 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005027 }
5028}
5029
Mike Stump11289f42009-09-09 15:08:12 +00005030/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5031/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005032/// 'typeDomain' is a real floating point or complex type.
5033/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005034QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5035 QualType Domain) const {
5036 FloatingRank EltRank = getFloatingRank(Size);
5037 if (Domain->isComplexType()) {
5038 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005039 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005040 case FloatRank: return FloatComplexTy;
5041 case DoubleRank: return DoubleComplexTy;
5042 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005043 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005044 }
Steve Naroff0af91202007-04-27 21:51:21 +00005045 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005046
5047 assert(Domain->isRealFloatingType() && "Unknown domain!");
5048 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005049 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005050 case FloatRank: return FloatTy;
5051 case DoubleRank: return DoubleTy;
5052 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005053 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005054 }
David Blaikief47fa302012-01-17 02:30:50 +00005055 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005056}
5057
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005058/// getFloatingTypeOrder - Compare the rank of the two specified floating
5059/// point types, ignoring the domain of the type (i.e. 'double' ==
5060/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005061/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005062int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005063 FloatingRank LHSR = getFloatingRank(LHS);
5064 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005065
Chris Lattnerb90739d2008-04-06 23:38:49 +00005066 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005067 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005068 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005069 return 1;
5070 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005071}
5072
Chris Lattner76a00cf2008-04-06 22:59:24 +00005073/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5074/// routine will assert if passed a built-in type that isn't an integer or enum,
5075/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005076unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005077 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005078
Chris Lattner76a00cf2008-04-06 22:59:24 +00005079 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005080 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005081 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005082 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005083 case BuiltinType::Char_S:
5084 case BuiltinType::Char_U:
5085 case BuiltinType::SChar:
5086 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005087 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005088 case BuiltinType::Short:
5089 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005090 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005091 case BuiltinType::Int:
5092 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005093 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005094 case BuiltinType::Long:
5095 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005096 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005097 case BuiltinType::LongLong:
5098 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005099 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005100 case BuiltinType::Int128:
5101 case BuiltinType::UInt128:
5102 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005103 }
5104}
5105
Eli Friedman629ffb92009-08-20 04:21:42 +00005106/// \brief Whether this is a promotable bitfield reference according
5107/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5108///
5109/// \returns the type this bit-field will promote to, or NULL if no
5110/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005111QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005112 if (E->isTypeDependent() || E->isValueDependent())
5113 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005114
5115 // FIXME: We should not do this unless E->refersToBitField() is true. This
5116 // matters in C where getSourceBitField() will find bit-fields for various
5117 // cases where the source expression is not a bit-field designator.
5118
John McCalld25db7e2013-05-06 21:39:12 +00005119 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005120 if (!Field)
5121 return QualType();
5122
5123 QualType FT = Field->getType();
5124
Richard Smithcaf33902011-10-10 18:28:20 +00005125 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005126 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005127 // C++ [conv.prom]p5:
5128 // A prvalue for an integral bit-field can be converted to a prvalue of type
5129 // int if int can represent all the values of the bit-field; otherwise, it
5130 // can be converted to unsigned int if unsigned int can represent all the
5131 // values of the bit-field. If the bit-field is larger yet, no integral
5132 // promotion applies to it.
5133 // C11 6.3.1.1/2:
5134 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5135 // If an int can represent all values of the original type (as restricted by
5136 // the width, for a bit-field), the value is converted to an int; otherwise,
5137 // it is converted to an unsigned int.
5138 //
5139 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5140 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005141 if (BitWidth < IntSize)
5142 return IntTy;
5143
5144 if (BitWidth == IntSize)
5145 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5146
5147 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005148 // like the base type. GCC has some weird bugs in this area that we
5149 // deliberately do not follow (GCC follows a pre-standard resolution to
5150 // C's DR315 which treats bit-width as being part of the type, and this leaks
5151 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005152 return QualType();
5153}
5154
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005155/// getPromotedIntegerType - Returns the type that Promotable will
5156/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5157/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005158QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005159 assert(!Promotable.isNull());
5160 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005161 if (const EnumType *ET = Promotable->getAs<EnumType>())
5162 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005163
5164 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5165 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5166 // (3.9.1) can be converted to a prvalue of the first of the following
5167 // types that can represent all the values of its underlying type:
5168 // int, unsigned int, long int, unsigned long int, long long int, or
5169 // unsigned long long int [...]
5170 // FIXME: Is there some better way to compute this?
5171 if (BT->getKind() == BuiltinType::WChar_S ||
5172 BT->getKind() == BuiltinType::WChar_U ||
5173 BT->getKind() == BuiltinType::Char16 ||
5174 BT->getKind() == BuiltinType::Char32) {
5175 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5176 uint64_t FromSize = getTypeSize(BT);
5177 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5178 LongLongTy, UnsignedLongLongTy };
5179 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5180 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5181 if (FromSize < ToSize ||
5182 (FromSize == ToSize &&
5183 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5184 return PromoteTypes[Idx];
5185 }
5186 llvm_unreachable("char type should fit into long long");
5187 }
5188 }
5189
5190 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005191 if (Promotable->isSignedIntegerType())
5192 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005193 uint64_t PromotableSize = getIntWidth(Promotable);
5194 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005195 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5196 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5197}
5198
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005199/// \brief Recurses in pointer/array types until it finds an objc retainable
5200/// type and returns its ownership.
5201Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5202 while (!T.isNull()) {
5203 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5204 return T.getObjCLifetime();
5205 if (T->isArrayType())
5206 T = getBaseElementType(T);
5207 else if (const PointerType *PT = T->getAs<PointerType>())
5208 T = PT->getPointeeType();
5209 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005210 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005211 else
5212 break;
5213 }
5214
5215 return Qualifiers::OCL_None;
5216}
5217
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005218static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5219 // Incomplete enum types are not treated as integer types.
5220 // FIXME: In C++, enum types are never integer types.
5221 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5222 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005223 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005224}
5225
Mike Stump11289f42009-09-09 15:08:12 +00005226/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005227/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005228/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005229int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005230 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5231 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005232
5233 // Unwrap enums to their underlying type.
5234 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5235 LHSC = getIntegerTypeForEnum(ET);
5236 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5237 RHSC = getIntegerTypeForEnum(ET);
5238
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005239 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005240
Chris Lattner76a00cf2008-04-06 22:59:24 +00005241 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5242 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005243
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005244 unsigned LHSRank = getIntegerRank(LHSC);
5245 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005246
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005247 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5248 if (LHSRank == RHSRank) return 0;
5249 return LHSRank > RHSRank ? 1 : -1;
5250 }
Mike Stump11289f42009-09-09 15:08:12 +00005251
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005252 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5253 if (LHSUnsigned) {
5254 // If the unsigned [LHS] type is larger, return it.
5255 if (LHSRank >= RHSRank)
5256 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005257
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005258 // If the signed type can represent all values of the unsigned type, it
5259 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005260 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005261 return -1;
5262 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005263
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005264 // If the unsigned [RHS] type is larger, return it.
5265 if (RHSRank >= LHSRank)
5266 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005267
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005268 // If the signed type can represent all values of the unsigned type, it
5269 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005270 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005271 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005272}
Anders Carlsson98f07902007-08-17 05:31:46 +00005273
Ben Langmuirf5416742016-02-04 00:55:24 +00005274TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005275 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005276 assert(!CFConstantStringTagDecl &&
5277 "tag and typedef should be initialized together");
5278 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5279 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005280
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005281 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005282 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005283
Anders Carlsson98f07902007-08-17 05:31:46 +00005284 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005285 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005286 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005287 // int flags;
5288 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005289 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005290 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005291 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005292 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005293 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005294 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005295 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005296
Anders Carlsson98f07902007-08-17 05:31:46 +00005297 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005298 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005299 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005300 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005301 SourceLocation(),
5302 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005303 FieldTypes[i], /*TInfo=*/nullptr,
5304 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005305 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005306 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005307 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005308 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005309 }
5310
Ben Langmuirf5416742016-02-04 00:55:24 +00005311 CFConstantStringTagDecl->completeDefinition();
5312 // This type is designed to be compatible with NSConstantString, but cannot
5313 // use the same name, since NSConstantString is an interface.
5314 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5315 CFConstantStringTypeDecl =
5316 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
Quentin Colombet043406b2016-02-03 22:41:00 +00005319 return CFConstantStringTypeDecl;
5320}
5321
Ben Langmuirf5416742016-02-04 00:55:24 +00005322RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5323 if (!CFConstantStringTagDecl)
5324 getCFConstantStringDecl(); // Build the tag and the typedef.
5325 return CFConstantStringTagDecl;
5326}
5327
Quentin Colombet043406b2016-02-03 22:41:00 +00005328// getCFConstantStringType - Return the type used for constant CFStrings.
5329QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005330 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005331}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005332
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005333QualType ASTContext::getObjCSuperType() const {
5334 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005335 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005336 TUDecl->addDecl(ObjCSuperTypeDecl);
5337 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5338 }
5339 return ObjCSuperType;
5340}
5341
Douglas Gregor512b0772009-04-23 22:29:11 +00005342void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005343 const TypedefType *TD = T->getAs<TypedefType>();
5344 assert(TD && "Invalid CFConstantStringType");
5345 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5346 auto TagType =
5347 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5348 assert(TagType && "Invalid CFConstantStringType");
5349 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005350}
5351
Jay Foad39c79802011-01-12 09:06:06 +00005352QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005353 if (BlockDescriptorType)
5354 return getTagDeclType(BlockDescriptorType);
5355
Alp Toker2dea15b2013-12-17 01:22:38 +00005356 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005357 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005358 RD = buildImplicitRecord("__block_descriptor");
5359 RD->startDefinition();
5360
Mike Stumpd0153282009-10-20 02:12:22 +00005361 QualType FieldTypes[] = {
5362 UnsignedLongTy,
5363 UnsignedLongTy,
5364 };
5365
Craig Topperd6d31ac2013-07-15 08:24:27 +00005366 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005367 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005368 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005369 };
5370
5371 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005372 FieldDecl *Field = FieldDecl::Create(
5373 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005374 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5375 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005376 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005377 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005378 }
5379
Alp Toker2dea15b2013-12-17 01:22:38 +00005380 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005381
Alp Toker2dea15b2013-12-17 01:22:38 +00005382 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005383
5384 return getTagDeclType(BlockDescriptorType);
5385}
5386
Jay Foad39c79802011-01-12 09:06:06 +00005387QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005388 if (BlockDescriptorExtendedType)
5389 return getTagDeclType(BlockDescriptorExtendedType);
5390
Alp Toker2dea15b2013-12-17 01:22:38 +00005391 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005392 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005393 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5394 RD->startDefinition();
5395
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005396 QualType FieldTypes[] = {
5397 UnsignedLongTy,
5398 UnsignedLongTy,
5399 getPointerType(VoidPtrTy),
5400 getPointerType(VoidPtrTy)
5401 };
5402
Craig Topperd6d31ac2013-07-15 08:24:27 +00005403 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005404 "reserved",
5405 "Size",
5406 "CopyFuncPtr",
5407 "DestroyFuncPtr"
5408 };
5409
5410 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005411 FieldDecl *Field = FieldDecl::Create(
5412 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005413 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5414 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005415 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005416 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005417 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005418 }
5419
Alp Toker2dea15b2013-12-17 01:22:38 +00005420 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005421
Alp Toker2dea15b2013-12-17 01:22:38 +00005422 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005423 return getTagDeclType(BlockDescriptorExtendedType);
5424}
5425
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005426/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5427/// requires copy/dispose. Note that this must match the logic
5428/// in buildByrefHelpers.
5429bool ASTContext::BlockRequiresCopying(QualType Ty,
5430 const VarDecl *D) {
5431 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5432 const Expr *copyExpr = getBlockVarCopyInits(D);
5433 if (!copyExpr && record->hasTrivialDestructor()) return false;
5434
Mike Stump94967902009-10-21 18:16:27 +00005435 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005436 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005437
5438 if (!Ty->isObjCRetainableType()) return false;
5439
5440 Qualifiers qs = Ty.getQualifiers();
5441
5442 // If we have lifetime, that dominates.
5443 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005444 switch (lifetime) {
5445 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5446
5447 // These are just bits as far as the runtime is concerned.
5448 case Qualifiers::OCL_ExplicitNone:
5449 case Qualifiers::OCL_Autoreleasing:
5450 return false;
5451
5452 // Tell the runtime that this is ARC __weak, called by the
5453 // byref routines.
5454 case Qualifiers::OCL_Weak:
5455 // ARC __strong __block variables need to be retained.
5456 case Qualifiers::OCL_Strong:
5457 return true;
5458 }
5459 llvm_unreachable("fell out of lifetime switch!");
5460 }
5461 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5462 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005463}
5464
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005465bool ASTContext::getByrefLifetime(QualType Ty,
5466 Qualifiers::ObjCLifetime &LifeTime,
5467 bool &HasByrefExtendedLayout) const {
5468
5469 if (!getLangOpts().ObjC1 ||
5470 getLangOpts().getGC() != LangOptions::NonGC)
5471 return false;
5472
5473 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005474 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005475 HasByrefExtendedLayout = true;
5476 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005477 } else if ((LifeTime = Ty.getObjCLifetime())) {
5478 // Honor the ARC qualifiers.
5479 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5480 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005481 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005482 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005483 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005484 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005485 return true;
5486}
5487
Douglas Gregorbab8a962011-09-08 01:46:34 +00005488TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5489 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005490 ObjCInstanceTypeDecl =
5491 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005492 return ObjCInstanceTypeDecl;
5493}
5494
Anders Carlsson18acd442007-10-29 06:33:42 +00005495// This returns true if a type has been typedefed to BOOL:
5496// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005497static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005498 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005499 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5500 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005501
Anders Carlssond8499822007-10-29 05:01:08 +00005502 return false;
5503}
5504
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005505/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005506/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005507CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005508 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5509 return CharUnits::Zero();
5510
Ken Dyck40775002010-01-11 17:06:35 +00005511 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005512
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005513 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005514 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005515 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005516 // Treat arrays as pointers, since that's how they're passed in.
5517 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005518 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005519 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005520}
5521
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005522bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005523 return getTargetInfo().getCXXABI().isMicrosoft() &&
5524 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005525 VD->getType()->isIntegralOrEnumerationType() &&
5526 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005527}
5528
Richard Smithd9b90092016-07-02 01:32:16 +00005529ASTContext::InlineVariableDefinitionKind
5530ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5531 if (!VD->isInline())
5532 return InlineVariableDefinitionKind::None;
5533
5534 // In almost all cases, it's a weak definition.
5535 auto *First = VD->getFirstDecl();
5536 if (!First->isConstexpr() || First->isInlineSpecified() ||
5537 !VD->isStaticDataMember())
5538 return InlineVariableDefinitionKind::Weak;
5539
5540 // If there's a file-context declaration in this translation unit, it's a
5541 // non-discardable definition.
5542 for (auto *D : VD->redecls())
5543 if (D->getLexicalDeclContext()->isFileContext())
5544 return InlineVariableDefinitionKind::Strong;
5545
5546 // If we've not seen one yet, we don't know.
5547 return InlineVariableDefinitionKind::WeakUnknown;
5548}
5549
Ken Dyck40775002010-01-11 17:06:35 +00005550static inline
5551std::string charUnitsToString(const CharUnits &CU) {
5552 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005553}
5554
John McCall351762c2011-02-07 10:33:21 +00005555/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005556/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005557std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5558 std::string S;
5559
David Chisnall950a9512009-11-17 19:33:30 +00005560 const BlockDecl *Decl = Expr->getBlockDecl();
5561 QualType BlockTy =
5562 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5563 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005564 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005565 getObjCEncodingForMethodParameter(
5566 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5567 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005568 else
Alp Toker314cc812014-01-25 16:55:45 +00005569 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005570 // Compute size of all parameters.
5571 // Start with computing size of a pointer in number of bytes.
5572 // FIXME: There might(should) be a better way of doing this computation!
5573 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005574 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5575 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005576 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005577 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005578 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005579 if (sz.isZero())
5580 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005581 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005582 ParmOffset += sz;
5583 }
5584 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005585 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005586 // Block pointer and offset.
5587 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005588
5589 // Argument types.
5590 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005591 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005592 QualType PType = PVDecl->getOriginalType();
5593 if (const ArrayType *AT =
5594 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5595 // Use array's original type only if it has known number of
5596 // elements.
5597 if (!isa<ConstantArrayType>(AT))
5598 PType = PVDecl->getType();
5599 } else if (PType->isFunctionType())
5600 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005601 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005602 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5603 S, true /*Extended*/);
5604 else
5605 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005606 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005607 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005608 }
John McCall351762c2011-02-07 10:33:21 +00005609
5610 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005611}
5612
John McCall843dfcc2016-11-29 21:57:00 +00005613std::string
5614ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5615 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005616 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005617 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005618 CharUnits ParmOffset;
5619 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005620 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005621 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005622 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005623 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005624 continue;
5625
John McCall843dfcc2016-11-29 21:57:00 +00005626 assert(sz.isPositive() &&
5627 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005628 ParmOffset += sz;
5629 }
5630 S += charUnitsToString(ParmOffset);
5631 ParmOffset = CharUnits::Zero();
5632
5633 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005634 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005635 QualType PType = PVDecl->getOriginalType();
5636 if (const ArrayType *AT =
5637 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5638 // Use array's original type only if it has known number of
5639 // elements.
5640 if (!isa<ConstantArrayType>(AT))
5641 PType = PVDecl->getType();
5642 } else if (PType->isFunctionType())
5643 PType = PVDecl->getType();
5644 getObjCEncodingForType(PType, S);
5645 S += charUnitsToString(ParmOffset);
5646 ParmOffset += getObjCEncodingTypeSize(PType);
5647 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005648
John McCall843dfcc2016-11-29 21:57:00 +00005649 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005650}
5651
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005652/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5653/// method parameter or return type. If Extended, include class names and
5654/// block object types.
5655void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5656 QualType T, std::string& S,
5657 bool Extended) const {
5658 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5659 getObjCEncodingForTypeQualifier(QT, S);
5660 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005661 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005662 true /*OutermostType*/,
5663 false /*EncodingProperty*/,
5664 false /*StructField*/,
5665 Extended /*EncodeBlockParameters*/,
5666 Extended /*EncodeClassNames*/);
5667}
5668
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005669/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005670/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005671std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5672 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005673 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005674 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005675 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005676 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5677 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005678 // Compute size of all parameters.
5679 // Start with computing size of a pointer in number of bytes.
5680 // FIXME: There might(should) be a better way of doing this computation!
5681 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005682 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005683 // The first two arguments (self and _cmd) are pointers; account for
5684 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005685 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005686 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005687 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005688 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005689 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005690 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005691 continue;
5692
Ken Dyck40775002010-01-11 17:06:35 +00005693 assert (sz.isPositive() &&
5694 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005695 ParmOffset += sz;
5696 }
Ken Dyck40775002010-01-11 17:06:35 +00005697 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005698 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005699 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005700
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005701 // Argument types.
5702 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005703 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005704 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005705 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005706 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005707 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005708 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5709 // Use array's original type only if it has known number of
5710 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005711 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005712 PType = PVDecl->getType();
5713 } else if (PType->isFunctionType())
5714 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005715 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5716 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005717 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005718 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005719 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005720
John McCall843dfcc2016-11-29 21:57:00 +00005721 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005722}
5723
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005724ObjCPropertyImplDecl *
5725ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5726 const ObjCPropertyDecl *PD,
5727 const Decl *Container) const {
5728 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005729 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005730 if (const ObjCCategoryImplDecl *CID =
5731 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005732 for (auto *PID : CID->property_impls())
5733 if (PID->getPropertyDecl() == PD)
5734 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005735 } else {
5736 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5737 for (auto *PID : OID->property_impls())
5738 if (PID->getPropertyDecl() == PD)
5739 return PID;
5740 }
5741 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005742}
5743
Daniel Dunbar4932b362008-08-28 04:38:10 +00005744/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005745/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005746/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5747/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005748/// Property attributes are stored as a comma-delimited C string. The simple
5749/// attributes readonly and bycopy are encoded as single characters. The
5750/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5751/// encoded as single characters, followed by an identifier. Property types
5752/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005753/// these attributes are defined by the following enumeration:
5754/// @code
5755/// enum PropertyAttributes {
5756/// kPropertyReadOnly = 'R', // property is read-only.
5757/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5758/// kPropertyByref = '&', // property is a reference to the value last assigned
5759/// kPropertyDynamic = 'D', // property is dynamic
5760/// kPropertyGetter = 'G', // followed by getter selector name
5761/// kPropertySetter = 'S', // followed by setter selector name
5762/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005763/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005764/// kPropertyWeak = 'W' // 'weak' property
5765/// kPropertyStrong = 'P' // property GC'able
5766/// kPropertyNonAtomic = 'N' // property non-atomic
5767/// };
5768/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005769std::string
5770ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5771 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005772 // Collect information from the property implementation decl(s).
5773 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005774 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005775
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005776 if (ObjCPropertyImplDecl *PropertyImpDecl =
5777 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5778 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5779 Dynamic = true;
5780 else
5781 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005782 }
5783
5784 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005785 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005786
5787 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005788 // GCC has some special rules regarding encoding of properties which
5789 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005790 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005791
5792 if (PD->isReadOnly()) {
5793 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005794 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5795 S += ",C";
5796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5797 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005798 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5799 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005800 } else {
5801 switch (PD->getSetterKind()) {
5802 case ObjCPropertyDecl::Assign: break;
5803 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005804 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005805 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005806 }
5807 }
5808
5809 // It really isn't clear at all what this means, since properties
5810 // are "dynamic by default".
5811 if (Dynamic)
5812 S += ",D";
5813
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005814 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5815 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005816
Daniel Dunbar4932b362008-08-28 04:38:10 +00005817 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5818 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005819 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005820 }
5821
5822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5823 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005824 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005825 }
5826
5827 if (SynthesizePID) {
5828 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5829 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005830 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005831 }
5832
5833 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005834 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005835}
5836
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005837/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005838/// Another legacy compatibility encoding: 32-bit longs are encoded as
5839/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005840/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5841///
5842void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005843 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005844 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005845 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005846 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005847 else
Jay Foad39c79802011-01-12 09:06:06 +00005848 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005849 PointeeTy = IntTy;
5850 }
5851 }
5852}
5853
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005854void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005855 const FieldDecl *Field,
5856 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005857 // We follow the behavior of gcc, expanding structures which are
5858 // directly pointed to, and expanding embedded structures. Note that
5859 // these rules are sufficient to prevent recursive encoding of the
5860 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005861 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005862 true /* outermost type */, false, false,
5863 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005864}
5865
Joe Groff98ac7d22014-07-07 22:25:15 +00005866void ASTContext::getObjCEncodingForPropertyType(QualType T,
5867 std::string& S) const {
5868 // Encode result type.
5869 // GCC has some special rules regarding encoding of properties which
5870 // closely resembles encoding of ivars.
5871 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5872 true /* outermost type */,
5873 true /* encoding property */);
5874}
5875
John McCall393a78d2012-12-20 02:45:14 +00005876static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5877 BuiltinType::Kind kind) {
5878 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005879 case BuiltinType::Void: return 'v';
5880 case BuiltinType::Bool: return 'B';
5881 case BuiltinType::Char_U:
5882 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005883 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005884 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005885 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005886 case BuiltinType::UInt: return 'I';
5887 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005888 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005889 case BuiltinType::UInt128: return 'T';
5890 case BuiltinType::ULongLong: return 'Q';
5891 case BuiltinType::Char_S:
5892 case BuiltinType::SChar: return 'c';
5893 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005894 case BuiltinType::WChar_S:
5895 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005896 case BuiltinType::Int: return 'i';
5897 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005898 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005899 case BuiltinType::LongLong: return 'q';
5900 case BuiltinType::Int128: return 't';
5901 case BuiltinType::Float: return 'f';
5902 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005903 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005904 case BuiltinType::NullPtr: return '*'; // like char*
5905
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005906 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005907 case BuiltinType::Half:
5908 // FIXME: potentially need @encodes for these!
5909 return ' ';
5910
5911 case BuiltinType::ObjCId:
5912 case BuiltinType::ObjCClass:
5913 case BuiltinType::ObjCSel:
5914 llvm_unreachable("@encoding ObjC primitive type");
5915
5916 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005917#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5918 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005919#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005920 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005921 case BuiltinType::OCLClkEvent:
5922 case BuiltinType::OCLQueue:
5923 case BuiltinType::OCLNDRange:
5924 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005925 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005926 case BuiltinType::Dependent:
5927#define BUILTIN_TYPE(KIND, ID)
5928#define PLACEHOLDER_TYPE(KIND, ID) \
5929 case BuiltinType::KIND:
5930#include "clang/AST/BuiltinTypes.def"
5931 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005932 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005933 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005934}
5935
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005936static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5937 EnumDecl *Enum = ET->getDecl();
5938
5939 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5940 if (!Enum->isFixed())
5941 return 'i';
5942
5943 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005944 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5945 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005946}
5947
Jay Foad39c79802011-01-12 09:06:06 +00005948static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005949 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005950 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005951 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005952 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5953 // The GNU runtime requires more information; bitfields are encoded as b,
5954 // then the offset (in bits) of the first element, then the type of the
5955 // bitfield, then the size in bits. For example, in this structure:
5956 //
5957 // struct
5958 // {
5959 // int integer;
5960 // int flags:2;
5961 // };
5962 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5963 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5964 // information is not especially sensible, but we're stuck with it for
5965 // compatibility with GCC, although providing it breaks anything that
5966 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005967 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005968 const RecordDecl *RD = FD->getParent();
5969 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005970 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005971 if (const EnumType *ET = T->getAs<EnumType>())
5972 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005973 else {
5974 const BuiltinType *BT = T->castAs<BuiltinType>();
5975 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5976 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005977 }
Richard Smithcaf33902011-10-10 18:28:20 +00005978 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005979}
5980
Daniel Dunbar07d07852009-10-18 21:17:35 +00005981// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005982void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5983 bool ExpandPointedToStructures,
5984 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005985 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005986 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005987 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005988 bool StructField,
5989 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005990 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005991 bool EncodePointerToObjCTypedef,
5992 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005993 CanQualType CT = getCanonicalType(T);
5994 switch (CT->getTypeClass()) {
5995 case Type::Builtin:
5996 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005997 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005998 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005999 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6000 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6001 else
6002 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006003 return;
Mike Stump11289f42009-09-09 15:08:12 +00006004
John McCall393a78d2012-12-20 02:45:14 +00006005 case Type::Complex: {
6006 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006007 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006008 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006009 return;
6010 }
John McCall393a78d2012-12-20 02:45:14 +00006011
6012 case Type::Atomic: {
6013 const AtomicType *AT = T->castAs<AtomicType>();
6014 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006015 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006016 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006017 }
John McCall393a78d2012-12-20 02:45:14 +00006018
6019 // encoding for pointer or reference types.
6020 case Type::Pointer:
6021 case Type::LValueReference:
6022 case Type::RValueReference: {
6023 QualType PointeeTy;
6024 if (isa<PointerType>(CT)) {
6025 const PointerType *PT = T->castAs<PointerType>();
6026 if (PT->isObjCSelType()) {
6027 S += ':';
6028 return;
6029 }
6030 PointeeTy = PT->getPointeeType();
6031 } else {
6032 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6033 }
6034
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006035 bool isReadOnly = false;
6036 // For historical/compatibility reasons, the read-only qualifier of the
6037 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6038 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006039 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006040 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006041 if (OutermostType && T.isConstQualified()) {
6042 isReadOnly = true;
6043 S += 'r';
6044 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006045 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006046 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006047 while (P->getAs<PointerType>())
6048 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006049 if (P.isConstQualified()) {
6050 isReadOnly = true;
6051 S += 'r';
6052 }
6053 }
6054 if (isReadOnly) {
6055 // Another legacy compatibility encoding. Some ObjC qualifier and type
6056 // combinations need to be rearranged.
6057 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006058 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006059 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006060 }
Mike Stump11289f42009-09-09 15:08:12 +00006061
Anders Carlssond8499822007-10-29 05:01:08 +00006062 if (PointeeTy->isCharType()) {
6063 // char pointer types should be encoded as '*' unless it is a
6064 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006065 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006066 S += '*';
6067 return;
6068 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006069 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006070 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6071 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6072 S += '#';
6073 return;
6074 }
6075 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6076 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6077 S += '@';
6078 return;
6079 }
6080 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006081 }
Anders Carlssond8499822007-10-29 05:01:08 +00006082 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006083 getLegacyIntegralTypeEncoding(PointeeTy);
6084
Mike Stump11289f42009-09-09 15:08:12 +00006085 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006086 nullptr, false, false, false, false, false, false,
6087 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006088 return;
6089 }
John McCall393a78d2012-12-20 02:45:14 +00006090
6091 case Type::ConstantArray:
6092 case Type::IncompleteArray:
6093 case Type::VariableArray: {
6094 const ArrayType *AT = cast<ArrayType>(CT);
6095
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006096 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006097 // Incomplete arrays are encoded as a pointer to the array element.
6098 S += '^';
6099
Mike Stump11289f42009-09-09 15:08:12 +00006100 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006101 false, ExpandStructures, FD);
6102 } else {
6103 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006104
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006105 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6106 S += llvm::utostr(CAT->getSize().getZExtValue());
6107 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006108 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006109 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6110 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006111 S += '0';
6112 }
Mike Stump11289f42009-09-09 15:08:12 +00006113
6114 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006115 false, ExpandStructures, FD,
6116 false, false, false, false, false, false,
6117 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006118 S += ']';
6119 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006120 return;
6121 }
Mike Stump11289f42009-09-09 15:08:12 +00006122
John McCall393a78d2012-12-20 02:45:14 +00006123 case Type::FunctionNoProto:
6124 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006125 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006126 return;
Mike Stump11289f42009-09-09 15:08:12 +00006127
John McCall393a78d2012-12-20 02:45:14 +00006128 case Type::Record: {
6129 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006130 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006131 // Anonymous structures print as '?'
6132 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6133 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006134 if (ClassTemplateSpecializationDecl *Spec
6135 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6136 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006137 llvm::raw_string_ostream OS(S);
6138 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006139 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006140 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006141 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006142 } else {
6143 S += '?';
6144 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006145 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006146 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006147 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006148 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006149 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006150 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006151 if (FD) {
6152 S += '"';
6153 S += Field->getNameAsString();
6154 S += '"';
6155 }
Mike Stump11289f42009-09-09 15:08:12 +00006156
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006157 // Special case bit-fields.
6158 if (Field->isBitField()) {
6159 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006160 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006161 } else {
6162 QualType qt = Field->getType();
6163 getLegacyIntegralTypeEncoding(qt);
6164 getObjCEncodingForTypeImpl(qt, S, false, true,
6165 FD, /*OutermostType*/false,
6166 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006167 /*StructField*/true,
6168 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006169 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006170 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006171 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006172 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006173 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006174 return;
6175 }
Mike Stump11289f42009-09-09 15:08:12 +00006176
John McCall393a78d2012-12-20 02:45:14 +00006177 case Type::BlockPointer: {
6178 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006179 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006180 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006181 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006182
6183 S += '<';
6184 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006185 getObjCEncodingForTypeImpl(
6186 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6187 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006188 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6189 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006190 // Block self
6191 S += "@?";
6192 // Block parameters
6193 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006194 for (const auto &I : FPT->param_types())
6195 getObjCEncodingForTypeImpl(
6196 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6197 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006198 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6199 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006200 }
6201 S += '>';
6202 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006203 return;
6204 }
Mike Stump11289f42009-09-09 15:08:12 +00006205
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006206 case Type::ObjCObject: {
6207 // hack to match legacy encoding of *id and *Class
6208 QualType Ty = getObjCObjectPointerType(CT);
6209 if (Ty->isObjCIdType()) {
6210 S += "{objc_object=}";
6211 return;
6212 }
6213 else if (Ty->isObjCClassType()) {
6214 S += "{objc_class=}";
6215 return;
6216 }
6217 }
6218
John McCall393a78d2012-12-20 02:45:14 +00006219 case Type::ObjCInterface: {
6220 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006221 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006222 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006223 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006224 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006225 if (ExpandStructures) {
6226 S += '=';
6227 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6228 DeepCollectObjCIvars(OI, true, Ivars);
6229 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6230 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6231 if (Field->isBitField())
6232 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6233 else
6234 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6235 false, false, false, false, false,
6236 EncodePointerToObjCTypedef,
6237 NotEncodedT);
6238 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006239 }
6240 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006241 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006242 }
Mike Stump11289f42009-09-09 15:08:12 +00006243
John McCall393a78d2012-12-20 02:45:14 +00006244 case Type::ObjCObjectPointer: {
6245 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006246 if (OPT->isObjCIdType()) {
6247 S += '@';
6248 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006249 }
Mike Stump11289f42009-09-09 15:08:12 +00006250
Steve Narofff0c86112009-10-28 22:03:49 +00006251 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6252 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6253 // Since this is a binary compatibility issue, need to consult with runtime
6254 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006255 S += '#';
6256 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006257 }
Mike Stump11289f42009-09-09 15:08:12 +00006258
Chris Lattnere7cabb92009-07-13 00:10:46 +00006259 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006260 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006261 ExpandPointedToStructures,
6262 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006263 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006264 // Note that we do extended encoding of protocol qualifer list
6265 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006266 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006267 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006268 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006269 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006270 S += '>';
6271 }
6272 S += '"';
6273 }
6274 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006275 }
Mike Stump11289f42009-09-09 15:08:12 +00006276
Chris Lattnere7cabb92009-07-13 00:10:46 +00006277 QualType PointeeTy = OPT->getPointeeType();
6278 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006279 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6280 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006281 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006282 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006283 // {...};
6284 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006285 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006286 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006287 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6288 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6289 DeepCollectObjCIvars(OI, true, Ivars);
6290 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6291 if (cast<FieldDecl>(Ivars[i]) == FD) {
6292 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006293 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006294 S += '}';
6295 return;
6296 }
6297 }
6298 }
Mike Stump11289f42009-09-09 15:08:12 +00006299 getObjCEncodingForTypeImpl(PointeeTy, S,
6300 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006301 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006302 false, false, false, false, false,
6303 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006304 return;
6305 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006306
6307 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006308 if (OPT->getInterfaceDecl() &&
6309 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006310 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006311 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006312 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006313 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006314 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006315 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006316 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006317 S += '"';
6318 }
6319 return;
6320 }
Mike Stump11289f42009-09-09 15:08:12 +00006321
John McCalla9e6e8d2010-05-17 23:56:34 +00006322 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006323 // FIXME: we shoul do better than that. 'M' is available.
6324 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006325 // This matches gcc's encoding, even though technically it is insufficient.
6326 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006327 case Type::Vector:
6328 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006329 // Until we have a coherent encoding of these three types, issue warning.
6330 { if (NotEncodedT)
6331 *NotEncodedT = T;
6332 return;
6333 }
6334
6335 // We could see an undeduced auto type here during error recovery.
6336 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006337 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006338 return;
6339
Xiuli Pan9c14e282016-01-09 12:53:17 +00006340 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006341#define ABSTRACT_TYPE(KIND, BASE)
6342#define TYPE(KIND, BASE)
6343#define DEPENDENT_TYPE(KIND, BASE) \
6344 case Type::KIND:
6345#define NON_CANONICAL_TYPE(KIND, BASE) \
6346 case Type::KIND:
6347#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6348 case Type::KIND:
6349#include "clang/AST/TypeNodes.def"
6350 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006351 }
John McCall393a78d2012-12-20 02:45:14 +00006352 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006353}
6354
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006355void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6356 std::string &S,
6357 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006358 bool includeVBases,
6359 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006360 assert(RDecl && "Expected non-null RecordDecl");
6361 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006362 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006363 return;
6364
6365 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6366 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6367 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6368
6369 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006370 for (const auto &BI : CXXRec->bases()) {
6371 if (!BI.isVirtual()) {
6372 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006373 if (base->isEmpty())
6374 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006375 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006376 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6377 std::make_pair(offs, base));
6378 }
6379 }
6380 }
6381
6382 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006383 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006384 uint64_t offs = layout.getFieldOffset(i);
6385 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006386 std::make_pair(offs, Field));
6387 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006388 }
6389
6390 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006391 for (const auto &BI : CXXRec->vbases()) {
6392 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006393 if (base->isEmpty())
6394 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006395 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006396 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6397 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006398 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6399 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006400 }
6401 }
6402
6403 CharUnits size;
6404 if (CXXRec) {
6405 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6406 } else {
6407 size = layout.getSize();
6408 }
6409
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006410#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006411 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006412#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006413 std::multimap<uint64_t, NamedDecl *>::iterator
6414 CurLayObj = FieldOrBaseOffsets.begin();
6415
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006416 if (CXXRec && CXXRec->isDynamicClass() &&
6417 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006418 if (FD) {
6419 S += "\"_vptr$";
6420 std::string recname = CXXRec->getNameAsString();
6421 if (recname.empty()) recname = "?";
6422 S += recname;
6423 S += '"';
6424 }
6425 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006426#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006427 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006428#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006429 }
6430
6431 if (!RDecl->hasFlexibleArrayMember()) {
6432 // Mark the end of the structure.
6433 uint64_t offs = toBits(size);
6434 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006435 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006436 }
6437
6438 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006439#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006440 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006441 if (CurOffs < CurLayObj->first) {
6442 uint64_t padding = CurLayObj->first - CurOffs;
6443 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6444 // packing/alignment of members is different that normal, in which case
6445 // the encoding will be out-of-sync with the real layout.
6446 // If the runtime switches to just consider the size of types without
6447 // taking into account alignment, we could make padding explicit in the
6448 // encoding (e.g. using arrays of chars). The encoding strings would be
6449 // longer then though.
6450 CurOffs += padding;
6451 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006452#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006453
6454 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006455 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006456 break; // reached end of structure.
6457
6458 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6459 // We expand the bases without their virtual bases since those are going
6460 // in the initial structure. Note that this differs from gcc which
6461 // expands virtual bases each time one is encountered in the hierarchy,
6462 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006463 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6464 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006465 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006466#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006467 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006468#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006469 } else {
6470 FieldDecl *field = cast<FieldDecl>(dcl);
6471 if (FD) {
6472 S += '"';
6473 S += field->getNameAsString();
6474 S += '"';
6475 }
6476
6477 if (field->isBitField()) {
6478 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006479#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006480 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006481#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006482 } else {
6483 QualType qt = field->getType();
6484 getLegacyIntegralTypeEncoding(qt);
6485 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6486 /*OutermostType*/false,
6487 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006488 /*StructField*/true,
6489 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006490#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006491 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006492#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006493 }
6494 }
6495 }
6496}
6497
Mike Stump11289f42009-09-09 15:08:12 +00006498void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006499 std::string& S) const {
6500 if (QT & Decl::OBJC_TQ_In)
6501 S += 'n';
6502 if (QT & Decl::OBJC_TQ_Inout)
6503 S += 'N';
6504 if (QT & Decl::OBJC_TQ_Out)
6505 S += 'o';
6506 if (QT & Decl::OBJC_TQ_Bycopy)
6507 S += 'O';
6508 if (QT & Decl::OBJC_TQ_Byref)
6509 S += 'R';
6510 if (QT & Decl::OBJC_TQ_Oneway)
6511 S += 'V';
6512}
6513
Douglas Gregor3ea72692011-08-12 05:46:01 +00006514TypedefDecl *ASTContext::getObjCIdDecl() const {
6515 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006516 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006517 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006518 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006519 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006520 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006521}
6522
Douglas Gregor52e02802011-08-12 06:17:30 +00006523TypedefDecl *ASTContext::getObjCSelDecl() const {
6524 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006525 QualType T = getPointerType(ObjCBuiltinSelTy);
6526 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006527 }
6528 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006529}
6530
Douglas Gregor0a586182011-08-12 05:59:41 +00006531TypedefDecl *ASTContext::getObjCClassDecl() const {
6532 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006533 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006534 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006535 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006536 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006537 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006538}
6539
Douglas Gregord53ae832012-01-17 18:09:05 +00006540ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6541 if (!ObjCProtocolClassDecl) {
6542 ObjCProtocolClassDecl
6543 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6544 SourceLocation(),
6545 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006546 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006547 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006548 SourceLocation(), true);
6549 }
6550
6551 return ObjCProtocolClassDecl;
6552}
6553
Meador Inge5d3fb222012-06-16 03:34:49 +00006554//===----------------------------------------------------------------------===//
6555// __builtin_va_list Construction Functions
6556//===----------------------------------------------------------------------===//
6557
Charles Davisc7d5c942015-09-17 20:55:33 +00006558static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6559 StringRef Name) {
6560 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006561 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006562 return Context->buildImplicitTypedef(T, Name);
6563}
6564
6565static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6566 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6567}
6568
6569static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6570 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006571}
6572
6573static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6574 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006575 QualType T = Context->getPointerType(Context->VoidTy);
6576 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006577}
6578
Tim Northover9bb857a2013-01-31 12:13:10 +00006579static TypedefDecl *
6580CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006581 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006582 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006583 if (Context->getLangOpts().CPlusPlus) {
6584 // namespace std { struct __va_list {
6585 NamespaceDecl *NS;
6586 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6587 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006588 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006589 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006590 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006591 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006592 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006593 }
6594
6595 VaListTagDecl->startDefinition();
6596
6597 const size_t NumFields = 5;
6598 QualType FieldTypes[NumFields];
6599 const char *FieldNames[NumFields];
6600
6601 // void *__stack;
6602 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6603 FieldNames[0] = "__stack";
6604
6605 // void *__gr_top;
6606 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6607 FieldNames[1] = "__gr_top";
6608
6609 // void *__vr_top;
6610 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6611 FieldNames[2] = "__vr_top";
6612
6613 // int __gr_offs;
6614 FieldTypes[3] = Context->IntTy;
6615 FieldNames[3] = "__gr_offs";
6616
6617 // int __vr_offs;
6618 FieldTypes[4] = Context->IntTy;
6619 FieldNames[4] = "__vr_offs";
6620
6621 // Create fields
6622 for (unsigned i = 0; i < NumFields; ++i) {
6623 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6624 VaListTagDecl,
6625 SourceLocation(),
6626 SourceLocation(),
6627 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006628 FieldTypes[i], /*TInfo=*/nullptr,
6629 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006630 /*Mutable=*/false,
6631 ICIS_NoInit);
6632 Field->setAccess(AS_public);
6633 VaListTagDecl->addDecl(Field);
6634 }
6635 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006636 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006637 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006638
6639 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006640 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006641}
6642
Meador Inge5d3fb222012-06-16 03:34:49 +00006643static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6644 // typedef struct __va_list_tag {
6645 RecordDecl *VaListTagDecl;
6646
Alp Toker2dea15b2013-12-17 01:22:38 +00006647 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006648 VaListTagDecl->startDefinition();
6649
6650 const size_t NumFields = 5;
6651 QualType FieldTypes[NumFields];
6652 const char *FieldNames[NumFields];
6653
6654 // unsigned char gpr;
6655 FieldTypes[0] = Context->UnsignedCharTy;
6656 FieldNames[0] = "gpr";
6657
6658 // unsigned char fpr;
6659 FieldTypes[1] = Context->UnsignedCharTy;
6660 FieldNames[1] = "fpr";
6661
6662 // unsigned short reserved;
6663 FieldTypes[2] = Context->UnsignedShortTy;
6664 FieldNames[2] = "reserved";
6665
6666 // void* overflow_arg_area;
6667 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6668 FieldNames[3] = "overflow_arg_area";
6669
6670 // void* reg_save_area;
6671 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6672 FieldNames[4] = "reg_save_area";
6673
6674 // Create fields
6675 for (unsigned i = 0; i < NumFields; ++i) {
6676 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6677 SourceLocation(),
6678 SourceLocation(),
6679 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006680 FieldTypes[i], /*TInfo=*/nullptr,
6681 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006682 /*Mutable=*/false,
6683 ICIS_NoInit);
6684 Field->setAccess(AS_public);
6685 VaListTagDecl->addDecl(Field);
6686 }
6687 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006688 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006689 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6690
6691 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006692 TypedefDecl *VaListTagTypedefDecl =
6693 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6694
Meador Inge5d3fb222012-06-16 03:34:49 +00006695 QualType VaListTagTypedefType =
6696 Context->getTypedefType(VaListTagTypedefDecl);
6697
6698 // typedef __va_list_tag __builtin_va_list[1];
6699 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6700 QualType VaListTagArrayType
6701 = Context->getConstantArrayType(VaListTagTypedefType,
6702 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006703 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006704}
6705
6706static TypedefDecl *
6707CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006708 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006709 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006710 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006711 VaListTagDecl->startDefinition();
6712
6713 const size_t NumFields = 4;
6714 QualType FieldTypes[NumFields];
6715 const char *FieldNames[NumFields];
6716
6717 // unsigned gp_offset;
6718 FieldTypes[0] = Context->UnsignedIntTy;
6719 FieldNames[0] = "gp_offset";
6720
6721 // unsigned fp_offset;
6722 FieldTypes[1] = Context->UnsignedIntTy;
6723 FieldNames[1] = "fp_offset";
6724
6725 // void* overflow_arg_area;
6726 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6727 FieldNames[2] = "overflow_arg_area";
6728
6729 // void* reg_save_area;
6730 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6731 FieldNames[3] = "reg_save_area";
6732
6733 // Create fields
6734 for (unsigned i = 0; i < NumFields; ++i) {
6735 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6736 VaListTagDecl,
6737 SourceLocation(),
6738 SourceLocation(),
6739 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006740 FieldTypes[i], /*TInfo=*/nullptr,
6741 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006742 /*Mutable=*/false,
6743 ICIS_NoInit);
6744 Field->setAccess(AS_public);
6745 VaListTagDecl->addDecl(Field);
6746 }
6747 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006748 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006749 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6750
Richard Smith9b88a4c2015-07-27 05:40:23 +00006751 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006752
Richard Smith9b88a4c2015-07-27 05:40:23 +00006753 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006754 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006755 QualType VaListTagArrayType =
6756 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006757 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006758}
6759
6760static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6761 // typedef int __builtin_va_list[4];
6762 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006763 QualType IntArrayType =
6764 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006765 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006766}
6767
Logan Chien57086ce2012-10-10 06:56:20 +00006768static TypedefDecl *
6769CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006770 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006771 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006772 if (Context->getLangOpts().CPlusPlus) {
6773 // namespace std { struct __va_list {
6774 NamespaceDecl *NS;
6775 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6776 Context->getTranslationUnitDecl(),
6777 /*Inline*/false, SourceLocation(),
6778 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006779 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006780 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006781 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006782 }
6783
6784 VaListDecl->startDefinition();
6785
6786 // void * __ap;
6787 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6788 VaListDecl,
6789 SourceLocation(),
6790 SourceLocation(),
6791 &Context->Idents.get("__ap"),
6792 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006793 /*TInfo=*/nullptr,
6794 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006795 /*Mutable=*/false,
6796 ICIS_NoInit);
6797 Field->setAccess(AS_public);
6798 VaListDecl->addDecl(Field);
6799
6800 // };
6801 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006802 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006803
6804 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006805 QualType T = Context->getRecordType(VaListDecl);
6806 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006807}
6808
Ulrich Weigand47445072013-05-06 16:26:41 +00006809static TypedefDecl *
6810CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006811 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006812 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006813 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006814 VaListTagDecl->startDefinition();
6815
6816 const size_t NumFields = 4;
6817 QualType FieldTypes[NumFields];
6818 const char *FieldNames[NumFields];
6819
6820 // long __gpr;
6821 FieldTypes[0] = Context->LongTy;
6822 FieldNames[0] = "__gpr";
6823
6824 // long __fpr;
6825 FieldTypes[1] = Context->LongTy;
6826 FieldNames[1] = "__fpr";
6827
6828 // void *__overflow_arg_area;
6829 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6830 FieldNames[2] = "__overflow_arg_area";
6831
6832 // void *__reg_save_area;
6833 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6834 FieldNames[3] = "__reg_save_area";
6835
6836 // Create fields
6837 for (unsigned i = 0; i < NumFields; ++i) {
6838 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6839 VaListTagDecl,
6840 SourceLocation(),
6841 SourceLocation(),
6842 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006843 FieldTypes[i], /*TInfo=*/nullptr,
6844 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006845 /*Mutable=*/false,
6846 ICIS_NoInit);
6847 Field->setAccess(AS_public);
6848 VaListTagDecl->addDecl(Field);
6849 }
6850 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006851 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006852 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006853
Richard Smith9b88a4c2015-07-27 05:40:23 +00006854 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006855
6856 // typedef __va_list_tag __builtin_va_list[1];
6857 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006858 QualType VaListTagArrayType =
6859 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006860
Alp Toker56b5cc92013-12-15 10:36:26 +00006861 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006862}
6863
Meador Inge5d3fb222012-06-16 03:34:49 +00006864static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6865 TargetInfo::BuiltinVaListKind Kind) {
6866 switch (Kind) {
6867 case TargetInfo::CharPtrBuiltinVaList:
6868 return CreateCharPtrBuiltinVaListDecl(Context);
6869 case TargetInfo::VoidPtrBuiltinVaList:
6870 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006871 case TargetInfo::AArch64ABIBuiltinVaList:
6872 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006873 case TargetInfo::PowerABIBuiltinVaList:
6874 return CreatePowerABIBuiltinVaListDecl(Context);
6875 case TargetInfo::X86_64ABIBuiltinVaList:
6876 return CreateX86_64ABIBuiltinVaListDecl(Context);
6877 case TargetInfo::PNaClABIBuiltinVaList:
6878 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006879 case TargetInfo::AAPCSABIBuiltinVaList:
6880 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006881 case TargetInfo::SystemZBuiltinVaList:
6882 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006883 }
6884
6885 llvm_unreachable("Unhandled __builtin_va_list type kind");
6886}
6887
6888TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006889 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006890 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006891 assert(BuiltinVaListDecl->isImplicit());
6892 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006893
6894 return BuiltinVaListDecl;
6895}
6896
Richard Smith9b88a4c2015-07-27 05:40:23 +00006897Decl *ASTContext::getVaListTagDecl() const {
6898 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006899 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006900 if (!VaListTagDecl)
6901 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006902
Richard Smith9b88a4c2015-07-27 05:40:23 +00006903 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006904}
6905
Charles Davisc7d5c942015-09-17 20:55:33 +00006906TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6907 if (!BuiltinMSVaListDecl)
6908 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6909
6910 return BuiltinMSVaListDecl;
6911}
6912
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006913void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006914 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006915 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006916
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006917 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006918}
6919
John McCalld28ae272009-12-02 08:04:21 +00006920/// \brief Retrieve the template name that corresponds to a non-empty
6921/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006922TemplateName
6923ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6924 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006925 unsigned size = End - Begin;
6926 assert(size > 1 && "set is not overloaded!");
6927
6928 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6929 size * sizeof(FunctionTemplateDecl*));
6930 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6931
6932 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006933 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006934 NamedDecl *D = *I;
6935 assert(isa<FunctionTemplateDecl>(D) ||
6936 (isa<UsingShadowDecl>(D) &&
6937 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6938 *Storage++ = D;
6939 }
6940
6941 return TemplateName(OT);
6942}
6943
Douglas Gregordc572a32009-03-30 22:58:21 +00006944/// \brief Retrieve the template name that represents a qualified
6945/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006946TemplateName
6947ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6948 bool TemplateKeyword,
6949 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006950 assert(NNS && "Missing nested-name-specifier in qualified template name");
6951
Douglas Gregorc42075a2010-02-04 18:10:26 +00006952 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006953 llvm::FoldingSetNodeID ID;
6954 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6955
Craig Topper36250ad2014-05-12 05:36:57 +00006956 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006957 QualifiedTemplateName *QTN =
6958 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6959 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006960 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006961 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006962 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6963 }
6964
6965 return TemplateName(QTN);
6966}
6967
6968/// \brief Retrieve the template name that represents a dependent
6969/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006970TemplateName
6971ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6972 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006973 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006974 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006975
6976 llvm::FoldingSetNodeID ID;
6977 DependentTemplateName::Profile(ID, NNS, Name);
6978
Craig Topper36250ad2014-05-12 05:36:57 +00006979 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006980 DependentTemplateName *QTN =
6981 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6982
6983 if (QTN)
6984 return TemplateName(QTN);
6985
6986 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6987 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006988 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006989 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006990 } else {
6991 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006992 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006993 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006994 DependentTemplateName *CheckQTN =
6995 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6996 assert(!CheckQTN && "Dependent type name canonicalization broken");
6997 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006998 }
6999
7000 DependentTemplateNames.InsertNode(QTN, InsertPos);
7001 return TemplateName(QTN);
7002}
7003
Douglas Gregor71395fa2009-11-04 00:56:37 +00007004/// \brief Retrieve the template name that represents a dependent
7005/// template name such as \c MetaFun::template operator+.
7006TemplateName
7007ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007008 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007009 assert((!NNS || NNS->isDependent()) &&
7010 "Nested name specifier must be dependent");
7011
7012 llvm::FoldingSetNodeID ID;
7013 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007014
7015 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007016 DependentTemplateName *QTN
7017 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007018
7019 if (QTN)
7020 return TemplateName(QTN);
7021
7022 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7023 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007024 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007025 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007026 } else {
7027 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007028 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007029 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007030
Douglas Gregorc42075a2010-02-04 18:10:26 +00007031 DependentTemplateName *CheckQTN
7032 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7033 assert(!CheckQTN && "Dependent template name canonicalization broken");
7034 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007035 }
7036
7037 DependentTemplateNames.InsertNode(QTN, InsertPos);
7038 return TemplateName(QTN);
7039}
7040
Douglas Gregor5590be02011-01-15 06:45:20 +00007041TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007042ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7043 TemplateName replacement) const {
7044 llvm::FoldingSetNodeID ID;
7045 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007046
7047 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007048 SubstTemplateTemplateParmStorage *subst
7049 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7050
7051 if (!subst) {
7052 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7053 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7054 }
7055
7056 return TemplateName(subst);
7057}
7058
7059TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007060ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7061 const TemplateArgument &ArgPack) const {
7062 ASTContext &Self = const_cast<ASTContext &>(*this);
7063 llvm::FoldingSetNodeID ID;
7064 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007065
7066 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007067 SubstTemplateTemplateParmPackStorage *Subst
7068 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7069
7070 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007071 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007072 ArgPack.pack_size(),
7073 ArgPack.pack_begin());
7074 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7075 }
7076
7077 return TemplateName(Subst);
7078}
7079
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007080/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007081/// TargetInfo, produce the corresponding type. The unsigned @p Type
7082/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007083CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007084 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007085 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007086 case TargetInfo::SignedChar: return SignedCharTy;
7087 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007088 case TargetInfo::SignedShort: return ShortTy;
7089 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7090 case TargetInfo::SignedInt: return IntTy;
7091 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7092 case TargetInfo::SignedLong: return LongTy;
7093 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7094 case TargetInfo::SignedLongLong: return LongLongTy;
7095 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7096 }
7097
David Blaikie83d382b2011-09-23 05:06:16 +00007098 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007099}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007100
7101//===----------------------------------------------------------------------===//
7102// Type Predicates.
7103//===----------------------------------------------------------------------===//
7104
Fariborz Jahanian96207692009-02-18 21:49:28 +00007105/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7106/// garbage collection attribute.
7107///
John McCall553d45a2011-01-12 00:34:59 +00007108Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007109 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007110 return Qualifiers::GCNone;
7111
David Blaikiebbafb8a2012-03-11 07:00:24 +00007112 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007113 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7114
7115 // Default behaviour under objective-C's gc is for ObjC pointers
7116 // (or pointers to them) be treated as though they were declared
7117 // as __strong.
7118 if (GCAttrs == Qualifiers::GCNone) {
7119 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7120 return Qualifiers::Strong;
7121 else if (Ty->isPointerType())
7122 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7123 } else {
7124 // It's not valid to set GC attributes on anything that isn't a
7125 // pointer.
7126#ifndef NDEBUG
7127 QualType CT = Ty->getCanonicalTypeInternal();
7128 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7129 CT = AT->getElementType();
7130 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7131#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007132 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007133 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007134}
7135
Chris Lattner49af6a42008-04-07 06:51:04 +00007136//===----------------------------------------------------------------------===//
7137// Type Compatibility Testing
7138//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007139
Mike Stump11289f42009-09-09 15:08:12 +00007140/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007141/// compatible.
7142static bool areCompatVectorTypes(const VectorType *LHS,
7143 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007144 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007145 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007146 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007147}
7148
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007149bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7150 QualType SecondVec) {
7151 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7152 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7153
7154 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7155 return true;
7156
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007157 // Treat Neon vector types and most AltiVec vector types as if they are the
7158 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007159 const VectorType *First = FirstVec->getAs<VectorType>();
7160 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007161 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007162 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007163 First->getVectorKind() != VectorType::AltiVecPixel &&
7164 First->getVectorKind() != VectorType::AltiVecBool &&
7165 Second->getVectorKind() != VectorType::AltiVecPixel &&
7166 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007167 return true;
7168
7169 return false;
7170}
7171
Steve Naroff8e6aee52009-07-23 01:01:38 +00007172//===----------------------------------------------------------------------===//
7173// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7174//===----------------------------------------------------------------------===//
7175
7176/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7177/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007178bool
7179ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7180 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007181 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007182 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007183 for (auto *PI : rProto->protocols())
7184 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007185 return true;
7186 return false;
7187}
7188
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007189/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7190/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007191bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7192 QualType rhs) {
7193 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7194 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7195 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7196
Aaron Ballman83731462014-03-17 16:14:00 +00007197 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007198 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007199 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007200 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7201 match = true;
7202 break;
7203 }
7204 }
7205 if (!match)
7206 return false;
7207 }
7208 return true;
7209}
7210
Steve Naroff8e6aee52009-07-23 01:01:38 +00007211/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7212/// ObjCQualifiedIDType.
7213bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7214 bool compare) {
7215 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007216 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007217 lhs->isObjCIdType() || lhs->isObjCClassType())
7218 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007219 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007220 rhs->isObjCIdType() || rhs->isObjCClassType())
7221 return true;
7222
7223 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007224 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007225
Steve Naroff8e6aee52009-07-23 01:01:38 +00007226 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007227
Steve Naroff8e6aee52009-07-23 01:01:38 +00007228 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007229 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007230 // make sure we check the class hierarchy.
7231 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007232 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007233 // when comparing an id<P> on lhs with a static type on rhs,
7234 // see if static class implements all of id's protocols, directly or
7235 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007236 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007237 return false;
7238 }
7239 }
7240 // If there are no qualifiers and no interface, we have an 'id'.
7241 return true;
7242 }
Mike Stump11289f42009-09-09 15:08:12 +00007243 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007244 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007245 bool match = false;
7246
7247 // when comparing an id<P> on lhs with a static type on rhs,
7248 // see if static class implements all of id's protocols, directly or
7249 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007250 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007251 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7252 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7253 match = true;
7254 break;
7255 }
7256 }
Mike Stump11289f42009-09-09 15:08:12 +00007257 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007258 // make sure we check the class hierarchy.
7259 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007260 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007261 // when comparing an id<P> on lhs with a static type on rhs,
7262 // see if static class implements all of id's protocols, directly or
7263 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007264 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007265 match = true;
7266 break;
7267 }
7268 }
7269 }
7270 if (!match)
7271 return false;
7272 }
Mike Stump11289f42009-09-09 15:08:12 +00007273
Steve Naroff8e6aee52009-07-23 01:01:38 +00007274 return true;
7275 }
Mike Stump11289f42009-09-09 15:08:12 +00007276
Steve Naroff8e6aee52009-07-23 01:01:38 +00007277 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7278 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7279
Mike Stump11289f42009-09-09 15:08:12 +00007280 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007281 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007282 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007283 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007284 bool match = false;
7285
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007286 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007287 // see if static class implements all of id's protocols, directly or
7288 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007289 // First, lhs protocols in the qualifier list must be found, direct
7290 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007291 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007292 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7293 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7294 match = true;
7295 break;
7296 }
7297 }
7298 if (!match)
7299 return false;
7300 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007301
7302 // Static class's protocols, or its super class or category protocols
7303 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7304 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7305 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7306 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7307 // This is rather dubious but matches gcc's behavior. If lhs has
7308 // no type qualifier and its class has no static protocol(s)
7309 // assume that it is mismatch.
7310 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7311 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007312 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007313 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007314 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007315 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7316 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7317 match = true;
7318 break;
7319 }
7320 }
7321 if (!match)
7322 return false;
7323 }
7324 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007325 return true;
7326 }
7327 return false;
7328}
7329
Eli Friedman47f77112008-08-22 00:56:42 +00007330/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007331/// compatible for assignment from RHS to LHS. This handles validation of any
7332/// protocol qualifiers on the LHS or RHS.
7333///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007334bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7335 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007336 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7337 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7338
Steve Naroff1329fa02009-07-15 18:40:39 +00007339 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007340 if (LHS->isObjCUnqualifiedIdOrClass() ||
7341 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007342 return true;
7343
Douglas Gregorab209d82015-07-07 03:58:42 +00007344 // Function object that propagates a successful result or handles
7345 // __kindof types.
7346 auto finish = [&](bool succeeded) -> bool {
7347 if (succeeded)
7348 return true;
7349
7350 if (!RHS->isKindOfType())
7351 return false;
7352
7353 // Strip off __kindof and protocol qualifiers, then check whether
7354 // we can assign the other way.
7355 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7356 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7357 };
7358
7359 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7360 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7361 QualType(RHSOPT,0),
7362 false));
7363 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007364
Douglas Gregorab209d82015-07-07 03:58:42 +00007365 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7366 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7367 QualType(RHSOPT,0)));
7368 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007369
John McCall8b07ec22010-05-15 11:32:37 +00007370 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007371 if (LHS->getInterface() && RHS->getInterface()) {
7372 return finish(canAssignObjCInterfaces(LHS, RHS));
7373 }
Mike Stump11289f42009-09-09 15:08:12 +00007374
Steve Naroff8e6aee52009-07-23 01:01:38 +00007375 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007376}
7377
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007378/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007379/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007380/// arguments in block literals. When passed as arguments, passing 'A*' where
7381/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7382/// not OK. For the return type, the opposite is not OK.
7383bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7384 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007385 const ObjCObjectPointerType *RHSOPT,
7386 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007387
7388 // Function object that propagates a successful result or handles
7389 // __kindof types.
7390 auto finish = [&](bool succeeded) -> bool {
7391 if (succeeded)
7392 return true;
7393
7394 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7395 if (!Expected->isKindOfType())
7396 return false;
7397
7398 // Strip off __kindof and protocol qualifiers, then check whether
7399 // we can assign the other way.
7400 return canAssignObjCInterfacesInBlockPointer(
7401 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7402 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7403 BlockReturnType);
7404 };
7405
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007406 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007407 return true;
7408
7409 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007410 return finish(RHSOPT->isObjCBuiltinType() ||
7411 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007412 }
7413
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007414 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007415 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7416 QualType(RHSOPT,0),
7417 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007418
7419 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7420 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7421 if (LHS && RHS) { // We have 2 user-defined types.
7422 if (LHS != RHS) {
7423 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007424 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007425 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007426 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007427 }
7428 else
7429 return true;
7430 }
7431 return false;
7432}
7433
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007434/// Comparison routine for Objective-C protocols to be used with
7435/// llvm::array_pod_sort.
7436static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7437 ObjCProtocolDecl * const *rhs) {
7438 return (*lhs)->getName().compare((*rhs)->getName());
7439
7440}
7441
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007442/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007443/// of protocols inherited from two distinct objective-c pointer objects with
7444/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007445/// It is used to build composite qualifier list of the composite type of
7446/// the conditional expression involving two objective-c pointer objects.
7447static
7448void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007449 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007450 const ObjCObjectPointerType *LHSOPT,
7451 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007452 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007453
John McCall8b07ec22010-05-15 11:32:37 +00007454 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7455 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7456 assert(LHS->getInterface() && "LHS must have an interface base");
7457 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007458
7459 // Add all of the protocols for the LHS.
7460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7461
7462 // Start with the protocol qualifiers.
7463 for (auto proto : LHS->quals()) {
7464 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007465 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007466
7467 // Also add the protocols associated with the LHS interface.
7468 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7469
7470 // Add all of the protocls for the RHS.
7471 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7472
7473 // Start with the protocol qualifiers.
7474 for (auto proto : RHS->quals()) {
7475 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007476 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007477
7478 // Also add the protocols associated with the RHS interface.
7479 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7480
7481 // Compute the intersection of the collected protocol sets.
7482 for (auto proto : LHSProtocolSet) {
7483 if (RHSProtocolSet.count(proto))
7484 IntersectionSet.push_back(proto);
7485 }
7486
7487 // Compute the set of protocols that is implied by either the common type or
7488 // the protocols within the intersection.
7489 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7490 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7491
7492 // Remove any implied protocols from the list of inherited protocols.
7493 if (!ImpliedProtocols.empty()) {
7494 IntersectionSet.erase(
7495 std::remove_if(IntersectionSet.begin(),
7496 IntersectionSet.end(),
7497 [&](ObjCProtocolDecl *proto) -> bool {
7498 return ImpliedProtocols.count(proto) > 0;
7499 }),
7500 IntersectionSet.end());
7501 }
7502
7503 // Sort the remaining protocols by name.
7504 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7505 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007506}
7507
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007508/// Determine whether the first type is a subtype of the second.
7509static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7510 QualType rhs) {
7511 // Common case: two object pointers.
7512 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7513 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7514 if (lhsOPT && rhsOPT)
7515 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7516
7517 // Two block pointers.
7518 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7519 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7520 if (lhsBlock && rhsBlock)
7521 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7522
7523 // If either is an unqualified 'id' and the other is a block, it's
7524 // acceptable.
7525 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7526 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7527 return true;
7528
7529 return false;
7530}
7531
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007532// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007533static bool sameObjCTypeArgs(ASTContext &ctx,
7534 const ObjCInterfaceDecl *iface,
7535 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007536 ArrayRef<QualType> rhsArgs,
7537 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007538 if (lhsArgs.size() != rhsArgs.size())
7539 return false;
7540
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007541 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007542 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007543 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7544 continue;
7545
7546 switch (typeParams->begin()[i]->getVariance()) {
7547 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007548 if (!stripKindOf ||
7549 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7550 rhsArgs[i].stripObjCKindOfType(ctx))) {
7551 return false;
7552 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007553 break;
7554
7555 case ObjCTypeParamVariance::Covariant:
7556 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7557 return false;
7558 break;
7559
7560 case ObjCTypeParamVariance::Contravariant:
7561 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7562 return false;
7563 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007564 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007565 }
7566
7567 return true;
7568}
7569
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007570QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007571 const ObjCObjectPointerType *Lptr,
7572 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007573 const ObjCObjectType *LHS = Lptr->getObjectType();
7574 const ObjCObjectType *RHS = Rptr->getObjectType();
7575 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7576 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007577
7578 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007579 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007580
Manman Renc46f7d12016-05-06 19:35:02 +00007581 // When either LHS or RHS is a kindof type, we should return a kindof type.
7582 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7583 // kindof(A).
7584 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7585
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007586 // Follow the left-hand side up the class hierarchy until we either hit a
7587 // root or find the RHS. Record the ancestors in case we don't find it.
7588 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7589 LHSAncestors;
7590 while (true) {
7591 // Record this ancestor. We'll need this if the common type isn't in the
7592 // path from the LHS to the root.
7593 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007594
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007595 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7596 // Get the type arguments.
7597 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7598 bool anyChanges = false;
7599 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7600 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007601 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7602 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007603 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007604 return QualType();
7605 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7606 // If only one has type arguments, the result will not have type
7607 // arguments.
7608 LHSTypeArgs = { };
7609 anyChanges = true;
7610 }
7611
7612 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007613 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007614 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7615 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007616 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007617 anyChanges = true;
7618
7619 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007620 // If we need to return a kindof type but LHS is not a kindof type, we
7621 // build a new result type.
7622 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007623 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007624 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007625 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007626 return getObjCObjectPointerType(Result);
7627 }
7628
7629 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007630 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007631
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007632 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007633 QualType LHSSuperType = LHS->getSuperClassType();
7634 if (LHSSuperType.isNull())
7635 break;
7636
7637 LHS = LHSSuperType->castAs<ObjCObjectType>();
7638 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007639
7640 // We didn't find anything by following the LHS to its root; now check
7641 // the RHS against the cached set of ancestors.
7642 while (true) {
7643 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7644 if (KnownLHS != LHSAncestors.end()) {
7645 LHS = KnownLHS->second;
7646
7647 // Get the type arguments.
7648 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7649 bool anyChanges = false;
7650 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7651 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007652 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7653 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007654 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007655 return QualType();
7656 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7657 // If only one has type arguments, the result will not have type
7658 // arguments.
7659 RHSTypeArgs = { };
7660 anyChanges = true;
7661 }
7662
7663 // Compute the intersection of protocols.
7664 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7665 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7666 Protocols);
7667 if (!Protocols.empty())
7668 anyChanges = true;
7669
Manman Renc46f7d12016-05-06 19:35:02 +00007670 // If we need to return a kindof type but RHS is not a kindof type, we
7671 // build a new result type.
7672 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007673 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007674 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007675 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007676 return getObjCObjectPointerType(Result);
7677 }
7678
7679 return getObjCObjectPointerType(QualType(RHS, 0));
7680 }
7681
7682 // Find the superclass of the RHS.
7683 QualType RHSSuperType = RHS->getSuperClassType();
7684 if (RHSSuperType.isNull())
7685 break;
7686
7687 RHS = RHSSuperType->castAs<ObjCObjectType>();
7688 }
7689
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007690 return QualType();
7691}
7692
John McCall8b07ec22010-05-15 11:32:37 +00007693bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7694 const ObjCObjectType *RHS) {
7695 assert(LHS->getInterface() && "LHS is not an interface type");
7696 assert(RHS->getInterface() && "RHS is not an interface type");
7697
Chris Lattner49af6a42008-04-07 06:51:04 +00007698 // Verify that the base decls are compatible: the RHS must be a subclass of
7699 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007700 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7701 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7702 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007703 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007704
Douglas Gregore83b9562015-07-07 03:57:53 +00007705 // If the LHS has protocol qualifiers, determine whether all of them are
7706 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7707 // LHS).
7708 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007709 // OK if conversion of LHS to SuperClass results in narrowing of types
7710 // ; i.e., SuperClass may implement at least one of the protocols
7711 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7712 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7713 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7714 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7715 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7716 // qualifiers.
7717 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007718 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007719 // If there is no protocols associated with RHS, it is not a match.
7720 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007721 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007722
7723 for (const auto *LHSProto : LHS->quals()) {
7724 bool SuperImplementsProtocol = false;
7725 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7726 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7727 SuperImplementsProtocol = true;
7728 break;
7729 }
7730 if (!SuperImplementsProtocol)
7731 return false;
7732 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007733 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007734
7735 // If the LHS is specialized, we may need to check type arguments.
7736 if (LHS->isSpecialized()) {
7737 // Follow the superclass chain until we've matched the LHS class in the
7738 // hierarchy. This substitutes type arguments through.
7739 const ObjCObjectType *RHSSuper = RHS;
7740 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7741 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7742
7743 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007744 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007745 !sameObjCTypeArgs(*this, LHS->getInterface(),
7746 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007747 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007748 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007749 }
7750 }
7751
7752 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007753}
7754
Steve Naroffb7605152009-02-12 17:52:19 +00007755bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7756 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007757 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7758 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007759
Steve Naroff7cae42b2009-07-10 23:34:53 +00007760 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007761 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007762
7763 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7764 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007765}
7766
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007767bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7768 return canAssignObjCInterfaces(
7769 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7770 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7771}
7772
Mike Stump11289f42009-09-09 15:08:12 +00007773/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007774/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007775/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007776/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007777bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7778 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007779 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007780 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007781
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007782 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007783}
7784
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007785bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007786 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007787}
7788
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007789bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7790 return !mergeTypes(LHS, RHS, true).isNull();
7791}
7792
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007793/// mergeTransparentUnionType - if T is a transparent union type and a member
7794/// of T is compatible with SubType, return the merged type, else return
7795/// QualType()
7796QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7797 bool OfBlockPointer,
7798 bool Unqualified) {
7799 if (const RecordType *UT = T->getAsUnionType()) {
7800 RecordDecl *UD = UT->getDecl();
7801 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007802 for (const auto *I : UD->fields()) {
7803 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007804 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7805 if (!MT.isNull())
7806 return MT;
7807 }
7808 }
7809 }
7810
7811 return QualType();
7812}
7813
Alp Toker9cacbab2014-01-20 20:26:09 +00007814/// mergeFunctionParameterTypes - merge two types which appear as function
7815/// parameter types
7816QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7817 bool OfBlockPointer,
7818 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007819 // GNU extension: two types are compatible if they appear as a function
7820 // argument, one of the types is a transparent union type and the other
7821 // type is compatible with a union member
7822 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7823 Unqualified);
7824 if (!lmerge.isNull())
7825 return lmerge;
7826
7827 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7828 Unqualified);
7829 if (!rmerge.isNull())
7830 return rmerge;
7831
7832 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7833}
7834
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007835QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007836 bool OfBlockPointer,
7837 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007838 const FunctionType *lbase = lhs->getAs<FunctionType>();
7839 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007840 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7841 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007842 bool allLTypes = true;
7843 bool allRTypes = true;
7844
7845 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007846 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007847 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007848 QualType RHS = rbase->getReturnType();
7849 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007850 bool UnqualifiedResult = Unqualified;
7851 if (!UnqualifiedResult)
7852 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007853 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007854 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007855 else
Alp Toker314cc812014-01-25 16:55:45 +00007856 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007857 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007858 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007859
7860 if (Unqualified)
7861 retType = retType.getUnqualifiedType();
7862
Alp Toker314cc812014-01-25 16:55:45 +00007863 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7864 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007865 if (Unqualified) {
7866 LRetType = LRetType.getUnqualifiedType();
7867 RRetType = RRetType.getUnqualifiedType();
7868 }
7869
7870 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007871 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007872 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007873 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007874
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007875 // FIXME: double check this
7876 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7877 // rbase->getRegParmAttr() != 0 &&
7878 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007879 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7880 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007881
Douglas Gregor8c940862010-01-18 17:14:39 +00007882 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007883 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007884 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007885
John McCall8c6b56f2010-12-15 01:06:38 +00007886 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007887 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7888 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007889 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7890 return QualType();
7891
John McCall31168b02011-06-15 23:02:42 +00007892 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7893 return QualType();
7894
John McCall8c6b56f2010-12-15 01:06:38 +00007895 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7896 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007897
Rafael Espindola8778c282012-11-29 16:09:03 +00007898 if (lbaseInfo.getNoReturn() != NoReturn)
7899 allLTypes = false;
7900 if (rbaseInfo.getNoReturn() != NoReturn)
7901 allRTypes = false;
7902
John McCall31168b02011-06-15 23:02:42 +00007903 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007904
Eli Friedman47f77112008-08-22 00:56:42 +00007905 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007906 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7907 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007908 // Compatible functions must have the same number of parameters
7909 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007910 return QualType();
7911
7912 // Variadic and non-variadic functions aren't compatible
7913 if (lproto->isVariadic() != rproto->isVariadic())
7914 return QualType();
7915
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007916 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7917 return QualType();
7918
John McCall18afab72016-03-01 00:49:02 +00007919 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007920 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007921
7922 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007923 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007924 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7925 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7926 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7927 QualType paramType = mergeFunctionParameterTypes(
7928 lParamType, rParamType, OfBlockPointer, Unqualified);
7929 if (paramType.isNull())
7930 return QualType();
7931
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007932 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007933 paramType = paramType.getUnqualifiedType();
7934
7935 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007936 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007937 lParamType = lParamType.getUnqualifiedType();
7938 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007939 }
Alp Toker601b22c2014-01-21 23:35:24 +00007940
7941 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007942 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007943 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007944 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007945 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007946
Eli Friedman47f77112008-08-22 00:56:42 +00007947 if (allLTypes) return lhs;
7948 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007949
7950 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7951 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007952 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007953 }
7954
7955 if (lproto) allRTypes = false;
7956 if (rproto) allLTypes = false;
7957
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007958 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007959 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007960 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007961 if (proto->isVariadic()) return QualType();
7962 // Check that the types are compatible with the types that
7963 // would result from default argument promotions (C99 6.7.5.3p15).
7964 // The only types actually affected are promotable integer
7965 // types and floats, which would be passed as a different
7966 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007967 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7968 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007969
Eli Friedman448ce402012-08-30 00:44:15 +00007970 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007971 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007972 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7973 paramTy = Enum->getDecl()->getIntegerType();
7974 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007975 return QualType();
7976 }
Alp Toker601b22c2014-01-21 23:35:24 +00007977
7978 if (paramTy->isPromotableIntegerType() ||
7979 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007980 return QualType();
7981 }
7982
7983 if (allLTypes) return lhs;
7984 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007985
7986 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7987 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007988 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007989 }
7990
7991 if (allLTypes) return lhs;
7992 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007993 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007994}
7995
John McCall433c2e62013-03-21 00:10:07 +00007996/// Given that we have an enum type and a non-enum type, try to merge them.
7997static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7998 QualType other, bool isBlockReturnType) {
7999 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8000 // a signed integer type, or an unsigned integer type.
8001 // Compatibility is based on the underlying type, not the promotion
8002 // type.
8003 QualType underlyingType = ET->getDecl()->getIntegerType();
8004 if (underlyingType.isNull()) return QualType();
8005 if (Context.hasSameType(underlyingType, other))
8006 return other;
8007
8008 // In block return types, we're more permissive and accept any
8009 // integral type of the same size.
8010 if (isBlockReturnType && other->isIntegerType() &&
8011 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8012 return other;
8013
8014 return QualType();
8015}
8016
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008017QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008018 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008019 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008020 // C++ [expr]: If an expression initially has the type "reference to T", the
8021 // type is adjusted to "T" prior to any further analysis, the expression
8022 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008023 // expression is an lvalue unless the reference is an rvalue reference and
8024 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008025 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8026 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008027
8028 if (Unqualified) {
8029 LHS = LHS.getUnqualifiedType();
8030 RHS = RHS.getUnqualifiedType();
8031 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008032
Eli Friedman47f77112008-08-22 00:56:42 +00008033 QualType LHSCan = getCanonicalType(LHS),
8034 RHSCan = getCanonicalType(RHS);
8035
8036 // If two types are identical, they are compatible.
8037 if (LHSCan == RHSCan)
8038 return LHS;
8039
John McCall8ccfcb52009-09-24 19:53:00 +00008040 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008041 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8042 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008043 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008044 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00008045 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008046 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
8047 return QualType();
8048 if (LQuals.isAddressSpaceSupersetOf(RQuals))
8049 return LHS;
8050 if (RQuals.isAddressSpaceSupersetOf(LQuals))
8051 return RHS;
8052 }
John McCall8ccfcb52009-09-24 19:53:00 +00008053 // If any of these qualifiers are different, we have a type
8054 // mismatch.
8055 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008056 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8057 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00008058 return QualType();
8059
8060 // Exactly one GC qualifier difference is allowed: __strong is
8061 // okay if the other type has no GC qualifier but is an Objective
8062 // C object pointer (i.e. implicitly strong by default). We fix
8063 // this by pretending that the unqualified type was actually
8064 // qualified __strong.
8065 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8066 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8067 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8068
8069 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8070 return QualType();
8071
8072 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8073 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8074 }
8075 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8076 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8077 }
Eli Friedman47f77112008-08-22 00:56:42 +00008078 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008079 }
8080
8081 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008082
Eli Friedmandcca6332009-06-01 01:22:52 +00008083 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8084 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008085
Chris Lattnerfd652912008-01-14 05:45:46 +00008086 // We want to consider the two function types to be the same for these
8087 // comparisons, just force one to the other.
8088 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8089 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008090
8091 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008092 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8093 LHSClass = Type::ConstantArray;
8094 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8095 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008096
John McCall8b07ec22010-05-15 11:32:37 +00008097 // ObjCInterfaces are just specialized ObjCObjects.
8098 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8099 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8100
Nate Begemance4d7fc2008-04-18 23:10:10 +00008101 // Canonicalize ExtVector -> Vector.
8102 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8103 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008104
Chris Lattner95554662008-04-07 05:43:21 +00008105 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008106 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008107 // Note that we only have special rules for turning block enum
8108 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008109 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008110 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008111 }
John McCall9dd450b2009-09-21 23:43:11 +00008112 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008113 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008114 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008115 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008116 if (OfBlockPointer && !BlockReturnType) {
8117 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8118 return LHS;
8119 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8120 return RHS;
8121 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008122
Eli Friedman47f77112008-08-22 00:56:42 +00008123 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008124 }
Eli Friedman47f77112008-08-22 00:56:42 +00008125
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008126 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008127 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008128#define TYPE(Class, Base)
8129#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008130#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008131#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8132#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8133#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008134 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008135
Richard Smith27d807c2013-04-30 13:56:41 +00008136 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008137 case Type::LValueReference:
8138 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008139 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008140 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008141
John McCall8b07ec22010-05-15 11:32:37 +00008142 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008143 case Type::IncompleteArray:
8144 case Type::VariableArray:
8145 case Type::FunctionProto:
8146 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008147 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008148
Chris Lattnerfd652912008-01-14 05:45:46 +00008149 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008150 {
8151 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008152 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8153 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008154 if (Unqualified) {
8155 LHSPointee = LHSPointee.getUnqualifiedType();
8156 RHSPointee = RHSPointee.getUnqualifiedType();
8157 }
8158 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8159 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008160 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008161 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008162 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008163 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008164 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008165 return getPointerType(ResultType);
8166 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008167 case Type::BlockPointer:
8168 {
8169 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008170 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8171 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008172 if (Unqualified) {
8173 LHSPointee = LHSPointee.getUnqualifiedType();
8174 RHSPointee = RHSPointee.getUnqualifiedType();
8175 }
8176 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8177 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008178 if (ResultType.isNull()) return QualType();
8179 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8180 return LHS;
8181 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8182 return RHS;
8183 return getBlockPointerType(ResultType);
8184 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008185 case Type::Atomic:
8186 {
8187 // Merge two pointer types, while trying to preserve typedef info
8188 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8189 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8190 if (Unqualified) {
8191 LHSValue = LHSValue.getUnqualifiedType();
8192 RHSValue = RHSValue.getUnqualifiedType();
8193 }
8194 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8195 Unqualified);
8196 if (ResultType.isNull()) return QualType();
8197 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8198 return LHS;
8199 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8200 return RHS;
8201 return getAtomicType(ResultType);
8202 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008203 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008204 {
8205 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8206 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8207 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8208 return QualType();
8209
8210 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8211 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008212 if (Unqualified) {
8213 LHSElem = LHSElem.getUnqualifiedType();
8214 RHSElem = RHSElem.getUnqualifiedType();
8215 }
8216
8217 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008218 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008219 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8220 return LHS;
8221 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8222 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008223 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8224 ArrayType::ArraySizeModifier(), 0);
8225 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8226 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008227 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8228 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008229 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8230 return LHS;
8231 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8232 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008233 if (LVAT) {
8234 // FIXME: This isn't correct! But tricky to implement because
8235 // the array's size has to be the size of LHS, but the type
8236 // has to be different.
8237 return LHS;
8238 }
8239 if (RVAT) {
8240 // FIXME: This isn't correct! But tricky to implement because
8241 // the array's size has to be the size of RHS, but the type
8242 // has to be different.
8243 return RHS;
8244 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008245 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8246 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008247 return getIncompleteArrayType(ResultType,
8248 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008249 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008250 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008251 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008252 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008253 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008254 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008255 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008256 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008257 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008258 case Type::Complex:
8259 // Distinct complex types are incompatible.
8260 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008261 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008262 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008263 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8264 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008265 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008266 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008267 case Type::ObjCObject: {
8268 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008269 // FIXME: This should be type compatibility, e.g. whether
8270 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008271 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8272 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8273 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008274 return LHS;
8275
Eli Friedman47f77112008-08-22 00:56:42 +00008276 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008277 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008278 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008279 if (OfBlockPointer) {
8280 if (canAssignObjCInterfacesInBlockPointer(
8281 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008282 RHS->getAs<ObjCObjectPointerType>(),
8283 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008284 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008285 return QualType();
8286 }
John McCall9dd450b2009-09-21 23:43:11 +00008287 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8288 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008289 return LHS;
8290
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008291 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008292 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008293 case Type::Pipe:
8294 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008295 assert(LHS != RHS &&
8296 "Equivalent pipe types should have already been handled!");
8297 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008298 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008299 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008300
David Blaikie8a40f702012-01-17 06:56:22 +00008301 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008302}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008303
John McCall18afab72016-03-01 00:49:02 +00008304bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8305 const FunctionProtoType *firstFnType,
8306 const FunctionProtoType *secondFnType) {
8307 // Fast path: if the first type doesn't have ext parameter infos,
8308 // we match if and only if they second type also doesn't have them.
8309 if (!firstFnType->hasExtParameterInfos())
8310 return !secondFnType->hasExtParameterInfos();
8311
8312 // Otherwise, we can only match if the second type has them.
8313 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008314 return false;
John McCall18afab72016-03-01 00:49:02 +00008315
8316 auto firstEPI = firstFnType->getExtParameterInfos();
8317 auto secondEPI = secondFnType->getExtParameterInfos();
8318 assert(firstEPI.size() == secondEPI.size());
8319
8320 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8321 if (firstEPI[i] != secondEPI[i])
8322 return false;
8323 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008324 return true;
8325}
8326
Chandler Carruth21c90602015-12-30 03:24:14 +00008327void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8328 ObjCLayouts[CD] = nullptr;
8329}
8330
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008331/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8332/// 'RHS' attributes and returns the merged version; including for function
8333/// return types.
8334QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8335 QualType LHSCan = getCanonicalType(LHS),
8336 RHSCan = getCanonicalType(RHS);
8337 // If two types are identical, they are compatible.
8338 if (LHSCan == RHSCan)
8339 return LHS;
8340 if (RHSCan->isFunctionType()) {
8341 if (!LHSCan->isFunctionType())
8342 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008343 QualType OldReturnType =
8344 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008345 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008346 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008347 QualType ResReturnType =
8348 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8349 if (ResReturnType.isNull())
8350 return QualType();
8351 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8352 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8353 // In either case, use OldReturnType to build the new function type.
8354 const FunctionType *F = LHS->getAs<FunctionType>();
8355 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008356 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8357 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008358 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008359 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008360 return ResultType;
8361 }
8362 }
8363 return QualType();
8364 }
8365
8366 // If the qualifiers are different, the types can still be merged.
8367 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8368 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8369 if (LQuals != RQuals) {
8370 // If any of these qualifiers are different, we have a type mismatch.
8371 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8372 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8373 return QualType();
8374
8375 // Exactly one GC qualifier difference is allowed: __strong is
8376 // okay if the other type has no GC qualifier but is an Objective
8377 // C object pointer (i.e. implicitly strong by default). We fix
8378 // this by pretending that the unqualified type was actually
8379 // qualified __strong.
8380 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8381 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8382 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8383
8384 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8385 return QualType();
8386
8387 if (GC_L == Qualifiers::Strong)
8388 return LHS;
8389 if (GC_R == Qualifiers::Strong)
8390 return RHS;
8391 return QualType();
8392 }
8393
8394 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8395 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8396 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8397 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8398 if (ResQT == LHSBaseQT)
8399 return LHS;
8400 if (ResQT == RHSBaseQT)
8401 return RHS;
8402 }
8403 return QualType();
8404}
8405
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008406//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008407// Integer Predicates
8408//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008409
Jay Foad39c79802011-01-12 09:06:06 +00008410unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008411 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008412 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008413 if (T->isBooleanType())
8414 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008415 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008416 return (unsigned)getTypeSize(T);
8417}
8418
Abramo Bagnara13640492012-09-09 10:21:24 +00008419QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008420 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008421
8422 // Turn <4 x signed int> -> <4 x unsigned int>
8423 if (const VectorType *VTy = T->getAs<VectorType>())
8424 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008425 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008426
8427 // For enums, we return the unsigned version of the base type.
8428 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008429 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008430
8431 const BuiltinType *BTy = T->getAs<BuiltinType>();
8432 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008433 switch (BTy->getKind()) {
8434 case BuiltinType::Char_S:
8435 case BuiltinType::SChar:
8436 return UnsignedCharTy;
8437 case BuiltinType::Short:
8438 return UnsignedShortTy;
8439 case BuiltinType::Int:
8440 return UnsignedIntTy;
8441 case BuiltinType::Long:
8442 return UnsignedLongTy;
8443 case BuiltinType::LongLong:
8444 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008445 case BuiltinType::Int128:
8446 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008447 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008448 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008449 }
8450}
8451
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008452ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008453
Richard Smith1fa5d642013-05-11 05:45:24 +00008454void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8455 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008456
8457//===----------------------------------------------------------------------===//
8458// Builtin Type Computation
8459//===----------------------------------------------------------------------===//
8460
8461/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008462/// pointer over the consumed characters. This returns the resultant type. If
8463/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8464/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8465/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008466///
8467/// RequiresICE is filled in on return to indicate whether the value is required
8468/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008469static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008470 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008471 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008472 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008473 // Modifiers.
8474 int HowLong = 0;
8475 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008476 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008477
Chris Lattnerdc226c22010-10-01 22:42:38 +00008478 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008479 bool Done = false;
8480 while (!Done) {
8481 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008482 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008483 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008484 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008485 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008486 case 'S':
8487 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8488 assert(!Signed && "Can't use 'S' modifier multiple times!");
8489 Signed = true;
8490 break;
8491 case 'U':
8492 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008493 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008494 Unsigned = true;
8495 break;
8496 case 'L':
8497 assert(HowLong <= 2 && "Can't have LLLL modifier");
8498 ++HowLong;
8499 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008500 case 'W':
8501 // This modifier represents int64 type.
8502 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8503 switch (Context.getTargetInfo().getInt64Type()) {
8504 default:
8505 llvm_unreachable("Unexpected integer type");
8506 case TargetInfo::SignedLong:
8507 HowLong = 1;
8508 break;
8509 case TargetInfo::SignedLongLong:
8510 HowLong = 2;
8511 break;
8512 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008513 }
8514 }
8515
8516 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008517
Chris Lattnerecd79c62009-06-14 00:45:47 +00008518 // Read the base type.
8519 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008520 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008521 case 'v':
8522 assert(HowLong == 0 && !Signed && !Unsigned &&
8523 "Bad modifiers used with 'v'!");
8524 Type = Context.VoidTy;
8525 break;
Jack Carter24bef982013-08-15 15:16:57 +00008526 case 'h':
8527 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008528 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008529 Type = Context.HalfTy;
8530 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008531 case 'f':
8532 assert(HowLong == 0 && !Signed && !Unsigned &&
8533 "Bad modifiers used with 'f'!");
8534 Type = Context.FloatTy;
8535 break;
8536 case 'd':
8537 assert(HowLong < 2 && !Signed && !Unsigned &&
8538 "Bad modifiers used with 'd'!");
8539 if (HowLong)
8540 Type = Context.LongDoubleTy;
8541 else
8542 Type = Context.DoubleTy;
8543 break;
8544 case 's':
8545 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8546 if (Unsigned)
8547 Type = Context.UnsignedShortTy;
8548 else
8549 Type = Context.ShortTy;
8550 break;
8551 case 'i':
8552 if (HowLong == 3)
8553 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8554 else if (HowLong == 2)
8555 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8556 else if (HowLong == 1)
8557 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8558 else
8559 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8560 break;
8561 case 'c':
8562 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8563 if (Signed)
8564 Type = Context.SignedCharTy;
8565 else if (Unsigned)
8566 Type = Context.UnsignedCharTy;
8567 else
8568 Type = Context.CharTy;
8569 break;
8570 case 'b': // boolean
8571 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8572 Type = Context.BoolTy;
8573 break;
8574 case 'z': // size_t.
8575 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8576 Type = Context.getSizeType();
8577 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008578 case 'w': // wchar_t.
8579 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8580 Type = Context.getWideCharType();
8581 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008582 case 'F':
8583 Type = Context.getCFConstantStringType();
8584 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008585 case 'G':
8586 Type = Context.getObjCIdType();
8587 break;
8588 case 'H':
8589 Type = Context.getObjCSelType();
8590 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008591 case 'M':
8592 Type = Context.getObjCSuperType();
8593 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008594 case 'a':
8595 Type = Context.getBuiltinVaListType();
8596 assert(!Type.isNull() && "builtin va list type not initialized!");
8597 break;
8598 case 'A':
8599 // This is a "reference" to a va_list; however, what exactly
8600 // this means depends on how va_list is defined. There are two
8601 // different kinds of va_list: ones passed by value, and ones
8602 // passed by reference. An example of a by-value va_list is
8603 // x86, where va_list is a char*. An example of by-ref va_list
8604 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8605 // we want this argument to be a char*&; for x86-64, we want
8606 // it to be a __va_list_tag*.
8607 Type = Context.getBuiltinVaListType();
8608 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008609 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008610 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008611 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008612 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008613 break;
8614 case 'V': {
8615 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008616 unsigned NumElements = strtoul(Str, &End, 10);
8617 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008618 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008619
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8621 RequiresICE, false);
8622 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008623
8624 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008625 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008626 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008627 break;
8628 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008629 case 'E': {
8630 char *End;
8631
8632 unsigned NumElements = strtoul(Str, &End, 10);
8633 assert(End != Str && "Missing vector size");
8634
8635 Str = End;
8636
8637 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8638 false);
8639 Type = Context.getExtVectorType(ElementType, NumElements);
8640 break;
8641 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008642 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8644 false);
8645 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008646 Type = Context.getComplexType(ElementType);
8647 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008648 }
8649 case 'Y' : {
8650 Type = Context.getPointerDiffType();
8651 break;
8652 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008653 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008654 Type = Context.getFILEType();
8655 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008656 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008657 return QualType();
8658 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008659 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008660 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008661 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008662 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008663 else
8664 Type = Context.getjmp_bufType();
8665
Mike Stump2adb4da2009-07-28 23:47:15 +00008666 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008667 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008668 return QualType();
8669 }
8670 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008671 case 'K':
8672 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8673 Type = Context.getucontext_tType();
8674
8675 if (Type.isNull()) {
8676 Error = ASTContext::GE_Missing_ucontext;
8677 return QualType();
8678 }
8679 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008680 case 'p':
8681 Type = Context.getProcessIDType();
8682 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008683 }
Mike Stump11289f42009-09-09 15:08:12 +00008684
Chris Lattnerdc226c22010-10-01 22:42:38 +00008685 // If there are modifiers and if we're allowed to parse them, go for it.
8686 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008687 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008688 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008689 default: Done = true; --Str; break;
8690 case '*':
8691 case '&': {
8692 // Both pointers and references can have their pointee types
8693 // qualified with an address space.
8694 char *End;
8695 unsigned AddrSpace = strtoul(Str, &End, 10);
8696 if (End != Str && AddrSpace != 0) {
8697 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8698 Str = End;
8699 }
8700 if (c == '*')
8701 Type = Context.getPointerType(Type);
8702 else
8703 Type = Context.getLValueReferenceType(Type);
8704 break;
8705 }
8706 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8707 case 'C':
8708 Type = Type.withConst();
8709 break;
8710 case 'D':
8711 Type = Context.getVolatileType(Type);
8712 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008713 case 'R':
8714 Type = Type.withRestrict();
8715 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008716 }
8717 }
Chris Lattner84733392010-10-01 07:13:18 +00008718
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008719 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008720 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008721
Chris Lattnerecd79c62009-06-14 00:45:47 +00008722 return Type;
8723}
8724
8725/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008726QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008727 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008728 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008729 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008730
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008731 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008732
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008733 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008734 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008735 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8736 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008737 if (Error != GE_None)
8738 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008739
8740 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8741
Chris Lattnerecd79c62009-06-14 00:45:47 +00008742 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008743 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008744 if (Error != GE_None)
8745 return QualType();
8746
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008747 // If this argument is required to be an IntegerConstantExpression and the
8748 // caller cares, fill in the bitmask we return.
8749 if (RequiresICE && IntegerConstantArgs)
8750 *IntegerConstantArgs |= 1 << ArgTypes.size();
8751
Chris Lattnerecd79c62009-06-14 00:45:47 +00008752 // Do array -> pointer decay. The builtin should use the decayed type.
8753 if (Ty->isArrayType())
8754 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008755
Chris Lattnerecd79c62009-06-14 00:45:47 +00008756 ArgTypes.push_back(Ty);
8757 }
8758
David Majnemerba3e5ec2015-03-13 18:26:17 +00008759 if (Id == Builtin::BI__GetExceptionInfo)
8760 return QualType();
8761
Chris Lattnerecd79c62009-06-14 00:45:47 +00008762 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8763 "'.' should only occur at end of builtin type list!");
8764
Reid Kleckner78af0702013-08-27 23:08:25 +00008765 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008766 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8767
8768 bool Variadic = (TypeStr[0] == '.');
8769
Richard Smith836de6b2016-12-19 23:59:34 +00008770 // We really shouldn't be making a no-proto type here.
8771 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008772 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008773
John McCalldb40c7f2010-12-14 08:05:40 +00008774 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008775 EPI.ExtInfo = EI;
8776 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008777 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8778 EPI.ExceptionSpec.Type =
8779 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008780
Jordan Rose5c382722013-03-08 21:51:21 +00008781 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008782}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008783
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008784static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8785 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008786 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008787 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008788
Rafael Espindola3ae00052013-05-13 00:12:11 +00008789 GVALinkage External = GVA_StrongExternal;
8790 switch (FD->getTemplateSpecializationKind()) {
8791 case TSK_Undeclared:
8792 case TSK_ExplicitSpecialization:
8793 External = GVA_StrongExternal;
8794 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008795
Rafael Espindola3ae00052013-05-13 00:12:11 +00008796 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008797 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008798
David Majnemerc3d07332014-05-15 06:25:57 +00008799 // C++11 [temp.explicit]p10:
8800 // [ Note: The intent is that an inline function that is the subject of
8801 // an explicit instantiation declaration will still be implicitly
8802 // instantiated when used so that the body can be considered for
8803 // inlining, but that no out-of-line copy of the inline function would be
8804 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008805 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008806 return GVA_AvailableExternally;
8807
Rafael Espindola3ae00052013-05-13 00:12:11 +00008808 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008809 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008810 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008811 }
8812
8813 if (!FD->isInlined())
8814 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008815
David Majnemer3f021502015-10-08 04:53:31 +00008816 if ((!Context.getLangOpts().CPlusPlus &&
8817 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008818 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008819 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008820 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8821
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008822 // GNU or C99 inline semantics. Determine whether this symbol should be
8823 // externally visible.
8824 if (FD->isInlineDefinitionExternallyVisible())
8825 return External;
8826
8827 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008828 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008829 }
8830
David Majnemer54e3ba52014-04-02 23:17:29 +00008831 // Functions specified with extern and inline in -fms-compatibility mode
8832 // forcibly get emitted. While the body of the function cannot be later
8833 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008834 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008835 return GVA_StrongODR;
8836
David Majnemer27d69db2014-04-28 22:17:59 +00008837 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008838}
8839
Artem Belevichca2b9512016-05-02 20:30:03 +00008840static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8841 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008842 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8843 // dllexport/dllimport on inline functions.
8844 if (D->hasAttr<DLLImportAttr>()) {
8845 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8846 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008847 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008848 if (L == GVA_DiscardableODR)
8849 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008850 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8851 D->hasAttr<CUDAGlobalAttr>()) {
8852 // Device-side functions with __global__ attribute must always be
8853 // visible externally so they can be launched from host.
8854 if (L == GVA_DiscardableODR || L == GVA_Internal)
8855 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008856 }
8857 return L;
8858}
8859
8860GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008861 return adjustGVALinkageForAttributes(
8862 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008863}
8864
8865static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8866 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008867 if (!VD->isExternallyVisible())
8868 return GVA_Internal;
8869
David Majnemer27d69db2014-04-28 22:17:59 +00008870 if (VD->isStaticLocal()) {
8871 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8872 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8873 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8874 LexicalContext = LexicalContext->getLexicalParent();
8875
Richard Smith9e2341d2015-03-23 03:25:59 +00008876 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008877 // enclosing function.
8878 if (LexicalContext)
8879 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008880 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008881
8882 // GVA_StrongODR function linkage is stronger than what we need,
8883 // downgrade to GVA_DiscardableODR.
8884 // This allows us to discard the variable if we never end up needing it.
8885 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8886 : StaticLocalLinkage;
8887 }
8888
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008889 // MSVC treats in-class initialized static data members as definitions.
8890 // By giving them non-strong linkage, out-of-line definitions won't
8891 // cause link errors.
8892 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8893 return GVA_DiscardableODR;
8894
Richard Smithd9b90092016-07-02 01:32:16 +00008895 // Most non-template variables have strong linkage; inline variables are
8896 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8897 GVALinkage StrongLinkage;
8898 switch (Context.getInlineVariableDefinitionKind(VD)) {
8899 case ASTContext::InlineVariableDefinitionKind::None:
8900 StrongLinkage = GVA_StrongExternal;
8901 break;
8902 case ASTContext::InlineVariableDefinitionKind::Weak:
8903 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008904 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008905 break;
8906 case ASTContext::InlineVariableDefinitionKind::Strong:
8907 StrongLinkage = GVA_StrongODR;
8908 break;
8909 }
Richard Smith62f19e72016-06-25 00:15:56 +00008910
Richard Smith8809a0c2013-09-27 20:14:12 +00008911 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008912 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008913 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008914
David Majnemer6d1780c2015-07-17 23:36:49 +00008915 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008916 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8917 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008918 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008919 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008920
Rafael Espindola3ae00052013-05-13 00:12:11 +00008921 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008922 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008923
David Majnemer27d69db2014-04-28 22:17:59 +00008924 case TSK_ExplicitInstantiationDeclaration:
8925 return GVA_AvailableExternally;
8926
Rafael Espindola3ae00052013-05-13 00:12:11 +00008927 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008928 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008929 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008930
8931 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008932}
8933
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008934GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008935 return adjustGVALinkageForAttributes(
8936 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008937}
8938
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008939bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008940 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8941 if (!VD->isFileVarDecl())
8942 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008943 // Global named register variables (GNU extension) are never emitted.
8944 if (VD->getStorageClass() == SC_Register)
8945 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008946 if (VD->getDescribedVarTemplate() ||
8947 isa<VarTemplatePartialSpecializationDecl>(VD))
8948 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008949 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8950 // We never need to emit an uninstantiated function template.
8951 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8952 return false;
Nico Weber66220292016-03-02 17:28:48 +00008953 } else if (isa<PragmaCommentDecl>(D))
8954 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008955 else if (isa<OMPThreadPrivateDecl>(D) ||
8956 D->hasAttr<OMPDeclareTargetDeclAttr>())
8957 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008958 else if (isa<PragmaDetectMismatchDecl>(D))
8959 return true;
Nico Weber66220292016-03-02 17:28:48 +00008960 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008961 return !D->getDeclContext()->isDependentContext();
8962 else if (isa<OMPDeclareReductionDecl>(D))
8963 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008964 else if (isa<ImportDecl>(D))
8965 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008966 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008967 return false;
8968
8969 // If this is a member of a class template, we do not need to emit it.
8970 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008971 return false;
8972
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008973 // Weak references don't produce any output by themselves.
8974 if (D->hasAttr<WeakRefAttr>())
8975 return false;
8976
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008977 // Aliases and used decls are required.
8978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8979 return true;
8980
8981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8982 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008983 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008984 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008985
8986 // Constructors and destructors are required.
8987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8988 return true;
8989
John McCall6bd2a892013-01-25 22:31:03 +00008990 // The key function for a class is required. This rule only comes
8991 // into play when inline functions can be key functions, though.
8992 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8993 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8994 const CXXRecordDecl *RD = MD->getParent();
8995 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8996 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8997 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8998 return true;
8999 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009000 }
9001 }
9002
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009003 // static, static inline, always_inline, and extern inline functions can
9004 // always be deferred. Normal inline functions can be deferred in C99/C++.
9005 // Implicit template instantiations can also be deferred in C++.
Justin Lebar606f01f2016-10-13 20:52:17 +00009006 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009007 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009008
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009009 const VarDecl *VD = cast<VarDecl>(D);
9010 assert(VD->isFileVarDecl() && "Expected file scoped var");
9011
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009012 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9013 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009014 return false;
9015
Richard Smitha0e5e542012-11-12 21:38:00 +00009016 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009017 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009018 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009019
Richard Smitha0e5e542012-11-12 21:38:00 +00009020 // Variables that have destruction with side-effects are required.
9021 if (VD->getType().isDestructedType())
9022 return true;
9023
9024 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009025 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9026 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00009027 return true;
9028
Richard Smithda383632016-08-15 01:33:41 +00009029 // Likewise, variables with tuple-like bindings are required if their
9030 // bindings have side-effects.
9031 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9032 for (auto *BD : DD->bindings())
9033 if (auto *BindingVD = BD->getHoldingVar())
9034 if (DeclMustBeEmitted(BindingVD))
9035 return true;
9036
Richard Smitha0e5e542012-11-12 21:38:00 +00009037 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009038}
Charles Davis53c59df2010-08-16 03:33:14 +00009039
Reid Kleckner78af0702013-08-27 23:08:25 +00009040CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9041 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009042 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009043 if (IsCXXMethod)
9044 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009045
Alexey Bataeva7547182016-05-18 09:06:38 +00009046 switch (LangOpts.getDefaultCallingConv()) {
9047 case LangOptions::DCC_None:
9048 break;
9049 case LangOptions::DCC_CDecl:
9050 return CC_C;
9051 case LangOptions::DCC_FastCall:
9052 if (getTargetInfo().hasFeature("sse2"))
9053 return CC_X86FastCall;
9054 break;
9055 case LangOptions::DCC_StdCall:
9056 if (!IsVariadic)
9057 return CC_X86StdCall;
9058 break;
9059 case LangOptions::DCC_VectorCall:
9060 // __vectorcall cannot be applied to variadic functions.
9061 if (!IsVariadic)
9062 return CC_X86VectorCall;
9063 break;
9064 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009065 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009066}
9067
Jay Foad39c79802011-01-12 09:06:06 +00009068bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009069 // Pass through to the C++ ABI object
9070 return ABI->isNearlyEmpty(RD);
9071}
9072
Reid Kleckner96f8f932014-02-05 17:27:08 +00009073VTableContextBase *ASTContext::getVTableContext() {
9074 if (!VTContext.get()) {
9075 if (Target->getCXXABI().isMicrosoft())
9076 VTContext.reset(new MicrosoftVTableContext(*this));
9077 else
9078 VTContext.reset(new ItaniumVTableContext(*this));
9079 }
9080 return VTContext.get();
9081}
9082
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009083MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009084 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009085 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009086 case TargetCXXABI::GenericItanium:
9087 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009088 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009089 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009090 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009091 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009092 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009093 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009094 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009095 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009096 }
David Blaikie83d382b2011-09-23 05:06:16 +00009097 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009098}
9099
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009100CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009101
9102size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009103 return ASTRecordLayouts.getMemorySize() +
9104 llvm::capacity_in_bytes(ObjCLayouts) +
9105 llvm::capacity_in_bytes(KeyFunctions) +
9106 llvm::capacity_in_bytes(ObjCImpls) +
9107 llvm::capacity_in_bytes(BlockVarCopyInits) +
9108 llvm::capacity_in_bytes(DeclAttrs) +
9109 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9110 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9111 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9112 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9113 llvm::capacity_in_bytes(OverriddenMethods) +
9114 llvm::capacity_in_bytes(Types) +
9115 llvm::capacity_in_bytes(VariableArrayTypes) +
9116 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009117}
Ted Kremenek540017e2011-10-06 05:00:56 +00009118
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009119/// getIntTypeForBitwidth -
9120/// sets integer QualTy according to specified details:
9121/// bitwidth, signed/unsigned.
9122/// Returns empty type if there is no appropriate target types.
9123QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9124 unsigned Signed) const {
9125 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9126 CanQualType QualTy = getFromTargetType(Ty);
9127 if (!QualTy && DestWidth == 128)
9128 return Signed ? Int128Ty : UnsignedInt128Ty;
9129 return QualTy;
9130}
9131
9132/// getRealTypeForBitwidth -
9133/// sets floating point QualTy according to specified bitwidth.
9134/// Returns empty type if there is no appropriate target types.
9135QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9136 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9137 switch (Ty) {
9138 case TargetInfo::Float:
9139 return FloatTy;
9140 case TargetInfo::Double:
9141 return DoubleTy;
9142 case TargetInfo::LongDouble:
9143 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009144 case TargetInfo::Float128:
9145 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009146 case TargetInfo::NoFloat:
9147 return QualType();
9148 }
9149
9150 llvm_unreachable("Unhandled TargetInfo::RealType value");
9151}
9152
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009153void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9154 if (Number > 1)
9155 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009156}
9157
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009158unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009159 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009160 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009161}
9162
David Majnemer2206bf52014-03-05 08:57:59 +00009163void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9164 if (Number > 1)
9165 StaticLocalNumbers[VD] = Number;
9166}
9167
9168unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009169 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009170 return I != StaticLocalNumbers.end() ? I->second : 1;
9171}
9172
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009173MangleNumberingContext &
9174ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009175 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009176 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009177 if (!MCtx)
9178 MCtx = createMangleNumberingContext();
9179 return *MCtx;
9180}
9181
Justin Lebar20ebffc2016-10-10 16:26:19 +00009182std::unique_ptr<MangleNumberingContext>
9183ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009184 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009185}
9186
David Majnemere7a818f2015-03-06 18:53:55 +00009187const CXXConstructorDecl *
9188ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9189 return ABI->getCopyConstructorForExceptionObject(
9190 cast<CXXRecordDecl>(RD->getFirstDecl()));
9191}
9192
9193void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9194 CXXConstructorDecl *CD) {
9195 return ABI->addCopyConstructorForExceptionObject(
9196 cast<CXXRecordDecl>(RD->getFirstDecl()),
9197 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9198}
9199
David Majnemer00350522015-08-31 18:48:39 +00009200void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9201 TypedefNameDecl *DD) {
9202 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9203}
9204
9205TypedefNameDecl *
9206ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9207 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9208}
9209
9210void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9211 DeclaratorDecl *DD) {
9212 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9213}
9214
9215DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9216 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9217}
9218
Ted Kremenek540017e2011-10-06 05:00:56 +00009219void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9220 ParamIndices[D] = index;
9221}
9222
9223unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9224 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9225 assert(I != ParamIndices.end() &&
9226 "ParmIndices lacks entry set by ParmVarDecl");
9227 return I->second;
9228}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009229
Richard Smithe6c01442013-06-05 00:46:14 +00009230APValue *
9231ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9232 bool MayCreate) {
9233 assert(E && E->getStorageDuration() == SD_Static &&
9234 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009235 if (MayCreate) {
9236 APValue *&MTVI = MaterializedTemporaryValues[E];
9237 if (!MTVI)
9238 MTVI = new (*this) APValue;
9239 return MTVI;
9240 }
Richard Smithe6c01442013-06-05 00:46:14 +00009241
David Majnemer2dcef9e2015-08-13 23:50:15 +00009242 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009243}
9244
Fariborz Jahanian615de762013-05-28 17:37:39 +00009245bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9246 const llvm::Triple &T = getTargetInfo().getTriple();
9247 if (!T.isOSDarwin())
9248 return false;
9249
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009250 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9251 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9252 return false;
9253
Fariborz Jahanian615de762013-05-28 17:37:39 +00009254 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9255 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9256 uint64_t Size = sizeChars.getQuantity();
9257 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9258 unsigned Align = alignChars.getQuantity();
9259 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9260 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9261}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009262
9263namespace {
9264
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009265ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9266 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009267 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009268 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009269 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009270 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009271 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009272}
9273
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009274/// Template specializations to abstract away from pointers and TypeLocs.
9275/// @{
9276template <typename T>
9277ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9278 return ast_type_traits::DynTypedNode::create(*Node);
9279}
9280template <>
9281ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9282 return ast_type_traits::DynTypedNode::create(Node);
9283}
9284template <>
9285ast_type_traits::DynTypedNode
9286createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9287 return ast_type_traits::DynTypedNode::create(Node);
9288}
9289/// @}
9290
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009291 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9292 /// parents as defined by the \c RecursiveASTVisitor.
9293 ///
9294 /// Note that the relationship described here is purely in terms of AST
9295 /// traversal - there are other relationships (for example declaration context)
9296 /// in the AST that are better modeled by special matchers.
9297 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009298 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009299 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009300 public:
9301 /// \brief Builds and returns the translation unit's parent map.
9302 ///
9303 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009304 static std::pair<ASTContext::ParentMapPointers *,
9305 ASTContext::ParentMapOtherNodes *>
9306 buildMap(TranslationUnitDecl &TU) {
9307 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9308 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009309 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009310 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009311 }
9312
9313 private:
9314 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9315
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009316 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9317 ASTContext::ParentMapOtherNodes *OtherParents)
9318 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009319
9320 bool shouldVisitTemplateInstantiations() const {
9321 return true;
9322 }
9323 bool shouldVisitImplicitCode() const {
9324 return true;
9325 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009326
Richard Smith85838722015-11-24 03:09:01 +00009327 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9328 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009329 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009330 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009331 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009332 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009333 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009334 // FIXME: Currently we add the same parent multiple times, but only
9335 // when no memoization data is available for the type.
9336 // For example when we visit all subexpressions of template
9337 // instantiations; this is suboptimal, but benign: the only way to
9338 // visit those is with hasAncestor / hasParent, and those do not create
9339 // new matches.
9340 // The plan is to enable DynTypedNode to be storable in a map or hash
9341 // map. The main problem there is to implement hash functions /
9342 // comparison operators for all types that DynTypedNode supports that
9343 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009344 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009345 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009346 if (const auto *D = ParentStack.back().get<Decl>())
9347 NodeOrVector = D;
9348 else if (const auto *S = ParentStack.back().get<Stmt>())
9349 NodeOrVector = S;
9350 else
9351 NodeOrVector =
9352 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009353 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009354 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9355 auto *Vector = new ASTContext::ParentVector(
9356 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009357 if (auto *Node =
9358 NodeOrVector
9359 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9360 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009361 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009362 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009363
9364 auto *Vector =
9365 NodeOrVector.template get<ASTContext::ParentVector *>();
9366 // Skip duplicates for types that have memoization data.
9367 // We must check that the type has memoization data before calling
9368 // std::find() because DynTypedNode::operator== can't compare all
9369 // types.
9370 bool Found = ParentStack.back().getMemoizationData() &&
9371 std::find(Vector->begin(), Vector->end(),
9372 ParentStack.back()) != Vector->end();
9373 if (!Found)
9374 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009375 }
9376 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009377 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009378 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009379 ParentStack.pop_back();
9380 return Result;
9381 }
9382
9383 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009384 return TraverseNode(DeclNode, DeclNode,
9385 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009386 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009387 }
9388
9389 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009390 return TraverseNode(StmtNode, StmtNode,
9391 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009392 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009393 }
9394
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009395 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009396 return TraverseNode(
9397 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9398 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9399 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009400 }
9401
9402 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9403 return TraverseNode(
9404 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009405 [&] {
9406 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9407 },
9408 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009409 }
9410
9411 ASTContext::ParentMapPointers *Parents;
9412 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009413 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9414
9415 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9416 };
9417
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009418} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009419
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009420template <typename NodeTy, typename MapTy>
9421static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9422 const MapTy &Map) {
9423 auto I = Map.find(Node);
9424 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009425 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009426 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009427 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009428 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009429 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009430 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009431}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009432
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009433ASTContext::DynTypedNodeList
9434ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9435 if (!PointerParents) {
9436 // We always need to run over the whole translation unit, as
9437 // hasAncestor can escape any subtree.
9438 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9439 PointerParents.reset(Maps.first);
9440 OtherParents.reset(Maps.second);
9441 }
9442 if (Node.getNodeKind().hasPointerIdentity())
9443 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9444 return getDynNodeFromMap(Node, *OtherParents);
9445}
9446
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009447bool
9448ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9449 const ObjCMethodDecl *MethodImpl) {
9450 // No point trying to match an unavailable/deprecated mothod.
9451 if (MethodDecl->hasAttr<UnavailableAttr>()
9452 || MethodDecl->hasAttr<DeprecatedAttr>())
9453 return false;
9454 if (MethodDecl->getObjCDeclQualifier() !=
9455 MethodImpl->getObjCDeclQualifier())
9456 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009457 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009458 return false;
9459
9460 if (MethodDecl->param_size() != MethodImpl->param_size())
9461 return false;
9462
9463 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9464 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9465 EF = MethodDecl->param_end();
9466 IM != EM && IF != EF; ++IM, ++IF) {
9467 const ParmVarDecl *DeclVar = (*IF);
9468 const ParmVarDecl *ImplVar = (*IM);
9469 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9470 return false;
9471 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9472 return false;
9473 }
9474 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9475
9476}
Richard Smith053f6c62014-05-16 23:01:30 +00009477
Yaxun Liu402804b2016-12-15 08:09:08 +00009478uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9479 unsigned AS;
9480 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9481 AS = 0;
9482 else
9483 AS = QT->getPointeeType().getAddressSpace();
9484
9485 return getTargetInfo().getNullPointerValue(AS);
9486}
9487
Richard Smith053f6c62014-05-16 23:01:30 +00009488// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9489// doesn't include ASTContext.h
9490template
9491clang::LazyGenerationalUpdatePtr<
9492 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9493clang::LazyGenerationalUpdatePtr<
9494 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9495 const clang::ASTContext &Ctx, Decl *Value);