blob: 18240e79d80d4fda0c151a0f348853800d7705f3 [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"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.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 {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
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,
635 ExpandedTypes.data(),
636 ExpandedTypes.size(),
637 ExpandedTInfos.data());
638 } else {
639 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000640 SourceLocation(),
641 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000642 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000643 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000644 T,
645 NTTP->isParameterPack(),
646 TInfo);
647 }
648 CanonParams.push_back(Param);
649
650 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652 cast<TemplateTemplateParmDecl>(*P)));
653 }
654
655 TemplateTemplateParmDecl *CanonTTP
656 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000658 TTP->getPosition(),
659 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000661 TemplateParameterList::Create(*this, SourceLocation(),
662 SourceLocation(),
663 CanonParams.data(),
664 CanonParams.size(),
665 SourceLocation()));
666
667 // Get the new insert position for the node we care about.
668 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000669 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000670 (void)Canonical;
671
672 // Create the canonical template template parameter entry.
673 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
674 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
675 return CanonTTP;
676}
677
Charles Davis53c59df2010-08-16 03:33:14 +0000678CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000679 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000680
John McCall359b8852013-01-25 22:30:49 +0000681 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000682 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000683 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000684 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000685 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000686 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000687 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000689 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000690 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000692 return CreateMicrosoftCXXABI(*this);
693 }
David Blaikie8a40f702012-01-17 06:56:22 +0000694 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000695}
696
Douglas Gregore8bbc122011-09-02 00:18:52 +0000697static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000698 const LangOptions &LOpts) {
699 if (LOpts.FakeAddressSpaceMap) {
700 // The fake address space map must have a distinct entry for each
701 // language-specific address space.
702 static const unsigned FakeAddrSpaceMap[] = {
703 1, // opencl_global
704 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000705 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000706 4, // opencl_generic
707 5, // cuda_device
708 6, // cuda_constant
709 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 }
715}
716
David Tweed31d09b02013-09-13 12:04:22 +0000717static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
718 const LangOptions &LangOpts) {
719 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000720 case LangOptions::ASMM_Target:
721 return TI.useAddressSpaceMapMangling();
722 case LangOptions::ASMM_On:
723 return true;
724 case LangOptions::ASMM_Off:
725 return false;
726 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000727 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000728}
729
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000731 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000732 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
734 DependentTemplateSpecializationTypes(this_()),
735 SubstTemplateTemplateParmPacks(this_()),
736 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
737 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000738 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
739 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
740 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000741 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
742 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
743 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
744 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000745 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000746 MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000747 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000748 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
749 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
750 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
751 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000752 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000753 TUDecl = TranslationUnitDecl::Create(*this);
754}
755
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000756ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000757 ReleaseParentMapEntries();
758
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000759 // Release the DenseMaps associated with DeclContext objects.
760 // FIXME: Is this the ideal solution?
761 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000762
Manuel Klimeka7328992013-06-03 13:51:33 +0000763 // Call all of the deallocation functions on all of their targets.
764 for (DeallocationMap::const_iterator I = Deallocations.begin(),
765 E = Deallocations.end(); I != E; ++I)
766 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
767 (I->first)((I->second)[J]);
768
Ted Kremenek076baeb2010-06-08 23:00:58 +0000769 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000770 // because they can contain DenseMaps.
771 for (llvm::DenseMap<const ObjCContainerDecl*,
772 const ASTRecordLayout*>::iterator
773 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
774 // Increment in loop to prevent using deallocated memory.
775 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776 R->Destroy(*this);
777
Ted Kremenek076baeb2010-06-08 23:00:58 +0000778 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
779 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
780 // Increment in loop to prevent using deallocated memory.
781 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
782 R->Destroy(*this);
783 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000784
785 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
786 AEnd = DeclAttrs.end();
787 A != AEnd; ++A)
788 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000789
David Majnemere694f3e2015-08-14 14:43:50 +0000790 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
791 MaterializedTemporaryValues)
792 MTVPair.second->~APValue();
793
Reid Kleckner588c9372014-02-19 23:44:52 +0000794 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000795}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000796
Manuel Klimek95403e62014-05-21 13:28:59 +0000797void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000798 if (!PointerParents) return;
799 for (const auto &Entry : *PointerParents) {
800 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
801 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
802 } else if (Entry.second.is<ParentVector *>()) {
803 delete Entry.second.get<ParentVector *>();
804 }
805 }
806 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000807 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
808 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000809 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000810 delete Entry.second.get<ParentVector *>();
811 }
812 }
813}
814
Douglas Gregor1a809332010-05-23 18:26:36 +0000815void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000816 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000817}
818
Mike Stump11289f42009-09-09 15:08:12 +0000819void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000820ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
821 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000822}
823
Chris Lattner4eb445d2007-01-26 01:27:23 +0000824void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000825 llvm::errs() << "\n*** AST Context Stats:\n";
826 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000827
Douglas Gregora30d0462009-05-26 14:40:08 +0000828 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000829#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000830#define ABSTRACT_TYPE(Name, Parent)
831#include "clang/AST/TypeNodes.def"
832 0 // Extra
833 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000834
Chris Lattner4eb445d2007-01-26 01:27:23 +0000835 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
836 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000838 }
839
Douglas Gregora30d0462009-05-26 14:40:08 +0000840 unsigned Idx = 0;
841 unsigned TotalBytes = 0;
842#define TYPE(Name, Parent) \
843 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844 llvm::errs() << " " << counts[Idx] << " " << #Name \
845 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000846 TotalBytes += counts[Idx] * sizeof(Name##Type); \
847 ++Idx;
848#define ABSTRACT_TYPE(Name, Parent)
849#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chandler Carruth3c147a72011-07-04 05:32:14 +0000851 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
852
Douglas Gregor7454c562010-07-02 20:37:36 +0000853 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
855 << NumImplicitDefaultConstructors
856 << " implicit default constructors created\n";
857 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
858 << NumImplicitCopyConstructors
859 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000860 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000861 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
862 << NumImplicitMoveConstructors
863 << " implicit move constructors created\n";
864 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
865 << NumImplicitCopyAssignmentOperators
866 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000867 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
869 << NumImplicitMoveAssignmentOperators
870 << " implicit move assignment operators created\n";
871 llvm::errs() << NumImplicitDestructorsDeclared << "/"
872 << NumImplicitDestructors
873 << " implicit destructors created\n";
874
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000875 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000876 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000877 ExternalSource->PrintStats();
878 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000879
Douglas Gregor5b11d492010-07-25 17:53:33 +0000880 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000881}
882
Richard Smith42413142015-05-15 20:05:43 +0000883void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
884 bool NotifyListeners) {
885 if (NotifyListeners)
886 if (auto *Listener = getASTMutationListener())
887 Listener->RedefinedHiddenDefinition(ND, M);
888
889 if (getLangOpts().ModulesLocalVisibility)
890 MergedDefModules[ND].push_back(M);
891 else
892 ND->setHidden(false);
893}
894
895void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
896 auto It = MergedDefModules.find(ND);
897 if (It == MergedDefModules.end())
898 return;
899
900 auto &Merged = It->second;
901 llvm::DenseSet<Module*> Found;
902 for (Module *&M : Merged)
903 if (!Found.insert(M).second)
904 M = nullptr;
905 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
906}
907
Richard Smithf19e1272015-03-07 00:04:49 +0000908ExternCContextDecl *ASTContext::getExternCContextDecl() const {
909 if (!ExternCContext)
910 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
911
912 return ExternCContext;
913}
914
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000915BuiltinTemplateDecl *
916ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
917 const IdentifierInfo *II) const {
918 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
919 BuiltinTemplate->setImplicit();
920 TUDecl->addDecl(BuiltinTemplate);
921
922 return BuiltinTemplate;
923}
924
925BuiltinTemplateDecl *
926ASTContext::getMakeIntegerSeqDecl() const {
927 if (!MakeIntegerSeqDecl)
928 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
929 getMakeIntegerSeqName());
930 return MakeIntegerSeqDecl;
931}
932
Alp Toker2dea15b2013-12-17 01:22:38 +0000933RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
934 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000935 SourceLocation Loc;
936 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000937 if (getLangOpts().CPlusPlus)
938 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
939 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000941 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
942 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000943 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000944 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
945 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000946 return NewDecl;
947}
948
949TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
950 StringRef Name) const {
951 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
952 TypedefDecl *NewDecl = TypedefDecl::Create(
953 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
954 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
955 NewDecl->setImplicit();
956 return NewDecl;
957}
958
Douglas Gregor801c99d2011-08-12 06:49:56 +0000959TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000960 if (!Int128Decl)
961 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000962 return Int128Decl;
963}
964
965TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000966 if (!UInt128Decl)
967 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000968 return UInt128Decl;
969}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000970
Nico Webere1687c52013-06-20 21:44:55 +0000971TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000972 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000973 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000974 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000975
Nico Webere1687c52013-06-20 21:44:55 +0000976 return Float128StubDecl;
977}
978
John McCall48f2d582009-10-23 23:03:21 +0000979void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000980 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000981 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000982 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000983}
984
Artem Belevichb5bc9232015-09-22 17:23:22 +0000985void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
986 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000987 assert((!this->Target || this->Target == &Target) &&
988 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000989 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000990
Douglas Gregore8bbc122011-09-02 00:18:52 +0000991 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000992 this->AuxTarget = AuxTarget;
993
Douglas Gregore8bbc122011-09-02 00:18:52 +0000994 ABI.reset(createCXXABI(Target));
995 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000996 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000997
Chris Lattner970e54e2006-11-12 00:37:36 +0000998 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000999 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chris Lattner970e54e2006-11-12 00:37:36 +00001001 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001002 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001003 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001004 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001005 InitBuiltinType(CharTy, BuiltinType::Char_S);
1006 else
1007 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001008 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001009 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1010 InitBuiltinType(ShortTy, BuiltinType::Short);
1011 InitBuiltinType(IntTy, BuiltinType::Int);
1012 InitBuiltinType(LongTy, BuiltinType::Long);
1013 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattner970e54e2006-11-12 00:37:36 +00001015 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001016 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1017 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1018 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1019 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1020 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001021
Chris Lattner970e54e2006-11-12 00:37:36 +00001022 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001023 InitBuiltinType(FloatTy, BuiltinType::Float);
1024 InitBuiltinType(DoubleTy, BuiltinType::Double);
1025 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001026
Chris Lattnerf122cef2009-04-30 02:43:43 +00001027 // GNU extension, 128-bit integers.
1028 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1029 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1030
Hans Wennborg0d81e012013-05-10 10:08:40 +00001031 // C++ 3.9.1p5
1032 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1033 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1034 else // -fshort-wchar makes wchar_t be unsigned.
1035 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1036 if (LangOpts.CPlusPlus && LangOpts.WChar)
1037 WideCharTy = WCharTy;
1038 else {
1039 // C99 (or C++ using -fno-wchar).
1040 WideCharTy = getFromTargetType(Target.getWCharType());
1041 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001042
James Molloy36365542012-05-04 10:55:22 +00001043 WIntTy = getFromTargetType(Target.getWIntType());
1044
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001045 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1046 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1047 else // C99
1048 Char16Ty = getFromTargetType(Target.getChar16Type());
1049
1050 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1051 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1052 else // C99
1053 Char32Ty = getFromTargetType(Target.getChar32Type());
1054
Douglas Gregor4619e432008-12-05 23:32:09 +00001055 // Placeholder type for type-dependent expressions whose type is
1056 // completely unknown. No code should ever check a type against
1057 // DependentTy and users should never see it; however, it is here to
1058 // help diagnose failures to properly check for type-dependent
1059 // expressions.
1060 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
John McCall36e7fe32010-10-12 00:20:44 +00001062 // Placeholder type for functions.
1063 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1064
John McCall0009fcc2011-04-26 20:42:42 +00001065 // Placeholder type for bound members.
1066 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1067
John McCall526ab472011-10-25 17:37:35 +00001068 // Placeholder type for pseudo-objects.
1069 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1070
John McCall31996342011-04-07 08:22:57 +00001071 // "any" type; useful for debugger-like clients.
1072 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1073
John McCall8a6b59a2011-10-17 18:09:15 +00001074 // Placeholder type for unbridged ARC casts.
1075 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1076
Eli Friedman34866c72012-08-31 00:14:07 +00001077 // Placeholder type for builtin functions.
1078 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1079
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001080 // Placeholder type for OMP array sections.
1081 if (LangOpts.OpenMP)
1082 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1083
Chris Lattner970e54e2006-11-12 00:37:36 +00001084 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001085 FloatComplexTy = getComplexType(FloatTy);
1086 DoubleComplexTy = getComplexType(DoubleTy);
1087 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001088
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001089 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001090 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1091 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001092 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001093
1094 if (LangOpts.OpenCL) {
1095 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1096 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1097 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1098 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1099 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001100 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1101 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1102 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1103 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1104 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1105 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1106 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001107 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001108
Guy Benyei61054192013-02-07 10:55:47 +00001109 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001110 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001111 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1112 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1113 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1114 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001115 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001116
1117 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001118 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1119 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001120
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001121 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001122
1123 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001124
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001125 // void * type
1126 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001127
1128 // nullptr type (C++0x 2.14.7)
1129 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001130
1131 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1132 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001133
1134 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001135 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001136}
1137
David Blaikie9c902b52011-09-25 23:23:43 +00001138DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001139 return SourceMgr.getDiagnostics();
1140}
1141
Douglas Gregor561eceb2010-08-30 16:49:28 +00001142AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1143 AttrVec *&Result = DeclAttrs[D];
1144 if (!Result) {
1145 void *Mem = Allocate(sizeof(AttrVec));
1146 Result = new (Mem) AttrVec;
1147 }
1148
1149 return *Result;
1150}
1151
1152/// \brief Erase the attributes corresponding to the given declaration.
1153void ASTContext::eraseDeclAttrs(const Decl *D) {
1154 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1155 if (Pos != DeclAttrs.end()) {
1156 Pos->second->~AttrVec();
1157 DeclAttrs.erase(Pos);
1158 }
1159}
1160
Larisse Voufo39a1e502013-08-06 01:03:05 +00001161// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001162MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001163ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001164 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001165 return getTemplateOrSpecializationInfo(Var)
1166 .dyn_cast<MemberSpecializationInfo *>();
1167}
1168
1169ASTContext::TemplateOrSpecializationInfo
1170ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1171 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1172 TemplateOrInstantiation.find(Var);
1173 if (Pos == TemplateOrInstantiation.end())
1174 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001175
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001176 return Pos->second;
1177}
1178
Mike Stump11289f42009-09-09 15:08:12 +00001179void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001180ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001181 TemplateSpecializationKind TSK,
1182 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001183 assert(Inst->isStaticDataMember() && "Not a static data member");
1184 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001185 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1186 Tmpl, TSK, PointOfInstantiation));
1187}
1188
1189void
1190ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1191 TemplateOrSpecializationInfo TSI) {
1192 assert(!TemplateOrInstantiation[Inst] &&
1193 "Already noted what the variable was instantiated from");
1194 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001195}
1196
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001197FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1198 const FunctionDecl *FD){
1199 assert(FD && "Specialization is 0");
1200 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001201 = ClassScopeSpecializationPattern.find(FD);
1202 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001203 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001204
1205 return Pos->second;
1206}
1207
1208void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1209 FunctionDecl *Pattern) {
1210 assert(FD && "Specialization is 0");
1211 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001212 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001213}
1214
John McCalle61f2ba2009-11-18 02:36:19 +00001215NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001216ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001217 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001218 = InstantiatedFromUsingDecl.find(UUD);
1219 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001220 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001221
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001222 return Pos->second;
1223}
1224
1225void
John McCallb96ec562009-12-04 22:46:56 +00001226ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1227 assert((isa<UsingDecl>(Pattern) ||
1228 isa<UnresolvedUsingValueDecl>(Pattern) ||
1229 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1230 "pattern decl is not a using decl");
1231 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1232 InstantiatedFromUsingDecl[Inst] = Pattern;
1233}
1234
1235UsingShadowDecl *
1236ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1237 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1238 = InstantiatedFromUsingShadowDecl.find(Inst);
1239 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001240 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001241
1242 return Pos->second;
1243}
1244
1245void
1246ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1247 UsingShadowDecl *Pattern) {
1248 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1249 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001250}
1251
Anders Carlsson5da84842009-09-01 04:26:58 +00001252FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1253 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1254 = InstantiatedFromUnnamedFieldDecl.find(Field);
1255 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001256 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001257
Anders Carlsson5da84842009-09-01 04:26:58 +00001258 return Pos->second;
1259}
1260
1261void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1262 FieldDecl *Tmpl) {
1263 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1264 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1265 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1266 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001267
Anders Carlsson5da84842009-09-01 04:26:58 +00001268 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1269}
1270
Douglas Gregor832940b2010-03-02 23:58:15 +00001271ASTContext::overridden_cxx_method_iterator
1272ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1273 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001274 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001275 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001276 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001277
1278 return Pos->second.begin();
1279}
1280
1281ASTContext::overridden_cxx_method_iterator
1282ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1283 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001284 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001285 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001286 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001287
1288 return Pos->second.end();
1289}
1290
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001291unsigned
1292ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1293 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001294 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001295 if (Pos == OverriddenMethods.end())
1296 return 0;
1297
1298 return Pos->second.size();
1299}
1300
Douglas Gregor832940b2010-03-02 23:58:15 +00001301void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1302 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001303 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001304 OverriddenMethods[Method].push_back(Overridden);
1305}
1306
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001307void ASTContext::getOverriddenMethods(
1308 const NamedDecl *D,
1309 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001310 assert(D);
1311
1312 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001313 Overridden.append(overridden_methods_begin(CXXMethod),
1314 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001315 return;
1316 }
1317
1318 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1319 if (!Method)
1320 return;
1321
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001322 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1323 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001324 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001325}
1326
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001327void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1328 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1329 assert(!Import->isFromASTFile() && "Non-local import declaration");
1330 if (!FirstLocalImport) {
1331 FirstLocalImport = Import;
1332 LastLocalImport = Import;
1333 return;
1334 }
1335
1336 LastLocalImport->NextLocalImport = Import;
1337 LastLocalImport = Import;
1338}
1339
Chris Lattner53cfe802007-07-18 17:52:12 +00001340//===----------------------------------------------------------------------===//
1341// Type Sizing and Analysis
1342//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001343
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001344/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1345/// scalar floating point type.
1346const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001347 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001348 assert(BT && "Not a floating point type!");
1349 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001350 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001351 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001352 case BuiltinType::Float: return Target->getFloatFormat();
1353 case BuiltinType::Double: return Target->getDoubleFormat();
1354 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001355 }
1356}
1357
Rafael Espindola71eccb32013-08-08 19:53:46 +00001358CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001359 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001360
John McCall94268702010-10-08 18:24:19 +00001361 bool UseAlignAttrOnly = false;
1362 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1363 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001364
John McCall94268702010-10-08 18:24:19 +00001365 // __attribute__((aligned)) can increase or decrease alignment
1366 // *except* on a struct or struct member, where it only increases
1367 // alignment unless 'packed' is also specified.
1368 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001369 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001370 // ignore that possibility; Sema should diagnose it.
1371 if (isa<FieldDecl>(D)) {
1372 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1373 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1374 } else {
1375 UseAlignAttrOnly = true;
1376 }
1377 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001378 else if (isa<FieldDecl>(D))
1379 UseAlignAttrOnly =
1380 D->hasAttr<PackedAttr>() ||
1381 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001382
John McCall4e819612011-01-20 07:57:12 +00001383 // If we're using the align attribute only, just ignore everything
1384 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001385 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001386 // do nothing
1387
John McCall94268702010-10-08 18:24:19 +00001388 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001389 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001390 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001391 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001392 T = RT->getPointeeType();
1393 else
1394 T = getPointerType(RT->getPointeeType());
1395 }
Richard Smithf6d70302014-06-10 23:34:28 +00001396 QualType BaseT = getBaseElementType(T);
1397 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001398 // Adjust alignments of declarations with array type by the
1399 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001400 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001401 unsigned MinWidth = Target->getLargeArrayMinWidth();
1402 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001403 if (isa<VariableArrayType>(arrayType))
1404 Align = std::max(Align, Target->getLargeArrayAlign());
1405 else if (isa<ConstantArrayType>(arrayType) &&
1406 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1407 Align = std::max(Align, Target->getLargeArrayAlign());
1408 }
John McCall33ddac02011-01-19 10:06:00 +00001409 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001410 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001411 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001412 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001413 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1414 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001415 }
John McCall4e819612011-01-20 07:57:12 +00001416
1417 // Fields can be subject to extra alignment constraints, like if
1418 // the field is packed, the struct is packed, or the struct has a
1419 // a max-field-alignment constraint (#pragma pack). So calculate
1420 // the actual alignment of the field within the struct, and then
1421 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001422 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1423 const RecordDecl *Parent = Field->getParent();
1424 // We can only produce a sensible answer if the record is valid.
1425 if (!Parent->isInvalidDecl()) {
1426 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001427
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001428 // Start with the record's overall alignment.
1429 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001430
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001431 // Use the GCD of that and the offset within the record.
1432 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1433 if (Offset > 0) {
1434 // Alignment is always a power of 2, so the GCD will be a power of 2,
1435 // which means we get to do this crazy thing instead of Euclid's.
1436 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1437 if (LowBitOfOffset < FieldAlign)
1438 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1439 }
1440
1441 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001442 }
Charles Davis3fc51072010-02-23 04:52:00 +00001443 }
Chris Lattner68061312009-01-24 21:53:27 +00001444 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001445
Ken Dyckcc56c542011-01-15 18:38:59 +00001446 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001447}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001448
John McCallf1249922012-08-21 04:10:00 +00001449// getTypeInfoDataSizeInChars - Return the size of a type, in
1450// chars. If the type is a record, its data size is returned. This is
1451// the size of the memcpy that's performed when assigning this type
1452// using a trivial copy/move assignment operator.
1453std::pair<CharUnits, CharUnits>
1454ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1455 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1456
1457 // In C++, objects can sometimes be allocated into the tail padding
1458 // of a base-class subobject. We decide whether that's possible
1459 // during class layout, so here we can just trust the layout results.
1460 if (getLangOpts().CPlusPlus) {
1461 if (const RecordType *RT = T->getAs<RecordType>()) {
1462 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1463 sizeAndAlign.first = layout.getDataSize();
1464 }
1465 }
1466
1467 return sizeAndAlign;
1468}
1469
Richard Trieu04d2d942013-05-14 21:59:17 +00001470/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1471/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1472std::pair<CharUnits, CharUnits>
1473static getConstantArrayInfoInChars(const ASTContext &Context,
1474 const ConstantArrayType *CAT) {
1475 std::pair<CharUnits, CharUnits> EltInfo =
1476 Context.getTypeInfoInChars(CAT->getElementType());
1477 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001478 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1479 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001480 "Overflow in array type char size evaluation");
1481 uint64_t Width = EltInfo.first.getQuantity() * Size;
1482 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001483 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1484 Context.getTargetInfo().getPointerWidth(0) == 64)
1485 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001486 return std::make_pair(CharUnits::fromQuantity(Width),
1487 CharUnits::fromQuantity(Align));
1488}
1489
John McCall87fe5d52010-05-20 01:18:31 +00001490std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001491ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001492 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1493 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001494 TypeInfo Info = getTypeInfo(T);
1495 return std::make_pair(toCharUnitsFromBits(Info.Width),
1496 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001497}
1498
1499std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001500ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001501 return getTypeInfoInChars(T.getTypePtr());
1502}
1503
David Majnemer34b57492014-07-30 01:30:47 +00001504bool ASTContext::isAlignmentRequired(const Type *T) const {
1505 return getTypeInfo(T).AlignIsRequired;
1506}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001507
David Majnemer34b57492014-07-30 01:30:47 +00001508bool ASTContext::isAlignmentRequired(QualType T) const {
1509 return isAlignmentRequired(T.getTypePtr());
1510}
1511
1512TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001513 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1514 if (I != MemoizedTypeInfo.end())
1515 return I->second;
1516
1517 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1518 TypeInfo TI = getTypeInfoImpl(T);
1519 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001520 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001521}
1522
1523/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1524/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001525///
1526/// FIXME: Pointers into different addr spaces could have different sizes and
1527/// alignment requirements: getPointerInfo should take an AddrSpace, this
1528/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001529TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1530 uint64_t Width = 0;
1531 unsigned Align = 8;
1532 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001533 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001534#define TYPE(Class, Base)
1535#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001536#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001537#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001538#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1539 case Type::Class: \
1540 assert(!T->isDependentType() && "should not see dependent types here"); \
1541 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001542#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001543 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001544
Chris Lattner355332d2007-07-13 22:27:08 +00001545 case Type::FunctionNoProto:
1546 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001547 // GCC extension: alignof(function) = 32 bits
1548 Width = 0;
1549 Align = 32;
1550 break;
1551
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001552 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001553 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001554 Width = 0;
1555 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1556 break;
1557
Steve Naroff5c131802007-08-30 01:06:46 +00001558 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001559 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001560
David Majnemer34b57492014-07-30 01:30:47 +00001561 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001562 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001563 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001564 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001565 Width = EltInfo.Width * Size;
1566 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001567 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1568 getTargetInfo().getPointerWidth(0) == 64)
1569 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001570 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001571 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001572 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001573 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001574 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001575 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1576 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001577 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001578 // If the alignment is not a power of 2, round up to the next power of 2.
1579 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001580 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001581 Align = llvm::NextPowerOf2(Align);
1582 Width = llvm::RoundUpToAlignment(Width, Align);
1583 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001584 // Adjust the alignment based on the target max.
1585 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1586 if (TargetVectorAlign && TargetVectorAlign < Align)
1587 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001588 break;
1589 }
Chris Lattner647fb222007-07-18 18:26:58 +00001590
Chris Lattner7570e9c2008-03-08 08:52:55 +00001591 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001592 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001593 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001594 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001595 // GCC extension: alignof(void) = 8 bits.
1596 Width = 0;
1597 Align = 8;
1598 break;
1599
Chris Lattner6a4f7452007-12-19 19:23:28 +00001600 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001601 Width = Target->getBoolWidth();
1602 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001603 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001604 case BuiltinType::Char_S:
1605 case BuiltinType::Char_U:
1606 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getCharWidth();
1609 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001610 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001611 case BuiltinType::WChar_S:
1612 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001613 Width = Target->getWCharWidth();
1614 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001615 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001616 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Width = Target->getChar16Width();
1618 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001619 break;
1620 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001621 Width = Target->getChar32Width();
1622 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001623 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001624 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001625 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getShortWidth();
1627 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001628 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001629 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001631 Width = Target->getIntWidth();
1632 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001633 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001634 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001635 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getLongWidth();
1637 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001638 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001639 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001640 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001641 Width = Target->getLongLongWidth();
1642 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001643 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001644 case BuiltinType::Int128:
1645 case BuiltinType::UInt128:
1646 Width = 128;
1647 Align = 128; // int128_t is 128-bit aligned on all targets.
1648 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001649 case BuiltinType::Half:
1650 Width = Target->getHalfWidth();
1651 Align = Target->getHalfAlign();
1652 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001653 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001654 Width = Target->getFloatWidth();
1655 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001656 break;
1657 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001658 Width = Target->getDoubleWidth();
1659 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001660 break;
1661 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001662 Width = Target->getLongDoubleWidth();
1663 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001664 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001665 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001666 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1667 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001668 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001669 case BuiltinType::ObjCId:
1670 case BuiltinType::ObjCClass:
1671 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001672 Width = Target->getPointerWidth(0);
1673 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001674 break;
Guy Benyei61054192013-02-07 10:55:47 +00001675 case BuiltinType::OCLSampler:
1676 // Samplers are modeled as integers.
1677 Width = Target->getIntWidth();
1678 Align = Target->getIntAlign();
1679 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001680 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001681 case BuiltinType::OCLClkEvent:
1682 case BuiltinType::OCLQueue:
1683 case BuiltinType::OCLNDRange:
1684 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001685 case BuiltinType::OCLImage1d:
1686 case BuiltinType::OCLImage1dArray:
1687 case BuiltinType::OCLImage1dBuffer:
1688 case BuiltinType::OCLImage2d:
1689 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001690 case BuiltinType::OCLImage2dDepth:
1691 case BuiltinType::OCLImage2dArrayDepth:
1692 case BuiltinType::OCLImage2dMSAA:
1693 case BuiltinType::OCLImage2dArrayMSAA:
1694 case BuiltinType::OCLImage2dMSAADepth:
1695 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001696 case BuiltinType::OCLImage3d:
1697 // Currently these types are pointers to opaque types.
1698 Width = Target->getPointerWidth(0);
1699 Align = Target->getPointerAlign(0);
1700 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001701 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001702 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001703 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001704 Width = Target->getPointerWidth(0);
1705 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001706 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001707 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001708 unsigned AS = getTargetAddressSpace(
1709 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001710 Width = Target->getPointerWidth(AS);
1711 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001712 break;
1713 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001714 case Type::LValueReference:
1715 case Type::RValueReference: {
1716 // alignof and sizeof should never enter this code path here, so we go
1717 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001718 unsigned AS = getTargetAddressSpace(
1719 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001720 Width = Target->getPointerWidth(AS);
1721 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001722 break;
1723 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001724 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001725 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001726 Width = Target->getPointerWidth(AS);
1727 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001728 break;
1729 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001730 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001731 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001732 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001733 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001734 }
Chris Lattner647fb222007-07-18 18:26:58 +00001735 case Type::Complex: {
1736 // Complex types have the same alignment as their elements, but twice the
1737 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001738 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1739 Width = EltInfo.Width * 2;
1740 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001741 break;
1742 }
John McCall8b07ec22010-05-15 11:32:37 +00001743 case Type::ObjCObject:
1744 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001745 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001746 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001747 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001748 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001749 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001750 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001751 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001752 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001753 break;
1754 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001755 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001756 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001757 const TagType *TT = cast<TagType>(T);
1758
1759 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001760 Width = 8;
1761 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001762 break;
1763 }
Mike Stump11289f42009-09-09 15:08:12 +00001764
David Majnemer475b25e2015-01-21 10:54:38 +00001765 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1766 const EnumDecl *ED = ET->getDecl();
1767 TypeInfo Info =
1768 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1769 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1770 Info.Align = AttrAlign;
1771 Info.AlignIsRequired = true;
1772 }
1773 return Info;
1774 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001775
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001776 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001777 const RecordDecl *RD = RT->getDecl();
1778 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001779 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001780 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001781 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001782 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001783 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001784
Chris Lattner63d2b362009-10-22 05:17:15 +00001785 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001786 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1787 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001788
Richard Smith30482bc2011-02-20 03:19:35 +00001789 case Type::Auto: {
1790 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001791 assert(!A->getDeducedType().isNull() &&
1792 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001793 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001794 }
1795
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001796 case Type::Paren:
1797 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1798
Douglas Gregoref462e62009-04-30 17:32:17 +00001799 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001800 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001801 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001802 // If the typedef has an aligned attribute on it, it overrides any computed
1803 // alignment we have. This violates the GCC documentation (which says that
1804 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001805 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001806 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001807 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001808 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001809 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001810 AlignIsRequired = Info.AlignIsRequired;
1811 }
David Majnemer34b57492014-07-30 01:30:47 +00001812 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001813 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001814 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001815
Abramo Bagnara6150c882010-05-11 21:36:43 +00001816 case Type::Elaborated:
1817 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001818
John McCall81904512011-01-06 01:58:22 +00001819 case Type::Attributed:
1820 return getTypeInfo(
1821 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1822
Eli Friedman0dfb8892011-10-06 23:00:33 +00001823 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001824 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001825 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1826 Width = Info.Width;
1827 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001828
1829 // If the size of the type doesn't exceed the platform's max
1830 // atomic promotion width, make the size and alignment more
1831 // favorable to atomic operations:
1832 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1833 // Round the size up to a power of 2.
1834 if (!llvm::isPowerOf2_64(Width))
1835 Width = llvm::NextPowerOf2(Width);
1836
1837 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001838 Align = static_cast<unsigned>(Width);
1839 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001840 }
1841
Douglas Gregoref462e62009-04-30 17:32:17 +00001842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001844 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001845 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001846}
1847
Alexey Bataev00396512015-07-02 03:40:19 +00001848unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1849 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1850 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1851 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1852 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1853 getTargetInfo().getABI() == "elfv1-qpx" &&
1854 T->isSpecificBuiltinType(BuiltinType::Double))
1855 SimdAlign = 256;
1856 return SimdAlign;
1857}
1858
Ken Dyckcc56c542011-01-15 18:38:59 +00001859/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1860CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1861 return CharUnits::fromQuantity(BitSize / getCharWidth());
1862}
1863
Ken Dyckb0fcc592011-02-11 01:54:29 +00001864/// toBits - Convert a size in characters to a size in characters.
1865int64_t ASTContext::toBits(CharUnits CharSize) const {
1866 return CharSize.getQuantity() * getCharWidth();
1867}
1868
Ken Dyck8c89d592009-12-22 14:23:30 +00001869/// getTypeSizeInChars - Return the size of the specified type, in characters.
1870/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001871CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001872 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001873}
Jay Foad39c79802011-01-12 09:06:06 +00001874CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001875 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001876}
1877
Ken Dycka6046ab2010-01-26 17:25:18 +00001878/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001879/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001880CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001881 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001882}
Jay Foad39c79802011-01-12 09:06:06 +00001883CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001884 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001885}
1886
Chris Lattnera3402cd2009-01-27 18:08:34 +00001887/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1888/// type for the current target in bits. This can be different than the ABI
1889/// alignment in cases where it is beneficial for performance to overalign
1890/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001891unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001892 TypeInfo TI = getTypeInfo(T);
1893 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001894
David Majnemere1544562015-04-24 01:25:05 +00001895 T = T->getBaseElementTypeUnsafe();
1896
1897 // The preferred alignment of member pointers is that of a pointer.
1898 if (T->isMemberPointerType())
1899 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1900
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001901 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1902 return ABIAlign; // Never overalign on XCore.
1903
Eli Friedman7ab09572009-05-25 21:27:19 +00001904 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001905 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001906 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001907 if (const EnumType *ET = T->getAs<EnumType>())
1908 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001909 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001910 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1911 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001912 // Don't increase the alignment if an alignment attribute was specified on a
1913 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001914 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001915 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001916
Chris Lattnera3402cd2009-01-27 18:08:34 +00001917 return ABIAlign;
1918}
1919
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001920/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1921/// for __attribute__((aligned)) on this target, to be used if no alignment
1922/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001923unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001924 return getTargetInfo().getDefaultAlignForAttributeAligned();
1925}
1926
Ulrich Weigandfa806422013-05-06 16:23:57 +00001927/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1928/// to a global variable of the specified type.
1929unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1930 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1931}
1932
1933/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1934/// should be given to a global variable of the specified type.
1935CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1936 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1937}
1938
David Majnemer08ef2ba2015-06-23 20:34:18 +00001939CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1940 CharUnits Offset = CharUnits::Zero();
1941 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1942 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1943 Offset += Layout->getBaseClassOffset(Base);
1944 Layout = &getASTRecordLayout(Base);
1945 }
1946 return Offset;
1947}
1948
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001949/// DeepCollectObjCIvars -
1950/// This routine first collects all declared, but not synthesized, ivars in
1951/// super class and then collects all ivars, including those synthesized for
1952/// current class. This routine is used for implementation of current class
1953/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001954///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001955void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1956 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001957 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001958 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1959 DeepCollectObjCIvars(SuperClass, false, Ivars);
1960 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001961 for (const auto *I : OI->ivars())
1962 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001963 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001964 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001965 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001966 Iv= Iv->getNextIvar())
1967 Ivars.push_back(Iv);
1968 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001969}
1970
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001971/// CollectInheritedProtocols - Collect all protocols in current class and
1972/// those inherited by it.
1973void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001974 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001975 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001976 // We can use protocol_iterator here instead of
1977 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001978 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001979 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001980 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001981
1982 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001983 for (const auto *Cat : OI->visible_categories())
1984 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001985
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001986 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1987 while (SD) {
1988 CollectInheritedProtocols(SD, Protocols);
1989 SD = SD->getSuperClass();
1990 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001991 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001992 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001993 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001994 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001995 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001996 // Insert the protocol.
1997 if (!Protocols.insert(
1998 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1999 return;
2000
2001 for (auto *Proto : OP->protocols())
2002 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002003 }
2004}
2005
Jay Foad39c79802011-01-12 09:06:06 +00002006unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002007 unsigned count = 0;
2008 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002009 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002010 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002011
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002012 // Count ivar defined in this class's implementation. This
2013 // includes synthesized ivars.
2014 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002015 count += ImplDecl->ivar_size();
2016
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002017 return count;
2018}
2019
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002020bool ASTContext::isSentinelNullExpr(const Expr *E) {
2021 if (!E)
2022 return false;
2023
2024 // nullptr_t is always treated as null.
2025 if (E->getType()->isNullPtrType()) return true;
2026
2027 if (E->getType()->isAnyPointerType() &&
2028 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2029 Expr::NPC_ValueDependentIsNull))
2030 return true;
2031
2032 // Unfortunately, __null has type 'int'.
2033 if (isa<GNUNullExpr>(E)) return true;
2034
2035 return false;
2036}
2037
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002038/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2039ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2040 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2041 I = ObjCImpls.find(D);
2042 if (I != ObjCImpls.end())
2043 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002044 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002045}
2046/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2047ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2048 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2049 I = ObjCImpls.find(D);
2050 if (I != ObjCImpls.end())
2051 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002052 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002053}
2054
2055/// \brief Set the implementation of ObjCInterfaceDecl.
2056void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2057 ObjCImplementationDecl *ImplD) {
2058 assert(IFaceD && ImplD && "Passed null params");
2059 ObjCImpls[IFaceD] = ImplD;
2060}
2061/// \brief Set the implementation of ObjCCategoryDecl.
2062void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2063 ObjCCategoryImplDecl *ImplD) {
2064 assert(CatD && ImplD && "Passed null params");
2065 ObjCImpls[CatD] = ImplD;
2066}
2067
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002068const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2069 const NamedDecl *ND) const {
2070 if (const ObjCInterfaceDecl *ID =
2071 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002072 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002073 if (const ObjCCategoryDecl *CD =
2074 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002075 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002076 if (const ObjCImplDecl *IMD =
2077 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002078 return IMD->getClassInterface();
2079
Craig Topper36250ad2014-05-12 05:36:57 +00002080 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002081}
2082
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002083/// \brief Get the copy initialization expression of VarDecl,or NULL if
2084/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002085Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002086 assert(VD && "Passed null params");
2087 assert(VD->hasAttr<BlocksAttr>() &&
2088 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002089 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002090 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002091 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002092}
2093
2094/// \brief Set the copy inialization expression of a block var decl.
2095void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2096 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002097 assert(VD->hasAttr<BlocksAttr>() &&
2098 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002099 BlockVarCopyInits[VD] = Init;
2100}
2101
John McCallbcd03502009-12-07 02:54:59 +00002102TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002103 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002104 if (!DataSize)
2105 DataSize = TypeLoc::getFullDataSizeForType(T);
2106 else
2107 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002108 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002109
John McCallbcd03502009-12-07 02:54:59 +00002110 TypeSourceInfo *TInfo =
2111 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2112 new (TInfo) TypeSourceInfo(T);
2113 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002114}
2115
John McCallbcd03502009-12-07 02:54:59 +00002116TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002117 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002118 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002119 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002120 return DI;
2121}
2122
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002123const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002124ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002125 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002126}
2127
2128const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002129ASTContext::getASTObjCImplementationLayout(
2130 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002131 return getObjCLayout(D->getClassInterface(), D);
2132}
2133
Chris Lattner983a8bb2007-07-13 22:13:22 +00002134//===----------------------------------------------------------------------===//
2135// Type creation/memoization methods
2136//===----------------------------------------------------------------------===//
2137
Jay Foad39c79802011-01-12 09:06:06 +00002138QualType
John McCall33ddac02011-01-19 10:06:00 +00002139ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2140 unsigned fastQuals = quals.getFastQualifiers();
2141 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002142
2143 // Check if we've already instantiated this type.
2144 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002145 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002146 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002147 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2148 assert(eq->getQualifiers() == quals);
2149 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002150 }
2151
John McCall33ddac02011-01-19 10:06:00 +00002152 // If the base type is not canonical, make the appropriate canonical type.
2153 QualType canon;
2154 if (!baseType->isCanonicalUnqualified()) {
2155 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002156 canonSplit.Quals.addConsistentQualifiers(quals);
2157 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002158
2159 // Re-find the insert position.
2160 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2161 }
2162
2163 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2164 ExtQualNodes.InsertNode(eq, insertPos);
2165 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002166}
2167
Jay Foad39c79802011-01-12 09:06:06 +00002168QualType
2169ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002170 QualType CanT = getCanonicalType(T);
2171 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002172 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002173
John McCall8ccfcb52009-09-24 19:53:00 +00002174 // If we are composing extended qualifiers together, merge together
2175 // into one ExtQuals node.
2176 QualifierCollector Quals;
2177 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCall8ccfcb52009-09-24 19:53:00 +00002179 // If this type already has an address space specified, it cannot get
2180 // another one.
2181 assert(!Quals.hasAddressSpace() &&
2182 "Type cannot be in multiple addr spaces!");
2183 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002184
John McCall8ccfcb52009-09-24 19:53:00 +00002185 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002186}
2187
Chris Lattnerd60183d2009-02-18 22:53:11 +00002188QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002189 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002190 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002191 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002192 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall53fa7142010-12-24 02:08:15 +00002194 if (const PointerType *ptr = T->getAs<PointerType>()) {
2195 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002196 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002197 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2198 return getPointerType(ResultType);
2199 }
2200 }
Mike Stump11289f42009-09-09 15:08:12 +00002201
John McCall8ccfcb52009-09-24 19:53:00 +00002202 // If we are composing extended qualifiers together, merge together
2203 // into one ExtQuals node.
2204 QualifierCollector Quals;
2205 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002206
John McCall8ccfcb52009-09-24 19:53:00 +00002207 // If this type already has an ObjCGC specified, it cannot get
2208 // another one.
2209 assert(!Quals.hasObjCGCAttr() &&
2210 "Type cannot have multiple ObjCGCs!");
2211 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002212
John McCall8ccfcb52009-09-24 19:53:00 +00002213 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002214}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002215
John McCall4f5019e2010-12-19 02:44:49 +00002216const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2217 FunctionType::ExtInfo Info) {
2218 if (T->getExtInfo() == Info)
2219 return T;
2220
2221 QualType Result;
2222 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002223 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002224 } else {
2225 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2226 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2227 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002228 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002229 }
2230
2231 return cast<FunctionType>(Result.getTypePtr());
2232}
2233
Richard Smith2a7d4812013-05-04 07:00:32 +00002234void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2235 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002236 FD = FD->getMostRecentDecl();
2237 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002238 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2239 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002240 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002241 if (FunctionDecl *Next = FD->getPreviousDecl())
2242 FD = Next;
2243 else
2244 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002245 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002246 if (ASTMutationListener *L = getASTMutationListener())
2247 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002248}
2249
Richard Smith0b3a4622014-11-13 20:01:57 +00002250/// Get a function type and produce the equivalent function type with the
2251/// specified exception specification. Type sugar that can be present on a
2252/// declaration of a function with an exception specification is permitted
2253/// and preserved. Other type sugar (for instance, typedefs) is not.
2254static QualType getFunctionTypeWithExceptionSpec(
2255 ASTContext &Context, QualType Orig,
2256 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2257 // Might have some parens.
2258 if (auto *PT = dyn_cast<ParenType>(Orig))
2259 return Context.getParenType(
2260 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2261
2262 // Might have a calling-convention attribute.
2263 if (auto *AT = dyn_cast<AttributedType>(Orig))
2264 return Context.getAttributedType(
2265 AT->getAttrKind(),
2266 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2267 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2268 ESI));
2269
2270 // Anything else must be a function type. Rebuild it with the new exception
2271 // specification.
2272 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2273 return Context.getFunctionType(
2274 Proto->getReturnType(), Proto->getParamTypes(),
2275 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2276}
2277
2278void ASTContext::adjustExceptionSpec(
2279 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2280 bool AsWritten) {
2281 // Update the type.
2282 QualType Updated =
2283 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2284 FD->setType(Updated);
2285
2286 if (!AsWritten)
2287 return;
2288
2289 // Update the type in the type source information too.
2290 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2291 // If the type and the type-as-written differ, we may need to update
2292 // the type-as-written too.
2293 if (TSInfo->getType() != FD->getType())
2294 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2295
2296 // FIXME: When we get proper type location information for exceptions,
2297 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2298 // up the TypeSourceInfo;
2299 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2300 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2301 "TypeLoc size mismatch from updating exception specification");
2302 TSInfo->overrideType(Updated);
2303 }
2304}
2305
Chris Lattnerc6395932007-06-22 20:56:16 +00002306/// getComplexType - Return the uniqued reference to the type for a complex
2307/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002308QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002309 // Unique pointers, to guarantee there is only one pointer of a particular
2310 // structure.
2311 llvm::FoldingSetNodeID ID;
2312 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002313
Craig Topper36250ad2014-05-12 05:36:57 +00002314 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002315 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2316 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattnerc6395932007-06-22 20:56:16 +00002318 // If the pointee type isn't canonical, this won't be a canonical type either,
2319 // so fill in the canonical type field.
2320 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002321 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002322 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002323
Chris Lattnerc6395932007-06-22 20:56:16 +00002324 // Get the new insert position for the node we care about.
2325 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002326 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002327 }
John McCall90d1c2d2009-09-24 23:30:46 +00002328 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002329 Types.push_back(New);
2330 ComplexTypes.InsertNode(New, InsertPos);
2331 return QualType(New, 0);
2332}
2333
Chris Lattner970e54e2006-11-12 00:37:36 +00002334/// getPointerType - Return the uniqued reference to the type for a pointer to
2335/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002336QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002337 // Unique pointers, to guarantee there is only one pointer of a particular
2338 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002339 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002340 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002341
Craig Topper36250ad2014-05-12 05:36:57 +00002342 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002343 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002344 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002345
Chris Lattner7ccecb92006-11-12 08:50:50 +00002346 // If the pointee type isn't canonical, this won't be a canonical type either,
2347 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002348 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002349 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002350 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002351
Bob Wilsonc8541f22013-03-15 17:12:43 +00002352 // Get the new insert position for the node we care about.
2353 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002354 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002355 }
John McCall90d1c2d2009-09-24 23:30:46 +00002356 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002357 Types.push_back(New);
2358 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002359 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002360}
2361
Reid Kleckner0503a872013-12-05 01:23:43 +00002362QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2363 llvm::FoldingSetNodeID ID;
2364 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002365 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002366 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2367 if (AT)
2368 return QualType(AT, 0);
2369
2370 QualType Canonical = getCanonicalType(New);
2371
2372 // Get the new insert position for the node we care about.
2373 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002374 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002375
2376 AT = new (*this, TypeAlignment)
2377 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2378 Types.push_back(AT);
2379 AdjustedTypes.InsertNode(AT, InsertPos);
2380 return QualType(AT, 0);
2381}
2382
Reid Kleckner8a365022013-06-24 17:51:48 +00002383QualType ASTContext::getDecayedType(QualType T) const {
2384 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2385
Reid Kleckner8a365022013-06-24 17:51:48 +00002386 QualType Decayed;
2387
2388 // C99 6.7.5.3p7:
2389 // A declaration of a parameter as "array of type" shall be
2390 // adjusted to "qualified pointer to type", where the type
2391 // qualifiers (if any) are those specified within the [ and ] of
2392 // the array type derivation.
2393 if (T->isArrayType())
2394 Decayed = getArrayDecayedType(T);
2395
2396 // C99 6.7.5.3p8:
2397 // A declaration of a parameter as "function returning type"
2398 // shall be adjusted to "pointer to function returning type", as
2399 // in 6.3.2.1.
2400 if (T->isFunctionType())
2401 Decayed = getPointerType(T);
2402
Reid Kleckner0503a872013-12-05 01:23:43 +00002403 llvm::FoldingSetNodeID ID;
2404 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002405 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002406 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2407 if (AT)
2408 return QualType(AT, 0);
2409
Reid Kleckner8a365022013-06-24 17:51:48 +00002410 QualType Canonical = getCanonicalType(Decayed);
2411
2412 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002413 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002414 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002415
Reid Kleckner0503a872013-12-05 01:23:43 +00002416 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2417 Types.push_back(AT);
2418 AdjustedTypes.InsertNode(AT, InsertPos);
2419 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002420}
2421
Mike Stump11289f42009-09-09 15:08:12 +00002422/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002423/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002424QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002425 assert(T->isFunctionType() && "block of function types only");
2426 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002427 // structure.
2428 llvm::FoldingSetNodeID ID;
2429 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002430
Craig Topper36250ad2014-05-12 05:36:57 +00002431 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002432 if (BlockPointerType *PT =
2433 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2434 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002435
2436 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002437 // type either so fill in the canonical type field.
2438 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002439 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002440 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002441
Steve Naroffec33ed92008-08-27 16:04:49 +00002442 // Get the new insert position for the node we care about.
2443 BlockPointerType *NewIP =
2444 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002445 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002446 }
John McCall90d1c2d2009-09-24 23:30:46 +00002447 BlockPointerType *New
2448 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002449 Types.push_back(New);
2450 BlockPointerTypes.InsertNode(New, InsertPos);
2451 return QualType(New, 0);
2452}
2453
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002454/// getLValueReferenceType - Return the uniqued reference to the type for an
2455/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002456QualType
2457ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002458 assert(getCanonicalType(T) != OverloadTy &&
2459 "Unresolved overloaded function type");
2460
Bill Wendling3708c182007-05-27 10:15:43 +00002461 // Unique pointers, to guarantee there is only one pointer of a particular
2462 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002463 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002464 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002465
Craig Topper36250ad2014-05-12 05:36:57 +00002466 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002467 if (LValueReferenceType *RT =
2468 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002469 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002470
John McCallfc93cf92009-10-22 22:37:11 +00002471 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2472
Bill Wendling3708c182007-05-27 10:15:43 +00002473 // If the referencee type isn't canonical, this won't be a canonical type
2474 // either, so fill in the canonical type field.
2475 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002476 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2477 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2478 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002479
Bill Wendling3708c182007-05-27 10:15:43 +00002480 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002481 LValueReferenceType *NewIP =
2482 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002483 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002484 }
2485
John McCall90d1c2d2009-09-24 23:30:46 +00002486 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002487 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2488 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002489 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002490 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002491
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002492 return QualType(New, 0);
2493}
2494
2495/// getRValueReferenceType - Return the uniqued reference to the type for an
2496/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002497QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002498 // Unique pointers, to guarantee there is only one pointer of a particular
2499 // structure.
2500 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002501 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002502
Craig Topper36250ad2014-05-12 05:36:57 +00002503 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002504 if (RValueReferenceType *RT =
2505 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2506 return QualType(RT, 0);
2507
John McCallfc93cf92009-10-22 22:37:11 +00002508 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2509
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002510 // If the referencee type isn't canonical, this won't be a canonical type
2511 // either, so fill in the canonical type field.
2512 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002513 if (InnerRef || !T.isCanonical()) {
2514 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2515 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002516
2517 // Get the new insert position for the node we care about.
2518 RValueReferenceType *NewIP =
2519 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002520 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002521 }
2522
John McCall90d1c2d2009-09-24 23:30:46 +00002523 RValueReferenceType *New
2524 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002525 Types.push_back(New);
2526 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002527 return QualType(New, 0);
2528}
2529
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002530/// getMemberPointerType - Return the uniqued reference to the type for a
2531/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002532QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002533 // Unique pointers, to guarantee there is only one pointer of a particular
2534 // structure.
2535 llvm::FoldingSetNodeID ID;
2536 MemberPointerType::Profile(ID, T, Cls);
2537
Craig Topper36250ad2014-05-12 05:36:57 +00002538 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002539 if (MemberPointerType *PT =
2540 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2541 return QualType(PT, 0);
2542
2543 // If the pointee or class type isn't canonical, this won't be a canonical
2544 // type either, so fill in the canonical type field.
2545 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002546 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002547 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2548
2549 // Get the new insert position for the node we care about.
2550 MemberPointerType *NewIP =
2551 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002553 }
John McCall90d1c2d2009-09-24 23:30:46 +00002554 MemberPointerType *New
2555 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002556 Types.push_back(New);
2557 MemberPointerTypes.InsertNode(New, InsertPos);
2558 return QualType(New, 0);
2559}
2560
Mike Stump11289f42009-09-09 15:08:12 +00002561/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002562/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002563QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002564 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002565 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002566 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002567 assert((EltTy->isDependentType() ||
2568 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002569 "Constant array of VLAs is illegal!");
2570
Chris Lattnere2df3f92009-05-13 04:12:56 +00002571 // Convert the array size into a canonical width matching the pointer size for
2572 // the target.
2573 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002574 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002575 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002576
Chris Lattner23b7eb62007-06-15 23:05:46 +00002577 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002578 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002579
Craig Topper36250ad2014-05-12 05:36:57 +00002580 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002581 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002582 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002583 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002584
John McCall33ddac02011-01-19 10:06:00 +00002585 // If the element type isn't canonical or has qualifiers, this won't
2586 // be a canonical type either, so fill in the canonical type field.
2587 QualType Canon;
2588 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2589 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002590 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002591 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002592 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002593
Chris Lattner36f8e652007-01-27 08:31:04 +00002594 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002595 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002596 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002597 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
John McCall90d1c2d2009-09-24 23:30:46 +00002600 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002601 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002602 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002603 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002604 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002605}
2606
John McCall06549462011-01-18 08:40:38 +00002607/// getVariableArrayDecayedType - Turns the given type, which may be
2608/// variably-modified, into the corresponding type with all the known
2609/// sizes replaced with [*].
2610QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2611 // Vastly most common case.
2612 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002613
John McCall06549462011-01-18 08:40:38 +00002614 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002615
John McCall06549462011-01-18 08:40:38 +00002616 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002617 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002618 switch (ty->getTypeClass()) {
2619#define TYPE(Class, Base)
2620#define ABSTRACT_TYPE(Class, Base)
2621#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2622#include "clang/AST/TypeNodes.def"
2623 llvm_unreachable("didn't desugar past all non-canonical types?");
2624
2625 // These types should never be variably-modified.
2626 case Type::Builtin:
2627 case Type::Complex:
2628 case Type::Vector:
2629 case Type::ExtVector:
2630 case Type::DependentSizedExtVector:
2631 case Type::ObjCObject:
2632 case Type::ObjCInterface:
2633 case Type::ObjCObjectPointer:
2634 case Type::Record:
2635 case Type::Enum:
2636 case Type::UnresolvedUsing:
2637 case Type::TypeOfExpr:
2638 case Type::TypeOf:
2639 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002640 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002641 case Type::DependentName:
2642 case Type::InjectedClassName:
2643 case Type::TemplateSpecialization:
2644 case Type::DependentTemplateSpecialization:
2645 case Type::TemplateTypeParm:
2646 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002647 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002648 case Type::PackExpansion:
2649 llvm_unreachable("type should never be variably-modified");
2650
2651 // These types can be variably-modified but should never need to
2652 // further decay.
2653 case Type::FunctionNoProto:
2654 case Type::FunctionProto:
2655 case Type::BlockPointer:
2656 case Type::MemberPointer:
2657 return type;
2658
2659 // These types can be variably-modified. All these modifications
2660 // preserve structure except as noted by comments.
2661 // TODO: if we ever care about optimizing VLAs, there are no-op
2662 // optimizations available here.
2663 case Type::Pointer:
2664 result = getPointerType(getVariableArrayDecayedType(
2665 cast<PointerType>(ty)->getPointeeType()));
2666 break;
2667
2668 case Type::LValueReference: {
2669 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2670 result = getLValueReferenceType(
2671 getVariableArrayDecayedType(lv->getPointeeType()),
2672 lv->isSpelledAsLValue());
2673 break;
2674 }
2675
2676 case Type::RValueReference: {
2677 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2678 result = getRValueReferenceType(
2679 getVariableArrayDecayedType(lv->getPointeeType()));
2680 break;
2681 }
2682
Eli Friedman0dfb8892011-10-06 23:00:33 +00002683 case Type::Atomic: {
2684 const AtomicType *at = cast<AtomicType>(ty);
2685 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2686 break;
2687 }
2688
John McCall06549462011-01-18 08:40:38 +00002689 case Type::ConstantArray: {
2690 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2691 result = getConstantArrayType(
2692 getVariableArrayDecayedType(cat->getElementType()),
2693 cat->getSize(),
2694 cat->getSizeModifier(),
2695 cat->getIndexTypeCVRQualifiers());
2696 break;
2697 }
2698
2699 case Type::DependentSizedArray: {
2700 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2701 result = getDependentSizedArrayType(
2702 getVariableArrayDecayedType(dat->getElementType()),
2703 dat->getSizeExpr(),
2704 dat->getSizeModifier(),
2705 dat->getIndexTypeCVRQualifiers(),
2706 dat->getBracketsRange());
2707 break;
2708 }
2709
2710 // Turn incomplete types into [*] types.
2711 case Type::IncompleteArray: {
2712 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2713 result = getVariableArrayType(
2714 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002715 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002716 ArrayType::Normal,
2717 iat->getIndexTypeCVRQualifiers(),
2718 SourceRange());
2719 break;
2720 }
2721
2722 // Turn VLA types into [*] types.
2723 case Type::VariableArray: {
2724 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2725 result = getVariableArrayType(
2726 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002727 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002728 ArrayType::Star,
2729 vat->getIndexTypeCVRQualifiers(),
2730 vat->getBracketsRange());
2731 break;
2732 }
2733 }
2734
2735 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002736 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002737}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002738
Steve Naroffcadebd02007-08-30 18:14:25 +00002739/// getVariableArrayType - Returns a non-unique reference to the type for a
2740/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002741QualType ASTContext::getVariableArrayType(QualType EltTy,
2742 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002743 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002744 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002745 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002746 // Since we don't unique expressions, it isn't possible to unique VLA's
2747 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002748 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002749
John McCall33ddac02011-01-19 10:06:00 +00002750 // Be sure to pull qualifiers off the element type.
2751 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2752 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002753 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002754 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002755 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002756 }
2757
John McCall90d1c2d2009-09-24 23:30:46 +00002758 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002759 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002760
2761 VariableArrayTypes.push_back(New);
2762 Types.push_back(New);
2763 return QualType(New, 0);
2764}
2765
Douglas Gregor4619e432008-12-05 23:32:09 +00002766/// getDependentSizedArrayType - Returns a non-unique reference to
2767/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002768/// type.
John McCall33ddac02011-01-19 10:06:00 +00002769QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2770 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002771 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002772 unsigned elementTypeQuals,
2773 SourceRange brackets) const {
2774 assert((!numElements || numElements->isTypeDependent() ||
2775 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002776 "Size must be type- or value-dependent!");
2777
John McCall33ddac02011-01-19 10:06:00 +00002778 // Dependently-sized array types that do not have a specified number
2779 // of elements will have their sizes deduced from a dependent
2780 // initializer. We do no canonicalization here at all, which is okay
2781 // because they can't be used in most locations.
2782 if (!numElements) {
2783 DependentSizedArrayType *newType
2784 = new (*this, TypeAlignment)
2785 DependentSizedArrayType(*this, elementType, QualType(),
2786 numElements, ASM, elementTypeQuals,
2787 brackets);
2788 Types.push_back(newType);
2789 return QualType(newType, 0);
2790 }
2791
2792 // Otherwise, we actually build a new type every time, but we
2793 // also build a canonical type.
2794
2795 SplitQualType canonElementType = getCanonicalType(elementType).split();
2796
Craig Topper36250ad2014-05-12 05:36:57 +00002797 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002798 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002799 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002800 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002801 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002802
John McCall33ddac02011-01-19 10:06:00 +00002803 // Look for an existing type with these properties.
2804 DependentSizedArrayType *canonTy =
2805 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002806
John McCall33ddac02011-01-19 10:06:00 +00002807 // If we don't have one, build one.
2808 if (!canonTy) {
2809 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002810 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002811 QualType(), numElements, ASM, elementTypeQuals,
2812 brackets);
2813 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2814 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002815 }
2816
John McCall33ddac02011-01-19 10:06:00 +00002817 // Apply qualifiers from the element type to the array.
2818 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002819 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002820
David Majnemer16a74702015-07-24 05:54:19 +00002821 // If we didn't need extra canonicalization for the element type or the size
2822 // expression, then just use that as our result.
2823 if (QualType(canonElementType.Ty, 0) == elementType &&
2824 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002825 return canon;
2826
2827 // Otherwise, we need to build a type which follows the spelling
2828 // of the element type.
2829 DependentSizedArrayType *sugaredType
2830 = new (*this, TypeAlignment)
2831 DependentSizedArrayType(*this, elementType, canon, numElements,
2832 ASM, elementTypeQuals, brackets);
2833 Types.push_back(sugaredType);
2834 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002835}
2836
John McCall33ddac02011-01-19 10:06:00 +00002837QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002838 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002839 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002840 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002841 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002842
Craig Topper36250ad2014-05-12 05:36:57 +00002843 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002844 if (IncompleteArrayType *iat =
2845 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2846 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002847
2848 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002849 // either, so fill in the canonical type field. We also have to pull
2850 // qualifiers off the element type.
2851 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002852
John McCall33ddac02011-01-19 10:06:00 +00002853 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2854 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002855 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002856 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002857 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002858
2859 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002860 IncompleteArrayType *existing =
2861 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2862 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002863 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002864
John McCall33ddac02011-01-19 10:06:00 +00002865 IncompleteArrayType *newType = new (*this, TypeAlignment)
2866 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002867
John McCall33ddac02011-01-19 10:06:00 +00002868 IncompleteArrayTypes.InsertNode(newType, insertPos);
2869 Types.push_back(newType);
2870 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002871}
2872
Steve Naroff91fcddb2007-07-18 18:00:27 +00002873/// getVectorType - Return the unique reference to a vector type of
2874/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002875QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002876 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002877 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002878
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002879 // Check if we've already instantiated a vector of this type.
2880 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002881 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002882
Craig Topper36250ad2014-05-12 05:36:57 +00002883 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002884 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2885 return QualType(VTP, 0);
2886
2887 // If the element type isn't canonical, this won't be a canonical type either,
2888 // so fill in the canonical type field.
2889 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002890 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002891 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002893 // Get the new insert position for the node we care about.
2894 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002895 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002896 }
John McCall90d1c2d2009-09-24 23:30:46 +00002897 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002898 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002899 VectorTypes.InsertNode(New, InsertPos);
2900 Types.push_back(New);
2901 return QualType(New, 0);
2902}
2903
Nate Begemance4d7fc2008-04-18 23:10:10 +00002904/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002905/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002906QualType
2907ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002908 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002909
Steve Naroff91fcddb2007-07-18 18:00:27 +00002910 // Check if we've already instantiated a vector of this type.
2911 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002912 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002913 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002914 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002915 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2916 return QualType(VTP, 0);
2917
2918 // If the element type isn't canonical, this won't be a canonical type either,
2919 // so fill in the canonical type field.
2920 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002921 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002922 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002923
Steve Naroff91fcddb2007-07-18 18:00:27 +00002924 // Get the new insert position for the node we care about.
2925 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002926 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002927 }
John McCall90d1c2d2009-09-24 23:30:46 +00002928 ExtVectorType *New = new (*this, TypeAlignment)
2929 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002930 VectorTypes.InsertNode(New, InsertPos);
2931 Types.push_back(New);
2932 return QualType(New, 0);
2933}
2934
Jay Foad39c79802011-01-12 09:06:06 +00002935QualType
2936ASTContext::getDependentSizedExtVectorType(QualType vecType,
2937 Expr *SizeExpr,
2938 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002939 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002940 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002941 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002942
Craig Topper36250ad2014-05-12 05:36:57 +00002943 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002944 DependentSizedExtVectorType *Canon
2945 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2946 DependentSizedExtVectorType *New;
2947 if (Canon) {
2948 // We already have a canonical version of this array type; use it as
2949 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002950 New = new (*this, TypeAlignment)
2951 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2952 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002953 } else {
2954 QualType CanonVecTy = getCanonicalType(vecType);
2955 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002956 New = new (*this, TypeAlignment)
2957 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2958 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002959
2960 DependentSizedExtVectorType *CanonCheck
2961 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2962 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2963 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002964 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2965 } else {
2966 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2967 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002968 New = new (*this, TypeAlignment)
2969 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002970 }
2971 }
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregor758a8692009-06-17 21:51:59 +00002973 Types.push_back(New);
2974 return QualType(New, 0);
2975}
2976
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002977/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002978///
Jay Foad39c79802011-01-12 09:06:06 +00002979QualType
2980ASTContext::getFunctionNoProtoType(QualType ResultTy,
2981 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002982 const CallingConv CallConv = Info.getCC();
2983
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002984 // Unique functions, to guarantee there is only one function of a particular
2985 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002986 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002987 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002988
Craig Topper36250ad2014-05-12 05:36:57 +00002989 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002990 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002991 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002992 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002994 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002995 if (!ResultTy.isCanonical()) {
2996 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002997
Chris Lattner47955de2007-01-27 08:37:20 +00002998 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002999 FunctionNoProtoType *NewIP =
3000 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003001 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Roman Divacky65b88cd2011-03-01 17:40:53 +00003004 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00003005 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00003006 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00003007 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003008 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003009 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003010}
3011
Douglas Gregorcd780372013-01-17 23:36:45 +00003012/// \brief Determine whether \p T is canonical as the result type of a function.
3013static bool isCanonicalResultType(QualType T) {
3014 return T.isCanonical() &&
3015 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3016 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3017}
3018
Douglas Gregora602a152015-10-01 20:20:47 +00003019CanQualType
3020ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3021 CanQualType CanResultType = getCanonicalType(ResultType);
3022
3023 // Canonical result types do not have ARC lifetime qualifiers.
3024 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3025 Qualifiers Qs = CanResultType.getQualifiers();
3026 Qs.removeObjCLifetime();
3027 return CanQualType::CreateUnsafe(
3028 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3029 }
3030
3031 return CanResultType;
3032}
3033
Jay Foad39c79802011-01-12 09:06:06 +00003034QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003035ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003036 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003037 size_t NumArgs = ArgArray.size();
3038
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003039 // Unique functions, to guarantee there is only one function of a particular
3040 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003041 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003042 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3043 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003044
Craig Topper36250ad2014-05-12 05:36:57 +00003045 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003046 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003047 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003048 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003049
3050 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003051 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003052 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003053 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003054 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003055 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003056 isCanonical = false;
3057
3058 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003059 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003060 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003061 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003062 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003063 CanonicalArgs.reserve(NumArgs);
3064 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003065 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003066
John McCalldb40c7f2010-12-14 08:05:40 +00003067 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003068 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003069 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003070
Douglas Gregora602a152015-10-01 20:20:47 +00003071 // Adjust the canonical function result type.
3072 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003073 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003074
Chris Lattnerfd4de792007-01-27 01:15:32 +00003075 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003076 FunctionProtoType *NewIP =
3077 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003078 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003079 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003080
John McCall31168b02011-06-15 23:02:42 +00003081 // FunctionProtoType objects are allocated with extra bytes after
3082 // them for three variable size arrays at the end:
3083 // - parameter types
3084 // - exception types
3085 // - consumed-arguments flags
3086 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003087 // expression, or information used to resolve the exception
3088 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003089 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003090 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003091 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3092 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3093 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003094 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003095 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003096 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003097 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003098 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003099 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003100 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003101 Size += NumArgs * sizeof(bool);
3102
John McCalldb40c7f2010-12-14 08:05:40 +00003103 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003104 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003105 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003106 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003107 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003108 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003109}
Chris Lattneref51c202006-11-10 07:17:23 +00003110
John McCalle78aac42010-03-10 03:28:59 +00003111#ifndef NDEBUG
3112static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3113 if (!isa<CXXRecordDecl>(D)) return false;
3114 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3115 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3116 return true;
3117 if (RD->getDescribedClassTemplate() &&
3118 !isa<ClassTemplateSpecializationDecl>(RD))
3119 return true;
3120 return false;
3121}
3122#endif
3123
3124/// getInjectedClassNameType - Return the unique reference to the
3125/// injected class name type for the specified templated declaration.
3126QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003127 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003128 assert(NeedsInjectedClassNameType(Decl));
3129 if (Decl->TypeForDecl) {
3130 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003131 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003132 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3133 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3134 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3135 } else {
John McCall424cec92011-01-19 06:33:43 +00003136 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003137 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003138 Decl->TypeForDecl = newType;
3139 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003140 }
3141 return QualType(Decl->TypeForDecl, 0);
3142}
3143
Douglas Gregor83a586e2008-04-13 21:07:44 +00003144/// getTypeDeclType - Return the unique reference to the type for the
3145/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003146QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003147 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003148 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003149
Richard Smithdda56e42011-04-15 14:24:37 +00003150 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003151 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003152
John McCall96f0b5f2010-03-10 06:48:02 +00003153 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3154 "Template type parameter types are always available.");
3155
John McCall81e38502010-02-16 03:57:14 +00003156 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003157 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003158 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003159 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003160 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003161 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003162 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003163 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003164 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003165 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3166 Decl->TypeForDecl = newType;
3167 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003168 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003169 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003170
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003171 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003172}
3173
Chris Lattner32d920b2007-01-26 02:01:53 +00003174/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003175/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003176QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003177ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3178 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003179 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003180
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003181 if (Canonical.isNull())
3182 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003183 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003184 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003185 Decl->TypeForDecl = newType;
3186 Types.push_back(newType);
3187 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003188}
3189
Jay Foad39c79802011-01-12 09:06:06 +00003190QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003191 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3192
Douglas Gregorec9fd132012-01-14 16:38:05 +00003193 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003194 if (PrevDecl->TypeForDecl)
3195 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3196
John McCall424cec92011-01-19 06:33:43 +00003197 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3198 Decl->TypeForDecl = newType;
3199 Types.push_back(newType);
3200 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003201}
3202
Jay Foad39c79802011-01-12 09:06:06 +00003203QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003204 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3205
Douglas Gregorec9fd132012-01-14 16:38:05 +00003206 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003207 if (PrevDecl->TypeForDecl)
3208 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3209
John McCall424cec92011-01-19 06:33:43 +00003210 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3211 Decl->TypeForDecl = newType;
3212 Types.push_back(newType);
3213 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003214}
3215
John McCall81904512011-01-06 01:58:22 +00003216QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3217 QualType modifiedType,
3218 QualType equivalentType) {
3219 llvm::FoldingSetNodeID id;
3220 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3221
Craig Topper36250ad2014-05-12 05:36:57 +00003222 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003223 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3224 if (type) return QualType(type, 0);
3225
3226 QualType canon = getCanonicalType(equivalentType);
3227 type = new (*this, TypeAlignment)
3228 AttributedType(canon, attrKind, modifiedType, equivalentType);
3229
3230 Types.push_back(type);
3231 AttributedTypes.InsertNode(type, insertPos);
3232
3233 return QualType(type, 0);
3234}
3235
John McCallcebee162009-10-18 09:09:24 +00003236/// \brief Retrieve a substitution-result type.
3237QualType
3238ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003239 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003240 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003241 && "replacement types must always be canonical");
3242
3243 llvm::FoldingSetNodeID ID;
3244 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003245 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003246 SubstTemplateTypeParmType *SubstParm
3247 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3248
3249 if (!SubstParm) {
3250 SubstParm = new (*this, TypeAlignment)
3251 SubstTemplateTypeParmType(Parm, Replacement);
3252 Types.push_back(SubstParm);
3253 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3254 }
3255
3256 return QualType(SubstParm, 0);
3257}
3258
Douglas Gregorada4b792011-01-14 02:55:32 +00003259/// \brief Retrieve a
3260QualType ASTContext::getSubstTemplateTypeParmPackType(
3261 const TemplateTypeParmType *Parm,
3262 const TemplateArgument &ArgPack) {
3263#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003264 for (const auto &P : ArgPack.pack_elements()) {
3265 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3266 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003267 }
3268#endif
3269
3270 llvm::FoldingSetNodeID ID;
3271 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003272 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003273 if (SubstTemplateTypeParmPackType *SubstParm
3274 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3275 return QualType(SubstParm, 0);
3276
3277 QualType Canon;
3278 if (!Parm->isCanonicalUnqualified()) {
3279 Canon = getCanonicalType(QualType(Parm, 0));
3280 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3281 ArgPack);
3282 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3283 }
3284
3285 SubstTemplateTypeParmPackType *SubstParm
3286 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3287 ArgPack);
3288 Types.push_back(SubstParm);
3289 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3290 return QualType(SubstParm, 0);
3291}
3292
Douglas Gregoreff93e02009-02-05 23:33:38 +00003293/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003294/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003295/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003296QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003297 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003298 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003299 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003300 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003301 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003302 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003303 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3304
3305 if (TypeParm)
3306 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Chandler Carruth08836322011-05-01 00:51:33 +00003308 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003309 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003310 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003311
3312 TemplateTypeParmType *TypeCheck
3313 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 assert(!TypeCheck && "Template type parameter canonical type broken");
3315 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003316 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003317 TypeParm = new (*this, TypeAlignment)
3318 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003319
3320 Types.push_back(TypeParm);
3321 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3322
3323 return QualType(TypeParm, 0);
3324}
3325
John McCalle78aac42010-03-10 03:28:59 +00003326TypeSourceInfo *
3327ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3328 SourceLocation NameLoc,
3329 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003330 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003331 assert(!Name.getAsDependentTemplateName() &&
3332 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003333 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003334
3335 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003336 TemplateSpecializationTypeLoc TL =
3337 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003338 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003339 TL.setTemplateNameLoc(NameLoc);
3340 TL.setLAngleLoc(Args.getLAngleLoc());
3341 TL.setRAngleLoc(Args.getRAngleLoc());
3342 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3343 TL.setArgLocInfo(i, Args[i].getLocInfo());
3344 return DI;
3345}
3346
Mike Stump11289f42009-09-09 15:08:12 +00003347QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003348ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003349 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003350 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003351 assert(!Template.getAsDependentTemplateName() &&
3352 "No dependent template names here!");
3353
John McCall6b51f282009-11-23 01:53:49 +00003354 unsigned NumArgs = Args.size();
3355
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003357 ArgVec.reserve(NumArgs);
3358 for (unsigned i = 0; i != NumArgs; ++i)
3359 ArgVec.push_back(Args[i].getArgument());
3360
John McCall2408e322010-04-27 00:57:59 +00003361 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003362 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003363}
3364
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003365#ifndef NDEBUG
3366static bool hasAnyPackExpansions(const TemplateArgument *Args,
3367 unsigned NumArgs) {
3368 for (unsigned I = 0; I != NumArgs; ++I)
3369 if (Args[I].isPackExpansion())
3370 return true;
3371
3372 return true;
3373}
3374#endif
3375
John McCall0ad16662009-10-29 08:12:44 +00003376QualType
3377ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003378 const TemplateArgument *Args,
3379 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003380 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003381 assert(!Template.getAsDependentTemplateName() &&
3382 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003383 // Look through qualified template names.
3384 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3385 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003386
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003387 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003388 Template.getAsTemplateDecl() &&
3389 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003390 QualType CanonType;
3391 if (!Underlying.isNull())
3392 CanonType = getCanonicalType(Underlying);
3393 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003394 // We can get here with an alias template when the specialization contains
3395 // a pack expansion that does not match up with a parameter pack.
3396 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3397 "Caller must compute aliased type");
3398 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003399 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3400 NumArgs);
3401 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003402
Douglas Gregora8e02e72009-07-28 23:00:59 +00003403 // Allocate the (non-canonical) template specialization type, but don't
3404 // try to unique it: these types typically have location information that
3405 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003406 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3407 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003408 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003409 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003410 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003411 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3412 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003413
Douglas Gregor8bf42052009-02-09 18:46:07 +00003414 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003415 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003416}
3417
Mike Stump11289f42009-09-09 15:08:12 +00003418QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003419ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3420 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003421 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003422 assert(!Template.getAsDependentTemplateName() &&
3423 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003424
Douglas Gregore29139c2011-03-03 17:04:51 +00003425 // Look through qualified template names.
3426 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3427 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003428
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003429 // Build the canonical template specialization type.
3430 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003431 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003432 CanonArgs.reserve(NumArgs);
3433 for (unsigned I = 0; I != NumArgs; ++I)
3434 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3435
3436 // Determine whether this canonical template specialization type already
3437 // exists.
3438 llvm::FoldingSetNodeID ID;
3439 TemplateSpecializationType::Profile(ID, CanonTemplate,
3440 CanonArgs.data(), NumArgs, *this);
3441
Craig Topper36250ad2014-05-12 05:36:57 +00003442 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003443 TemplateSpecializationType *Spec
3444 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3445
3446 if (!Spec) {
3447 // Allocate a new canonical template specialization type.
3448 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3449 sizeof(TemplateArgument) * NumArgs),
3450 TypeAlignment);
3451 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3452 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003453 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003454 Types.push_back(Spec);
3455 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3456 }
3457
3458 assert(Spec->isDependentType() &&
3459 "Non-dependent template-id type must have a canonical type");
3460 return QualType(Spec, 0);
3461}
3462
3463QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003464ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3465 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003466 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003467 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003468 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003469
Craig Topper36250ad2014-05-12 05:36:57 +00003470 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003471 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003472 if (T)
3473 return QualType(T, 0);
3474
Douglas Gregorc42075a2010-02-04 18:10:26 +00003475 QualType Canon = NamedType;
3476 if (!Canon.isCanonical()) {
3477 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003478 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3479 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003480 (void)CheckT;
3481 }
3482
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003483 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003484 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003485 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003486 return QualType(T, 0);
3487}
3488
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003489QualType
Jay Foad39c79802011-01-12 09:06:06 +00003490ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003491 llvm::FoldingSetNodeID ID;
3492 ParenType::Profile(ID, InnerType);
3493
Craig Topper36250ad2014-05-12 05:36:57 +00003494 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003495 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3496 if (T)
3497 return QualType(T, 0);
3498
3499 QualType Canon = InnerType;
3500 if (!Canon.isCanonical()) {
3501 Canon = getCanonicalType(InnerType);
3502 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3503 assert(!CheckT && "Paren canonical type broken");
3504 (void)CheckT;
3505 }
3506
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003507 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003508 Types.push_back(T);
3509 ParenTypes.InsertNode(T, InsertPos);
3510 return QualType(T, 0);
3511}
3512
Douglas Gregor02085352010-03-31 20:19:30 +00003513QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3514 NestedNameSpecifier *NNS,
3515 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003516 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003517 if (Canon.isNull()) {
3518 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003519 ElaboratedTypeKeyword CanonKeyword = Keyword;
3520 if (Keyword == ETK_None)
3521 CanonKeyword = ETK_Typename;
3522
3523 if (CanonNNS != NNS || CanonKeyword != Keyword)
3524 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003525 }
3526
3527 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003528 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003529
Craig Topper36250ad2014-05-12 05:36:57 +00003530 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003531 DependentNameType *T
3532 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003533 if (T)
3534 return QualType(T, 0);
3535
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003536 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003537 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003538 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003539 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003540}
3541
Mike Stump11289f42009-09-09 15:08:12 +00003542QualType
John McCallc392f372010-06-11 00:33:02 +00003543ASTContext::getDependentTemplateSpecializationType(
3544 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003545 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003546 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003547 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003548 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003549 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003550 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3551 ArgCopy.push_back(Args[I].getArgument());
3552 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3553 ArgCopy.size(),
3554 ArgCopy.data());
3555}
3556
3557QualType
3558ASTContext::getDependentTemplateSpecializationType(
3559 ElaboratedTypeKeyword Keyword,
3560 NestedNameSpecifier *NNS,
3561 const IdentifierInfo *Name,
3562 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003563 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003564 assert((!NNS || NNS->isDependent()) &&
3565 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003566
Douglas Gregorc42075a2010-02-04 18:10:26 +00003567 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003568 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3569 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003570
Craig Topper36250ad2014-05-12 05:36:57 +00003571 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003572 DependentTemplateSpecializationType *T
3573 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003574 if (T)
3575 return QualType(T, 0);
3576
John McCallc392f372010-06-11 00:33:02 +00003577 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003578
John McCallc392f372010-06-11 00:33:02 +00003579 ElaboratedTypeKeyword CanonKeyword = Keyword;
3580 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3581
3582 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003583 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003584 for (unsigned I = 0; I != NumArgs; ++I) {
3585 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3586 if (!CanonArgs[I].structurallyEquals(Args[I]))
3587 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003588 }
3589
John McCallc392f372010-06-11 00:33:02 +00003590 QualType Canon;
3591 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3592 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3593 Name, NumArgs,
3594 CanonArgs.data());
3595
3596 // Find the insert position again.
3597 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3598 }
3599
3600 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3601 sizeof(TemplateArgument) * NumArgs),
3602 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003603 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003604 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003605 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003606 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003607 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003608}
3609
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003610QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003611 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003612 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003613 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003614
3615 assert(Pattern->containsUnexpandedParameterPack() &&
3616 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003617 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003618 PackExpansionType *T
3619 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3620 if (T)
3621 return QualType(T, 0);
3622
3623 QualType Canon;
3624 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003625 Canon = getCanonicalType(Pattern);
3626 // The canonical type might not contain an unexpanded parameter pack, if it
3627 // contains an alias template specialization which ignores one of its
3628 // parameters.
3629 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003630 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003631
Richard Smith68eea502012-07-16 00:20:35 +00003632 // Find the insert position again, in case we inserted an element into
3633 // PackExpansionTypes and invalidated our insert position.
3634 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3635 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003636 }
3637
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003638 T = new (*this, TypeAlignment)
3639 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003640 Types.push_back(T);
3641 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003642 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003643}
3644
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003645/// CmpProtocolNames - Comparison predicate for sorting protocols
3646/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003647static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3648 ObjCProtocolDecl *const *RHS) {
3649 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003650}
3651
John McCall8b07ec22010-05-15 11:32:37 +00003652static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003653 unsigned NumProtocols) {
3654 if (NumProtocols == 0) return true;
3655
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003656 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3657 return false;
3658
John McCallfc93cf92009-10-22 22:37:11 +00003659 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003660 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003661 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003662 return false;
3663 return true;
3664}
3665
Craig Topper6a8c1512015-10-22 01:56:18 +00003666static void
3667SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003668 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003669 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003670
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003671 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003672 for (ObjCProtocolDecl *&P : Protocols)
3673 P = P->getCanonicalDecl();
3674
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003675 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003676 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3677 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003678}
3679
John McCall8b07ec22010-05-15 11:32:37 +00003680QualType ASTContext::getObjCObjectType(QualType BaseType,
3681 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003682 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003683 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003684 llvm::makeArrayRef(Protocols, NumProtocols),
3685 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003686}
3687
3688QualType ASTContext::getObjCObjectType(
3689 QualType baseType,
3690 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003691 ArrayRef<ObjCProtocolDecl *> protocols,
3692 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003693 // If the base type is an interface and there aren't any protocols or
3694 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003695 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3696 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003697 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003698
3699 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003700 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003701 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003702 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003703 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3704 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003705
Douglas Gregore9d95f12015-07-07 03:57:35 +00003706 // Determine the type arguments to be used for canonicalization,
3707 // which may be explicitly specified here or written on the base
3708 // type.
3709 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3710 if (effectiveTypeArgs.empty()) {
3711 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3712 effectiveTypeArgs = baseObject->getTypeArgs();
3713 }
John McCallfc93cf92009-10-22 22:37:11 +00003714
Douglas Gregore9d95f12015-07-07 03:57:35 +00003715 // Build the canonical type, which has the canonical base type and a
3716 // sorted-and-uniqued list of protocols and the type arguments
3717 // canonicalized.
3718 QualType canonical;
3719 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3720 effectiveTypeArgs.end(),
3721 [&](QualType type) {
3722 return type.isCanonical();
3723 });
3724 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3725 protocols.size());
3726 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3727 // Determine the canonical type arguments.
3728 ArrayRef<QualType> canonTypeArgs;
3729 SmallVector<QualType, 4> canonTypeArgsVec;
3730 if (!typeArgsAreCanonical) {
3731 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3732 for (auto typeArg : effectiveTypeArgs)
3733 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3734 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003735 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003736 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003737 }
3738
Douglas Gregore9d95f12015-07-07 03:57:35 +00003739 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3740 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3741 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003742 canonProtocolsVec.append(protocols.begin(), protocols.end());
3743 SortAndUniqueProtocols(canonProtocolsVec);
3744 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003745 } else {
3746 canonProtocols = protocols;
3747 }
3748
3749 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003750 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003751
John McCallfc93cf92009-10-22 22:37:11 +00003752 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003753 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3754 }
3755
Douglas Gregore9d95f12015-07-07 03:57:35 +00003756 unsigned size = sizeof(ObjCObjectTypeImpl);
3757 size += typeArgs.size() * sizeof(QualType);
3758 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3759 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003760 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003761 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3762 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003763
3764 Types.push_back(T);
3765 ObjCObjectTypes.InsertNode(T, InsertPos);
3766 return QualType(T, 0);
3767}
3768
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003769/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3770/// protocol list adopt all protocols in QT's qualified-id protocol
3771/// list.
3772bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3773 ObjCInterfaceDecl *IC) {
3774 if (!QT->isObjCQualifiedIdType())
3775 return false;
3776
3777 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3778 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003779 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003780 if (!IC->ClassImplementsProtocol(Proto, false))
3781 return false;
3782 }
3783 return true;
3784 }
3785 return false;
3786}
3787
3788/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3789/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3790/// of protocols.
3791bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3792 ObjCInterfaceDecl *IDecl) {
3793 if (!QT->isObjCQualifiedIdType())
3794 return false;
3795 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3796 if (!OPT)
3797 return false;
3798 if (!IDecl->hasDefinition())
3799 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003800 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3801 CollectInheritedProtocols(IDecl, InheritedProtocols);
3802 if (InheritedProtocols.empty())
3803 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003804 // Check that if every protocol in list of id<plist> conforms to a protcol
3805 // of IDecl's, then bridge casting is ok.
3806 bool Conforms = false;
3807 for (auto *Proto : OPT->quals()) {
3808 Conforms = false;
3809 for (auto *PI : InheritedProtocols) {
3810 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3811 Conforms = true;
3812 break;
3813 }
3814 }
3815 if (!Conforms)
3816 break;
3817 }
3818 if (Conforms)
3819 return true;
3820
Aaron Ballman83731462014-03-17 16:14:00 +00003821 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003822 // If both the right and left sides have qualifiers.
3823 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003824 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003825 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003826 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003827 break;
3828 }
3829 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003830 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003831 }
3832 return true;
3833}
3834
John McCall8b07ec22010-05-15 11:32:37 +00003835/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3836/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003837QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003838 llvm::FoldingSetNodeID ID;
3839 ObjCObjectPointerType::Profile(ID, ObjectT);
3840
Craig Topper36250ad2014-05-12 05:36:57 +00003841 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003842 if (ObjCObjectPointerType *QT =
3843 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3844 return QualType(QT, 0);
3845
3846 // Find the canonical object type.
3847 QualType Canonical;
3848 if (!ObjectT.isCanonical()) {
3849 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3850
3851 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003852 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3853 }
3854
Douglas Gregorf85bee62010-02-08 22:59:26 +00003855 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003856 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3857 ObjCObjectPointerType *QType =
3858 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003859
Steve Narofffb4330f2009-06-17 22:40:22 +00003860 Types.push_back(QType);
3861 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003862 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003863}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003864
Douglas Gregor1c283312010-08-11 12:19:30 +00003865/// getObjCInterfaceType - Return the unique reference to the type for the
3866/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003867QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3868 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003869 if (Decl->TypeForDecl)
3870 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003871
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003872 if (PrevDecl) {
3873 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3874 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3875 return QualType(PrevDecl->TypeForDecl, 0);
3876 }
3877
Douglas Gregor7671e532011-12-16 16:34:57 +00003878 // Prefer the definition, if there is one.
3879 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3880 Decl = Def;
3881
Douglas Gregor1c283312010-08-11 12:19:30 +00003882 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3883 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3884 Decl->TypeForDecl = T;
3885 Types.push_back(T);
3886 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003887}
3888
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003889/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3890/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003891/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003892/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003893/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003894QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003895 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003896 if (tofExpr->isTypeDependent()) {
3897 llvm::FoldingSetNodeID ID;
3898 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003899
Craig Topper36250ad2014-05-12 05:36:57 +00003900 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003901 DependentTypeOfExprType *Canon
3902 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3903 if (Canon) {
3904 // We already have a "canonical" version of an identical, dependent
3905 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003906 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003907 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003908 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003909 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003910 Canon
3911 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003912 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3913 toe = Canon;
3914 }
3915 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003916 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003917 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003918 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003919 Types.push_back(toe);
3920 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003921}
3922
Steve Naroffa773cd52007-08-01 18:02:17 +00003923/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003924/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003925/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003926/// an issue. This doesn't affect the type checker, since it operates
3927/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003928QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003929 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003930 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003931 Types.push_back(tot);
3932 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003933}
3934
Richard Smith8eb1d322014-06-05 20:13:13 +00003935/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3936/// nodes. This would never be helpful, since each such type has its own
3937/// expression, and would not give a significant memory saving, since there
3938/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003939QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003940 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003941
3942 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003943 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003944 // unique dependent type. Two such decltype-specifiers refer to the same
3945 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003946 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003947 llvm::FoldingSetNodeID ID;
3948 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003949
Craig Topper36250ad2014-05-12 05:36:57 +00003950 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003951 DependentDecltypeType *Canon
3952 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003953 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003954 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003955 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003956 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003957 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003958 dt = new (*this, TypeAlignment)
3959 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003960 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003961 dt = new (*this, TypeAlignment)
3962 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003963 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003964 Types.push_back(dt);
3965 return QualType(dt, 0);
3966}
3967
Alexis Hunte852b102011-05-24 22:41:36 +00003968/// getUnaryTransformationType - We don't unique these, since the memory
3969/// savings are minimal and these are rare.
3970QualType ASTContext::getUnaryTransformType(QualType BaseType,
3971 QualType UnderlyingType,
3972 UnaryTransformType::UTTKind Kind)
3973 const {
3974 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003975 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3976 Kind,
3977 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003978 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003979 Types.push_back(Ty);
3980 return QualType(Ty, 0);
3981}
3982
Richard Smith2a7d4812013-05-04 07:00:32 +00003983/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3984/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3985/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00003986QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003987 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00003988 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003989 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003990
Richard Smith2a7d4812013-05-04 07:00:32 +00003991 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003992 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003993 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00003994 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003995 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3996 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003997
Richard Smith74aeef52013-04-26 16:15:35 +00003998 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00003999 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004000 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004001 Types.push_back(AT);
4002 if (InsertPos)
4003 AutoTypes.InsertNode(AT, InsertPos);
4004 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004005}
4006
Eli Friedman0dfb8892011-10-06 23:00:33 +00004007/// getAtomicType - Return the uniqued reference to the atomic type for
4008/// the given value type.
4009QualType ASTContext::getAtomicType(QualType T) const {
4010 // Unique pointers, to guarantee there is only one pointer of a particular
4011 // structure.
4012 llvm::FoldingSetNodeID ID;
4013 AtomicType::Profile(ID, T);
4014
Craig Topper36250ad2014-05-12 05:36:57 +00004015 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004016 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4017 return QualType(AT, 0);
4018
4019 // If the atomic value type isn't canonical, this won't be a canonical type
4020 // either, so fill in the canonical type field.
4021 QualType Canonical;
4022 if (!T.isCanonical()) {
4023 Canonical = getAtomicType(getCanonicalType(T));
4024
4025 // Get the new insert position for the node we care about.
4026 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004027 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004028 }
4029 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4030 Types.push_back(New);
4031 AtomicTypes.InsertNode(New, InsertPos);
4032 return QualType(New, 0);
4033}
4034
Richard Smith02e85f32011-04-14 22:09:26 +00004035/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4036QualType ASTContext::getAutoDeductType() const {
4037 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004038 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004039 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004040 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004041 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004042 return AutoDeductTy;
4043}
4044
4045/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4046QualType ASTContext::getAutoRRefDeductType() const {
4047 if (AutoRRefDeductTy.isNull())
4048 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4049 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4050 return AutoRRefDeductTy;
4051}
4052
Chris Lattnerfb072462007-01-23 05:45:31 +00004053/// getTagDeclType - Return the unique reference to the type for the
4054/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004055QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004056 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004057 // FIXME: What is the design on getTagDeclType when it requires casting
4058 // away const? mutable?
4059 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004060}
4061
Mike Stump11289f42009-09-09 15:08:12 +00004062/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4063/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4064/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004065CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004066 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004067}
Chris Lattnerfb072462007-01-23 05:45:31 +00004068
Hans Wennborg27541db2011-10-27 08:29:09 +00004069/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4070CanQualType ASTContext::getIntMaxType() const {
4071 return getFromTargetType(Target->getIntMaxType());
4072}
4073
4074/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4075CanQualType ASTContext::getUIntMaxType() const {
4076 return getFromTargetType(Target->getUIntMaxType());
4077}
4078
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004079/// getSignedWCharType - Return the type of "signed wchar_t".
4080/// Used when in C++, as a GCC extension.
4081QualType ASTContext::getSignedWCharType() const {
4082 // FIXME: derive from "Target" ?
4083 return WCharTy;
4084}
4085
4086/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4087/// Used when in C++, as a GCC extension.
4088QualType ASTContext::getUnsignedWCharType() const {
4089 // FIXME: derive from "Target" ?
4090 return UnsignedIntTy;
4091}
4092
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004093QualType ASTContext::getIntPtrType() const {
4094 return getFromTargetType(Target->getIntPtrType());
4095}
4096
4097QualType ASTContext::getUIntPtrType() const {
4098 return getCorrespondingUnsignedType(getIntPtrType());
4099}
4100
Hans Wennborg27541db2011-10-27 08:29:09 +00004101/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004102/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4103QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004104 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004105}
4106
Eli Friedman4e91899e2012-11-27 02:58:24 +00004107/// \brief Return the unique type for "pid_t" defined in
4108/// <sys/types.h>. We need this to compute the correct type for vfork().
4109QualType ASTContext::getProcessIDType() const {
4110 return getFromTargetType(Target->getProcessIDType());
4111}
4112
Chris Lattnera21ad802008-04-02 05:18:44 +00004113//===----------------------------------------------------------------------===//
4114// Type Operators
4115//===----------------------------------------------------------------------===//
4116
Jay Foad39c79802011-01-12 09:06:06 +00004117CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004118 // Push qualifiers into arrays, and then discard any remaining
4119 // qualifiers.
4120 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004121 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004122 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004123 QualType Result;
4124 if (isa<ArrayType>(Ty)) {
4125 Result = getArrayDecayedType(QualType(Ty,0));
4126 } else if (isa<FunctionType>(Ty)) {
4127 Result = getPointerType(QualType(Ty, 0));
4128 } else {
4129 Result = QualType(Ty, 0);
4130 }
4131
4132 return CanQualType::CreateUnsafe(Result);
4133}
4134
John McCall6c9dd522011-01-18 07:41:22 +00004135QualType ASTContext::getUnqualifiedArrayType(QualType type,
4136 Qualifiers &quals) {
4137 SplitQualType splitType = type.getSplitUnqualifiedType();
4138
4139 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4140 // the unqualified desugared type and then drops it on the floor.
4141 // We then have to strip that sugar back off with
4142 // getUnqualifiedDesugaredType(), which is silly.
4143 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004144 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004145
4146 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004147 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004148 quals = splitType.Quals;
4149 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004150 }
4151
John McCall6c9dd522011-01-18 07:41:22 +00004152 // Otherwise, recurse on the array's element type.
4153 QualType elementType = AT->getElementType();
4154 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4155
4156 // If that didn't change the element type, AT has no qualifiers, so we
4157 // can just use the results in splitType.
4158 if (elementType == unqualElementType) {
4159 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004160 quals = splitType.Quals;
4161 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004162 }
4163
4164 // Otherwise, add in the qualifiers from the outermost type, then
4165 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004166 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004167
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004168 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004169 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004170 CAT->getSizeModifier(), 0);
4171 }
4172
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004173 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004174 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004175 }
4176
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004177 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004178 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004179 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004180 VAT->getSizeModifier(),
4181 VAT->getIndexTypeCVRQualifiers(),
4182 VAT->getBracketsRange());
4183 }
4184
4185 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004186 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004187 DSAT->getSizeModifier(), 0,
4188 SourceRange());
4189}
4190
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004191/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4192/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4193/// they point to and return true. If T1 and T2 aren't pointer types
4194/// or pointer-to-member types, or if they are not similar at this
4195/// level, returns false and leaves T1 and T2 unchanged. Top-level
4196/// qualifiers on T1 and T2 are ignored. This function will typically
4197/// be called in a loop that successively "unwraps" pointer and
4198/// pointer-to-member types to compare them at each level.
4199bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4200 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4201 *T2PtrType = T2->getAs<PointerType>();
4202 if (T1PtrType && T2PtrType) {
4203 T1 = T1PtrType->getPointeeType();
4204 T2 = T2PtrType->getPointeeType();
4205 return true;
4206 }
4207
4208 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4209 *T2MPType = T2->getAs<MemberPointerType>();
4210 if (T1MPType && T2MPType &&
4211 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4212 QualType(T2MPType->getClass(), 0))) {
4213 T1 = T1MPType->getPointeeType();
4214 T2 = T2MPType->getPointeeType();
4215 return true;
4216 }
4217
David Blaikiebbafb8a2012-03-11 07:00:24 +00004218 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004219 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4220 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4221 if (T1OPType && T2OPType) {
4222 T1 = T1OPType->getPointeeType();
4223 T2 = T2OPType->getPointeeType();
4224 return true;
4225 }
4226 }
4227
4228 // FIXME: Block pointers, too?
4229
4230 return false;
4231}
4232
Jay Foad39c79802011-01-12 09:06:06 +00004233DeclarationNameInfo
4234ASTContext::getNameForTemplate(TemplateName Name,
4235 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004236 switch (Name.getKind()) {
4237 case TemplateName::QualifiedTemplate:
4238 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004239 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004240 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4241 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004242
John McCalld9dfe3a2011-06-30 08:33:18 +00004243 case TemplateName::OverloadedTemplate: {
4244 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4245 // DNInfo work in progress: CHECKME: what about DNLoc?
4246 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4247 }
4248
4249 case TemplateName::DependentTemplate: {
4250 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004251 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004252 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004253 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4254 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004255 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004256 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4257 // DNInfo work in progress: FIXME: source locations?
4258 DeclarationNameLoc DNLoc;
4259 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4260 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4261 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004262 }
4263 }
4264
John McCalld9dfe3a2011-06-30 08:33:18 +00004265 case TemplateName::SubstTemplateTemplateParm: {
4266 SubstTemplateTemplateParmStorage *subst
4267 = Name.getAsSubstTemplateTemplateParm();
4268 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4269 NameLoc);
4270 }
4271
4272 case TemplateName::SubstTemplateTemplateParmPack: {
4273 SubstTemplateTemplateParmPackStorage *subst
4274 = Name.getAsSubstTemplateTemplateParmPack();
4275 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4276 NameLoc);
4277 }
4278 }
4279
4280 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004281}
4282
Jay Foad39c79802011-01-12 09:06:06 +00004283TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004284 switch (Name.getKind()) {
4285 case TemplateName::QualifiedTemplate:
4286 case TemplateName::Template: {
4287 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004288 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004289 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004290 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4291
4292 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004293 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004294 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004295
John McCalld9dfe3a2011-06-30 08:33:18 +00004296 case TemplateName::OverloadedTemplate:
4297 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCalld9dfe3a2011-06-30 08:33:18 +00004299 case TemplateName::DependentTemplate: {
4300 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4301 assert(DTN && "Non-dependent template names must refer to template decls.");
4302 return DTN->CanonicalTemplateName;
4303 }
4304
4305 case TemplateName::SubstTemplateTemplateParm: {
4306 SubstTemplateTemplateParmStorage *subst
4307 = Name.getAsSubstTemplateTemplateParm();
4308 return getCanonicalTemplateName(subst->getReplacement());
4309 }
4310
4311 case TemplateName::SubstTemplateTemplateParmPack: {
4312 SubstTemplateTemplateParmPackStorage *subst
4313 = Name.getAsSubstTemplateTemplateParmPack();
4314 TemplateTemplateParmDecl *canonParameter
4315 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4316 TemplateArgument canonArgPack
4317 = getCanonicalTemplateArgument(subst->getArgumentPack());
4318 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4319 }
4320 }
4321
4322 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004323}
4324
Douglas Gregoradee3e32009-11-11 23:06:43 +00004325bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4326 X = getCanonicalTemplateName(X);
4327 Y = getCanonicalTemplateName(Y);
4328 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4329}
4330
Mike Stump11289f42009-09-09 15:08:12 +00004331TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004332ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004333 switch (Arg.getKind()) {
4334 case TemplateArgument::Null:
4335 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004336
Douglas Gregora8e02e72009-07-28 23:00:59 +00004337 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004338 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004340 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004341 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004342 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004343 }
Mike Stump11289f42009-09-09 15:08:12 +00004344
Eli Friedmanb826a002012-09-26 02:36:12 +00004345 case TemplateArgument::NullPtr:
4346 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4347 /*isNullPtr*/true);
4348
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004349 case TemplateArgument::Template:
4350 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004351
4352 case TemplateArgument::TemplateExpansion:
4353 return TemplateArgument(getCanonicalTemplateName(
4354 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004355 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004356
Douglas Gregora8e02e72009-07-28 23:00:59 +00004357 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004358 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004359
Douglas Gregora8e02e72009-07-28 23:00:59 +00004360 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004361 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004362
Douglas Gregora8e02e72009-07-28 23:00:59 +00004363 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004364 if (Arg.pack_size() == 0)
4365 return Arg;
4366
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004367 TemplateArgument *CanonArgs
4368 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004369 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004370 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004371 AEnd = Arg.pack_end();
4372 A != AEnd; (void)++A, ++Idx)
4373 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004374
Benjamin Kramercce63472015-08-05 09:40:22 +00004375 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004376 }
4377 }
4378
4379 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004380 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004381}
4382
Douglas Gregor333489b2009-03-27 23:10:48 +00004383NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004384ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004385 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004386 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004387
4388 switch (NNS->getKind()) {
4389 case NestedNameSpecifier::Identifier:
4390 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004391 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004392 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4393 NNS->getAsIdentifier());
4394
4395 case NestedNameSpecifier::Namespace:
4396 // A namespace is canonical; build a nested-name-specifier with
4397 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004398 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004399 NNS->getAsNamespace()->getOriginalNamespace());
4400
4401 case NestedNameSpecifier::NamespaceAlias:
4402 // A namespace is canonical; build a nested-name-specifier with
4403 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004404 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004405 NNS->getAsNamespaceAlias()->getNamespace()
4406 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004407
4408 case NestedNameSpecifier::TypeSpec:
4409 case NestedNameSpecifier::TypeSpecWithTemplate: {
4410 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004411
4412 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4413 // break it apart into its prefix and identifier, then reconsititute those
4414 // as the canonical nested-name-specifier. This is required to canonicalize
4415 // a dependent nested-name-specifier involving typedefs of dependent-name
4416 // types, e.g.,
4417 // typedef typename T::type T1;
4418 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004419 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4420 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004421 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004422
Eli Friedman5358a0a2012-03-03 04:09:56 +00004423 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4424 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4425 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004426 return NestedNameSpecifier::Create(*this, nullptr, false,
4427 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004428 }
4429
4430 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004431 case NestedNameSpecifier::Super:
4432 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004433 return NNS;
4434 }
4435
David Blaikie8a40f702012-01-17 06:56:22 +00004436 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004437}
4438
Jay Foad39c79802011-01-12 09:06:06 +00004439const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004440 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004441 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004442 // Handle the common positive case fast.
4443 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4444 return AT;
4445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446
John McCall8ccfcb52009-09-24 19:53:00 +00004447 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004448 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004449 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004450
John McCall8ccfcb52009-09-24 19:53:00 +00004451 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004452 // implements C99 6.7.3p8: "If the specification of an array type includes
4453 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004454
Chris Lattner7adf0762008-08-04 07:31:14 +00004455 // If we get here, we either have type qualifiers on the type, or we have
4456 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004457 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004458
John McCall33ddac02011-01-19 10:06:00 +00004459 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004460 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004461
Chris Lattner7adf0762008-08-04 07:31:14 +00004462 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004463 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004464 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004465 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004466
Chris Lattner7adf0762008-08-04 07:31:14 +00004467 // Otherwise, we have an array and we have qualifiers on it. Push the
4468 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004469 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004470
Chris Lattner7adf0762008-08-04 07:31:14 +00004471 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4472 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4473 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004474 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004475 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4476 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4477 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004478 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004479
Mike Stump11289f42009-09-09 15:08:12 +00004480 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004481 = dyn_cast<DependentSizedArrayType>(ATy))
4482 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004483 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004484 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004485 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004486 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004487 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004488
Chris Lattner7adf0762008-08-04 07:31:14 +00004489 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004490 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004491 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004492 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004493 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004494 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004495}
4496
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004497QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004498 if (T->isArrayType() || T->isFunctionType())
4499 return getDecayedType(T);
4500 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004501}
4502
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004503QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004504 T = getVariableArrayDecayedType(T);
4505 T = getAdjustedParameterType(T);
4506 return T.getUnqualifiedType();
4507}
4508
David Majnemerd09a51c2015-03-03 01:50:05 +00004509QualType ASTContext::getExceptionObjectType(QualType T) const {
4510 // C++ [except.throw]p3:
4511 // A throw-expression initializes a temporary object, called the exception
4512 // object, the type of which is determined by removing any top-level
4513 // cv-qualifiers from the static type of the operand of throw and adjusting
4514 // the type from "array of T" or "function returning T" to "pointer to T"
4515 // or "pointer to function returning T", [...]
4516 T = getVariableArrayDecayedType(T);
4517 if (T->isArrayType() || T->isFunctionType())
4518 T = getDecayedType(T);
4519 return T.getUnqualifiedType();
4520}
4521
Chris Lattnera21ad802008-04-02 05:18:44 +00004522/// getArrayDecayedType - Return the properly qualified result of decaying the
4523/// specified array type to a pointer. This operation is non-trivial when
4524/// handling typedefs etc. The canonical type of "T" must be an array type,
4525/// this returns a pointer to a properly qualified element of the array.
4526///
4527/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004528QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004529 // Get the element type with 'getAsArrayType' so that we don't lose any
4530 // typedefs in the element type of the array. This also handles propagation
4531 // of type qualifiers from the array type into the element type if present
4532 // (C99 6.7.3p8).
4533 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4534 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattner7adf0762008-08-04 07:31:14 +00004536 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004537
4538 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004539 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004540}
4541
John McCall33ddac02011-01-19 10:06:00 +00004542QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4543 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004544}
4545
John McCall33ddac02011-01-19 10:06:00 +00004546QualType ASTContext::getBaseElementType(QualType type) const {
4547 Qualifiers qs;
4548 while (true) {
4549 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004550 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004551 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004552
John McCall33ddac02011-01-19 10:06:00 +00004553 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004554 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
John McCall33ddac02011-01-19 10:06:00 +00004557 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004558}
4559
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004560/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004561uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004562ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4563 uint64_t ElementCount = 1;
4564 do {
4565 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004566 CA = dyn_cast_or_null<ConstantArrayType>(
4567 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004568 } while (CA);
4569 return ElementCount;
4570}
4571
Steve Naroff0af91202007-04-27 21:51:21 +00004572/// getFloatingRank - Return a relative rank for floating point types.
4573/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004574static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004575 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004576 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004577
John McCall9dd450b2009-09-21 23:43:11 +00004578 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4579 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004580 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004581 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004582 case BuiltinType::Float: return FloatRank;
4583 case BuiltinType::Double: return DoubleRank;
4584 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004585 }
4586}
4587
Mike Stump11289f42009-09-09 15:08:12 +00004588/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4589/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004590/// 'typeDomain' is a real floating point or complex type.
4591/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004592QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4593 QualType Domain) const {
4594 FloatingRank EltRank = getFloatingRank(Size);
4595 if (Domain->isComplexType()) {
4596 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004597 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004598 case FloatRank: return FloatComplexTy;
4599 case DoubleRank: return DoubleComplexTy;
4600 case LongDoubleRank: return LongDoubleComplexTy;
4601 }
Steve Naroff0af91202007-04-27 21:51:21 +00004602 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004603
4604 assert(Domain->isRealFloatingType() && "Unknown domain!");
4605 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004606 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004607 case FloatRank: return FloatTy;
4608 case DoubleRank: return DoubleTy;
4609 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004610 }
David Blaikief47fa302012-01-17 02:30:50 +00004611 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004612}
4613
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004614/// getFloatingTypeOrder - Compare the rank of the two specified floating
4615/// point types, ignoring the domain of the type (i.e. 'double' ==
4616/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004617/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004618int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004619 FloatingRank LHSR = getFloatingRank(LHS);
4620 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004621
Chris Lattnerb90739d2008-04-06 23:38:49 +00004622 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004623 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004624 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004625 return 1;
4626 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004627}
4628
Chris Lattner76a00cf2008-04-06 22:59:24 +00004629/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4630/// routine will assert if passed a built-in type that isn't an integer or enum,
4631/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004632unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004633 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004634
Chris Lattner76a00cf2008-04-06 22:59:24 +00004635 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004636 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004637 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004638 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004639 case BuiltinType::Char_S:
4640 case BuiltinType::Char_U:
4641 case BuiltinType::SChar:
4642 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004643 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004644 case BuiltinType::Short:
4645 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004646 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004647 case BuiltinType::Int:
4648 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004649 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004650 case BuiltinType::Long:
4651 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004652 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004653 case BuiltinType::LongLong:
4654 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004655 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004656 case BuiltinType::Int128:
4657 case BuiltinType::UInt128:
4658 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004659 }
4660}
4661
Eli Friedman629ffb92009-08-20 04:21:42 +00004662/// \brief Whether this is a promotable bitfield reference according
4663/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4664///
4665/// \returns the type this bit-field will promote to, or NULL if no
4666/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004667QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004668 if (E->isTypeDependent() || E->isValueDependent())
4669 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004670
4671 // FIXME: We should not do this unless E->refersToBitField() is true. This
4672 // matters in C where getSourceBitField() will find bit-fields for various
4673 // cases where the source expression is not a bit-field designator.
4674
John McCalld25db7e2013-05-06 21:39:12 +00004675 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004676 if (!Field)
4677 return QualType();
4678
4679 QualType FT = Field->getType();
4680
Richard Smithcaf33902011-10-10 18:28:20 +00004681 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004682 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004683 // C++ [conv.prom]p5:
4684 // A prvalue for an integral bit-field can be converted to a prvalue of type
4685 // int if int can represent all the values of the bit-field; otherwise, it
4686 // can be converted to unsigned int if unsigned int can represent all the
4687 // values of the bit-field. If the bit-field is larger yet, no integral
4688 // promotion applies to it.
4689 // C11 6.3.1.1/2:
4690 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4691 // If an int can represent all values of the original type (as restricted by
4692 // the width, for a bit-field), the value is converted to an int; otherwise,
4693 // it is converted to an unsigned int.
4694 //
4695 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4696 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004697 if (BitWidth < IntSize)
4698 return IntTy;
4699
4700 if (BitWidth == IntSize)
4701 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4702
4703 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004704 // like the base type. GCC has some weird bugs in this area that we
4705 // deliberately do not follow (GCC follows a pre-standard resolution to
4706 // C's DR315 which treats bit-width as being part of the type, and this leaks
4707 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004708 return QualType();
4709}
4710
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004711/// getPromotedIntegerType - Returns the type that Promotable will
4712/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4713/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004714QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004715 assert(!Promotable.isNull());
4716 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004717 if (const EnumType *ET = Promotable->getAs<EnumType>())
4718 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004719
4720 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4721 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4722 // (3.9.1) can be converted to a prvalue of the first of the following
4723 // types that can represent all the values of its underlying type:
4724 // int, unsigned int, long int, unsigned long int, long long int, or
4725 // unsigned long long int [...]
4726 // FIXME: Is there some better way to compute this?
4727 if (BT->getKind() == BuiltinType::WChar_S ||
4728 BT->getKind() == BuiltinType::WChar_U ||
4729 BT->getKind() == BuiltinType::Char16 ||
4730 BT->getKind() == BuiltinType::Char32) {
4731 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4732 uint64_t FromSize = getTypeSize(BT);
4733 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4734 LongLongTy, UnsignedLongLongTy };
4735 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4736 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4737 if (FromSize < ToSize ||
4738 (FromSize == ToSize &&
4739 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4740 return PromoteTypes[Idx];
4741 }
4742 llvm_unreachable("char type should fit into long long");
4743 }
4744 }
4745
4746 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004747 if (Promotable->isSignedIntegerType())
4748 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004749 uint64_t PromotableSize = getIntWidth(Promotable);
4750 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004751 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4752 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4753}
4754
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004755/// \brief Recurses in pointer/array types until it finds an objc retainable
4756/// type and returns its ownership.
4757Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4758 while (!T.isNull()) {
4759 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4760 return T.getObjCLifetime();
4761 if (T->isArrayType())
4762 T = getBaseElementType(T);
4763 else if (const PointerType *PT = T->getAs<PointerType>())
4764 T = PT->getPointeeType();
4765 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004766 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004767 else
4768 break;
4769 }
4770
4771 return Qualifiers::OCL_None;
4772}
4773
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004774static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4775 // Incomplete enum types are not treated as integer types.
4776 // FIXME: In C++, enum types are never integer types.
4777 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4778 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004779 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004780}
4781
Mike Stump11289f42009-09-09 15:08:12 +00004782/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004783/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004784/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004785int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004786 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4787 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004788
4789 // Unwrap enums to their underlying type.
4790 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4791 LHSC = getIntegerTypeForEnum(ET);
4792 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4793 RHSC = getIntegerTypeForEnum(ET);
4794
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004795 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004796
Chris Lattner76a00cf2008-04-06 22:59:24 +00004797 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4798 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004799
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004800 unsigned LHSRank = getIntegerRank(LHSC);
4801 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004802
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004803 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4804 if (LHSRank == RHSRank) return 0;
4805 return LHSRank > RHSRank ? 1 : -1;
4806 }
Mike Stump11289f42009-09-09 15:08:12 +00004807
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004808 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4809 if (LHSUnsigned) {
4810 // If the unsigned [LHS] type is larger, return it.
4811 if (LHSRank >= RHSRank)
4812 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004814 // If the signed type can represent all values of the unsigned type, it
4815 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004816 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004817 return -1;
4818 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004819
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004820 // If the unsigned [RHS] type is larger, return it.
4821 if (RHSRank >= LHSRank)
4822 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004823
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004824 // If the signed type can represent all values of the unsigned type, it
4825 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004826 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004827 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004828}
Anders Carlsson98f07902007-08-17 05:31:46 +00004829
Mike Stump11289f42009-09-09 15:08:12 +00004830// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004831QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004832 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004833 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004834 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004835
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004836 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004837
Anders Carlsson98f07902007-08-17 05:31:46 +00004838 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004839 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004840 // int flags;
4841 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004842 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004843 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004844 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004845 FieldTypes[3] = LongTy;
4846
Anders Carlsson98f07902007-08-17 05:31:46 +00004847 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004848 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004849 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004850 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004851 SourceLocation(), nullptr,
4852 FieldTypes[i], /*TInfo=*/nullptr,
4853 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004854 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004855 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004856 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004857 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004858 }
4859
Douglas Gregord5058122010-02-11 01:19:42 +00004860 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004861 }
Mike Stump11289f42009-09-09 15:08:12 +00004862
Anders Carlsson98f07902007-08-17 05:31:46 +00004863 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004864}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004865
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004866QualType ASTContext::getObjCSuperType() const {
4867 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004868 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004869 TUDecl->addDecl(ObjCSuperTypeDecl);
4870 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4871 }
4872 return ObjCSuperType;
4873}
4874
Douglas Gregor512b0772009-04-23 22:29:11 +00004875void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004876 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004877 assert(Rec && "Invalid CFConstantStringType");
4878 CFConstantStringTypeDecl = Rec->getDecl();
4879}
4880
Jay Foad39c79802011-01-12 09:06:06 +00004881QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004882 if (BlockDescriptorType)
4883 return getTagDeclType(BlockDescriptorType);
4884
Alp Toker2dea15b2013-12-17 01:22:38 +00004885 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004886 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004887 RD = buildImplicitRecord("__block_descriptor");
4888 RD->startDefinition();
4889
Mike Stumpd0153282009-10-20 02:12:22 +00004890 QualType FieldTypes[] = {
4891 UnsignedLongTy,
4892 UnsignedLongTy,
4893 };
4894
Craig Topperd6d31ac2013-07-15 08:24:27 +00004895 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004896 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004897 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004898 };
4899
4900 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004901 FieldDecl *Field = FieldDecl::Create(
4902 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004903 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4904 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004905 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004906 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004907 }
4908
Alp Toker2dea15b2013-12-17 01:22:38 +00004909 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004910
Alp Toker2dea15b2013-12-17 01:22:38 +00004911 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004912
4913 return getTagDeclType(BlockDescriptorType);
4914}
4915
Jay Foad39c79802011-01-12 09:06:06 +00004916QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004917 if (BlockDescriptorExtendedType)
4918 return getTagDeclType(BlockDescriptorExtendedType);
4919
Alp Toker2dea15b2013-12-17 01:22:38 +00004920 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004921 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004922 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4923 RD->startDefinition();
4924
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004925 QualType FieldTypes[] = {
4926 UnsignedLongTy,
4927 UnsignedLongTy,
4928 getPointerType(VoidPtrTy),
4929 getPointerType(VoidPtrTy)
4930 };
4931
Craig Topperd6d31ac2013-07-15 08:24:27 +00004932 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004933 "reserved",
4934 "Size",
4935 "CopyFuncPtr",
4936 "DestroyFuncPtr"
4937 };
4938
4939 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004940 FieldDecl *Field = FieldDecl::Create(
4941 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004942 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4943 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004944 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004945 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004946 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004947 }
4948
Alp Toker2dea15b2013-12-17 01:22:38 +00004949 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004950
Alp Toker2dea15b2013-12-17 01:22:38 +00004951 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004952 return getTagDeclType(BlockDescriptorExtendedType);
4953}
4954
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004955/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4956/// requires copy/dispose. Note that this must match the logic
4957/// in buildByrefHelpers.
4958bool ASTContext::BlockRequiresCopying(QualType Ty,
4959 const VarDecl *D) {
4960 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4961 const Expr *copyExpr = getBlockVarCopyInits(D);
4962 if (!copyExpr && record->hasTrivialDestructor()) return false;
4963
Mike Stump94967902009-10-21 18:16:27 +00004964 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004965 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004966
4967 if (!Ty->isObjCRetainableType()) return false;
4968
4969 Qualifiers qs = Ty.getQualifiers();
4970
4971 // If we have lifetime, that dominates.
4972 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004973 switch (lifetime) {
4974 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4975
4976 // These are just bits as far as the runtime is concerned.
4977 case Qualifiers::OCL_ExplicitNone:
4978 case Qualifiers::OCL_Autoreleasing:
4979 return false;
4980
4981 // Tell the runtime that this is ARC __weak, called by the
4982 // byref routines.
4983 case Qualifiers::OCL_Weak:
4984 // ARC __strong __block variables need to be retained.
4985 case Qualifiers::OCL_Strong:
4986 return true;
4987 }
4988 llvm_unreachable("fell out of lifetime switch!");
4989 }
4990 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4991 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004992}
4993
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004994bool ASTContext::getByrefLifetime(QualType Ty,
4995 Qualifiers::ObjCLifetime &LifeTime,
4996 bool &HasByrefExtendedLayout) const {
4997
4998 if (!getLangOpts().ObjC1 ||
4999 getLangOpts().getGC() != LangOptions::NonGC)
5000 return false;
5001
5002 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005003 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005004 HasByrefExtendedLayout = true;
5005 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005006 } else if ((LifeTime = Ty.getObjCLifetime())) {
5007 // Honor the ARC qualifiers.
5008 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5009 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005010 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005011 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005012 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005013 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005014 return true;
5015}
5016
Douglas Gregorbab8a962011-09-08 01:46:34 +00005017TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5018 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005019 ObjCInstanceTypeDecl =
5020 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005021 return ObjCInstanceTypeDecl;
5022}
5023
Anders Carlsson18acd442007-10-29 06:33:42 +00005024// This returns true if a type has been typedefed to BOOL:
5025// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005026static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005027 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005028 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5029 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005030
Anders Carlssond8499822007-10-29 05:01:08 +00005031 return false;
5032}
5033
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005034/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005035/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005036CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005037 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5038 return CharUnits::Zero();
5039
Ken Dyck40775002010-01-11 17:06:35 +00005040 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005041
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005042 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005043 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005044 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005045 // Treat arrays as pointers, since that's how they're passed in.
5046 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005047 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005048 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005049}
5050
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005051bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005052 return getTargetInfo().getCXXABI().isMicrosoft() &&
5053 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005054 VD->getType()->isIntegralOrEnumerationType() &&
5055 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005056}
5057
Ken Dyck40775002010-01-11 17:06:35 +00005058static inline
5059std::string charUnitsToString(const CharUnits &CU) {
5060 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005061}
5062
John McCall351762c2011-02-07 10:33:21 +00005063/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005064/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005065std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5066 std::string S;
5067
David Chisnall950a9512009-11-17 19:33:30 +00005068 const BlockDecl *Decl = Expr->getBlockDecl();
5069 QualType BlockTy =
5070 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5071 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005072 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005073 getObjCEncodingForMethodParameter(
5074 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5075 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005076 else
Alp Toker314cc812014-01-25 16:55:45 +00005077 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005078 // Compute size of all parameters.
5079 // Start with computing size of a pointer in number of bytes.
5080 // FIXME: There might(should) be a better way of doing this computation!
5081 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005082 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5083 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005084 for (auto PI : Decl->params()) {
5085 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005086 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005087 if (sz.isZero())
5088 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005089 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005090 ParmOffset += sz;
5091 }
5092 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005093 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005094 // Block pointer and offset.
5095 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005096
5097 // Argument types.
5098 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005099 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005100 QualType PType = PVDecl->getOriginalType();
5101 if (const ArrayType *AT =
5102 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5103 // Use array's original type only if it has known number of
5104 // elements.
5105 if (!isa<ConstantArrayType>(AT))
5106 PType = PVDecl->getType();
5107 } else if (PType->isFunctionType())
5108 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005109 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005110 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5111 S, true /*Extended*/);
5112 else
5113 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005114 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005115 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005116 }
John McCall351762c2011-02-07 10:33:21 +00005117
5118 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005119}
5120
Douglas Gregora9d84932011-05-27 01:19:52 +00005121bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005122 std::string& S) {
5123 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005124 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005125 CharUnits ParmOffset;
5126 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005127 for (auto PI : Decl->params()) {
5128 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005129 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005130 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005131 continue;
5132
David Chisnall50e4eba2010-12-30 14:05:53 +00005133 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005134 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005135 ParmOffset += sz;
5136 }
5137 S += charUnitsToString(ParmOffset);
5138 ParmOffset = CharUnits::Zero();
5139
5140 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005141 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005142 QualType PType = PVDecl->getOriginalType();
5143 if (const ArrayType *AT =
5144 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5145 // Use array's original type only if it has known number of
5146 // elements.
5147 if (!isa<ConstantArrayType>(AT))
5148 PType = PVDecl->getType();
5149 } else if (PType->isFunctionType())
5150 PType = PVDecl->getType();
5151 getObjCEncodingForType(PType, S);
5152 S += charUnitsToString(ParmOffset);
5153 ParmOffset += getObjCEncodingTypeSize(PType);
5154 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005155
5156 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005157}
5158
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005159/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5160/// method parameter or return type. If Extended, include class names and
5161/// block object types.
5162void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5163 QualType T, std::string& S,
5164 bool Extended) const {
5165 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5166 getObjCEncodingForTypeQualifier(QT, S);
5167 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005168 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005169 true /*OutermostType*/,
5170 false /*EncodingProperty*/,
5171 false /*StructField*/,
5172 Extended /*EncodeBlockParameters*/,
5173 Extended /*EncodeClassNames*/);
5174}
5175
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005176/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005177/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005178bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005179 std::string& S,
5180 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005181 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005182 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005183 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5184 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005185 // Compute size of all parameters.
5186 // Start with computing size of a pointer in number of bytes.
5187 // FIXME: There might(should) be a better way of doing this computation!
5188 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005189 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005190 // The first two arguments (self and _cmd) are pointers; account for
5191 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005192 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005193 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005194 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005195 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005196 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005197 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005198 continue;
5199
Ken Dyck40775002010-01-11 17:06:35 +00005200 assert (sz.isPositive() &&
5201 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005202 ParmOffset += sz;
5203 }
Ken Dyck40775002010-01-11 17:06:35 +00005204 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005205 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005206 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005207
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005208 // Argument types.
5209 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005210 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005211 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005212 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005213 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005214 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005215 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5216 // Use array's original type only if it has known number of
5217 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005218 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005219 PType = PVDecl->getType();
5220 } else if (PType->isFunctionType())
5221 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005222 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5223 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005224 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005225 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005226 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005227
5228 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005229}
5230
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005231ObjCPropertyImplDecl *
5232ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5233 const ObjCPropertyDecl *PD,
5234 const Decl *Container) const {
5235 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005236 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005237 if (const ObjCCategoryImplDecl *CID =
5238 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005239 for (auto *PID : CID->property_impls())
5240 if (PID->getPropertyDecl() == PD)
5241 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005242 } else {
5243 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5244 for (auto *PID : OID->property_impls())
5245 if (PID->getPropertyDecl() == PD)
5246 return PID;
5247 }
5248 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005249}
5250
Daniel Dunbar4932b362008-08-28 04:38:10 +00005251/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005252/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005253/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5254/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005255/// Property attributes are stored as a comma-delimited C string. The simple
5256/// attributes readonly and bycopy are encoded as single characters. The
5257/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5258/// encoded as single characters, followed by an identifier. Property types
5259/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005260/// these attributes are defined by the following enumeration:
5261/// @code
5262/// enum PropertyAttributes {
5263/// kPropertyReadOnly = 'R', // property is read-only.
5264/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5265/// kPropertyByref = '&', // property is a reference to the value last assigned
5266/// kPropertyDynamic = 'D', // property is dynamic
5267/// kPropertyGetter = 'G', // followed by getter selector name
5268/// kPropertySetter = 'S', // followed by setter selector name
5269/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005270/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005271/// kPropertyWeak = 'W' // 'weak' property
5272/// kPropertyStrong = 'P' // property GC'able
5273/// kPropertyNonAtomic = 'N' // property non-atomic
5274/// };
5275/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005276void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005277 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005278 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005279 // Collect information from the property implementation decl(s).
5280 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005281 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005282
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005283 if (ObjCPropertyImplDecl *PropertyImpDecl =
5284 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5285 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5286 Dynamic = true;
5287 else
5288 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005289 }
5290
5291 // FIXME: This is not very efficient.
5292 S = "T";
5293
5294 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005295 // GCC has some special rules regarding encoding of properties which
5296 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005297 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005298
5299 if (PD->isReadOnly()) {
5300 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005301 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5302 S += ",C";
5303 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5304 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005305 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5306 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005307 } else {
5308 switch (PD->getSetterKind()) {
5309 case ObjCPropertyDecl::Assign: break;
5310 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005311 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005312 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005313 }
5314 }
5315
5316 // It really isn't clear at all what this means, since properties
5317 // are "dynamic by default".
5318 if (Dynamic)
5319 S += ",D";
5320
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005321 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5322 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005323
Daniel Dunbar4932b362008-08-28 04:38:10 +00005324 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5325 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005326 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005327 }
5328
5329 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5330 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005331 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005332 }
5333
5334 if (SynthesizePID) {
5335 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5336 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005337 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005338 }
5339
5340 // FIXME: OBJCGC: weak & strong
5341}
5342
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005343/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005344/// Another legacy compatibility encoding: 32-bit longs are encoded as
5345/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005346/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5347///
5348void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005349 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005350 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005351 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005352 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005353 else
Jay Foad39c79802011-01-12 09:06:06 +00005354 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005355 PointeeTy = IntTy;
5356 }
5357 }
5358}
5359
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005360void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005361 const FieldDecl *Field,
5362 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005363 // We follow the behavior of gcc, expanding structures which are
5364 // directly pointed to, and expanding embedded structures. Note that
5365 // these rules are sufficient to prevent recursive encoding of the
5366 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005367 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005368 true /* outermost type */, false, false,
5369 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005370}
5371
Joe Groff98ac7d22014-07-07 22:25:15 +00005372void ASTContext::getObjCEncodingForPropertyType(QualType T,
5373 std::string& S) const {
5374 // Encode result type.
5375 // GCC has some special rules regarding encoding of properties which
5376 // closely resembles encoding of ivars.
5377 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5378 true /* outermost type */,
5379 true /* encoding property */);
5380}
5381
John McCall393a78d2012-12-20 02:45:14 +00005382static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5383 BuiltinType::Kind kind) {
5384 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005385 case BuiltinType::Void: return 'v';
5386 case BuiltinType::Bool: return 'B';
5387 case BuiltinType::Char_U:
5388 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005389 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005390 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005391 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005392 case BuiltinType::UInt: return 'I';
5393 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005394 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005395 case BuiltinType::UInt128: return 'T';
5396 case BuiltinType::ULongLong: return 'Q';
5397 case BuiltinType::Char_S:
5398 case BuiltinType::SChar: return 'c';
5399 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005400 case BuiltinType::WChar_S:
5401 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005402 case BuiltinType::Int: return 'i';
5403 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005404 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005405 case BuiltinType::LongLong: return 'q';
5406 case BuiltinType::Int128: return 't';
5407 case BuiltinType::Float: return 'f';
5408 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005409 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005410 case BuiltinType::NullPtr: return '*'; // like char*
5411
5412 case BuiltinType::Half:
5413 // FIXME: potentially need @encodes for these!
5414 return ' ';
5415
5416 case BuiltinType::ObjCId:
5417 case BuiltinType::ObjCClass:
5418 case BuiltinType::ObjCSel:
5419 llvm_unreachable("@encoding ObjC primitive type");
5420
5421 // OpenCL and placeholder types don't need @encodings.
5422 case BuiltinType::OCLImage1d:
5423 case BuiltinType::OCLImage1dArray:
5424 case BuiltinType::OCLImage1dBuffer:
5425 case BuiltinType::OCLImage2d:
5426 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005427 case BuiltinType::OCLImage2dDepth:
5428 case BuiltinType::OCLImage2dArrayDepth:
5429 case BuiltinType::OCLImage2dMSAA:
5430 case BuiltinType::OCLImage2dArrayMSAA:
5431 case BuiltinType::OCLImage2dMSAADepth:
5432 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005433 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005434 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005435 case BuiltinType::OCLClkEvent:
5436 case BuiltinType::OCLQueue:
5437 case BuiltinType::OCLNDRange:
5438 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005439 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005440 case BuiltinType::Dependent:
5441#define BUILTIN_TYPE(KIND, ID)
5442#define PLACEHOLDER_TYPE(KIND, ID) \
5443 case BuiltinType::KIND:
5444#include "clang/AST/BuiltinTypes.def"
5445 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005446 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005447 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005448}
5449
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005450static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5451 EnumDecl *Enum = ET->getDecl();
5452
5453 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5454 if (!Enum->isFixed())
5455 return 'i';
5456
5457 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005458 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5459 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005460}
5461
Jay Foad39c79802011-01-12 09:06:06 +00005462static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005463 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005464 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005465 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005466 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5467 // The GNU runtime requires more information; bitfields are encoded as b,
5468 // then the offset (in bits) of the first element, then the type of the
5469 // bitfield, then the size in bits. For example, in this structure:
5470 //
5471 // struct
5472 // {
5473 // int integer;
5474 // int flags:2;
5475 // };
5476 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5477 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5478 // information is not especially sensible, but we're stuck with it for
5479 // compatibility with GCC, although providing it breaks anything that
5480 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005481 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005482 const RecordDecl *RD = FD->getParent();
5483 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005484 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005485 if (const EnumType *ET = T->getAs<EnumType>())
5486 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005487 else {
5488 const BuiltinType *BT = T->castAs<BuiltinType>();
5489 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5490 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005491 }
Richard Smithcaf33902011-10-10 18:28:20 +00005492 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005493}
5494
Daniel Dunbar07d07852009-10-18 21:17:35 +00005495// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005496void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5497 bool ExpandPointedToStructures,
5498 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005499 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005500 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005501 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005502 bool StructField,
5503 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005504 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005505 bool EncodePointerToObjCTypedef,
5506 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005507 CanQualType CT = getCanonicalType(T);
5508 switch (CT->getTypeClass()) {
5509 case Type::Builtin:
5510 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005511 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005512 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005513 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5514 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5515 else
5516 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005517 return;
Mike Stump11289f42009-09-09 15:08:12 +00005518
John McCall393a78d2012-12-20 02:45:14 +00005519 case Type::Complex: {
5520 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005521 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005522 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005523 return;
5524 }
John McCall393a78d2012-12-20 02:45:14 +00005525
5526 case Type::Atomic: {
5527 const AtomicType *AT = T->castAs<AtomicType>();
5528 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005529 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005530 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005531 }
John McCall393a78d2012-12-20 02:45:14 +00005532
5533 // encoding for pointer or reference types.
5534 case Type::Pointer:
5535 case Type::LValueReference:
5536 case Type::RValueReference: {
5537 QualType PointeeTy;
5538 if (isa<PointerType>(CT)) {
5539 const PointerType *PT = T->castAs<PointerType>();
5540 if (PT->isObjCSelType()) {
5541 S += ':';
5542 return;
5543 }
5544 PointeeTy = PT->getPointeeType();
5545 } else {
5546 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5547 }
5548
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005549 bool isReadOnly = false;
5550 // For historical/compatibility reasons, the read-only qualifier of the
5551 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5552 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005553 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005554 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005555 if (OutermostType && T.isConstQualified()) {
5556 isReadOnly = true;
5557 S += 'r';
5558 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005559 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005560 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005561 while (P->getAs<PointerType>())
5562 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005563 if (P.isConstQualified()) {
5564 isReadOnly = true;
5565 S += 'r';
5566 }
5567 }
5568 if (isReadOnly) {
5569 // Another legacy compatibility encoding. Some ObjC qualifier and type
5570 // combinations need to be rearranged.
5571 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005572 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005573 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005574 }
Mike Stump11289f42009-09-09 15:08:12 +00005575
Anders Carlssond8499822007-10-29 05:01:08 +00005576 if (PointeeTy->isCharType()) {
5577 // char pointer types should be encoded as '*' unless it is a
5578 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005579 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005580 S += '*';
5581 return;
5582 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005583 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005584 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5585 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5586 S += '#';
5587 return;
5588 }
5589 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5590 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5591 S += '@';
5592 return;
5593 }
5594 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005595 }
Anders Carlssond8499822007-10-29 05:01:08 +00005596 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005597 getLegacyIntegralTypeEncoding(PointeeTy);
5598
Mike Stump11289f42009-09-09 15:08:12 +00005599 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005600 nullptr, false, false, false, false, false, false,
5601 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005602 return;
5603 }
John McCall393a78d2012-12-20 02:45:14 +00005604
5605 case Type::ConstantArray:
5606 case Type::IncompleteArray:
5607 case Type::VariableArray: {
5608 const ArrayType *AT = cast<ArrayType>(CT);
5609
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005610 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005611 // Incomplete arrays are encoded as a pointer to the array element.
5612 S += '^';
5613
Mike Stump11289f42009-09-09 15:08:12 +00005614 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005615 false, ExpandStructures, FD);
5616 } else {
5617 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005618
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005619 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5620 S += llvm::utostr(CAT->getSize().getZExtValue());
5621 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005622 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005623 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5624 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005625 S += '0';
5626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
5628 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005629 false, ExpandStructures, FD,
5630 false, false, false, false, false, false,
5631 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005632 S += ']';
5633 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005634 return;
5635 }
Mike Stump11289f42009-09-09 15:08:12 +00005636
John McCall393a78d2012-12-20 02:45:14 +00005637 case Type::FunctionNoProto:
5638 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005639 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005640 return;
Mike Stump11289f42009-09-09 15:08:12 +00005641
John McCall393a78d2012-12-20 02:45:14 +00005642 case Type::Record: {
5643 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005644 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005645 // Anonymous structures print as '?'
5646 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5647 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005648 if (ClassTemplateSpecializationDecl *Spec
5649 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5650 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005651 llvm::raw_string_ostream OS(S);
5652 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005653 TemplateArgs.data(),
5654 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005655 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005656 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005657 } else {
5658 S += '?';
5659 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005660 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005661 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005662 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005663 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005664 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005665 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005666 if (FD) {
5667 S += '"';
5668 S += Field->getNameAsString();
5669 S += '"';
5670 }
Mike Stump11289f42009-09-09 15:08:12 +00005671
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005672 // Special case bit-fields.
5673 if (Field->isBitField()) {
5674 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005675 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005676 } else {
5677 QualType qt = Field->getType();
5678 getLegacyIntegralTypeEncoding(qt);
5679 getObjCEncodingForTypeImpl(qt, S, false, true,
5680 FD, /*OutermostType*/false,
5681 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005682 /*StructField*/true,
5683 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005684 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005685 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005686 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005687 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005688 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005689 return;
5690 }
Mike Stump11289f42009-09-09 15:08:12 +00005691
John McCall393a78d2012-12-20 02:45:14 +00005692 case Type::BlockPointer: {
5693 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005694 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005695 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005696 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005697
5698 S += '<';
5699 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005700 getObjCEncodingForTypeImpl(
5701 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5702 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005703 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5704 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005705 // Block self
5706 S += "@?";
5707 // Block parameters
5708 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005709 for (const auto &I : FPT->param_types())
5710 getObjCEncodingForTypeImpl(
5711 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5712 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005713 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5714 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005715 }
5716 S += '>';
5717 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005718 return;
5719 }
Mike Stump11289f42009-09-09 15:08:12 +00005720
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005721 case Type::ObjCObject: {
5722 // hack to match legacy encoding of *id and *Class
5723 QualType Ty = getObjCObjectPointerType(CT);
5724 if (Ty->isObjCIdType()) {
5725 S += "{objc_object=}";
5726 return;
5727 }
5728 else if (Ty->isObjCClassType()) {
5729 S += "{objc_class=}";
5730 return;
5731 }
5732 }
5733
John McCall393a78d2012-12-20 02:45:14 +00005734 case Type::ObjCInterface: {
5735 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005736 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005737 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005738 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005739 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005740 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005741 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005742 DeepCollectObjCIvars(OI, true, Ivars);
5743 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005744 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005745 if (Field->isBitField())
5746 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005747 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005748 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5749 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005750 EncodePointerToObjCTypedef,
5751 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005752 }
5753 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005754 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005755 }
Mike Stump11289f42009-09-09 15:08:12 +00005756
John McCall393a78d2012-12-20 02:45:14 +00005757 case Type::ObjCObjectPointer: {
5758 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005759 if (OPT->isObjCIdType()) {
5760 S += '@';
5761 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005762 }
Mike Stump11289f42009-09-09 15:08:12 +00005763
Steve Narofff0c86112009-10-28 22:03:49 +00005764 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5765 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5766 // Since this is a binary compatibility issue, need to consult with runtime
5767 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005768 S += '#';
5769 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005770 }
Mike Stump11289f42009-09-09 15:08:12 +00005771
Chris Lattnere7cabb92009-07-13 00:10:46 +00005772 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005773 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005774 ExpandPointedToStructures,
5775 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005776 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005777 // Note that we do extended encoding of protocol qualifer list
5778 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005779 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005780 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005781 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005782 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005783 S += '>';
5784 }
5785 S += '"';
5786 }
5787 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005788 }
Mike Stump11289f42009-09-09 15:08:12 +00005789
Chris Lattnere7cabb92009-07-13 00:10:46 +00005790 QualType PointeeTy = OPT->getPointeeType();
5791 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005792 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5793 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005794 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005795 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005796 // {...};
5797 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005798 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005799 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005800 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5801 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5802 DeepCollectObjCIvars(OI, true, Ivars);
5803 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5804 if (cast<FieldDecl>(Ivars[i]) == FD) {
5805 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005806 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005807 S += '}';
5808 return;
5809 }
5810 }
5811 }
Mike Stump11289f42009-09-09 15:08:12 +00005812 getObjCEncodingForTypeImpl(PointeeTy, S,
5813 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005814 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005815 false, false, false, false, false,
5816 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005817 return;
5818 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005819
5820 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005821 if (OPT->getInterfaceDecl() &&
5822 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005823 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005824 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005825 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005826 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005827 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005828 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005829 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005830 S += '"';
5831 }
5832 return;
5833 }
Mike Stump11289f42009-09-09 15:08:12 +00005834
John McCalla9e6e8d2010-05-17 23:56:34 +00005835 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005836 // FIXME: we shoul do better than that. 'M' is available.
5837 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005838 // This matches gcc's encoding, even though technically it is insufficient.
5839 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005840 case Type::Vector:
5841 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005842 // Until we have a coherent encoding of these three types, issue warning.
5843 { if (NotEncodedT)
5844 *NotEncodedT = T;
5845 return;
5846 }
5847
5848 // We could see an undeduced auto type here during error recovery.
5849 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005850 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005851 return;
5852
John McCall393a78d2012-12-20 02:45:14 +00005853#define ABSTRACT_TYPE(KIND, BASE)
5854#define TYPE(KIND, BASE)
5855#define DEPENDENT_TYPE(KIND, BASE) \
5856 case Type::KIND:
5857#define NON_CANONICAL_TYPE(KIND, BASE) \
5858 case Type::KIND:
5859#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5860 case Type::KIND:
5861#include "clang/AST/TypeNodes.def"
5862 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005863 }
John McCall393a78d2012-12-20 02:45:14 +00005864 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005865}
5866
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005867void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5868 std::string &S,
5869 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005870 bool includeVBases,
5871 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005872 assert(RDecl && "Expected non-null RecordDecl");
5873 assert(!RDecl->isUnion() && "Should not be called for unions");
5874 if (!RDecl->getDefinition())
5875 return;
5876
5877 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5878 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5879 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5880
5881 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005882 for (const auto &BI : CXXRec->bases()) {
5883 if (!BI.isVirtual()) {
5884 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005885 if (base->isEmpty())
5886 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005887 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005888 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5889 std::make_pair(offs, base));
5890 }
5891 }
5892 }
5893
5894 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005895 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005896 uint64_t offs = layout.getFieldOffset(i);
5897 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005898 std::make_pair(offs, Field));
5899 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005900 }
5901
5902 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005903 for (const auto &BI : CXXRec->vbases()) {
5904 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005905 if (base->isEmpty())
5906 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005907 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005908 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5909 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005910 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5911 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005912 }
5913 }
5914
5915 CharUnits size;
5916 if (CXXRec) {
5917 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5918 } else {
5919 size = layout.getSize();
5920 }
5921
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005922#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005923 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005924#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005925 std::multimap<uint64_t, NamedDecl *>::iterator
5926 CurLayObj = FieldOrBaseOffsets.begin();
5927
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005928 if (CXXRec && CXXRec->isDynamicClass() &&
5929 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005930 if (FD) {
5931 S += "\"_vptr$";
5932 std::string recname = CXXRec->getNameAsString();
5933 if (recname.empty()) recname = "?";
5934 S += recname;
5935 S += '"';
5936 }
5937 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005938#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005939 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005940#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005941 }
5942
5943 if (!RDecl->hasFlexibleArrayMember()) {
5944 // Mark the end of the structure.
5945 uint64_t offs = toBits(size);
5946 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005947 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005948 }
5949
5950 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005951#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005952 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005953 if (CurOffs < CurLayObj->first) {
5954 uint64_t padding = CurLayObj->first - CurOffs;
5955 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5956 // packing/alignment of members is different that normal, in which case
5957 // the encoding will be out-of-sync with the real layout.
5958 // If the runtime switches to just consider the size of types without
5959 // taking into account alignment, we could make padding explicit in the
5960 // encoding (e.g. using arrays of chars). The encoding strings would be
5961 // longer then though.
5962 CurOffs += padding;
5963 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005964#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005965
5966 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005967 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005968 break; // reached end of structure.
5969
5970 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5971 // We expand the bases without their virtual bases since those are going
5972 // in the initial structure. Note that this differs from gcc which
5973 // expands virtual bases each time one is encountered in the hierarchy,
5974 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005975 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5976 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005977 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005978#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005979 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005980#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005981 } else {
5982 FieldDecl *field = cast<FieldDecl>(dcl);
5983 if (FD) {
5984 S += '"';
5985 S += field->getNameAsString();
5986 S += '"';
5987 }
5988
5989 if (field->isBitField()) {
5990 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005991#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005992 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005993#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005994 } else {
5995 QualType qt = field->getType();
5996 getLegacyIntegralTypeEncoding(qt);
5997 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5998 /*OutermostType*/false,
5999 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006000 /*StructField*/true,
6001 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006002#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006003 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006004#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006005 }
6006 }
6007 }
6008}
6009
Mike Stump11289f42009-09-09 15:08:12 +00006010void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006011 std::string& S) const {
6012 if (QT & Decl::OBJC_TQ_In)
6013 S += 'n';
6014 if (QT & Decl::OBJC_TQ_Inout)
6015 S += 'N';
6016 if (QT & Decl::OBJC_TQ_Out)
6017 S += 'o';
6018 if (QT & Decl::OBJC_TQ_Bycopy)
6019 S += 'O';
6020 if (QT & Decl::OBJC_TQ_Byref)
6021 S += 'R';
6022 if (QT & Decl::OBJC_TQ_Oneway)
6023 S += 'V';
6024}
6025
Douglas Gregor3ea72692011-08-12 05:46:01 +00006026TypedefDecl *ASTContext::getObjCIdDecl() const {
6027 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006028 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006029 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006030 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006031 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006032 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006033}
6034
Douglas Gregor52e02802011-08-12 06:17:30 +00006035TypedefDecl *ASTContext::getObjCSelDecl() const {
6036 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006037 QualType T = getPointerType(ObjCBuiltinSelTy);
6038 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006039 }
6040 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006041}
6042
Douglas Gregor0a586182011-08-12 05:59:41 +00006043TypedefDecl *ASTContext::getObjCClassDecl() const {
6044 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006045 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006046 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006047 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006048 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006049 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006050}
6051
Douglas Gregord53ae832012-01-17 18:09:05 +00006052ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6053 if (!ObjCProtocolClassDecl) {
6054 ObjCProtocolClassDecl
6055 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6056 SourceLocation(),
6057 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006058 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006059 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006060 SourceLocation(), true);
6061 }
6062
6063 return ObjCProtocolClassDecl;
6064}
6065
Meador Inge5d3fb222012-06-16 03:34:49 +00006066//===----------------------------------------------------------------------===//
6067// __builtin_va_list Construction Functions
6068//===----------------------------------------------------------------------===//
6069
Charles Davisc7d5c942015-09-17 20:55:33 +00006070static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6071 StringRef Name) {
6072 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006073 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006074 return Context->buildImplicitTypedef(T, Name);
6075}
6076
6077static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6078 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6079}
6080
6081static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6082 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006083}
6084
6085static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6086 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006087 QualType T = Context->getPointerType(Context->VoidTy);
6088 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006089}
6090
Tim Northover9bb857a2013-01-31 12:13:10 +00006091static TypedefDecl *
6092CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006093 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006094 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006095 if (Context->getLangOpts().CPlusPlus) {
6096 // namespace std { struct __va_list {
6097 NamespaceDecl *NS;
6098 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6099 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006100 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006101 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006102 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006103 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006104 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006105 }
6106
6107 VaListTagDecl->startDefinition();
6108
6109 const size_t NumFields = 5;
6110 QualType FieldTypes[NumFields];
6111 const char *FieldNames[NumFields];
6112
6113 // void *__stack;
6114 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6115 FieldNames[0] = "__stack";
6116
6117 // void *__gr_top;
6118 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6119 FieldNames[1] = "__gr_top";
6120
6121 // void *__vr_top;
6122 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6123 FieldNames[2] = "__vr_top";
6124
6125 // int __gr_offs;
6126 FieldTypes[3] = Context->IntTy;
6127 FieldNames[3] = "__gr_offs";
6128
6129 // int __vr_offs;
6130 FieldTypes[4] = Context->IntTy;
6131 FieldNames[4] = "__vr_offs";
6132
6133 // Create fields
6134 for (unsigned i = 0; i < NumFields; ++i) {
6135 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6136 VaListTagDecl,
6137 SourceLocation(),
6138 SourceLocation(),
6139 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006140 FieldTypes[i], /*TInfo=*/nullptr,
6141 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006142 /*Mutable=*/false,
6143 ICIS_NoInit);
6144 Field->setAccess(AS_public);
6145 VaListTagDecl->addDecl(Field);
6146 }
6147 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006148 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006149 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006150
6151 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006152 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006153}
6154
Meador Inge5d3fb222012-06-16 03:34:49 +00006155static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6156 // typedef struct __va_list_tag {
6157 RecordDecl *VaListTagDecl;
6158
Alp Toker2dea15b2013-12-17 01:22:38 +00006159 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006160 VaListTagDecl->startDefinition();
6161
6162 const size_t NumFields = 5;
6163 QualType FieldTypes[NumFields];
6164 const char *FieldNames[NumFields];
6165
6166 // unsigned char gpr;
6167 FieldTypes[0] = Context->UnsignedCharTy;
6168 FieldNames[0] = "gpr";
6169
6170 // unsigned char fpr;
6171 FieldTypes[1] = Context->UnsignedCharTy;
6172 FieldNames[1] = "fpr";
6173
6174 // unsigned short reserved;
6175 FieldTypes[2] = Context->UnsignedShortTy;
6176 FieldNames[2] = "reserved";
6177
6178 // void* overflow_arg_area;
6179 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6180 FieldNames[3] = "overflow_arg_area";
6181
6182 // void* reg_save_area;
6183 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6184 FieldNames[4] = "reg_save_area";
6185
6186 // Create fields
6187 for (unsigned i = 0; i < NumFields; ++i) {
6188 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6189 SourceLocation(),
6190 SourceLocation(),
6191 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006192 FieldTypes[i], /*TInfo=*/nullptr,
6193 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006194 /*Mutable=*/false,
6195 ICIS_NoInit);
6196 Field->setAccess(AS_public);
6197 VaListTagDecl->addDecl(Field);
6198 }
6199 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006200 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006201 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6202
6203 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006204 TypedefDecl *VaListTagTypedefDecl =
6205 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6206
Meador Inge5d3fb222012-06-16 03:34:49 +00006207 QualType VaListTagTypedefType =
6208 Context->getTypedefType(VaListTagTypedefDecl);
6209
6210 // typedef __va_list_tag __builtin_va_list[1];
6211 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6212 QualType VaListTagArrayType
6213 = Context->getConstantArrayType(VaListTagTypedefType,
6214 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006215 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006216}
6217
6218static TypedefDecl *
6219CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006220 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006221 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006222 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006223 VaListTagDecl->startDefinition();
6224
6225 const size_t NumFields = 4;
6226 QualType FieldTypes[NumFields];
6227 const char *FieldNames[NumFields];
6228
6229 // unsigned gp_offset;
6230 FieldTypes[0] = Context->UnsignedIntTy;
6231 FieldNames[0] = "gp_offset";
6232
6233 // unsigned fp_offset;
6234 FieldTypes[1] = Context->UnsignedIntTy;
6235 FieldNames[1] = "fp_offset";
6236
6237 // void* overflow_arg_area;
6238 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6239 FieldNames[2] = "overflow_arg_area";
6240
6241 // void* reg_save_area;
6242 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6243 FieldNames[3] = "reg_save_area";
6244
6245 // Create fields
6246 for (unsigned i = 0; i < NumFields; ++i) {
6247 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6248 VaListTagDecl,
6249 SourceLocation(),
6250 SourceLocation(),
6251 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006252 FieldTypes[i], /*TInfo=*/nullptr,
6253 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006254 /*Mutable=*/false,
6255 ICIS_NoInit);
6256 Field->setAccess(AS_public);
6257 VaListTagDecl->addDecl(Field);
6258 }
6259 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006260 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006261 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6262
Richard Smith9b88a4c2015-07-27 05:40:23 +00006263 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006264
Richard Smith9b88a4c2015-07-27 05:40:23 +00006265 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006266 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006267 QualType VaListTagArrayType =
6268 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006269 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006270}
6271
6272static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6273 // typedef int __builtin_va_list[4];
6274 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6275 QualType IntArrayType
6276 = Context->getConstantArrayType(Context->IntTy,
6277 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006278 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006279}
6280
Logan Chien57086ce2012-10-10 06:56:20 +00006281static TypedefDecl *
6282CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006283 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006284 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006285 if (Context->getLangOpts().CPlusPlus) {
6286 // namespace std { struct __va_list {
6287 NamespaceDecl *NS;
6288 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6289 Context->getTranslationUnitDecl(),
6290 /*Inline*/false, SourceLocation(),
6291 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006292 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006293 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006294 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006295 }
6296
6297 VaListDecl->startDefinition();
6298
6299 // void * __ap;
6300 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6301 VaListDecl,
6302 SourceLocation(),
6303 SourceLocation(),
6304 &Context->Idents.get("__ap"),
6305 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006306 /*TInfo=*/nullptr,
6307 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006308 /*Mutable=*/false,
6309 ICIS_NoInit);
6310 Field->setAccess(AS_public);
6311 VaListDecl->addDecl(Field);
6312
6313 // };
6314 VaListDecl->completeDefinition();
6315
6316 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006317 QualType T = Context->getRecordType(VaListDecl);
6318 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006319}
6320
Ulrich Weigand47445072013-05-06 16:26:41 +00006321static TypedefDecl *
6322CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006323 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006324 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006325 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006326 VaListTagDecl->startDefinition();
6327
6328 const size_t NumFields = 4;
6329 QualType FieldTypes[NumFields];
6330 const char *FieldNames[NumFields];
6331
6332 // long __gpr;
6333 FieldTypes[0] = Context->LongTy;
6334 FieldNames[0] = "__gpr";
6335
6336 // long __fpr;
6337 FieldTypes[1] = Context->LongTy;
6338 FieldNames[1] = "__fpr";
6339
6340 // void *__overflow_arg_area;
6341 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6342 FieldNames[2] = "__overflow_arg_area";
6343
6344 // void *__reg_save_area;
6345 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6346 FieldNames[3] = "__reg_save_area";
6347
6348 // Create fields
6349 for (unsigned i = 0; i < NumFields; ++i) {
6350 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6351 VaListTagDecl,
6352 SourceLocation(),
6353 SourceLocation(),
6354 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006355 FieldTypes[i], /*TInfo=*/nullptr,
6356 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006357 /*Mutable=*/false,
6358 ICIS_NoInit);
6359 Field->setAccess(AS_public);
6360 VaListTagDecl->addDecl(Field);
6361 }
6362 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006363 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006364 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006365
Richard Smith9b88a4c2015-07-27 05:40:23 +00006366 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006367
6368 // typedef __va_list_tag __builtin_va_list[1];
6369 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006370 QualType VaListTagArrayType =
6371 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006372
Alp Toker56b5cc92013-12-15 10:36:26 +00006373 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006374}
6375
Meador Inge5d3fb222012-06-16 03:34:49 +00006376static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6377 TargetInfo::BuiltinVaListKind Kind) {
6378 switch (Kind) {
6379 case TargetInfo::CharPtrBuiltinVaList:
6380 return CreateCharPtrBuiltinVaListDecl(Context);
6381 case TargetInfo::VoidPtrBuiltinVaList:
6382 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006383 case TargetInfo::AArch64ABIBuiltinVaList:
6384 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006385 case TargetInfo::PowerABIBuiltinVaList:
6386 return CreatePowerABIBuiltinVaListDecl(Context);
6387 case TargetInfo::X86_64ABIBuiltinVaList:
6388 return CreateX86_64ABIBuiltinVaListDecl(Context);
6389 case TargetInfo::PNaClABIBuiltinVaList:
6390 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006391 case TargetInfo::AAPCSABIBuiltinVaList:
6392 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006393 case TargetInfo::SystemZBuiltinVaList:
6394 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006395 }
6396
6397 llvm_unreachable("Unhandled __builtin_va_list type kind");
6398}
6399
6400TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006401 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006402 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006403 assert(BuiltinVaListDecl->isImplicit());
6404 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006405
6406 return BuiltinVaListDecl;
6407}
6408
Richard Smith9b88a4c2015-07-27 05:40:23 +00006409Decl *ASTContext::getVaListTagDecl() const {
6410 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006411 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006412 if (!VaListTagDecl)
6413 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006414
Richard Smith9b88a4c2015-07-27 05:40:23 +00006415 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006416}
6417
Charles Davisc7d5c942015-09-17 20:55:33 +00006418TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6419 if (!BuiltinMSVaListDecl)
6420 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6421
6422 return BuiltinMSVaListDecl;
6423}
6424
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006425void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006426 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006427 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006428
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006429 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006430}
6431
John McCalld28ae272009-12-02 08:04:21 +00006432/// \brief Retrieve the template name that corresponds to a non-empty
6433/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006434TemplateName
6435ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6436 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006437 unsigned size = End - Begin;
6438 assert(size > 1 && "set is not overloaded!");
6439
6440 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6441 size * sizeof(FunctionTemplateDecl*));
6442 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6443
6444 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006445 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006446 NamedDecl *D = *I;
6447 assert(isa<FunctionTemplateDecl>(D) ||
6448 (isa<UsingShadowDecl>(D) &&
6449 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6450 *Storage++ = D;
6451 }
6452
6453 return TemplateName(OT);
6454}
6455
Douglas Gregordc572a32009-03-30 22:58:21 +00006456/// \brief Retrieve the template name that represents a qualified
6457/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006458TemplateName
6459ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6460 bool TemplateKeyword,
6461 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006462 assert(NNS && "Missing nested-name-specifier in qualified template name");
6463
Douglas Gregorc42075a2010-02-04 18:10:26 +00006464 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006465 llvm::FoldingSetNodeID ID;
6466 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6467
Craig Topper36250ad2014-05-12 05:36:57 +00006468 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006469 QualifiedTemplateName *QTN =
6470 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6471 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006472 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6473 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006474 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6475 }
6476
6477 return TemplateName(QTN);
6478}
6479
6480/// \brief Retrieve the template name that represents a dependent
6481/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006482TemplateName
6483ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6484 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006485 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006486 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006487
6488 llvm::FoldingSetNodeID ID;
6489 DependentTemplateName::Profile(ID, NNS, Name);
6490
Craig Topper36250ad2014-05-12 05:36:57 +00006491 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006492 DependentTemplateName *QTN =
6493 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6494
6495 if (QTN)
6496 return TemplateName(QTN);
6497
6498 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6499 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006500 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6501 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006502 } else {
6503 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006504 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6505 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006506 DependentTemplateName *CheckQTN =
6507 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6508 assert(!CheckQTN && "Dependent type name canonicalization broken");
6509 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006510 }
6511
6512 DependentTemplateNames.InsertNode(QTN, InsertPos);
6513 return TemplateName(QTN);
6514}
6515
Douglas Gregor71395fa2009-11-04 00:56:37 +00006516/// \brief Retrieve the template name that represents a dependent
6517/// template name such as \c MetaFun::template operator+.
6518TemplateName
6519ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006520 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006521 assert((!NNS || NNS->isDependent()) &&
6522 "Nested name specifier must be dependent");
6523
6524 llvm::FoldingSetNodeID ID;
6525 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006526
6527 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006528 DependentTemplateName *QTN
6529 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006530
6531 if (QTN)
6532 return TemplateName(QTN);
6533
6534 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6535 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006536 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6537 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006538 } else {
6539 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006540 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6541 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006542
6543 DependentTemplateName *CheckQTN
6544 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6545 assert(!CheckQTN && "Dependent template name canonicalization broken");
6546 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006547 }
6548
6549 DependentTemplateNames.InsertNode(QTN, InsertPos);
6550 return TemplateName(QTN);
6551}
6552
Douglas Gregor5590be02011-01-15 06:45:20 +00006553TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006554ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6555 TemplateName replacement) const {
6556 llvm::FoldingSetNodeID ID;
6557 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006558
6559 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006560 SubstTemplateTemplateParmStorage *subst
6561 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6562
6563 if (!subst) {
6564 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6565 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6566 }
6567
6568 return TemplateName(subst);
6569}
6570
6571TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006572ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6573 const TemplateArgument &ArgPack) const {
6574 ASTContext &Self = const_cast<ASTContext &>(*this);
6575 llvm::FoldingSetNodeID ID;
6576 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006577
6578 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006579 SubstTemplateTemplateParmPackStorage *Subst
6580 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6581
6582 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006583 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006584 ArgPack.pack_size(),
6585 ArgPack.pack_begin());
6586 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6587 }
6588
6589 return TemplateName(Subst);
6590}
6591
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006592/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006593/// TargetInfo, produce the corresponding type. The unsigned @p Type
6594/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006595CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006596 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006597 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006598 case TargetInfo::SignedChar: return SignedCharTy;
6599 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006600 case TargetInfo::SignedShort: return ShortTy;
6601 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6602 case TargetInfo::SignedInt: return IntTy;
6603 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6604 case TargetInfo::SignedLong: return LongTy;
6605 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6606 case TargetInfo::SignedLongLong: return LongLongTy;
6607 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6608 }
6609
David Blaikie83d382b2011-09-23 05:06:16 +00006610 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006611}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006612
6613//===----------------------------------------------------------------------===//
6614// Type Predicates.
6615//===----------------------------------------------------------------------===//
6616
Fariborz Jahanian96207692009-02-18 21:49:28 +00006617/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6618/// garbage collection attribute.
6619///
John McCall553d45a2011-01-12 00:34:59 +00006620Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006621 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006622 return Qualifiers::GCNone;
6623
David Blaikiebbafb8a2012-03-11 07:00:24 +00006624 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006625 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6626
6627 // Default behaviour under objective-C's gc is for ObjC pointers
6628 // (or pointers to them) be treated as though they were declared
6629 // as __strong.
6630 if (GCAttrs == Qualifiers::GCNone) {
6631 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6632 return Qualifiers::Strong;
6633 else if (Ty->isPointerType())
6634 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6635 } else {
6636 // It's not valid to set GC attributes on anything that isn't a
6637 // pointer.
6638#ifndef NDEBUG
6639 QualType CT = Ty->getCanonicalTypeInternal();
6640 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6641 CT = AT->getElementType();
6642 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6643#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006644 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006645 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006646}
6647
Chris Lattner49af6a42008-04-07 06:51:04 +00006648//===----------------------------------------------------------------------===//
6649// Type Compatibility Testing
6650//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006651
Mike Stump11289f42009-09-09 15:08:12 +00006652/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006653/// compatible.
6654static bool areCompatVectorTypes(const VectorType *LHS,
6655 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006656 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006657 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006658 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006659}
6660
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006661bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6662 QualType SecondVec) {
6663 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6664 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6665
6666 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6667 return true;
6668
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006669 // Treat Neon vector types and most AltiVec vector types as if they are the
6670 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006671 const VectorType *First = FirstVec->getAs<VectorType>();
6672 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006673 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006674 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006675 First->getVectorKind() != VectorType::AltiVecPixel &&
6676 First->getVectorKind() != VectorType::AltiVecBool &&
6677 Second->getVectorKind() != VectorType::AltiVecPixel &&
6678 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006679 return true;
6680
6681 return false;
6682}
6683
Steve Naroff8e6aee52009-07-23 01:01:38 +00006684//===----------------------------------------------------------------------===//
6685// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6686//===----------------------------------------------------------------------===//
6687
6688/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6689/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006690bool
6691ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6692 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006693 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006694 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006695 for (auto *PI : rProto->protocols())
6696 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006697 return true;
6698 return false;
6699}
6700
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006701/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6702/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006703bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6704 QualType rhs) {
6705 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6706 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6707 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6708
Aaron Ballman83731462014-03-17 16:14:00 +00006709 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006710 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006711 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006712 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6713 match = true;
6714 break;
6715 }
6716 }
6717 if (!match)
6718 return false;
6719 }
6720 return true;
6721}
6722
Steve Naroff8e6aee52009-07-23 01:01:38 +00006723/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6724/// ObjCQualifiedIDType.
6725bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6726 bool compare) {
6727 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006728 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 lhs->isObjCIdType() || lhs->isObjCClassType())
6730 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006731 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006732 rhs->isObjCIdType() || rhs->isObjCClassType())
6733 return true;
6734
6735 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006736 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006737
Steve Naroff8e6aee52009-07-23 01:01:38 +00006738 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006739
Steve Naroff8e6aee52009-07-23 01:01:38 +00006740 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006741 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006742 // make sure we check the class hierarchy.
6743 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006744 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006745 // when comparing an id<P> on lhs with a static type on rhs,
6746 // see if static class implements all of id's protocols, directly or
6747 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006748 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006749 return false;
6750 }
6751 }
6752 // If there are no qualifiers and no interface, we have an 'id'.
6753 return true;
6754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006756 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 bool match = false;
6758
6759 // when comparing an id<P> on lhs with a static type on rhs,
6760 // see if static class implements all of id's protocols, directly or
6761 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006762 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006763 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6764 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6765 match = true;
6766 break;
6767 }
6768 }
Mike Stump11289f42009-09-09 15:08:12 +00006769 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006770 // make sure we check the class hierarchy.
6771 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006772 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006773 // when comparing an id<P> on lhs with a static type on rhs,
6774 // see if static class implements all of id's protocols, directly or
6775 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006776 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006777 match = true;
6778 break;
6779 }
6780 }
6781 }
6782 if (!match)
6783 return false;
6784 }
Mike Stump11289f42009-09-09 15:08:12 +00006785
Steve Naroff8e6aee52009-07-23 01:01:38 +00006786 return true;
6787 }
Mike Stump11289f42009-09-09 15:08:12 +00006788
Steve Naroff8e6aee52009-07-23 01:01:38 +00006789 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6790 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6791
Mike Stump11289f42009-09-09 15:08:12 +00006792 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006793 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006794 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006795 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006796 bool match = false;
6797
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006798 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006799 // see if static class implements all of id's protocols, directly or
6800 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006801 // First, lhs protocols in the qualifier list must be found, direct
6802 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006803 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006804 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6805 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6806 match = true;
6807 break;
6808 }
6809 }
6810 if (!match)
6811 return false;
6812 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006813
6814 // Static class's protocols, or its super class or category protocols
6815 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6816 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6817 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6818 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6819 // This is rather dubious but matches gcc's behavior. If lhs has
6820 // no type qualifier and its class has no static protocol(s)
6821 // assume that it is mismatch.
6822 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6823 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006824 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006825 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006826 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006827 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6828 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6829 match = true;
6830 break;
6831 }
6832 }
6833 if (!match)
6834 return false;
6835 }
6836 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006837 return true;
6838 }
6839 return false;
6840}
6841
Eli Friedman47f77112008-08-22 00:56:42 +00006842/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006843/// compatible for assignment from RHS to LHS. This handles validation of any
6844/// protocol qualifiers on the LHS or RHS.
6845///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006846bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6847 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006848 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6849 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6850
Steve Naroff1329fa02009-07-15 18:40:39 +00006851 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006852 if (LHS->isObjCUnqualifiedIdOrClass() ||
6853 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006854 return true;
6855
Douglas Gregorab209d82015-07-07 03:58:42 +00006856 // Function object that propagates a successful result or handles
6857 // __kindof types.
6858 auto finish = [&](bool succeeded) -> bool {
6859 if (succeeded)
6860 return true;
6861
6862 if (!RHS->isKindOfType())
6863 return false;
6864
6865 // Strip off __kindof and protocol qualifiers, then check whether
6866 // we can assign the other way.
6867 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6868 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6869 };
6870
6871 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6872 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6873 QualType(RHSOPT,0),
6874 false));
6875 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006876
Douglas Gregorab209d82015-07-07 03:58:42 +00006877 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6878 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6879 QualType(RHSOPT,0)));
6880 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006881
John McCall8b07ec22010-05-15 11:32:37 +00006882 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006883 if (LHS->getInterface() && RHS->getInterface()) {
6884 return finish(canAssignObjCInterfaces(LHS, RHS));
6885 }
Mike Stump11289f42009-09-09 15:08:12 +00006886
Steve Naroff8e6aee52009-07-23 01:01:38 +00006887 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006888}
6889
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006890/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006891/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006892/// arguments in block literals. When passed as arguments, passing 'A*' where
6893/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6894/// not OK. For the return type, the opposite is not OK.
6895bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6896 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006897 const ObjCObjectPointerType *RHSOPT,
6898 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006899
6900 // Function object that propagates a successful result or handles
6901 // __kindof types.
6902 auto finish = [&](bool succeeded) -> bool {
6903 if (succeeded)
6904 return true;
6905
6906 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6907 if (!Expected->isKindOfType())
6908 return false;
6909
6910 // Strip off __kindof and protocol qualifiers, then check whether
6911 // we can assign the other way.
6912 return canAssignObjCInterfacesInBlockPointer(
6913 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6914 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6915 BlockReturnType);
6916 };
6917
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006918 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006919 return true;
6920
6921 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006922 return finish(RHSOPT->isObjCBuiltinType() ||
6923 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006924 }
6925
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006926 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006927 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6928 QualType(RHSOPT,0),
6929 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006930
6931 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6932 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6933 if (LHS && RHS) { // We have 2 user-defined types.
6934 if (LHS != RHS) {
6935 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006936 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006937 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006938 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006939 }
6940 else
6941 return true;
6942 }
6943 return false;
6944}
6945
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006946/// Comparison routine for Objective-C protocols to be used with
6947/// llvm::array_pod_sort.
6948static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6949 ObjCProtocolDecl * const *rhs) {
6950 return (*lhs)->getName().compare((*rhs)->getName());
6951
6952}
6953
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006954/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006955/// of protocols inherited from two distinct objective-c pointer objects with
6956/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006957/// It is used to build composite qualifier list of the composite type of
6958/// the conditional expression involving two objective-c pointer objects.
6959static
6960void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006961 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006962 const ObjCObjectPointerType *LHSOPT,
6963 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006964 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006965
John McCall8b07ec22010-05-15 11:32:37 +00006966 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6967 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6968 assert(LHS->getInterface() && "LHS must have an interface base");
6969 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006970
6971 // Add all of the protocols for the LHS.
6972 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6973
6974 // Start with the protocol qualifiers.
6975 for (auto proto : LHS->quals()) {
6976 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006977 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006978
6979 // Also add the protocols associated with the LHS interface.
6980 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6981
6982 // Add all of the protocls for the RHS.
6983 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6984
6985 // Start with the protocol qualifiers.
6986 for (auto proto : RHS->quals()) {
6987 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006988 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006989
6990 // Also add the protocols associated with the RHS interface.
6991 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6992
6993 // Compute the intersection of the collected protocol sets.
6994 for (auto proto : LHSProtocolSet) {
6995 if (RHSProtocolSet.count(proto))
6996 IntersectionSet.push_back(proto);
6997 }
6998
6999 // Compute the set of protocols that is implied by either the common type or
7000 // the protocols within the intersection.
7001 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7002 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7003
7004 // Remove any implied protocols from the list of inherited protocols.
7005 if (!ImpliedProtocols.empty()) {
7006 IntersectionSet.erase(
7007 std::remove_if(IntersectionSet.begin(),
7008 IntersectionSet.end(),
7009 [&](ObjCProtocolDecl *proto) -> bool {
7010 return ImpliedProtocols.count(proto) > 0;
7011 }),
7012 IntersectionSet.end());
7013 }
7014
7015 // Sort the remaining protocols by name.
7016 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7017 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007018}
7019
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007020/// Determine whether the first type is a subtype of the second.
7021static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7022 QualType rhs) {
7023 // Common case: two object pointers.
7024 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7025 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7026 if (lhsOPT && rhsOPT)
7027 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7028
7029 // Two block pointers.
7030 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7031 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7032 if (lhsBlock && rhsBlock)
7033 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7034
7035 // If either is an unqualified 'id' and the other is a block, it's
7036 // acceptable.
7037 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7038 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7039 return true;
7040
7041 return false;
7042}
7043
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007044// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007045static bool sameObjCTypeArgs(ASTContext &ctx,
7046 const ObjCInterfaceDecl *iface,
7047 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007048 ArrayRef<QualType> rhsArgs,
7049 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007050 if (lhsArgs.size() != rhsArgs.size())
7051 return false;
7052
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007053 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007054 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007055 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7056 continue;
7057
7058 switch (typeParams->begin()[i]->getVariance()) {
7059 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007060 if (!stripKindOf ||
7061 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7062 rhsArgs[i].stripObjCKindOfType(ctx))) {
7063 return false;
7064 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007065 break;
7066
7067 case ObjCTypeParamVariance::Covariant:
7068 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7069 return false;
7070 break;
7071
7072 case ObjCTypeParamVariance::Contravariant:
7073 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7074 return false;
7075 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007076 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007077 }
7078
7079 return true;
7080}
7081
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007082QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007083 const ObjCObjectPointerType *Lptr,
7084 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007085 const ObjCObjectType *LHS = Lptr->getObjectType();
7086 const ObjCObjectType *RHS = Rptr->getObjectType();
7087 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7088 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007089
7090 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007091 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007092
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007093 // Follow the left-hand side up the class hierarchy until we either hit a
7094 // root or find the RHS. Record the ancestors in case we don't find it.
7095 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7096 LHSAncestors;
7097 while (true) {
7098 // Record this ancestor. We'll need this if the common type isn't in the
7099 // path from the LHS to the root.
7100 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007101
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007102 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7103 // Get the type arguments.
7104 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7105 bool anyChanges = false;
7106 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7107 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007108 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7109 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007110 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007111 return QualType();
7112 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7113 // If only one has type arguments, the result will not have type
7114 // arguments.
7115 LHSTypeArgs = { };
7116 anyChanges = true;
7117 }
7118
7119 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007120 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007121 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7122 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007123 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007124 anyChanges = true;
7125
7126 // If anything in the LHS will have changed, build a new result type.
7127 if (anyChanges) {
7128 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007129 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7130 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007131 return getObjCObjectPointerType(Result);
7132 }
7133
7134 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007135 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007136
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007137 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007138 QualType LHSSuperType = LHS->getSuperClassType();
7139 if (LHSSuperType.isNull())
7140 break;
7141
7142 LHS = LHSSuperType->castAs<ObjCObjectType>();
7143 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007144
7145 // We didn't find anything by following the LHS to its root; now check
7146 // the RHS against the cached set of ancestors.
7147 while (true) {
7148 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7149 if (KnownLHS != LHSAncestors.end()) {
7150 LHS = KnownLHS->second;
7151
7152 // Get the type arguments.
7153 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7154 bool anyChanges = false;
7155 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7156 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007157 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7158 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007159 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007160 return QualType();
7161 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7162 // If only one has type arguments, the result will not have type
7163 // arguments.
7164 RHSTypeArgs = { };
7165 anyChanges = true;
7166 }
7167
7168 // Compute the intersection of protocols.
7169 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7170 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7171 Protocols);
7172 if (!Protocols.empty())
7173 anyChanges = true;
7174
7175 if (anyChanges) {
7176 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007177 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7178 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007179 return getObjCObjectPointerType(Result);
7180 }
7181
7182 return getObjCObjectPointerType(QualType(RHS, 0));
7183 }
7184
7185 // Find the superclass of the RHS.
7186 QualType RHSSuperType = RHS->getSuperClassType();
7187 if (RHSSuperType.isNull())
7188 break;
7189
7190 RHS = RHSSuperType->castAs<ObjCObjectType>();
7191 }
7192
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007193 return QualType();
7194}
7195
John McCall8b07ec22010-05-15 11:32:37 +00007196bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7197 const ObjCObjectType *RHS) {
7198 assert(LHS->getInterface() && "LHS is not an interface type");
7199 assert(RHS->getInterface() && "RHS is not an interface type");
7200
Chris Lattner49af6a42008-04-07 06:51:04 +00007201 // Verify that the base decls are compatible: the RHS must be a subclass of
7202 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007203 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7204 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7205 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007206 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007207
Douglas Gregore83b9562015-07-07 03:57:53 +00007208 // If the LHS has protocol qualifiers, determine whether all of them are
7209 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7210 // LHS).
7211 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007212 // OK if conversion of LHS to SuperClass results in narrowing of types
7213 // ; i.e., SuperClass may implement at least one of the protocols
7214 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7215 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7216 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7217 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7218 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7219 // qualifiers.
7220 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007221 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007222 // If there is no protocols associated with RHS, it is not a match.
7223 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007224 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007225
7226 for (const auto *LHSProto : LHS->quals()) {
7227 bool SuperImplementsProtocol = false;
7228 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7229 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7230 SuperImplementsProtocol = true;
7231 break;
7232 }
7233 if (!SuperImplementsProtocol)
7234 return false;
7235 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007236 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007237
7238 // If the LHS is specialized, we may need to check type arguments.
7239 if (LHS->isSpecialized()) {
7240 // Follow the superclass chain until we've matched the LHS class in the
7241 // hierarchy. This substitutes type arguments through.
7242 const ObjCObjectType *RHSSuper = RHS;
7243 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7244 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7245
7246 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007247 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007248 !sameObjCTypeArgs(*this, LHS->getInterface(),
7249 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007250 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007251 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007252 }
7253 }
7254
7255 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007256}
7257
Steve Naroffb7605152009-02-12 17:52:19 +00007258bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7259 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007260 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7261 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007262
Steve Naroff7cae42b2009-07-10 23:34:53 +00007263 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007264 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007265
7266 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7267 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007268}
7269
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007270bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7271 return canAssignObjCInterfaces(
7272 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7273 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7274}
7275
Mike Stump11289f42009-09-09 15:08:12 +00007276/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007277/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007278/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007279/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007280bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7281 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007282 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007283 return hasSameType(LHS, RHS);
7284
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007285 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007286}
7287
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007288bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007289 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007290}
7291
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007292bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7293 return !mergeTypes(LHS, RHS, true).isNull();
7294}
7295
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007296/// mergeTransparentUnionType - if T is a transparent union type and a member
7297/// of T is compatible with SubType, return the merged type, else return
7298/// QualType()
7299QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7300 bool OfBlockPointer,
7301 bool Unqualified) {
7302 if (const RecordType *UT = T->getAsUnionType()) {
7303 RecordDecl *UD = UT->getDecl();
7304 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007305 for (const auto *I : UD->fields()) {
7306 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007307 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7308 if (!MT.isNull())
7309 return MT;
7310 }
7311 }
7312 }
7313
7314 return QualType();
7315}
7316
Alp Toker9cacbab2014-01-20 20:26:09 +00007317/// mergeFunctionParameterTypes - merge two types which appear as function
7318/// parameter types
7319QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7320 bool OfBlockPointer,
7321 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007322 // GNU extension: two types are compatible if they appear as a function
7323 // argument, one of the types is a transparent union type and the other
7324 // type is compatible with a union member
7325 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7326 Unqualified);
7327 if (!lmerge.isNull())
7328 return lmerge;
7329
7330 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7331 Unqualified);
7332 if (!rmerge.isNull())
7333 return rmerge;
7334
7335 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7336}
7337
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007338QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007339 bool OfBlockPointer,
7340 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007341 const FunctionType *lbase = lhs->getAs<FunctionType>();
7342 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007343 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7344 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007345 bool allLTypes = true;
7346 bool allRTypes = true;
7347
7348 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007349 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007350 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007351 QualType RHS = rbase->getReturnType();
7352 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007353 bool UnqualifiedResult = Unqualified;
7354 if (!UnqualifiedResult)
7355 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007356 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007357 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007358 else
Alp Toker314cc812014-01-25 16:55:45 +00007359 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007360 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007361 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007362
7363 if (Unqualified)
7364 retType = retType.getUnqualifiedType();
7365
Alp Toker314cc812014-01-25 16:55:45 +00007366 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7367 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007368 if (Unqualified) {
7369 LRetType = LRetType.getUnqualifiedType();
7370 RRetType = RRetType.getUnqualifiedType();
7371 }
7372
7373 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007374 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007375 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007376 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007377
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007378 // FIXME: double check this
7379 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7380 // rbase->getRegParmAttr() != 0 &&
7381 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007382 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7383 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007384
Douglas Gregor8c940862010-01-18 17:14:39 +00007385 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007386 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007387 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007388
John McCall8c6b56f2010-12-15 01:06:38 +00007389 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007390 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7391 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007392 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7393 return QualType();
7394
John McCall31168b02011-06-15 23:02:42 +00007395 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7396 return QualType();
7397
John McCall8c6b56f2010-12-15 01:06:38 +00007398 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7399 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007400
Rafael Espindola8778c282012-11-29 16:09:03 +00007401 if (lbaseInfo.getNoReturn() != NoReturn)
7402 allLTypes = false;
7403 if (rbaseInfo.getNoReturn() != NoReturn)
7404 allRTypes = false;
7405
John McCall31168b02011-06-15 23:02:42 +00007406 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007407
Eli Friedman47f77112008-08-22 00:56:42 +00007408 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007409 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7410 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007411 // Compatible functions must have the same number of parameters
7412 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007413 return QualType();
7414
7415 // Variadic and non-variadic functions aren't compatible
7416 if (lproto->isVariadic() != rproto->isVariadic())
7417 return QualType();
7418
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007419 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7420 return QualType();
7421
Fariborz Jahanian97676972011-09-28 21:52:05 +00007422 if (LangOpts.ObjCAutoRefCount &&
7423 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7424 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007425
7426 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007427 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007428 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7429 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7430 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7431 QualType paramType = mergeFunctionParameterTypes(
7432 lParamType, rParamType, OfBlockPointer, Unqualified);
7433 if (paramType.isNull())
7434 return QualType();
7435
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007436 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007437 paramType = paramType.getUnqualifiedType();
7438
7439 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007440 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007441 lParamType = lParamType.getUnqualifiedType();
7442 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007443 }
Alp Toker601b22c2014-01-21 23:35:24 +00007444
7445 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007446 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007447 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007448 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007449 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007450
Eli Friedman47f77112008-08-22 00:56:42 +00007451 if (allLTypes) return lhs;
7452 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007453
7454 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7455 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007456 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007457 }
7458
7459 if (lproto) allRTypes = false;
7460 if (rproto) allLTypes = false;
7461
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007462 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007463 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007464 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007465 if (proto->isVariadic()) return QualType();
7466 // Check that the types are compatible with the types that
7467 // would result from default argument promotions (C99 6.7.5.3p15).
7468 // The only types actually affected are promotable integer
7469 // types and floats, which would be passed as a different
7470 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007471 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7472 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007473
Eli Friedman448ce402012-08-30 00:44:15 +00007474 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007475 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007476 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7477 paramTy = Enum->getDecl()->getIntegerType();
7478 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007479 return QualType();
7480 }
Alp Toker601b22c2014-01-21 23:35:24 +00007481
7482 if (paramTy->isPromotableIntegerType() ||
7483 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007484 return QualType();
7485 }
7486
7487 if (allLTypes) return lhs;
7488 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007489
7490 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7491 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007492 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007493 }
7494
7495 if (allLTypes) return lhs;
7496 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007497 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007498}
7499
John McCall433c2e62013-03-21 00:10:07 +00007500/// Given that we have an enum type and a non-enum type, try to merge them.
7501static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7502 QualType other, bool isBlockReturnType) {
7503 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7504 // a signed integer type, or an unsigned integer type.
7505 // Compatibility is based on the underlying type, not the promotion
7506 // type.
7507 QualType underlyingType = ET->getDecl()->getIntegerType();
7508 if (underlyingType.isNull()) return QualType();
7509 if (Context.hasSameType(underlyingType, other))
7510 return other;
7511
7512 // In block return types, we're more permissive and accept any
7513 // integral type of the same size.
7514 if (isBlockReturnType && other->isIntegerType() &&
7515 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7516 return other;
7517
7518 return QualType();
7519}
7520
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007521QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007522 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007523 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007524 // C++ [expr]: If an expression initially has the type "reference to T", the
7525 // type is adjusted to "T" prior to any further analysis, the expression
7526 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007527 // expression is an lvalue unless the reference is an rvalue reference and
7528 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007529 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7530 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007531
7532 if (Unqualified) {
7533 LHS = LHS.getUnqualifiedType();
7534 RHS = RHS.getUnqualifiedType();
7535 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007536
Eli Friedman47f77112008-08-22 00:56:42 +00007537 QualType LHSCan = getCanonicalType(LHS),
7538 RHSCan = getCanonicalType(RHS);
7539
7540 // If two types are identical, they are compatible.
7541 if (LHSCan == RHSCan)
7542 return LHS;
7543
John McCall8ccfcb52009-09-24 19:53:00 +00007544 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007545 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7546 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007547 if (LQuals != RQuals) {
7548 // If any of these qualifiers are different, we have a type
7549 // mismatch.
7550 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007551 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7552 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007553 return QualType();
7554
7555 // Exactly one GC qualifier difference is allowed: __strong is
7556 // okay if the other type has no GC qualifier but is an Objective
7557 // C object pointer (i.e. implicitly strong by default). We fix
7558 // this by pretending that the unqualified type was actually
7559 // qualified __strong.
7560 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7561 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7562 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7563
7564 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7565 return QualType();
7566
7567 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7568 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7569 }
7570 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7571 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7572 }
Eli Friedman47f77112008-08-22 00:56:42 +00007573 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007574 }
7575
7576 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007577
Eli Friedmandcca6332009-06-01 01:22:52 +00007578 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7579 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007580
Chris Lattnerfd652912008-01-14 05:45:46 +00007581 // We want to consider the two function types to be the same for these
7582 // comparisons, just force one to the other.
7583 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7584 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007585
7586 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007587 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7588 LHSClass = Type::ConstantArray;
7589 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7590 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007591
John McCall8b07ec22010-05-15 11:32:37 +00007592 // ObjCInterfaces are just specialized ObjCObjects.
7593 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7594 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7595
Nate Begemance4d7fc2008-04-18 23:10:10 +00007596 // Canonicalize ExtVector -> Vector.
7597 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7598 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007599
Chris Lattner95554662008-04-07 05:43:21 +00007600 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007601 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007602 // Note that we only have special rules for turning block enum
7603 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007604 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007605 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007606 }
John McCall9dd450b2009-09-21 23:43:11 +00007607 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007608 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007609 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007610 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007611 if (OfBlockPointer && !BlockReturnType) {
7612 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7613 return LHS;
7614 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7615 return RHS;
7616 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007617
Eli Friedman47f77112008-08-22 00:56:42 +00007618 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007619 }
Eli Friedman47f77112008-08-22 00:56:42 +00007620
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007621 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007622 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007623#define TYPE(Class, Base)
7624#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007625#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007626#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7627#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7628#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007629 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007630
Richard Smith27d807c2013-04-30 13:56:41 +00007631 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007632 case Type::LValueReference:
7633 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007634 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007635 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007636
John McCall8b07ec22010-05-15 11:32:37 +00007637 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007638 case Type::IncompleteArray:
7639 case Type::VariableArray:
7640 case Type::FunctionProto:
7641 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007642 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007643
Chris Lattnerfd652912008-01-14 05:45:46 +00007644 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007645 {
7646 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007647 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7648 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007649 if (Unqualified) {
7650 LHSPointee = LHSPointee.getUnqualifiedType();
7651 RHSPointee = RHSPointee.getUnqualifiedType();
7652 }
7653 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7654 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007655 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007656 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007657 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007658 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007659 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007660 return getPointerType(ResultType);
7661 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007662 case Type::BlockPointer:
7663 {
7664 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007665 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7666 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007667 if (Unqualified) {
7668 LHSPointee = LHSPointee.getUnqualifiedType();
7669 RHSPointee = RHSPointee.getUnqualifiedType();
7670 }
7671 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7672 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007673 if (ResultType.isNull()) return QualType();
7674 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7675 return LHS;
7676 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7677 return RHS;
7678 return getBlockPointerType(ResultType);
7679 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007680 case Type::Atomic:
7681 {
7682 // Merge two pointer types, while trying to preserve typedef info
7683 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7684 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7685 if (Unqualified) {
7686 LHSValue = LHSValue.getUnqualifiedType();
7687 RHSValue = RHSValue.getUnqualifiedType();
7688 }
7689 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7690 Unqualified);
7691 if (ResultType.isNull()) return QualType();
7692 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7693 return LHS;
7694 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7695 return RHS;
7696 return getAtomicType(ResultType);
7697 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007698 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007699 {
7700 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7701 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7702 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7703 return QualType();
7704
7705 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7706 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007707 if (Unqualified) {
7708 LHSElem = LHSElem.getUnqualifiedType();
7709 RHSElem = RHSElem.getUnqualifiedType();
7710 }
7711
7712 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007713 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007714 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7715 return LHS;
7716 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7717 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007718 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7719 ArrayType::ArraySizeModifier(), 0);
7720 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7721 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007722 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7723 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007724 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7725 return LHS;
7726 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7727 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007728 if (LVAT) {
7729 // FIXME: This isn't correct! But tricky to implement because
7730 // the array's size has to be the size of LHS, but the type
7731 // has to be different.
7732 return LHS;
7733 }
7734 if (RVAT) {
7735 // FIXME: This isn't correct! But tricky to implement because
7736 // the array's size has to be the size of RHS, but the type
7737 // has to be different.
7738 return RHS;
7739 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007740 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7741 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007742 return getIncompleteArrayType(ResultType,
7743 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007744 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007745 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007746 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007747 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007748 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007749 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007750 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007751 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007752 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007753 case Type::Complex:
7754 // Distinct complex types are incompatible.
7755 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007756 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007757 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007758 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7759 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007760 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007761 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007762 case Type::ObjCObject: {
7763 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007764 // FIXME: This should be type compatibility, e.g. whether
7765 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007766 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7767 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7768 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007769 return LHS;
7770
Eli Friedman47f77112008-08-22 00:56:42 +00007771 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007772 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007773 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007774 if (OfBlockPointer) {
7775 if (canAssignObjCInterfacesInBlockPointer(
7776 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007777 RHS->getAs<ObjCObjectPointerType>(),
7778 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007779 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007780 return QualType();
7781 }
John McCall9dd450b2009-09-21 23:43:11 +00007782 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7783 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007784 return LHS;
7785
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007786 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007787 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007788 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007789
David Blaikie8a40f702012-01-17 06:56:22 +00007790 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007791}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007792
Fariborz Jahanian97676972011-09-28 21:52:05 +00007793bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7794 const FunctionProtoType *FromFunctionType,
7795 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007796 if (FromFunctionType->hasAnyConsumedParams() !=
7797 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007798 return false;
7799 FunctionProtoType::ExtProtoInfo FromEPI =
7800 FromFunctionType->getExtProtoInfo();
7801 FunctionProtoType::ExtProtoInfo ToEPI =
7802 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007803 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007804 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7805 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007806 return false;
7807 }
7808 return true;
7809}
7810
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007811/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7812/// 'RHS' attributes and returns the merged version; including for function
7813/// return types.
7814QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7815 QualType LHSCan = getCanonicalType(LHS),
7816 RHSCan = getCanonicalType(RHS);
7817 // If two types are identical, they are compatible.
7818 if (LHSCan == RHSCan)
7819 return LHS;
7820 if (RHSCan->isFunctionType()) {
7821 if (!LHSCan->isFunctionType())
7822 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007823 QualType OldReturnType =
7824 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007825 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007826 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007827 QualType ResReturnType =
7828 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7829 if (ResReturnType.isNull())
7830 return QualType();
7831 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7832 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7833 // In either case, use OldReturnType to build the new function type.
7834 const FunctionType *F = LHS->getAs<FunctionType>();
7835 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007836 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7837 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007838 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007839 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007840 return ResultType;
7841 }
7842 }
7843 return QualType();
7844 }
7845
7846 // If the qualifiers are different, the types can still be merged.
7847 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7848 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7849 if (LQuals != RQuals) {
7850 // If any of these qualifiers are different, we have a type mismatch.
7851 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7852 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7853 return QualType();
7854
7855 // Exactly one GC qualifier difference is allowed: __strong is
7856 // okay if the other type has no GC qualifier but is an Objective
7857 // C object pointer (i.e. implicitly strong by default). We fix
7858 // this by pretending that the unqualified type was actually
7859 // qualified __strong.
7860 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7861 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7862 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7863
7864 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7865 return QualType();
7866
7867 if (GC_L == Qualifiers::Strong)
7868 return LHS;
7869 if (GC_R == Qualifiers::Strong)
7870 return RHS;
7871 return QualType();
7872 }
7873
7874 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7875 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7876 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7877 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7878 if (ResQT == LHSBaseQT)
7879 return LHS;
7880 if (ResQT == RHSBaseQT)
7881 return RHS;
7882 }
7883 return QualType();
7884}
7885
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007886//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007887// Integer Predicates
7888//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007889
Jay Foad39c79802011-01-12 09:06:06 +00007890unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007891 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007892 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007893 if (T->isBooleanType())
7894 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007895 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007896 return (unsigned)getTypeSize(T);
7897}
7898
Abramo Bagnara13640492012-09-09 10:21:24 +00007899QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007900 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007901
7902 // Turn <4 x signed int> -> <4 x unsigned int>
7903 if (const VectorType *VTy = T->getAs<VectorType>())
7904 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007905 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007906
7907 // For enums, we return the unsigned version of the base type.
7908 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007909 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007910
7911 const BuiltinType *BTy = T->getAs<BuiltinType>();
7912 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007913 switch (BTy->getKind()) {
7914 case BuiltinType::Char_S:
7915 case BuiltinType::SChar:
7916 return UnsignedCharTy;
7917 case BuiltinType::Short:
7918 return UnsignedShortTy;
7919 case BuiltinType::Int:
7920 return UnsignedIntTy;
7921 case BuiltinType::Long:
7922 return UnsignedLongTy;
7923 case BuiltinType::LongLong:
7924 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007925 case BuiltinType::Int128:
7926 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007927 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007928 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007929 }
7930}
7931
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007932ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007933
Richard Smith1fa5d642013-05-11 05:45:24 +00007934void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7935 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007936
7937//===----------------------------------------------------------------------===//
7938// Builtin Type Computation
7939//===----------------------------------------------------------------------===//
7940
7941/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007942/// pointer over the consumed characters. This returns the resultant type. If
7943/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7944/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7945/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007946///
7947/// RequiresICE is filled in on return to indicate whether the value is required
7948/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007949static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007950 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007951 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007952 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007953 // Modifiers.
7954 int HowLong = 0;
7955 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007956 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007957
Chris Lattnerdc226c22010-10-01 22:42:38 +00007958 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007959 bool Done = false;
7960 while (!Done) {
7961 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007962 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007963 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007964 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007965 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007966 case 'S':
7967 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7968 assert(!Signed && "Can't use 'S' modifier multiple times!");
7969 Signed = true;
7970 break;
7971 case 'U':
7972 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007973 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007974 Unsigned = true;
7975 break;
7976 case 'L':
7977 assert(HowLong <= 2 && "Can't have LLLL modifier");
7978 ++HowLong;
7979 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007980 case 'W':
7981 // This modifier represents int64 type.
7982 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7983 switch (Context.getTargetInfo().getInt64Type()) {
7984 default:
7985 llvm_unreachable("Unexpected integer type");
7986 case TargetInfo::SignedLong:
7987 HowLong = 1;
7988 break;
7989 case TargetInfo::SignedLongLong:
7990 HowLong = 2;
7991 break;
7992 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007993 }
7994 }
7995
7996 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007997
Chris Lattnerecd79c62009-06-14 00:45:47 +00007998 // Read the base type.
7999 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008000 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008001 case 'v':
8002 assert(HowLong == 0 && !Signed && !Unsigned &&
8003 "Bad modifiers used with 'v'!");
8004 Type = Context.VoidTy;
8005 break;
Jack Carter24bef982013-08-15 15:16:57 +00008006 case 'h':
8007 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008008 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008009 Type = Context.HalfTy;
8010 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008011 case 'f':
8012 assert(HowLong == 0 && !Signed && !Unsigned &&
8013 "Bad modifiers used with 'f'!");
8014 Type = Context.FloatTy;
8015 break;
8016 case 'd':
8017 assert(HowLong < 2 && !Signed && !Unsigned &&
8018 "Bad modifiers used with 'd'!");
8019 if (HowLong)
8020 Type = Context.LongDoubleTy;
8021 else
8022 Type = Context.DoubleTy;
8023 break;
8024 case 's':
8025 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8026 if (Unsigned)
8027 Type = Context.UnsignedShortTy;
8028 else
8029 Type = Context.ShortTy;
8030 break;
8031 case 'i':
8032 if (HowLong == 3)
8033 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8034 else if (HowLong == 2)
8035 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8036 else if (HowLong == 1)
8037 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8038 else
8039 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8040 break;
8041 case 'c':
8042 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8043 if (Signed)
8044 Type = Context.SignedCharTy;
8045 else if (Unsigned)
8046 Type = Context.UnsignedCharTy;
8047 else
8048 Type = Context.CharTy;
8049 break;
8050 case 'b': // boolean
8051 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8052 Type = Context.BoolTy;
8053 break;
8054 case 'z': // size_t.
8055 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8056 Type = Context.getSizeType();
8057 break;
8058 case 'F':
8059 Type = Context.getCFConstantStringType();
8060 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008061 case 'G':
8062 Type = Context.getObjCIdType();
8063 break;
8064 case 'H':
8065 Type = Context.getObjCSelType();
8066 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008067 case 'M':
8068 Type = Context.getObjCSuperType();
8069 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008070 case 'a':
8071 Type = Context.getBuiltinVaListType();
8072 assert(!Type.isNull() && "builtin va list type not initialized!");
8073 break;
8074 case 'A':
8075 // This is a "reference" to a va_list; however, what exactly
8076 // this means depends on how va_list is defined. There are two
8077 // different kinds of va_list: ones passed by value, and ones
8078 // passed by reference. An example of a by-value va_list is
8079 // x86, where va_list is a char*. An example of by-ref va_list
8080 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8081 // we want this argument to be a char*&; for x86-64, we want
8082 // it to be a __va_list_tag*.
8083 Type = Context.getBuiltinVaListType();
8084 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008085 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008086 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008087 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008088 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008089 break;
8090 case 'V': {
8091 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008092 unsigned NumElements = strtoul(Str, &End, 10);
8093 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008094 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008095
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008096 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8097 RequiresICE, false);
8098 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008099
8100 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008101 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008102 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008103 break;
8104 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008105 case 'E': {
8106 char *End;
8107
8108 unsigned NumElements = strtoul(Str, &End, 10);
8109 assert(End != Str && "Missing vector size");
8110
8111 Str = End;
8112
8113 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8114 false);
8115 Type = Context.getExtVectorType(ElementType, NumElements);
8116 break;
8117 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008118 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008119 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8120 false);
8121 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008122 Type = Context.getComplexType(ElementType);
8123 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008124 }
8125 case 'Y' : {
8126 Type = Context.getPointerDiffType();
8127 break;
8128 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008129 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008130 Type = Context.getFILEType();
8131 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008132 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008133 return QualType();
8134 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008135 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008136 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008137 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008138 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008139 else
8140 Type = Context.getjmp_bufType();
8141
Mike Stump2adb4da2009-07-28 23:47:15 +00008142 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008143 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008144 return QualType();
8145 }
8146 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008147 case 'K':
8148 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8149 Type = Context.getucontext_tType();
8150
8151 if (Type.isNull()) {
8152 Error = ASTContext::GE_Missing_ucontext;
8153 return QualType();
8154 }
8155 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008156 case 'p':
8157 Type = Context.getProcessIDType();
8158 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008159 }
Mike Stump11289f42009-09-09 15:08:12 +00008160
Chris Lattnerdc226c22010-10-01 22:42:38 +00008161 // If there are modifiers and if we're allowed to parse them, go for it.
8162 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008163 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008164 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008165 default: Done = true; --Str; break;
8166 case '*':
8167 case '&': {
8168 // Both pointers and references can have their pointee types
8169 // qualified with an address space.
8170 char *End;
8171 unsigned AddrSpace = strtoul(Str, &End, 10);
8172 if (End != Str && AddrSpace != 0) {
8173 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8174 Str = End;
8175 }
8176 if (c == '*')
8177 Type = Context.getPointerType(Type);
8178 else
8179 Type = Context.getLValueReferenceType(Type);
8180 break;
8181 }
8182 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8183 case 'C':
8184 Type = Type.withConst();
8185 break;
8186 case 'D':
8187 Type = Context.getVolatileType(Type);
8188 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008189 case 'R':
8190 Type = Type.withRestrict();
8191 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008192 }
8193 }
Chris Lattner84733392010-10-01 07:13:18 +00008194
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008195 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008196 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008197
Chris Lattnerecd79c62009-06-14 00:45:47 +00008198 return Type;
8199}
8200
8201/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008202QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008203 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008204 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008205 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008206
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008207 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008208
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008209 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008210 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008211 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8212 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008213 if (Error != GE_None)
8214 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008215
8216 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8217
Chris Lattnerecd79c62009-06-14 00:45:47 +00008218 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008219 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008220 if (Error != GE_None)
8221 return QualType();
8222
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008223 // If this argument is required to be an IntegerConstantExpression and the
8224 // caller cares, fill in the bitmask we return.
8225 if (RequiresICE && IntegerConstantArgs)
8226 *IntegerConstantArgs |= 1 << ArgTypes.size();
8227
Chris Lattnerecd79c62009-06-14 00:45:47 +00008228 // Do array -> pointer decay. The builtin should use the decayed type.
8229 if (Ty->isArrayType())
8230 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008231
Chris Lattnerecd79c62009-06-14 00:45:47 +00008232 ArgTypes.push_back(Ty);
8233 }
8234
David Majnemerba3e5ec2015-03-13 18:26:17 +00008235 if (Id == Builtin::BI__GetExceptionInfo)
8236 return QualType();
8237
Chris Lattnerecd79c62009-06-14 00:45:47 +00008238 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8239 "'.' should only occur at end of builtin type list!");
8240
Reid Kleckner78af0702013-08-27 23:08:25 +00008241 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008242 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8243
8244 bool Variadic = (TypeStr[0] == '.');
8245
8246 // We really shouldn't be making a no-proto type here, especially in C++.
8247 if (ArgTypes.empty() && Variadic)
8248 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008249
John McCalldb40c7f2010-12-14 08:05:40 +00008250 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008251 EPI.ExtInfo = EI;
8252 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008253
Jordan Rose5c382722013-03-08 21:51:21 +00008254 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008255}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008256
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008257static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8258 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008259 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008260 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008261
Rafael Espindola3ae00052013-05-13 00:12:11 +00008262 GVALinkage External = GVA_StrongExternal;
8263 switch (FD->getTemplateSpecializationKind()) {
8264 case TSK_Undeclared:
8265 case TSK_ExplicitSpecialization:
8266 External = GVA_StrongExternal;
8267 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008268
Rafael Espindola3ae00052013-05-13 00:12:11 +00008269 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008270 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008271
David Majnemerc3d07332014-05-15 06:25:57 +00008272 // C++11 [temp.explicit]p10:
8273 // [ Note: The intent is that an inline function that is the subject of
8274 // an explicit instantiation declaration will still be implicitly
8275 // instantiated when used so that the body can be considered for
8276 // inlining, but that no out-of-line copy of the inline function would be
8277 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008278 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008279 return GVA_AvailableExternally;
8280
Rafael Espindola3ae00052013-05-13 00:12:11 +00008281 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008282 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008283 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008284 }
8285
8286 if (!FD->isInlined())
8287 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008288
David Majnemer3f021502015-10-08 04:53:31 +00008289 if ((!Context.getLangOpts().CPlusPlus &&
8290 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008291 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008292 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008293 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8294
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008295 // GNU or C99 inline semantics. Determine whether this symbol should be
8296 // externally visible.
8297 if (FD->isInlineDefinitionExternallyVisible())
8298 return External;
8299
8300 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008301 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008302 }
8303
David Majnemer54e3ba52014-04-02 23:17:29 +00008304 // Functions specified with extern and inline in -fms-compatibility mode
8305 // forcibly get emitted. While the body of the function cannot be later
8306 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008307 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008308 return GVA_StrongODR;
8309
David Majnemer27d69db2014-04-28 22:17:59 +00008310 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008311}
8312
Artem Belevich7b41f702015-09-23 17:44:53 +00008313static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008314 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8315 // dllexport/dllimport on inline functions.
8316 if (D->hasAttr<DLLImportAttr>()) {
8317 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8318 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008319 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008320 if (L == GVA_DiscardableODR)
8321 return GVA_StrongODR;
8322 }
8323 return L;
8324}
8325
8326GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008327 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8328 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008329}
8330
8331static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8332 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008333 if (!VD->isExternallyVisible())
8334 return GVA_Internal;
8335
David Majnemer27d69db2014-04-28 22:17:59 +00008336 if (VD->isStaticLocal()) {
8337 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8338 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8339 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8340 LexicalContext = LexicalContext->getLexicalParent();
8341
Richard Smith9e2341d2015-03-23 03:25:59 +00008342 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008343 // enclosing function.
8344 if (LexicalContext)
8345 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008346 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008347
8348 // GVA_StrongODR function linkage is stronger than what we need,
8349 // downgrade to GVA_DiscardableODR.
8350 // This allows us to discard the variable if we never end up needing it.
8351 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8352 : StaticLocalLinkage;
8353 }
8354
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008355 // MSVC treats in-class initialized static data members as definitions.
8356 // By giving them non-strong linkage, out-of-line definitions won't
8357 // cause link errors.
8358 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8359 return GVA_DiscardableODR;
8360
Richard Smith8809a0c2013-09-27 20:14:12 +00008361 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008362 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008363 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008364
David Majnemer6d1780c2015-07-17 23:36:49 +00008365 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008366 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8367 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008368 ? GVA_StrongODR
8369 : GVA_StrongExternal;
8370
Rafael Espindola3ae00052013-05-13 00:12:11 +00008371 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008372 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008373
David Majnemer27d69db2014-04-28 22:17:59 +00008374 case TSK_ExplicitInstantiationDeclaration:
8375 return GVA_AvailableExternally;
8376
Rafael Espindola3ae00052013-05-13 00:12:11 +00008377 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008378 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008379 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008380
8381 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008382}
8383
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008384GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008385 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8386 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008387}
8388
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008389bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008390 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8391 if (!VD->isFileVarDecl())
8392 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008393 // Global named register variables (GNU extension) are never emitted.
8394 if (VD->getStorageClass() == SC_Register)
8395 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008396 if (VD->getDescribedVarTemplate() ||
8397 isa<VarTemplatePartialSpecializationDecl>(VD))
8398 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008399 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8400 // We never need to emit an uninstantiated function template.
8401 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8402 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008403 } else if (isa<OMPThreadPrivateDecl>(D))
8404 return true;
8405 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008406 return false;
8407
8408 // If this is a member of a class template, we do not need to emit it.
8409 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008410 return false;
8411
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008412 // Weak references don't produce any output by themselves.
8413 if (D->hasAttr<WeakRefAttr>())
8414 return false;
8415
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008416 // Aliases and used decls are required.
8417 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8418 return true;
8419
8420 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8421 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008422 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008423 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008424
8425 // Constructors and destructors are required.
8426 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8427 return true;
8428
John McCall6bd2a892013-01-25 22:31:03 +00008429 // The key function for a class is required. This rule only comes
8430 // into play when inline functions can be key functions, though.
8431 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8433 const CXXRecordDecl *RD = MD->getParent();
8434 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8435 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8436 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8437 return true;
8438 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008439 }
8440 }
8441
8442 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8443
8444 // static, static inline, always_inline, and extern inline functions can
8445 // always be deferred. Normal inline functions can be deferred in C99/C++.
8446 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008447 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8448 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008449 return false;
8450 return true;
8451 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008452
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008453 const VarDecl *VD = cast<VarDecl>(D);
8454 assert(VD->isFileVarDecl() && "Expected file scoped var");
8455
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008456 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8457 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008458 return false;
8459
Richard Smitha0e5e542012-11-12 21:38:00 +00008460 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008461 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008462 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8463 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008464 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008465
Richard Smitha0e5e542012-11-12 21:38:00 +00008466 // Variables that have destruction with side-effects are required.
8467 if (VD->getType().isDestructedType())
8468 return true;
8469
8470 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008471 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8472 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008473 return true;
8474
8475 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008476}
Charles Davis53c59df2010-08-16 03:33:14 +00008477
Reid Kleckner78af0702013-08-27 23:08:25 +00008478CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8479 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008480 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008481 if (IsCXXMethod)
8482 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008483
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008484 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8485
8486 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008487}
8488
Jay Foad39c79802011-01-12 09:06:06 +00008489bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008490 // Pass through to the C++ ABI object
8491 return ABI->isNearlyEmpty(RD);
8492}
8493
Reid Kleckner96f8f932014-02-05 17:27:08 +00008494VTableContextBase *ASTContext::getVTableContext() {
8495 if (!VTContext.get()) {
8496 if (Target->getCXXABI().isMicrosoft())
8497 VTContext.reset(new MicrosoftVTableContext(*this));
8498 else
8499 VTContext.reset(new ItaniumVTableContext(*this));
8500 }
8501 return VTContext.get();
8502}
8503
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008504MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008505 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008506 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008507 case TargetCXXABI::GenericItanium:
8508 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008509 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008510 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008511 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008512 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008513 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008514 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008515 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008516 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008517 }
David Blaikie83d382b2011-09-23 05:06:16 +00008518 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008519}
8520
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008521CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008522
8523size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008524 return ASTRecordLayouts.getMemorySize() +
8525 llvm::capacity_in_bytes(ObjCLayouts) +
8526 llvm::capacity_in_bytes(KeyFunctions) +
8527 llvm::capacity_in_bytes(ObjCImpls) +
8528 llvm::capacity_in_bytes(BlockVarCopyInits) +
8529 llvm::capacity_in_bytes(DeclAttrs) +
8530 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8531 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8532 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8533 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8534 llvm::capacity_in_bytes(OverriddenMethods) +
8535 llvm::capacity_in_bytes(Types) +
8536 llvm::capacity_in_bytes(VariableArrayTypes) +
8537 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008538}
Ted Kremenek540017e2011-10-06 05:00:56 +00008539
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008540/// getIntTypeForBitwidth -
8541/// sets integer QualTy according to specified details:
8542/// bitwidth, signed/unsigned.
8543/// Returns empty type if there is no appropriate target types.
8544QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8545 unsigned Signed) const {
8546 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8547 CanQualType QualTy = getFromTargetType(Ty);
8548 if (!QualTy && DestWidth == 128)
8549 return Signed ? Int128Ty : UnsignedInt128Ty;
8550 return QualTy;
8551}
8552
8553/// getRealTypeForBitwidth -
8554/// sets floating point QualTy according to specified bitwidth.
8555/// Returns empty type if there is no appropriate target types.
8556QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8557 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8558 switch (Ty) {
8559 case TargetInfo::Float:
8560 return FloatTy;
8561 case TargetInfo::Double:
8562 return DoubleTy;
8563 case TargetInfo::LongDouble:
8564 return LongDoubleTy;
8565 case TargetInfo::NoFloat:
8566 return QualType();
8567 }
8568
8569 llvm_unreachable("Unhandled TargetInfo::RealType value");
8570}
8571
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008572void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8573 if (Number > 1)
8574 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008575}
8576
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008577unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8578 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8579 MangleNumbers.find(ND);
8580 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008581}
8582
David Majnemer2206bf52014-03-05 08:57:59 +00008583void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8584 if (Number > 1)
8585 StaticLocalNumbers[VD] = Number;
8586}
8587
8588unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8589 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8590 StaticLocalNumbers.find(VD);
8591 return I != StaticLocalNumbers.end() ? I->second : 1;
8592}
8593
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008594MangleNumberingContext &
8595ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008596 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8597 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8598 if (!MCtx)
8599 MCtx = createMangleNumberingContext();
8600 return *MCtx;
8601}
8602
8603MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8604 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008605}
8606
David Majnemere7a818f2015-03-06 18:53:55 +00008607const CXXConstructorDecl *
8608ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8609 return ABI->getCopyConstructorForExceptionObject(
8610 cast<CXXRecordDecl>(RD->getFirstDecl()));
8611}
8612
8613void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8614 CXXConstructorDecl *CD) {
8615 return ABI->addCopyConstructorForExceptionObject(
8616 cast<CXXRecordDecl>(RD->getFirstDecl()),
8617 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8618}
8619
David Majnemerdfa6d202015-03-11 18:36:39 +00008620void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8621 unsigned ParmIdx, Expr *DAE) {
8622 ABI->addDefaultArgExprForConstructor(
8623 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8624}
8625
8626Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8627 unsigned ParmIdx) {
8628 return ABI->getDefaultArgExprForConstructor(
8629 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8630}
8631
David Majnemer00350522015-08-31 18:48:39 +00008632void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8633 TypedefNameDecl *DD) {
8634 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8635}
8636
8637TypedefNameDecl *
8638ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8639 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8640}
8641
8642void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8643 DeclaratorDecl *DD) {
8644 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8645}
8646
8647DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8648 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8649}
8650
Ted Kremenek540017e2011-10-06 05:00:56 +00008651void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8652 ParamIndices[D] = index;
8653}
8654
8655unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8656 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8657 assert(I != ParamIndices.end() &&
8658 "ParmIndices lacks entry set by ParmVarDecl");
8659 return I->second;
8660}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008661
Richard Smithe6c01442013-06-05 00:46:14 +00008662APValue *
8663ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8664 bool MayCreate) {
8665 assert(E && E->getStorageDuration() == SD_Static &&
8666 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008667 if (MayCreate) {
8668 APValue *&MTVI = MaterializedTemporaryValues[E];
8669 if (!MTVI)
8670 MTVI = new (*this) APValue;
8671 return MTVI;
8672 }
Richard Smithe6c01442013-06-05 00:46:14 +00008673
David Majnemer2dcef9e2015-08-13 23:50:15 +00008674 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008675}
8676
Fariborz Jahanian615de762013-05-28 17:37:39 +00008677bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8678 const llvm::Triple &T = getTargetInfo().getTriple();
8679 if (!T.isOSDarwin())
8680 return false;
8681
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008682 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8683 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8684 return false;
8685
Fariborz Jahanian615de762013-05-28 17:37:39 +00008686 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8687 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8688 uint64_t Size = sizeChars.getQuantity();
8689 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8690 unsigned Align = alignChars.getQuantity();
8691 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8692 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8693}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008694
8695namespace {
8696
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008697ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8698 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008699 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008700 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008701 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008702 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008703 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008704}
8705
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008706/// Template specializations to abstract away from pointers and TypeLocs.
8707/// @{
8708template <typename T>
8709ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8710 return ast_type_traits::DynTypedNode::create(*Node);
8711}
8712template <>
8713ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8714 return ast_type_traits::DynTypedNode::create(Node);
8715}
8716template <>
8717ast_type_traits::DynTypedNode
8718createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8719 return ast_type_traits::DynTypedNode::create(Node);
8720}
8721/// @}
8722
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008723 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8724 /// parents as defined by the \c RecursiveASTVisitor.
8725 ///
8726 /// Note that the relationship described here is purely in terms of AST
8727 /// traversal - there are other relationships (for example declaration context)
8728 /// in the AST that are better modeled by special matchers.
8729 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008730 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008731 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8732
8733 public:
8734 /// \brief Builds and returns the translation unit's parent map.
8735 ///
8736 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008737 static std::pair<ASTContext::ParentMapPointers *,
8738 ASTContext::ParentMapOtherNodes *>
8739 buildMap(TranslationUnitDecl &TU) {
8740 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8741 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008742 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008743 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008744 }
8745
8746 private:
8747 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8748
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008749 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8750 ASTContext::ParentMapOtherNodes *OtherParents)
8751 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008752
8753 bool shouldVisitTemplateInstantiations() const {
8754 return true;
8755 }
8756 bool shouldVisitImplicitCode() const {
8757 return true;
8758 }
8759 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8760 // are not triggered during data recursion.
8761 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8762 return false;
8763 }
8764
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008765 template <typename T, typename MapNodeTy, typename MapTy>
8766 bool TraverseNode(T Node, MapNodeTy MapNode,
8767 bool (VisitorBase::*traverse)(T), MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008768 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008769 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008770 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008771 // FIXME: Currently we add the same parent multiple times, but only
8772 // when no memoization data is available for the type.
8773 // For example when we visit all subexpressions of template
8774 // instantiations; this is suboptimal, but benign: the only way to
8775 // visit those is with hasAncestor / hasParent, and those do not create
8776 // new matches.
8777 // The plan is to enable DynTypedNode to be storable in a map or hash
8778 // map. The main problem there is to implement hash functions /
8779 // comparison operators for all types that DynTypedNode supports that
8780 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008781 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008782 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008783 if (const auto *D = ParentStack.back().get<Decl>())
8784 NodeOrVector = D;
8785 else if (const auto *S = ParentStack.back().get<Stmt>())
8786 NodeOrVector = S;
8787 else
8788 NodeOrVector =
8789 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008790 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008791 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8792 auto *Vector = new ASTContext::ParentVector(
8793 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008794 if (auto *Node =
8795 NodeOrVector
8796 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8797 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008798 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008799 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008800
8801 auto *Vector =
8802 NodeOrVector.template get<ASTContext::ParentVector *>();
8803 // Skip duplicates for types that have memoization data.
8804 // We must check that the type has memoization data before calling
8805 // std::find() because DynTypedNode::operator== can't compare all
8806 // types.
8807 bool Found = ParentStack.back().getMemoizationData() &&
8808 std::find(Vector->begin(), Vector->end(),
8809 ParentStack.back()) != Vector->end();
8810 if (!Found)
8811 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008812 }
8813 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008814 ParentStack.push_back(createDynTypedNode(Node));
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008815 bool Result = (this ->* traverse) (Node);
8816 ParentStack.pop_back();
8817 return Result;
8818 }
8819
8820 bool TraverseDecl(Decl *DeclNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008821 return TraverseNode(DeclNode, DeclNode, &VisitorBase::TraverseDecl,
8822 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008823 }
8824
8825 bool TraverseStmt(Stmt *StmtNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008826 return TraverseNode(StmtNode, StmtNode, &VisitorBase::TraverseStmt,
8827 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008828 }
8829
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008830 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8831 return TraverseNode(TypeLocNode,
8832 ast_type_traits::DynTypedNode::create(TypeLocNode),
8833 &VisitorBase::TraverseTypeLoc, OtherParents);
8834 }
8835
8836 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8837 return TraverseNode(
8838 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8839 &VisitorBase::TraverseNestedNameSpecifierLoc, OtherParents);
8840 }
8841
8842 ASTContext::ParentMapPointers *Parents;
8843 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008844 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8845
8846 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8847 };
8848
Eugene Zelenkod4304d22015-11-04 21:37:17 +00008849} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008850
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008851template <typename NodeTy, typename MapTy>
8852static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8853 const MapTy &Map) {
8854 auto I = Map.find(Node);
8855 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008856 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008857 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008858 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008859 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008860 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008861 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008862}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008863
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008864ASTContext::DynTypedNodeList
8865ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8866 if (!PointerParents) {
8867 // We always need to run over the whole translation unit, as
8868 // hasAncestor can escape any subtree.
8869 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8870 PointerParents.reset(Maps.first);
8871 OtherParents.reset(Maps.second);
8872 }
8873 if (Node.getNodeKind().hasPointerIdentity())
8874 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8875 return getDynNodeFromMap(Node, *OtherParents);
8876}
8877
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008878bool
8879ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8880 const ObjCMethodDecl *MethodImpl) {
8881 // No point trying to match an unavailable/deprecated mothod.
8882 if (MethodDecl->hasAttr<UnavailableAttr>()
8883 || MethodDecl->hasAttr<DeprecatedAttr>())
8884 return false;
8885 if (MethodDecl->getObjCDeclQualifier() !=
8886 MethodImpl->getObjCDeclQualifier())
8887 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008888 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008889 return false;
8890
8891 if (MethodDecl->param_size() != MethodImpl->param_size())
8892 return false;
8893
8894 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8895 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8896 EF = MethodDecl->param_end();
8897 IM != EM && IF != EF; ++IM, ++IF) {
8898 const ParmVarDecl *DeclVar = (*IF);
8899 const ParmVarDecl *ImplVar = (*IM);
8900 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8901 return false;
8902 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8903 return false;
8904 }
8905 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8906
8907}
Richard Smith053f6c62014-05-16 23:01:30 +00008908
8909// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8910// doesn't include ASTContext.h
8911template
8912clang::LazyGenerationalUpdatePtr<
8913 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8914clang::LazyGenerationalUpdatePtr<
8915 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8916 const clang::ASTContext &Ctx, Decl *Value);