blob: 973445ca2a71b3b58bbdfca4d43530b31cb03dbf [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(),
David Majnemer902f8c62015-12-27 07:16:27 +0000663 CanonParams,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000684 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000686 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000688 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000689 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000690 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000691 return CreateMicrosoftCXXABI(*this);
692 }
David Blaikie8a40f702012-01-17 06:56:22 +0000693 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000694}
695
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000697 const LangOptions &LOpts) {
698 if (LOpts.FakeAddressSpaceMap) {
699 // The fake address space map must have a distinct entry for each
700 // language-specific address space.
701 static const unsigned FakeAddrSpaceMap[] = {
702 1, // opencl_global
703 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000704 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000705 4, // opencl_generic
706 5, // cuda_device
707 6, // cuda_constant
708 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 }
714}
715
David Tweed31d09b02013-09-13 12:04:22 +0000716static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
717 const LangOptions &LangOpts) {
718 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000719 case LangOptions::ASMM_Target:
720 return TI.useAddressSpaceMapMangling();
721 case LangOptions::ASMM_On:
722 return true;
723 case LangOptions::ASMM_Off:
724 return false;
725 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000726 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000727}
728
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000729ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000730 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000731 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000732 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
733 DependentTemplateSpecializationTypes(this_()),
734 SubstTemplateTemplateParmPacks(this_()),
735 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
736 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000737 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
738 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
739 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000740 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
741 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
742 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
743 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000744 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000745 MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000746 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000747 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
748 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
749 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
750 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000752 TUDecl = TranslationUnitDecl::Create(*this);
753}
754
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000755ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000756 ReleaseParentMapEntries();
757
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000758 // Release the DenseMaps associated with DeclContext objects.
759 // FIXME: Is this the ideal solution?
760 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000761
Manuel Klimeka7328992013-06-03 13:51:33 +0000762 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000763 for (auto &Pair : Deallocations)
764 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000765
Ted Kremenek076baeb2010-06-08 23:00:58 +0000766 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000767 // because they can contain DenseMaps.
768 for (llvm::DenseMap<const ObjCContainerDecl*,
769 const ASTRecordLayout*>::iterator
770 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
771 // Increment in loop to prevent using deallocated memory.
772 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773 R->Destroy(*this);
774
Ted Kremenek076baeb2010-06-08 23:00:58 +0000775 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
776 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
777 // Increment in loop to prevent using deallocated memory.
778 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779 R->Destroy(*this);
780 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000781
782 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
783 AEnd = DeclAttrs.end();
784 A != AEnd; ++A)
785 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000786
David Majnemere694f3e2015-08-14 14:43:50 +0000787 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
788 MaterializedTemporaryValues)
789 MTVPair.second->~APValue();
790
Reid Kleckner588c9372014-02-19 23:44:52 +0000791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000792}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000793
Manuel Klimek95403e62014-05-21 13:28:59 +0000794void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000795 if (!PointerParents) return;
796 for (const auto &Entry : *PointerParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else if (Entry.second.is<ParentVector *>()) {
800 delete Entry.second.get<ParentVector *>();
801 }
802 }
803 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000804 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
805 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000806 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000807 delete Entry.second.get<ParentVector *>();
808 }
809 }
810}
811
Douglas Gregor1a809332010-05-23 18:26:36 +0000812void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000813 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000814}
815
Mike Stump11289f42009-09-09 15:08:12 +0000816void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000817ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
818 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000819}
820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000822 llvm::errs() << "\n*** AST Context Stats:\n";
823 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000824
Douglas Gregora30d0462009-05-26 14:40:08 +0000825 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000826#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000827#define ABSTRACT_TYPE(Name, Parent)
828#include "clang/AST/TypeNodes.def"
829 0 // Extra
830 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000831
Chris Lattner4eb445d2007-01-26 01:27:23 +0000832 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
833 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000834 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000835 }
836
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 unsigned Idx = 0;
838 unsigned TotalBytes = 0;
839#define TYPE(Name, Parent) \
840 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000841 llvm::errs() << " " << counts[Idx] << " " << #Name \
842 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000843 TotalBytes += counts[Idx] * sizeof(Name##Type); \
844 ++Idx;
845#define ABSTRACT_TYPE(Name, Parent)
846#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chandler Carruth3c147a72011-07-04 05:32:14 +0000848 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
849
Douglas Gregor7454c562010-07-02 20:37:36 +0000850 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000851 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
852 << NumImplicitDefaultConstructors
853 << " implicit default constructors created\n";
854 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
855 << NumImplicitCopyConstructors
856 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000857 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000858 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
859 << NumImplicitMoveConstructors
860 << " implicit move constructors created\n";
861 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
862 << NumImplicitCopyAssignmentOperators
863 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000864 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
866 << NumImplicitMoveAssignmentOperators
867 << " implicit move assignment operators created\n";
868 llvm::errs() << NumImplicitDestructorsDeclared << "/"
869 << NumImplicitDestructors
870 << " implicit destructors created\n";
871
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000872 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000873 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000874 ExternalSource->PrintStats();
875 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000876
Douglas Gregor5b11d492010-07-25 17:53:33 +0000877 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000878}
879
Richard Smith42413142015-05-15 20:05:43 +0000880void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
881 bool NotifyListeners) {
882 if (NotifyListeners)
883 if (auto *Listener = getASTMutationListener())
884 Listener->RedefinedHiddenDefinition(ND, M);
885
886 if (getLangOpts().ModulesLocalVisibility)
887 MergedDefModules[ND].push_back(M);
888 else
889 ND->setHidden(false);
890}
891
892void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
893 auto It = MergedDefModules.find(ND);
894 if (It == MergedDefModules.end())
895 return;
896
897 auto &Merged = It->second;
898 llvm::DenseSet<Module*> Found;
899 for (Module *&M : Merged)
900 if (!Found.insert(M).second)
901 M = nullptr;
902 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
903}
904
Richard Smithf19e1272015-03-07 00:04:49 +0000905ExternCContextDecl *ASTContext::getExternCContextDecl() const {
906 if (!ExternCContext)
907 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
908
909 return ExternCContext;
910}
911
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000912BuiltinTemplateDecl *
913ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
914 const IdentifierInfo *II) const {
915 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
916 BuiltinTemplate->setImplicit();
917 TUDecl->addDecl(BuiltinTemplate);
918
919 return BuiltinTemplate;
920}
921
922BuiltinTemplateDecl *
923ASTContext::getMakeIntegerSeqDecl() const {
924 if (!MakeIntegerSeqDecl)
925 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
926 getMakeIntegerSeqName());
927 return MakeIntegerSeqDecl;
928}
929
Alp Toker2dea15b2013-12-17 01:22:38 +0000930RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
931 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000932 SourceLocation Loc;
933 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000934 if (getLangOpts().CPlusPlus)
935 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
936 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000937 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000938 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
939 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000941 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
942 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000943 return NewDecl;
944}
945
946TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
947 StringRef Name) const {
948 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
949 TypedefDecl *NewDecl = TypedefDecl::Create(
950 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
951 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
952 NewDecl->setImplicit();
953 return NewDecl;
954}
955
Douglas Gregor801c99d2011-08-12 06:49:56 +0000956TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000957 if (!Int128Decl)
958 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000959 return Int128Decl;
960}
961
962TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000963 if (!UInt128Decl)
964 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000965 return UInt128Decl;
966}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000967
Nico Webere1687c52013-06-20 21:44:55 +0000968TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000969 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000970 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000971 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000972
Nico Webere1687c52013-06-20 21:44:55 +0000973 return Float128StubDecl;
974}
975
John McCall48f2d582009-10-23 23:03:21 +0000976void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000977 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000978 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000979 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000980}
981
Artem Belevichb5bc9232015-09-22 17:23:22 +0000982void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
983 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000984 assert((!this->Target || this->Target == &Target) &&
985 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000986 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregore8bbc122011-09-02 00:18:52 +0000988 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000989 this->AuxTarget = AuxTarget;
990
Douglas Gregore8bbc122011-09-02 00:18:52 +0000991 ABI.reset(createCXXABI(Target));
992 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000993 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000994
Chris Lattner970e54e2006-11-12 00:37:36 +0000995 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000996 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner970e54e2006-11-12 00:37:36 +0000998 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000999 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001001 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001002 InitBuiltinType(CharTy, BuiltinType::Char_S);
1003 else
1004 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001005 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001006 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1007 InitBuiltinType(ShortTy, BuiltinType::Short);
1008 InitBuiltinType(IntTy, BuiltinType::Int);
1009 InitBuiltinType(LongTy, BuiltinType::Long);
1010 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner970e54e2006-11-12 00:37:36 +00001012 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001013 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1014 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1015 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1016 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1017 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner970e54e2006-11-12 00:37:36 +00001019 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001020 InitBuiltinType(FloatTy, BuiltinType::Float);
1021 InitBuiltinType(DoubleTy, BuiltinType::Double);
1022 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001023
Chris Lattnerf122cef2009-04-30 02:43:43 +00001024 // GNU extension, 128-bit integers.
1025 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1026 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1027
Hans Wennborg0d81e012013-05-10 10:08:40 +00001028 // C++ 3.9.1p5
1029 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1030 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1031 else // -fshort-wchar makes wchar_t be unsigned.
1032 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1033 if (LangOpts.CPlusPlus && LangOpts.WChar)
1034 WideCharTy = WCharTy;
1035 else {
1036 // C99 (or C++ using -fno-wchar).
1037 WideCharTy = getFromTargetType(Target.getWCharType());
1038 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001039
James Molloy36365542012-05-04 10:55:22 +00001040 WIntTy = getFromTargetType(Target.getWIntType());
1041
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001042 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1043 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1044 else // C99
1045 Char16Ty = getFromTargetType(Target.getChar16Type());
1046
1047 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1048 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1049 else // C99
1050 Char32Ty = getFromTargetType(Target.getChar32Type());
1051
Douglas Gregor4619e432008-12-05 23:32:09 +00001052 // Placeholder type for type-dependent expressions whose type is
1053 // completely unknown. No code should ever check a type against
1054 // DependentTy and users should never see it; however, it is here to
1055 // help diagnose failures to properly check for type-dependent
1056 // expressions.
1057 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058
John McCall36e7fe32010-10-12 00:20:44 +00001059 // Placeholder type for functions.
1060 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1061
John McCall0009fcc2011-04-26 20:42:42 +00001062 // Placeholder type for bound members.
1063 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1064
John McCall526ab472011-10-25 17:37:35 +00001065 // Placeholder type for pseudo-objects.
1066 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1067
John McCall31996342011-04-07 08:22:57 +00001068 // "any" type; useful for debugger-like clients.
1069 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1070
John McCall8a6b59a2011-10-17 18:09:15 +00001071 // Placeholder type for unbridged ARC casts.
1072 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1073
Eli Friedman34866c72012-08-31 00:14:07 +00001074 // Placeholder type for builtin functions.
1075 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1076
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001077 // Placeholder type for OMP array sections.
1078 if (LangOpts.OpenMP)
1079 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1080
Chris Lattner970e54e2006-11-12 00:37:36 +00001081 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001082 FloatComplexTy = getComplexType(FloatTy);
1083 DoubleComplexTy = getComplexType(DoubleTy);
1084 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001086 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001087 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1088 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001089 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001090
1091 if (LangOpts.OpenCL) {
1092 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1093 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1094 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1095 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1096 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001097 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1098 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1099 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1100 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1101 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1102 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1103 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001104 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001105
Guy Benyei61054192013-02-07 10:55:47 +00001106 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001107 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001108 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1109 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1110 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1111 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001112 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001113
1114 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001115 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1116 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001117
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001118 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001119
1120 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001121
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001122 // void * type
1123 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001124
1125 // nullptr type (C++0x 2.14.7)
1126 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001127
1128 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1129 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001130
1131 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001132 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001133}
1134
David Blaikie9c902b52011-09-25 23:23:43 +00001135DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001136 return SourceMgr.getDiagnostics();
1137}
1138
Douglas Gregor561eceb2010-08-30 16:49:28 +00001139AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1140 AttrVec *&Result = DeclAttrs[D];
1141 if (!Result) {
1142 void *Mem = Allocate(sizeof(AttrVec));
1143 Result = new (Mem) AttrVec;
1144 }
1145
1146 return *Result;
1147}
1148
1149/// \brief Erase the attributes corresponding to the given declaration.
1150void ASTContext::eraseDeclAttrs(const Decl *D) {
1151 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1152 if (Pos != DeclAttrs.end()) {
1153 Pos->second->~AttrVec();
1154 DeclAttrs.erase(Pos);
1155 }
1156}
1157
Larisse Voufo39a1e502013-08-06 01:03:05 +00001158// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001159MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001160ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001161 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001162 return getTemplateOrSpecializationInfo(Var)
1163 .dyn_cast<MemberSpecializationInfo *>();
1164}
1165
1166ASTContext::TemplateOrSpecializationInfo
1167ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1168 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1169 TemplateOrInstantiation.find(Var);
1170 if (Pos == TemplateOrInstantiation.end())
1171 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001172
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001173 return Pos->second;
1174}
1175
Mike Stump11289f42009-09-09 15:08:12 +00001176void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001177ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001178 TemplateSpecializationKind TSK,
1179 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001180 assert(Inst->isStaticDataMember() && "Not a static data member");
1181 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001182 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1183 Tmpl, TSK, PointOfInstantiation));
1184}
1185
1186void
1187ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1188 TemplateOrSpecializationInfo TSI) {
1189 assert(!TemplateOrInstantiation[Inst] &&
1190 "Already noted what the variable was instantiated from");
1191 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001192}
1193
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001194FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1195 const FunctionDecl *FD){
1196 assert(FD && "Specialization is 0");
1197 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001198 = ClassScopeSpecializationPattern.find(FD);
1199 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001200 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001201
1202 return Pos->second;
1203}
1204
1205void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1206 FunctionDecl *Pattern) {
1207 assert(FD && "Specialization is 0");
1208 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001209 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001210}
1211
John McCalle61f2ba2009-11-18 02:36:19 +00001212NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001213ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001214 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001215 = InstantiatedFromUsingDecl.find(UUD);
1216 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001217 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001218
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001219 return Pos->second;
1220}
1221
1222void
John McCallb96ec562009-12-04 22:46:56 +00001223ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1224 assert((isa<UsingDecl>(Pattern) ||
1225 isa<UnresolvedUsingValueDecl>(Pattern) ||
1226 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1227 "pattern decl is not a using decl");
1228 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1229 InstantiatedFromUsingDecl[Inst] = Pattern;
1230}
1231
1232UsingShadowDecl *
1233ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1234 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1235 = InstantiatedFromUsingShadowDecl.find(Inst);
1236 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001237 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001238
1239 return Pos->second;
1240}
1241
1242void
1243ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1244 UsingShadowDecl *Pattern) {
1245 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1246 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001247}
1248
Anders Carlsson5da84842009-09-01 04:26:58 +00001249FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1250 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1251 = InstantiatedFromUnnamedFieldDecl.find(Field);
1252 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001253 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Anders Carlsson5da84842009-09-01 04:26:58 +00001255 return Pos->second;
1256}
1257
1258void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1259 FieldDecl *Tmpl) {
1260 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1261 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1262 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1263 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001264
Anders Carlsson5da84842009-09-01 04:26:58 +00001265 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1266}
1267
Douglas Gregor832940b2010-03-02 23:58:15 +00001268ASTContext::overridden_cxx_method_iterator
1269ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1270 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001271 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001272 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001273 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001274
1275 return Pos->second.begin();
1276}
1277
1278ASTContext::overridden_cxx_method_iterator
1279ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1280 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001281 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001282 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001283 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001284
1285 return Pos->second.end();
1286}
1287
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001288unsigned
1289ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1290 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001291 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001292 if (Pos == OverriddenMethods.end())
1293 return 0;
1294
1295 return Pos->second.size();
1296}
1297
Douglas Gregor832940b2010-03-02 23:58:15 +00001298void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1299 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001300 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001301 OverriddenMethods[Method].push_back(Overridden);
1302}
1303
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001304void ASTContext::getOverriddenMethods(
1305 const NamedDecl *D,
1306 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001307 assert(D);
1308
1309 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001310 Overridden.append(overridden_methods_begin(CXXMethod),
1311 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001312 return;
1313 }
1314
1315 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1316 if (!Method)
1317 return;
1318
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001319 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1320 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001321 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001322}
1323
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001324void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1325 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1326 assert(!Import->isFromASTFile() && "Non-local import declaration");
1327 if (!FirstLocalImport) {
1328 FirstLocalImport = Import;
1329 LastLocalImport = Import;
1330 return;
1331 }
1332
1333 LastLocalImport->NextLocalImport = Import;
1334 LastLocalImport = Import;
1335}
1336
Chris Lattner53cfe802007-07-18 17:52:12 +00001337//===----------------------------------------------------------------------===//
1338// Type Sizing and Analysis
1339//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001340
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001341/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1342/// scalar floating point type.
1343const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001344 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001345 assert(BT && "Not a floating point type!");
1346 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001347 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001348 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001349 case BuiltinType::Float: return Target->getFloatFormat();
1350 case BuiltinType::Double: return Target->getDoubleFormat();
1351 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001352 }
1353}
1354
Rafael Espindola71eccb32013-08-08 19:53:46 +00001355CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001356 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001357
John McCall94268702010-10-08 18:24:19 +00001358 bool UseAlignAttrOnly = false;
1359 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1360 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001361
John McCall94268702010-10-08 18:24:19 +00001362 // __attribute__((aligned)) can increase or decrease alignment
1363 // *except* on a struct or struct member, where it only increases
1364 // alignment unless 'packed' is also specified.
1365 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001366 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001367 // ignore that possibility; Sema should diagnose it.
1368 if (isa<FieldDecl>(D)) {
1369 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1370 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1371 } else {
1372 UseAlignAttrOnly = true;
1373 }
1374 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001375 else if (isa<FieldDecl>(D))
1376 UseAlignAttrOnly =
1377 D->hasAttr<PackedAttr>() ||
1378 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001379
John McCall4e819612011-01-20 07:57:12 +00001380 // If we're using the align attribute only, just ignore everything
1381 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001382 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001383 // do nothing
1384
John McCall94268702010-10-08 18:24:19 +00001385 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001386 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001387 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001388 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001389 T = RT->getPointeeType();
1390 else
1391 T = getPointerType(RT->getPointeeType());
1392 }
Richard Smithf6d70302014-06-10 23:34:28 +00001393 QualType BaseT = getBaseElementType(T);
1394 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001395 // Adjust alignments of declarations with array type by the
1396 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001397 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001398 unsigned MinWidth = Target->getLargeArrayMinWidth();
1399 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001400 if (isa<VariableArrayType>(arrayType))
1401 Align = std::max(Align, Target->getLargeArrayAlign());
1402 else if (isa<ConstantArrayType>(arrayType) &&
1403 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1404 Align = std::max(Align, Target->getLargeArrayAlign());
1405 }
John McCall33ddac02011-01-19 10:06:00 +00001406 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001407 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001408 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001409 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001410 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1411 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001412 }
John McCall4e819612011-01-20 07:57:12 +00001413
1414 // Fields can be subject to extra alignment constraints, like if
1415 // the field is packed, the struct is packed, or the struct has a
1416 // a max-field-alignment constraint (#pragma pack). So calculate
1417 // the actual alignment of the field within the struct, and then
1418 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001419 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1420 const RecordDecl *Parent = Field->getParent();
1421 // We can only produce a sensible answer if the record is valid.
1422 if (!Parent->isInvalidDecl()) {
1423 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001424
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001425 // Start with the record's overall alignment.
1426 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001427
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001428 // Use the GCD of that and the offset within the record.
1429 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1430 if (Offset > 0) {
1431 // Alignment is always a power of 2, so the GCD will be a power of 2,
1432 // which means we get to do this crazy thing instead of Euclid's.
1433 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1434 if (LowBitOfOffset < FieldAlign)
1435 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1436 }
1437
1438 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001439 }
Charles Davis3fc51072010-02-23 04:52:00 +00001440 }
Chris Lattner68061312009-01-24 21:53:27 +00001441 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001442
Ken Dyckcc56c542011-01-15 18:38:59 +00001443 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001444}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001445
John McCallf1249922012-08-21 04:10:00 +00001446// getTypeInfoDataSizeInChars - Return the size of a type, in
1447// chars. If the type is a record, its data size is returned. This is
1448// the size of the memcpy that's performed when assigning this type
1449// using a trivial copy/move assignment operator.
1450std::pair<CharUnits, CharUnits>
1451ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1452 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1453
1454 // In C++, objects can sometimes be allocated into the tail padding
1455 // of a base-class subobject. We decide whether that's possible
1456 // during class layout, so here we can just trust the layout results.
1457 if (getLangOpts().CPlusPlus) {
1458 if (const RecordType *RT = T->getAs<RecordType>()) {
1459 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1460 sizeAndAlign.first = layout.getDataSize();
1461 }
1462 }
1463
1464 return sizeAndAlign;
1465}
1466
Richard Trieu04d2d942013-05-14 21:59:17 +00001467/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1468/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1469std::pair<CharUnits, CharUnits>
1470static getConstantArrayInfoInChars(const ASTContext &Context,
1471 const ConstantArrayType *CAT) {
1472 std::pair<CharUnits, CharUnits> EltInfo =
1473 Context.getTypeInfoInChars(CAT->getElementType());
1474 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001475 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1476 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001477 "Overflow in array type char size evaluation");
1478 uint64_t Width = EltInfo.first.getQuantity() * Size;
1479 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001480 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1481 Context.getTargetInfo().getPointerWidth(0) == 64)
1482 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001483 return std::make_pair(CharUnits::fromQuantity(Width),
1484 CharUnits::fromQuantity(Align));
1485}
1486
John McCall87fe5d52010-05-20 01:18:31 +00001487std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001488ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001489 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1490 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001491 TypeInfo Info = getTypeInfo(T);
1492 return std::make_pair(toCharUnitsFromBits(Info.Width),
1493 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001494}
1495
1496std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001497ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001498 return getTypeInfoInChars(T.getTypePtr());
1499}
1500
David Majnemer34b57492014-07-30 01:30:47 +00001501bool ASTContext::isAlignmentRequired(const Type *T) const {
1502 return getTypeInfo(T).AlignIsRequired;
1503}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001504
David Majnemer34b57492014-07-30 01:30:47 +00001505bool ASTContext::isAlignmentRequired(QualType T) const {
1506 return isAlignmentRequired(T.getTypePtr());
1507}
1508
1509TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001510 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1511 if (I != MemoizedTypeInfo.end())
1512 return I->second;
1513
1514 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1515 TypeInfo TI = getTypeInfoImpl(T);
1516 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001517 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001518}
1519
1520/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1521/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001522///
1523/// FIXME: Pointers into different addr spaces could have different sizes and
1524/// alignment requirements: getPointerInfo should take an AddrSpace, this
1525/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001526TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1527 uint64_t Width = 0;
1528 unsigned Align = 8;
1529 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001530 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001531#define TYPE(Class, Base)
1532#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001533#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001534#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001535#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1536 case Type::Class: \
1537 assert(!T->isDependentType() && "should not see dependent types here"); \
1538 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001539#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001540 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001541
Chris Lattner355332d2007-07-13 22:27:08 +00001542 case Type::FunctionNoProto:
1543 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001544 // GCC extension: alignof(function) = 32 bits
1545 Width = 0;
1546 Align = 32;
1547 break;
1548
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001549 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001550 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001551 Width = 0;
1552 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1553 break;
1554
Steve Naroff5c131802007-08-30 01:06:46 +00001555 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001556 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001557
David Majnemer34b57492014-07-30 01:30:47 +00001558 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001559 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001560 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001561 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001562 Width = EltInfo.Width * Size;
1563 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001564 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1565 getTargetInfo().getPointerWidth(0) == 64)
1566 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001567 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001568 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001569 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001570 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001571 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001572 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1573 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001574 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001575 // If the alignment is not a power of 2, round up to the next power of 2.
1576 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001577 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001578 Align = llvm::NextPowerOf2(Align);
1579 Width = llvm::RoundUpToAlignment(Width, Align);
1580 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001581 // Adjust the alignment based on the target max.
1582 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1583 if (TargetVectorAlign && TargetVectorAlign < Align)
1584 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001585 break;
1586 }
Chris Lattner647fb222007-07-18 18:26:58 +00001587
Chris Lattner7570e9c2008-03-08 08:52:55 +00001588 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001589 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001590 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001591 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001592 // GCC extension: alignof(void) = 8 bits.
1593 Width = 0;
1594 Align = 8;
1595 break;
1596
Chris Lattner6a4f7452007-12-19 19:23:28 +00001597 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getBoolWidth();
1599 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001600 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001601 case BuiltinType::Char_S:
1602 case BuiltinType::Char_U:
1603 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getCharWidth();
1606 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001608 case BuiltinType::WChar_S:
1609 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getWCharWidth();
1611 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001612 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001613 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getChar16Width();
1615 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001616 break;
1617 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001618 Width = Target->getChar32Width();
1619 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001620 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001621 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001622 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001623 Width = Target->getShortWidth();
1624 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001625 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001626 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 Width = Target->getIntWidth();
1629 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001631 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001632 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001633 Width = Target->getLongWidth();
1634 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001635 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001636 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001637 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001638 Width = Target->getLongLongWidth();
1639 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001640 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001641 case BuiltinType::Int128:
1642 case BuiltinType::UInt128:
1643 Width = 128;
1644 Align = 128; // int128_t is 128-bit aligned on all targets.
1645 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001646 case BuiltinType::Half:
1647 Width = Target->getHalfWidth();
1648 Align = Target->getHalfAlign();
1649 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001650 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001651 Width = Target->getFloatWidth();
1652 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001653 break;
1654 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getDoubleWidth();
1656 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001657 break;
1658 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001659 Width = Target->getLongDoubleWidth();
1660 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001661 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001662 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001663 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1664 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001665 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001666 case BuiltinType::ObjCId:
1667 case BuiltinType::ObjCClass:
1668 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001669 Width = Target->getPointerWidth(0);
1670 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001671 break;
Guy Benyei61054192013-02-07 10:55:47 +00001672 case BuiltinType::OCLSampler:
1673 // Samplers are modeled as integers.
1674 Width = Target->getIntWidth();
1675 Align = Target->getIntAlign();
1676 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001677 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001678 case BuiltinType::OCLClkEvent:
1679 case BuiltinType::OCLQueue:
1680 case BuiltinType::OCLNDRange:
1681 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001682 case BuiltinType::OCLImage1d:
1683 case BuiltinType::OCLImage1dArray:
1684 case BuiltinType::OCLImage1dBuffer:
1685 case BuiltinType::OCLImage2d:
1686 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001687 case BuiltinType::OCLImage2dDepth:
1688 case BuiltinType::OCLImage2dArrayDepth:
1689 case BuiltinType::OCLImage2dMSAA:
1690 case BuiltinType::OCLImage2dArrayMSAA:
1691 case BuiltinType::OCLImage2dMSAADepth:
1692 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001693 case BuiltinType::OCLImage3d:
1694 // Currently these types are pointers to opaque types.
1695 Width = Target->getPointerWidth(0);
1696 Align = Target->getPointerAlign(0);
1697 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001698 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001699 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001700 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001701 Width = Target->getPointerWidth(0);
1702 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001703 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001704 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001705 unsigned AS = getTargetAddressSpace(
1706 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Width = Target->getPointerWidth(AS);
1708 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001709 break;
1710 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001711 case Type::LValueReference:
1712 case Type::RValueReference: {
1713 // alignof and sizeof should never enter this code path here, so we go
1714 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001715 unsigned AS = getTargetAddressSpace(
1716 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001717 Width = Target->getPointerWidth(AS);
1718 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001719 break;
1720 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001721 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001722 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001723 Width = Target->getPointerWidth(AS);
1724 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001725 break;
1726 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001727 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001728 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001729 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001730 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001731 }
Chris Lattner647fb222007-07-18 18:26:58 +00001732 case Type::Complex: {
1733 // Complex types have the same alignment as their elements, but twice the
1734 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001735 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1736 Width = EltInfo.Width * 2;
1737 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001738 break;
1739 }
John McCall8b07ec22010-05-15 11:32:37 +00001740 case Type::ObjCObject:
1741 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001742 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001743 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001744 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001745 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001746 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001747 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001748 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001749 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001750 break;
1751 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001752 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001753 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001754 const TagType *TT = cast<TagType>(T);
1755
1756 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001757 Width = 8;
1758 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001759 break;
1760 }
Mike Stump11289f42009-09-09 15:08:12 +00001761
David Majnemer475b25e2015-01-21 10:54:38 +00001762 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1763 const EnumDecl *ED = ET->getDecl();
1764 TypeInfo Info =
1765 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1766 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1767 Info.Align = AttrAlign;
1768 Info.AlignIsRequired = true;
1769 }
1770 return Info;
1771 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001772
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001773 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001774 const RecordDecl *RD = RT->getDecl();
1775 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001776 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001777 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001778 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001779 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001780 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001781
Chris Lattner63d2b362009-10-22 05:17:15 +00001782 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001783 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1784 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001785
Richard Smith30482bc2011-02-20 03:19:35 +00001786 case Type::Auto: {
1787 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001788 assert(!A->getDeducedType().isNull() &&
1789 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001790 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001791 }
1792
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001793 case Type::Paren:
1794 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1795
Douglas Gregoref462e62009-04-30 17:32:17 +00001796 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001797 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001798 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001799 // If the typedef has an aligned attribute on it, it overrides any computed
1800 // alignment we have. This violates the GCC documentation (which says that
1801 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001802 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001803 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001804 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001805 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001806 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001807 AlignIsRequired = Info.AlignIsRequired;
1808 }
David Majnemer34b57492014-07-30 01:30:47 +00001809 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001810 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001811 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001812
Abramo Bagnara6150c882010-05-11 21:36:43 +00001813 case Type::Elaborated:
1814 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001815
John McCall81904512011-01-06 01:58:22 +00001816 case Type::Attributed:
1817 return getTypeInfo(
1818 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1819
Eli Friedman0dfb8892011-10-06 23:00:33 +00001820 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001821 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001822 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1823 Width = Info.Width;
1824 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001825
1826 // If the size of the type doesn't exceed the platform's max
1827 // atomic promotion width, make the size and alignment more
1828 // favorable to atomic operations:
1829 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1830 // Round the size up to a power of 2.
1831 if (!llvm::isPowerOf2_64(Width))
1832 Width = llvm::NextPowerOf2(Width);
1833
1834 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001835 Align = static_cast<unsigned>(Width);
1836 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001837 }
1838
Douglas Gregoref462e62009-04-30 17:32:17 +00001839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001841 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001842 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001843}
1844
Alexey Bataev00396512015-07-02 03:40:19 +00001845unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1846 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1847 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1848 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1849 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1850 getTargetInfo().getABI() == "elfv1-qpx" &&
1851 T->isSpecificBuiltinType(BuiltinType::Double))
1852 SimdAlign = 256;
1853 return SimdAlign;
1854}
1855
Ken Dyckcc56c542011-01-15 18:38:59 +00001856/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1857CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1858 return CharUnits::fromQuantity(BitSize / getCharWidth());
1859}
1860
Ken Dyckb0fcc592011-02-11 01:54:29 +00001861/// toBits - Convert a size in characters to a size in characters.
1862int64_t ASTContext::toBits(CharUnits CharSize) const {
1863 return CharSize.getQuantity() * getCharWidth();
1864}
1865
Ken Dyck8c89d592009-12-22 14:23:30 +00001866/// getTypeSizeInChars - Return the size of the specified type, in characters.
1867/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001868CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001869 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001870}
Jay Foad39c79802011-01-12 09:06:06 +00001871CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001872 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001873}
1874
Ken Dycka6046ab2010-01-26 17:25:18 +00001875/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001876/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001877CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001878 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001879}
Jay Foad39c79802011-01-12 09:06:06 +00001880CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001881 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001882}
1883
Chris Lattnera3402cd2009-01-27 18:08:34 +00001884/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1885/// type for the current target in bits. This can be different than the ABI
1886/// alignment in cases where it is beneficial for performance to overalign
1887/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001888unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001889 TypeInfo TI = getTypeInfo(T);
1890 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001891
David Majnemere1544562015-04-24 01:25:05 +00001892 T = T->getBaseElementTypeUnsafe();
1893
1894 // The preferred alignment of member pointers is that of a pointer.
1895 if (T->isMemberPointerType())
1896 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1897
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001898 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1899 return ABIAlign; // Never overalign on XCore.
1900
Eli Friedman7ab09572009-05-25 21:27:19 +00001901 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001902 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001903 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001904 if (const EnumType *ET = T->getAs<EnumType>())
1905 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001906 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001907 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1908 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001909 // Don't increase the alignment if an alignment attribute was specified on a
1910 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001911 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001912 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001913
Chris Lattnera3402cd2009-01-27 18:08:34 +00001914 return ABIAlign;
1915}
1916
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001917/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1918/// for __attribute__((aligned)) on this target, to be used if no alignment
1919/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001920unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001921 return getTargetInfo().getDefaultAlignForAttributeAligned();
1922}
1923
Ulrich Weigandfa806422013-05-06 16:23:57 +00001924/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1925/// to a global variable of the specified type.
1926unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1927 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1928}
1929
1930/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1931/// should be given to a global variable of the specified type.
1932CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1933 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1934}
1935
David Majnemer08ef2ba2015-06-23 20:34:18 +00001936CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1937 CharUnits Offset = CharUnits::Zero();
1938 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1939 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1940 Offset += Layout->getBaseClassOffset(Base);
1941 Layout = &getASTRecordLayout(Base);
1942 }
1943 return Offset;
1944}
1945
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001946/// DeepCollectObjCIvars -
1947/// This routine first collects all declared, but not synthesized, ivars in
1948/// super class and then collects all ivars, including those synthesized for
1949/// current class. This routine is used for implementation of current class
1950/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001951///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001952void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1953 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001954 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001955 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1956 DeepCollectObjCIvars(SuperClass, false, Ivars);
1957 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001958 for (const auto *I : OI->ivars())
1959 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001960 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001961 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001962 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001963 Iv= Iv->getNextIvar())
1964 Ivars.push_back(Iv);
1965 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001966}
1967
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001968/// CollectInheritedProtocols - Collect all protocols in current class and
1969/// those inherited by it.
1970void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001971 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001972 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001973 // We can use protocol_iterator here instead of
1974 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001975 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001976 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001977 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001978
1979 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001980 for (const auto *Cat : OI->visible_categories())
1981 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001982
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001983 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1984 while (SD) {
1985 CollectInheritedProtocols(SD, Protocols);
1986 SD = SD->getSuperClass();
1987 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001988 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001989 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001990 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001991 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001992 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001993 // Insert the protocol.
1994 if (!Protocols.insert(
1995 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1996 return;
1997
1998 for (auto *Proto : OP->protocols())
1999 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002000 }
2001}
2002
Jay Foad39c79802011-01-12 09:06:06 +00002003unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002004 unsigned count = 0;
2005 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002006 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002007 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002008
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002009 // Count ivar defined in this class's implementation. This
2010 // includes synthesized ivars.
2011 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002012 count += ImplDecl->ivar_size();
2013
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002014 return count;
2015}
2016
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002017bool ASTContext::isSentinelNullExpr(const Expr *E) {
2018 if (!E)
2019 return false;
2020
2021 // nullptr_t is always treated as null.
2022 if (E->getType()->isNullPtrType()) return true;
2023
2024 if (E->getType()->isAnyPointerType() &&
2025 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2026 Expr::NPC_ValueDependentIsNull))
2027 return true;
2028
2029 // Unfortunately, __null has type 'int'.
2030 if (isa<GNUNullExpr>(E)) return true;
2031
2032 return false;
2033}
2034
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002035/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2036ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2037 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2038 I = ObjCImpls.find(D);
2039 if (I != ObjCImpls.end())
2040 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002041 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002042}
2043/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2044ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2045 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2046 I = ObjCImpls.find(D);
2047 if (I != ObjCImpls.end())
2048 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002049 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002050}
2051
2052/// \brief Set the implementation of ObjCInterfaceDecl.
2053void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2054 ObjCImplementationDecl *ImplD) {
2055 assert(IFaceD && ImplD && "Passed null params");
2056 ObjCImpls[IFaceD] = ImplD;
2057}
2058/// \brief Set the implementation of ObjCCategoryDecl.
2059void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2060 ObjCCategoryImplDecl *ImplD) {
2061 assert(CatD && ImplD && "Passed null params");
2062 ObjCImpls[CatD] = ImplD;
2063}
2064
Chandler Carruth21c90602015-12-30 03:24:14 +00002065const ObjCMethodDecl *
2066ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2067 return ObjCMethodRedecls.lookup(MD);
2068}
2069
2070void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2071 const ObjCMethodDecl *Redecl) {
2072 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2073 ObjCMethodRedecls[MD] = Redecl;
2074}
2075
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002076const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2077 const NamedDecl *ND) const {
2078 if (const ObjCInterfaceDecl *ID =
2079 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002080 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002081 if (const ObjCCategoryDecl *CD =
2082 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002083 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002084 if (const ObjCImplDecl *IMD =
2085 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002086 return IMD->getClassInterface();
2087
Craig Topper36250ad2014-05-12 05:36:57 +00002088 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002089}
2090
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002091/// \brief Get the copy initialization expression of VarDecl,or NULL if
2092/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002093Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002094 assert(VD && "Passed null params");
2095 assert(VD->hasAttr<BlocksAttr>() &&
2096 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002097 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002098 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002099 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002100}
2101
2102/// \brief Set the copy inialization expression of a block var decl.
2103void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2104 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002105 assert(VD->hasAttr<BlocksAttr>() &&
2106 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002107 BlockVarCopyInits[VD] = Init;
2108}
2109
John McCallbcd03502009-12-07 02:54:59 +00002110TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002111 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002112 if (!DataSize)
2113 DataSize = TypeLoc::getFullDataSizeForType(T);
2114 else
2115 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002116 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002117
John McCallbcd03502009-12-07 02:54:59 +00002118 TypeSourceInfo *TInfo =
2119 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2120 new (TInfo) TypeSourceInfo(T);
2121 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002122}
2123
John McCallbcd03502009-12-07 02:54:59 +00002124TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002125 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002126 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002127 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002128 return DI;
2129}
2130
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002131const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002132ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002133 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002134}
2135
2136const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002137ASTContext::getASTObjCImplementationLayout(
2138 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002139 return getObjCLayout(D->getClassInterface(), D);
2140}
2141
Chris Lattner983a8bb2007-07-13 22:13:22 +00002142//===----------------------------------------------------------------------===//
2143// Type creation/memoization methods
2144//===----------------------------------------------------------------------===//
2145
Jay Foad39c79802011-01-12 09:06:06 +00002146QualType
John McCall33ddac02011-01-19 10:06:00 +00002147ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2148 unsigned fastQuals = quals.getFastQualifiers();
2149 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002150
2151 // Check if we've already instantiated this type.
2152 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002153 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002154 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002155 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2156 assert(eq->getQualifiers() == quals);
2157 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002158 }
2159
John McCall33ddac02011-01-19 10:06:00 +00002160 // If the base type is not canonical, make the appropriate canonical type.
2161 QualType canon;
2162 if (!baseType->isCanonicalUnqualified()) {
2163 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002164 canonSplit.Quals.addConsistentQualifiers(quals);
2165 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002166
2167 // Re-find the insert position.
2168 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2169 }
2170
2171 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2172 ExtQualNodes.InsertNode(eq, insertPos);
2173 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002174}
2175
Jay Foad39c79802011-01-12 09:06:06 +00002176QualType
2177ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002178 QualType CanT = getCanonicalType(T);
2179 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002180 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002181
John McCall8ccfcb52009-09-24 19:53:00 +00002182 // If we are composing extended qualifiers together, merge together
2183 // into one ExtQuals node.
2184 QualifierCollector Quals;
2185 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall8ccfcb52009-09-24 19:53:00 +00002187 // If this type already has an address space specified, it cannot get
2188 // another one.
2189 assert(!Quals.hasAddressSpace() &&
2190 "Type cannot be in multiple addr spaces!");
2191 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002192
John McCall8ccfcb52009-09-24 19:53:00 +00002193 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002194}
2195
Chris Lattnerd60183d2009-02-18 22:53:11 +00002196QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002197 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002198 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002199 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002200 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002201
John McCall53fa7142010-12-24 02:08:15 +00002202 if (const PointerType *ptr = T->getAs<PointerType>()) {
2203 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002204 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002205 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2206 return getPointerType(ResultType);
2207 }
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
John McCall8ccfcb52009-09-24 19:53:00 +00002210 // If we are composing extended qualifiers together, merge together
2211 // into one ExtQuals node.
2212 QualifierCollector Quals;
2213 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002214
John McCall8ccfcb52009-09-24 19:53:00 +00002215 // If this type already has an ObjCGC specified, it cannot get
2216 // another one.
2217 assert(!Quals.hasObjCGCAttr() &&
2218 "Type cannot have multiple ObjCGCs!");
2219 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002220
John McCall8ccfcb52009-09-24 19:53:00 +00002221 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002222}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002223
John McCall4f5019e2010-12-19 02:44:49 +00002224const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2225 FunctionType::ExtInfo Info) {
2226 if (T->getExtInfo() == Info)
2227 return T;
2228
2229 QualType Result;
2230 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002231 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002232 } else {
2233 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2234 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2235 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002236 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002237 }
2238
2239 return cast<FunctionType>(Result.getTypePtr());
2240}
2241
Richard Smith2a7d4812013-05-04 07:00:32 +00002242void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2243 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002244 FD = FD->getMostRecentDecl();
2245 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002246 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2247 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002248 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002249 if (FunctionDecl *Next = FD->getPreviousDecl())
2250 FD = Next;
2251 else
2252 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002253 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002254 if (ASTMutationListener *L = getASTMutationListener())
2255 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002256}
2257
Richard Smith0b3a4622014-11-13 20:01:57 +00002258/// Get a function type and produce the equivalent function type with the
2259/// specified exception specification. Type sugar that can be present on a
2260/// declaration of a function with an exception specification is permitted
2261/// and preserved. Other type sugar (for instance, typedefs) is not.
2262static QualType getFunctionTypeWithExceptionSpec(
2263 ASTContext &Context, QualType Orig,
2264 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2265 // Might have some parens.
2266 if (auto *PT = dyn_cast<ParenType>(Orig))
2267 return Context.getParenType(
2268 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2269
2270 // Might have a calling-convention attribute.
2271 if (auto *AT = dyn_cast<AttributedType>(Orig))
2272 return Context.getAttributedType(
2273 AT->getAttrKind(),
2274 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2275 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2276 ESI));
2277
2278 // Anything else must be a function type. Rebuild it with the new exception
2279 // specification.
2280 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2281 return Context.getFunctionType(
2282 Proto->getReturnType(), Proto->getParamTypes(),
2283 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2284}
2285
2286void ASTContext::adjustExceptionSpec(
2287 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2288 bool AsWritten) {
2289 // Update the type.
2290 QualType Updated =
2291 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2292 FD->setType(Updated);
2293
2294 if (!AsWritten)
2295 return;
2296
2297 // Update the type in the type source information too.
2298 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2299 // If the type and the type-as-written differ, we may need to update
2300 // the type-as-written too.
2301 if (TSInfo->getType() != FD->getType())
2302 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2303
2304 // FIXME: When we get proper type location information for exceptions,
2305 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2306 // up the TypeSourceInfo;
2307 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2308 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2309 "TypeLoc size mismatch from updating exception specification");
2310 TSInfo->overrideType(Updated);
2311 }
2312}
2313
Chris Lattnerc6395932007-06-22 20:56:16 +00002314/// getComplexType - Return the uniqued reference to the type for a complex
2315/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002316QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002317 // Unique pointers, to guarantee there is only one pointer of a particular
2318 // structure.
2319 llvm::FoldingSetNodeID ID;
2320 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002321
Craig Topper36250ad2014-05-12 05:36:57 +00002322 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002323 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2324 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Chris Lattnerc6395932007-06-22 20:56:16 +00002326 // If the pointee type isn't canonical, this won't be a canonical type either,
2327 // so fill in the canonical type field.
2328 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002329 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002330 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002331
Chris Lattnerc6395932007-06-22 20:56:16 +00002332 // Get the new insert position for the node we care about.
2333 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002334 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002335 }
John McCall90d1c2d2009-09-24 23:30:46 +00002336 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002337 Types.push_back(New);
2338 ComplexTypes.InsertNode(New, InsertPos);
2339 return QualType(New, 0);
2340}
2341
Chris Lattner970e54e2006-11-12 00:37:36 +00002342/// getPointerType - Return the uniqued reference to the type for a pointer to
2343/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002344QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002345 // Unique pointers, to guarantee there is only one pointer of a particular
2346 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002347 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002348 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002349
Craig Topper36250ad2014-05-12 05:36:57 +00002350 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002351 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002352 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002353
Chris Lattner7ccecb92006-11-12 08:50:50 +00002354 // If the pointee type isn't canonical, this won't be a canonical type either,
2355 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002356 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002357 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002358 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002359
Bob Wilsonc8541f22013-03-15 17:12:43 +00002360 // Get the new insert position for the node we care about.
2361 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002362 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002363 }
John McCall90d1c2d2009-09-24 23:30:46 +00002364 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002365 Types.push_back(New);
2366 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002367 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002368}
2369
Reid Kleckner0503a872013-12-05 01:23:43 +00002370QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2371 llvm::FoldingSetNodeID ID;
2372 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002373 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002374 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2375 if (AT)
2376 return QualType(AT, 0);
2377
2378 QualType Canonical = getCanonicalType(New);
2379
2380 // Get the new insert position for the node we care about.
2381 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002382 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002383
2384 AT = new (*this, TypeAlignment)
2385 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2386 Types.push_back(AT);
2387 AdjustedTypes.InsertNode(AT, InsertPos);
2388 return QualType(AT, 0);
2389}
2390
Reid Kleckner8a365022013-06-24 17:51:48 +00002391QualType ASTContext::getDecayedType(QualType T) const {
2392 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2393
Reid Kleckner8a365022013-06-24 17:51:48 +00002394 QualType Decayed;
2395
2396 // C99 6.7.5.3p7:
2397 // A declaration of a parameter as "array of type" shall be
2398 // adjusted to "qualified pointer to type", where the type
2399 // qualifiers (if any) are those specified within the [ and ] of
2400 // the array type derivation.
2401 if (T->isArrayType())
2402 Decayed = getArrayDecayedType(T);
2403
2404 // C99 6.7.5.3p8:
2405 // A declaration of a parameter as "function returning type"
2406 // shall be adjusted to "pointer to function returning type", as
2407 // in 6.3.2.1.
2408 if (T->isFunctionType())
2409 Decayed = getPointerType(T);
2410
Reid Kleckner0503a872013-12-05 01:23:43 +00002411 llvm::FoldingSetNodeID ID;
2412 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002413 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002414 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2415 if (AT)
2416 return QualType(AT, 0);
2417
Reid Kleckner8a365022013-06-24 17:51:48 +00002418 QualType Canonical = getCanonicalType(Decayed);
2419
2420 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002421 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002422 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002423
Reid Kleckner0503a872013-12-05 01:23:43 +00002424 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2425 Types.push_back(AT);
2426 AdjustedTypes.InsertNode(AT, InsertPos);
2427 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002428}
2429
Mike Stump11289f42009-09-09 15:08:12 +00002430/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002431/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002432QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002433 assert(T->isFunctionType() && "block of function types only");
2434 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002435 // structure.
2436 llvm::FoldingSetNodeID ID;
2437 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002438
Craig Topper36250ad2014-05-12 05:36:57 +00002439 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002440 if (BlockPointerType *PT =
2441 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2442 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002443
2444 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002445 // type either so fill in the canonical type field.
2446 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002447 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002448 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002449
Steve Naroffec33ed92008-08-27 16:04:49 +00002450 // Get the new insert position for the node we care about.
2451 BlockPointerType *NewIP =
2452 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002453 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002454 }
John McCall90d1c2d2009-09-24 23:30:46 +00002455 BlockPointerType *New
2456 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002457 Types.push_back(New);
2458 BlockPointerTypes.InsertNode(New, InsertPos);
2459 return QualType(New, 0);
2460}
2461
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002462/// getLValueReferenceType - Return the uniqued reference to the type for an
2463/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002464QualType
2465ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002466 assert(getCanonicalType(T) != OverloadTy &&
2467 "Unresolved overloaded function type");
2468
Bill Wendling3708c182007-05-27 10:15:43 +00002469 // Unique pointers, to guarantee there is only one pointer of a particular
2470 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002471 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002472 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002473
Craig Topper36250ad2014-05-12 05:36:57 +00002474 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002475 if (LValueReferenceType *RT =
2476 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002477 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002478
John McCallfc93cf92009-10-22 22:37:11 +00002479 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2480
Bill Wendling3708c182007-05-27 10:15:43 +00002481 // If the referencee type isn't canonical, this won't be a canonical type
2482 // either, so fill in the canonical type field.
2483 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002484 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2485 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2486 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002487
Bill Wendling3708c182007-05-27 10:15:43 +00002488 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002489 LValueReferenceType *NewIP =
2490 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002491 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002492 }
2493
John McCall90d1c2d2009-09-24 23:30:46 +00002494 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002495 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2496 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002497 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002498 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002499
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002500 return QualType(New, 0);
2501}
2502
2503/// getRValueReferenceType - Return the uniqued reference to the type for an
2504/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002505QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002506 // Unique pointers, to guarantee there is only one pointer of a particular
2507 // structure.
2508 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002509 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002510
Craig Topper36250ad2014-05-12 05:36:57 +00002511 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002512 if (RValueReferenceType *RT =
2513 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2514 return QualType(RT, 0);
2515
John McCallfc93cf92009-10-22 22:37:11 +00002516 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2517
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002518 // If the referencee type isn't canonical, this won't be a canonical type
2519 // either, so fill in the canonical type field.
2520 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002521 if (InnerRef || !T.isCanonical()) {
2522 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2523 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002524
2525 // Get the new insert position for the node we care about.
2526 RValueReferenceType *NewIP =
2527 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002528 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002529 }
2530
John McCall90d1c2d2009-09-24 23:30:46 +00002531 RValueReferenceType *New
2532 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002533 Types.push_back(New);
2534 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002535 return QualType(New, 0);
2536}
2537
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002538/// getMemberPointerType - Return the uniqued reference to the type for a
2539/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002540QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002541 // Unique pointers, to guarantee there is only one pointer of a particular
2542 // structure.
2543 llvm::FoldingSetNodeID ID;
2544 MemberPointerType::Profile(ID, T, Cls);
2545
Craig Topper36250ad2014-05-12 05:36:57 +00002546 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002547 if (MemberPointerType *PT =
2548 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2549 return QualType(PT, 0);
2550
2551 // If the pointee or class type isn't canonical, this won't be a canonical
2552 // type either, so fill in the canonical type field.
2553 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002554 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002555 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2556
2557 // Get the new insert position for the node we care about.
2558 MemberPointerType *NewIP =
2559 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002560 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002561 }
John McCall90d1c2d2009-09-24 23:30:46 +00002562 MemberPointerType *New
2563 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002564 Types.push_back(New);
2565 MemberPointerTypes.InsertNode(New, InsertPos);
2566 return QualType(New, 0);
2567}
2568
Mike Stump11289f42009-09-09 15:08:12 +00002569/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002570/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002571QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002572 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002573 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002574 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002575 assert((EltTy->isDependentType() ||
2576 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002577 "Constant array of VLAs is illegal!");
2578
Chris Lattnere2df3f92009-05-13 04:12:56 +00002579 // Convert the array size into a canonical width matching the pointer size for
2580 // the target.
2581 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002582 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002583 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002584
Chris Lattner23b7eb62007-06-15 23:05:46 +00002585 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002586 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002587
Craig Topper36250ad2014-05-12 05:36:57 +00002588 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002589 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002590 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002591 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002592
John McCall33ddac02011-01-19 10:06:00 +00002593 // If the element type isn't canonical or has qualifiers, this won't
2594 // be a canonical type either, so fill in the canonical type field.
2595 QualType Canon;
2596 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2597 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002598 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002599 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002600 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002601
Chris Lattner36f8e652007-01-27 08:31:04 +00002602 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002603 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002604 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002605 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002606 }
Mike Stump11289f42009-09-09 15:08:12 +00002607
John McCall90d1c2d2009-09-24 23:30:46 +00002608 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002609 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002610 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002611 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002612 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002613}
2614
John McCall06549462011-01-18 08:40:38 +00002615/// getVariableArrayDecayedType - Turns the given type, which may be
2616/// variably-modified, into the corresponding type with all the known
2617/// sizes replaced with [*].
2618QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2619 // Vastly most common case.
2620 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002621
John McCall06549462011-01-18 08:40:38 +00002622 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002623
John McCall06549462011-01-18 08:40:38 +00002624 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002625 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002626 switch (ty->getTypeClass()) {
2627#define TYPE(Class, Base)
2628#define ABSTRACT_TYPE(Class, Base)
2629#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2630#include "clang/AST/TypeNodes.def"
2631 llvm_unreachable("didn't desugar past all non-canonical types?");
2632
2633 // These types should never be variably-modified.
2634 case Type::Builtin:
2635 case Type::Complex:
2636 case Type::Vector:
2637 case Type::ExtVector:
2638 case Type::DependentSizedExtVector:
2639 case Type::ObjCObject:
2640 case Type::ObjCInterface:
2641 case Type::ObjCObjectPointer:
2642 case Type::Record:
2643 case Type::Enum:
2644 case Type::UnresolvedUsing:
2645 case Type::TypeOfExpr:
2646 case Type::TypeOf:
2647 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002648 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002649 case Type::DependentName:
2650 case Type::InjectedClassName:
2651 case Type::TemplateSpecialization:
2652 case Type::DependentTemplateSpecialization:
2653 case Type::TemplateTypeParm:
2654 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002655 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002656 case Type::PackExpansion:
2657 llvm_unreachable("type should never be variably-modified");
2658
2659 // These types can be variably-modified but should never need to
2660 // further decay.
2661 case Type::FunctionNoProto:
2662 case Type::FunctionProto:
2663 case Type::BlockPointer:
2664 case Type::MemberPointer:
2665 return type;
2666
2667 // These types can be variably-modified. All these modifications
2668 // preserve structure except as noted by comments.
2669 // TODO: if we ever care about optimizing VLAs, there are no-op
2670 // optimizations available here.
2671 case Type::Pointer:
2672 result = getPointerType(getVariableArrayDecayedType(
2673 cast<PointerType>(ty)->getPointeeType()));
2674 break;
2675
2676 case Type::LValueReference: {
2677 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2678 result = getLValueReferenceType(
2679 getVariableArrayDecayedType(lv->getPointeeType()),
2680 lv->isSpelledAsLValue());
2681 break;
2682 }
2683
2684 case Type::RValueReference: {
2685 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2686 result = getRValueReferenceType(
2687 getVariableArrayDecayedType(lv->getPointeeType()));
2688 break;
2689 }
2690
Eli Friedman0dfb8892011-10-06 23:00:33 +00002691 case Type::Atomic: {
2692 const AtomicType *at = cast<AtomicType>(ty);
2693 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2694 break;
2695 }
2696
John McCall06549462011-01-18 08:40:38 +00002697 case Type::ConstantArray: {
2698 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2699 result = getConstantArrayType(
2700 getVariableArrayDecayedType(cat->getElementType()),
2701 cat->getSize(),
2702 cat->getSizeModifier(),
2703 cat->getIndexTypeCVRQualifiers());
2704 break;
2705 }
2706
2707 case Type::DependentSizedArray: {
2708 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2709 result = getDependentSizedArrayType(
2710 getVariableArrayDecayedType(dat->getElementType()),
2711 dat->getSizeExpr(),
2712 dat->getSizeModifier(),
2713 dat->getIndexTypeCVRQualifiers(),
2714 dat->getBracketsRange());
2715 break;
2716 }
2717
2718 // Turn incomplete types into [*] types.
2719 case Type::IncompleteArray: {
2720 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2721 result = getVariableArrayType(
2722 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002723 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002724 ArrayType::Normal,
2725 iat->getIndexTypeCVRQualifiers(),
2726 SourceRange());
2727 break;
2728 }
2729
2730 // Turn VLA types into [*] types.
2731 case Type::VariableArray: {
2732 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2733 result = getVariableArrayType(
2734 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002735 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002736 ArrayType::Star,
2737 vat->getIndexTypeCVRQualifiers(),
2738 vat->getBracketsRange());
2739 break;
2740 }
2741 }
2742
2743 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002744 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002745}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002746
Steve Naroffcadebd02007-08-30 18:14:25 +00002747/// getVariableArrayType - Returns a non-unique reference to the type for a
2748/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002749QualType ASTContext::getVariableArrayType(QualType EltTy,
2750 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002751 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002752 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002753 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002754 // Since we don't unique expressions, it isn't possible to unique VLA's
2755 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002756 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002757
John McCall33ddac02011-01-19 10:06:00 +00002758 // Be sure to pull qualifiers off the element type.
2759 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2760 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002761 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002762 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002763 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002764 }
2765
John McCall90d1c2d2009-09-24 23:30:46 +00002766 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002767 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002768
2769 VariableArrayTypes.push_back(New);
2770 Types.push_back(New);
2771 return QualType(New, 0);
2772}
2773
Douglas Gregor4619e432008-12-05 23:32:09 +00002774/// getDependentSizedArrayType - Returns a non-unique reference to
2775/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002776/// type.
John McCall33ddac02011-01-19 10:06:00 +00002777QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2778 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002779 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002780 unsigned elementTypeQuals,
2781 SourceRange brackets) const {
2782 assert((!numElements || numElements->isTypeDependent() ||
2783 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002784 "Size must be type- or value-dependent!");
2785
John McCall33ddac02011-01-19 10:06:00 +00002786 // Dependently-sized array types that do not have a specified number
2787 // of elements will have their sizes deduced from a dependent
2788 // initializer. We do no canonicalization here at all, which is okay
2789 // because they can't be used in most locations.
2790 if (!numElements) {
2791 DependentSizedArrayType *newType
2792 = new (*this, TypeAlignment)
2793 DependentSizedArrayType(*this, elementType, QualType(),
2794 numElements, ASM, elementTypeQuals,
2795 brackets);
2796 Types.push_back(newType);
2797 return QualType(newType, 0);
2798 }
2799
2800 // Otherwise, we actually build a new type every time, but we
2801 // also build a canonical type.
2802
2803 SplitQualType canonElementType = getCanonicalType(elementType).split();
2804
Craig Topper36250ad2014-05-12 05:36:57 +00002805 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002806 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002807 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002808 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002809 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002810
John McCall33ddac02011-01-19 10:06:00 +00002811 // Look for an existing type with these properties.
2812 DependentSizedArrayType *canonTy =
2813 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002814
John McCall33ddac02011-01-19 10:06:00 +00002815 // If we don't have one, build one.
2816 if (!canonTy) {
2817 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002818 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002819 QualType(), numElements, ASM, elementTypeQuals,
2820 brackets);
2821 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2822 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002823 }
2824
John McCall33ddac02011-01-19 10:06:00 +00002825 // Apply qualifiers from the element type to the array.
2826 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002827 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002828
David Majnemer16a74702015-07-24 05:54:19 +00002829 // If we didn't need extra canonicalization for the element type or the size
2830 // expression, then just use that as our result.
2831 if (QualType(canonElementType.Ty, 0) == elementType &&
2832 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002833 return canon;
2834
2835 // Otherwise, we need to build a type which follows the spelling
2836 // of the element type.
2837 DependentSizedArrayType *sugaredType
2838 = new (*this, TypeAlignment)
2839 DependentSizedArrayType(*this, elementType, canon, numElements,
2840 ASM, elementTypeQuals, brackets);
2841 Types.push_back(sugaredType);
2842 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002843}
2844
John McCall33ddac02011-01-19 10:06:00 +00002845QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002846 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002847 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002848 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002849 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002850
Craig Topper36250ad2014-05-12 05:36:57 +00002851 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002852 if (IncompleteArrayType *iat =
2853 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2854 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002855
2856 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002857 // either, so fill in the canonical type field. We also have to pull
2858 // qualifiers off the element type.
2859 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002860
John McCall33ddac02011-01-19 10:06:00 +00002861 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2862 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002863 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002864 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002865 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002866
2867 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002868 IncompleteArrayType *existing =
2869 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2870 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002871 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002872
John McCall33ddac02011-01-19 10:06:00 +00002873 IncompleteArrayType *newType = new (*this, TypeAlignment)
2874 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002875
John McCall33ddac02011-01-19 10:06:00 +00002876 IncompleteArrayTypes.InsertNode(newType, insertPos);
2877 Types.push_back(newType);
2878 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002879}
2880
Steve Naroff91fcddb2007-07-18 18:00:27 +00002881/// getVectorType - Return the unique reference to a vector type of
2882/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002883QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002884 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002885 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002886
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002887 // Check if we've already instantiated a vector of this type.
2888 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002889 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002890
Craig Topper36250ad2014-05-12 05:36:57 +00002891 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002892 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2893 return QualType(VTP, 0);
2894
2895 // If the element type isn't canonical, this won't be a canonical type either,
2896 // so fill in the canonical type field.
2897 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002898 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002899 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002900
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002901 // Get the new insert position for the node we care about.
2902 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002903 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002904 }
John McCall90d1c2d2009-09-24 23:30:46 +00002905 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002906 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002907 VectorTypes.InsertNode(New, InsertPos);
2908 Types.push_back(New);
2909 return QualType(New, 0);
2910}
2911
Nate Begemance4d7fc2008-04-18 23:10:10 +00002912/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002913/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002914QualType
2915ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002916 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002917
Steve Naroff91fcddb2007-07-18 18:00:27 +00002918 // Check if we've already instantiated a vector of this type.
2919 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002920 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002921 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002922 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002923 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2924 return QualType(VTP, 0);
2925
2926 // If the element type isn't canonical, this won't be a canonical type either,
2927 // so fill in the canonical type field.
2928 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002929 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002930 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002931
Steve Naroff91fcddb2007-07-18 18:00:27 +00002932 // Get the new insert position for the node we care about.
2933 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002935 }
John McCall90d1c2d2009-09-24 23:30:46 +00002936 ExtVectorType *New = new (*this, TypeAlignment)
2937 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002938 VectorTypes.InsertNode(New, InsertPos);
2939 Types.push_back(New);
2940 return QualType(New, 0);
2941}
2942
Jay Foad39c79802011-01-12 09:06:06 +00002943QualType
2944ASTContext::getDependentSizedExtVectorType(QualType vecType,
2945 Expr *SizeExpr,
2946 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002947 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002948 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002949 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Craig Topper36250ad2014-05-12 05:36:57 +00002951 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002952 DependentSizedExtVectorType *Canon
2953 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2954 DependentSizedExtVectorType *New;
2955 if (Canon) {
2956 // We already have a canonical version of this array type; use it as
2957 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002958 New = new (*this, TypeAlignment)
2959 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2960 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002961 } else {
2962 QualType CanonVecTy = getCanonicalType(vecType);
2963 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002964 New = new (*this, TypeAlignment)
2965 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2966 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002967
2968 DependentSizedExtVectorType *CanonCheck
2969 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2970 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2971 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002972 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2973 } else {
2974 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2975 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002976 New = new (*this, TypeAlignment)
2977 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002978 }
2979 }
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregor758a8692009-06-17 21:51:59 +00002981 Types.push_back(New);
2982 return QualType(New, 0);
2983}
2984
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002985/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002986///
Jay Foad39c79802011-01-12 09:06:06 +00002987QualType
2988ASTContext::getFunctionNoProtoType(QualType ResultTy,
2989 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002990 const CallingConv CallConv = Info.getCC();
2991
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002992 // Unique functions, to guarantee there is only one function of a particular
2993 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002994 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002995 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002996
Craig Topper36250ad2014-05-12 05:36:57 +00002997 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002998 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002999 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003000 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003001
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003002 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003003 if (!ResultTy.isCanonical()) {
3004 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattner47955de2007-01-27 08:37:20 +00003006 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003007 FunctionNoProtoType *NewIP =
3008 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003009 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003010 }
Mike Stump11289f42009-09-09 15:08:12 +00003011
Roman Divacky65b88cd2011-03-01 17:40:53 +00003012 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00003013 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00003014 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00003015 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003016 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003017 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003018}
3019
Douglas Gregorcd780372013-01-17 23:36:45 +00003020/// \brief Determine whether \p T is canonical as the result type of a function.
3021static bool isCanonicalResultType(QualType T) {
3022 return T.isCanonical() &&
3023 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3024 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3025}
3026
Douglas Gregora602a152015-10-01 20:20:47 +00003027CanQualType
3028ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3029 CanQualType CanResultType = getCanonicalType(ResultType);
3030
3031 // Canonical result types do not have ARC lifetime qualifiers.
3032 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3033 Qualifiers Qs = CanResultType.getQualifiers();
3034 Qs.removeObjCLifetime();
3035 return CanQualType::CreateUnsafe(
3036 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3037 }
3038
3039 return CanResultType;
3040}
3041
Jay Foad39c79802011-01-12 09:06:06 +00003042QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003043ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003044 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003045 size_t NumArgs = ArgArray.size();
3046
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003047 // Unique functions, to guarantee there is only one function of a particular
3048 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003049 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003050 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3051 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003052
Craig Topper36250ad2014-05-12 05:36:57 +00003053 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003054 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003055 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003056 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003057
3058 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003059 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003060 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003061 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003063 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003064 isCanonical = false;
3065
3066 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003067 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003068 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003069 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003070 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003071 CanonicalArgs.reserve(NumArgs);
3072 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003073 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003074
John McCalldb40c7f2010-12-14 08:05:40 +00003075 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003076 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003077 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003078
Douglas Gregora602a152015-10-01 20:20:47 +00003079 // Adjust the canonical function result type.
3080 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003081 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003082
Chris Lattnerfd4de792007-01-27 01:15:32 +00003083 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003084 FunctionProtoType *NewIP =
3085 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003086 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003087 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003088
John McCall31168b02011-06-15 23:02:42 +00003089 // FunctionProtoType objects are allocated with extra bytes after
3090 // them for three variable size arrays at the end:
3091 // - parameter types
3092 // - exception types
3093 // - consumed-arguments flags
3094 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003095 // expression, or information used to resolve the exception
3096 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003097 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003098 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003099 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3100 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3101 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003102 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003103 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003104 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003105 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003106 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003107 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003108 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003109 Size += NumArgs * sizeof(bool);
3110
John McCalldb40c7f2010-12-14 08:05:40 +00003111 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003112 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003113 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003114 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003115 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003116 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003117}
Chris Lattneref51c202006-11-10 07:17:23 +00003118
John McCalle78aac42010-03-10 03:28:59 +00003119#ifndef NDEBUG
3120static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3121 if (!isa<CXXRecordDecl>(D)) return false;
3122 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3123 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3124 return true;
3125 if (RD->getDescribedClassTemplate() &&
3126 !isa<ClassTemplateSpecializationDecl>(RD))
3127 return true;
3128 return false;
3129}
3130#endif
3131
3132/// getInjectedClassNameType - Return the unique reference to the
3133/// injected class name type for the specified templated declaration.
3134QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003135 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003136 assert(NeedsInjectedClassNameType(Decl));
3137 if (Decl->TypeForDecl) {
3138 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003139 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003140 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3141 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3142 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3143 } else {
John McCall424cec92011-01-19 06:33:43 +00003144 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003145 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003146 Decl->TypeForDecl = newType;
3147 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003148 }
3149 return QualType(Decl->TypeForDecl, 0);
3150}
3151
Douglas Gregor83a586e2008-04-13 21:07:44 +00003152/// getTypeDeclType - Return the unique reference to the type for the
3153/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003154QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003155 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003156 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003157
Richard Smithdda56e42011-04-15 14:24:37 +00003158 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003159 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003160
John McCall96f0b5f2010-03-10 06:48:02 +00003161 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3162 "Template type parameter types are always available.");
3163
John McCall81e38502010-02-16 03:57:14 +00003164 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003165 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003166 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003167 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003168 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003169 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003170 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003171 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003172 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003173 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3174 Decl->TypeForDecl = newType;
3175 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003176 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003177 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003178
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003179 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003180}
3181
Chris Lattner32d920b2007-01-26 02:01:53 +00003182/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003183/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003184QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003185ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3186 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003187 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003188
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003189 if (Canonical.isNull())
3190 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003191 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003192 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003193 Decl->TypeForDecl = newType;
3194 Types.push_back(newType);
3195 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003196}
3197
Jay Foad39c79802011-01-12 09:06:06 +00003198QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003199 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3200
Douglas Gregorec9fd132012-01-14 16:38:05 +00003201 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003202 if (PrevDecl->TypeForDecl)
3203 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3204
John McCall424cec92011-01-19 06:33:43 +00003205 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3206 Decl->TypeForDecl = newType;
3207 Types.push_back(newType);
3208 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003209}
3210
Jay Foad39c79802011-01-12 09:06:06 +00003211QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003212 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3213
Douglas Gregorec9fd132012-01-14 16:38:05 +00003214 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003215 if (PrevDecl->TypeForDecl)
3216 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3217
John McCall424cec92011-01-19 06:33:43 +00003218 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3219 Decl->TypeForDecl = newType;
3220 Types.push_back(newType);
3221 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003222}
3223
John McCall81904512011-01-06 01:58:22 +00003224QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3225 QualType modifiedType,
3226 QualType equivalentType) {
3227 llvm::FoldingSetNodeID id;
3228 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3229
Craig Topper36250ad2014-05-12 05:36:57 +00003230 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003231 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3232 if (type) return QualType(type, 0);
3233
3234 QualType canon = getCanonicalType(equivalentType);
3235 type = new (*this, TypeAlignment)
3236 AttributedType(canon, attrKind, modifiedType, equivalentType);
3237
3238 Types.push_back(type);
3239 AttributedTypes.InsertNode(type, insertPos);
3240
3241 return QualType(type, 0);
3242}
3243
John McCallcebee162009-10-18 09:09:24 +00003244/// \brief Retrieve a substitution-result type.
3245QualType
3246ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003247 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003248 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003249 && "replacement types must always be canonical");
3250
3251 llvm::FoldingSetNodeID ID;
3252 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003253 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003254 SubstTemplateTypeParmType *SubstParm
3255 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3256
3257 if (!SubstParm) {
3258 SubstParm = new (*this, TypeAlignment)
3259 SubstTemplateTypeParmType(Parm, Replacement);
3260 Types.push_back(SubstParm);
3261 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3262 }
3263
3264 return QualType(SubstParm, 0);
3265}
3266
Douglas Gregorada4b792011-01-14 02:55:32 +00003267/// \brief Retrieve a
3268QualType ASTContext::getSubstTemplateTypeParmPackType(
3269 const TemplateTypeParmType *Parm,
3270 const TemplateArgument &ArgPack) {
3271#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003272 for (const auto &P : ArgPack.pack_elements()) {
3273 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3274 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003275 }
3276#endif
3277
3278 llvm::FoldingSetNodeID ID;
3279 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003280 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003281 if (SubstTemplateTypeParmPackType *SubstParm
3282 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3283 return QualType(SubstParm, 0);
3284
3285 QualType Canon;
3286 if (!Parm->isCanonicalUnqualified()) {
3287 Canon = getCanonicalType(QualType(Parm, 0));
3288 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3289 ArgPack);
3290 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3291 }
3292
3293 SubstTemplateTypeParmPackType *SubstParm
3294 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3295 ArgPack);
3296 Types.push_back(SubstParm);
3297 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3298 return QualType(SubstParm, 0);
3299}
3300
Douglas Gregoreff93e02009-02-05 23:33:38 +00003301/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003302/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003303/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003304QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003305 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003306 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003307 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003308 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003309 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003310 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003311 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3312
3313 if (TypeParm)
3314 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003315
Chandler Carruth08836322011-05-01 00:51:33 +00003316 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003317 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003318 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003319
3320 TemplateTypeParmType *TypeCheck
3321 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3322 assert(!TypeCheck && "Template type parameter canonical type broken");
3323 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003324 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003325 TypeParm = new (*this, TypeAlignment)
3326 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003327
3328 Types.push_back(TypeParm);
3329 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3330
3331 return QualType(TypeParm, 0);
3332}
3333
John McCalle78aac42010-03-10 03:28:59 +00003334TypeSourceInfo *
3335ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3336 SourceLocation NameLoc,
3337 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003338 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003339 assert(!Name.getAsDependentTemplateName() &&
3340 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003341 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003342
3343 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003344 TemplateSpecializationTypeLoc TL =
3345 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003346 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003347 TL.setTemplateNameLoc(NameLoc);
3348 TL.setLAngleLoc(Args.getLAngleLoc());
3349 TL.setRAngleLoc(Args.getRAngleLoc());
3350 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3351 TL.setArgLocInfo(i, Args[i].getLocInfo());
3352 return DI;
3353}
3354
Mike Stump11289f42009-09-09 15:08:12 +00003355QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003356ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003357 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003358 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003359 assert(!Template.getAsDependentTemplateName() &&
3360 "No dependent template names here!");
3361
John McCall6b51f282009-11-23 01:53:49 +00003362 unsigned NumArgs = Args.size();
3363
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003364 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003365 ArgVec.reserve(NumArgs);
3366 for (unsigned i = 0; i != NumArgs; ++i)
3367 ArgVec.push_back(Args[i].getArgument());
3368
John McCall2408e322010-04-27 00:57:59 +00003369 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003370 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003371}
3372
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003373#ifndef NDEBUG
3374static bool hasAnyPackExpansions(const TemplateArgument *Args,
3375 unsigned NumArgs) {
3376 for (unsigned I = 0; I != NumArgs; ++I)
3377 if (Args[I].isPackExpansion())
3378 return true;
3379
3380 return true;
3381}
3382#endif
3383
John McCall0ad16662009-10-29 08:12:44 +00003384QualType
3385ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003386 const TemplateArgument *Args,
3387 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003388 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003389 assert(!Template.getAsDependentTemplateName() &&
3390 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003391 // Look through qualified template names.
3392 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3393 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003394
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003395 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003396 Template.getAsTemplateDecl() &&
3397 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003398 QualType CanonType;
3399 if (!Underlying.isNull())
3400 CanonType = getCanonicalType(Underlying);
3401 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003402 // We can get here with an alias template when the specialization contains
3403 // a pack expansion that does not match up with a parameter pack.
3404 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3405 "Caller must compute aliased type");
3406 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003407 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3408 NumArgs);
3409 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003410
Douglas Gregora8e02e72009-07-28 23:00:59 +00003411 // Allocate the (non-canonical) template specialization type, but don't
3412 // try to unique it: these types typically have location information that
3413 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003414 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3415 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003416 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003417 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003418 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003419 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3420 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003421
Douglas Gregor8bf42052009-02-09 18:46:07 +00003422 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003423 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003424}
3425
Mike Stump11289f42009-09-09 15:08:12 +00003426QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003427ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3428 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003429 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003430 assert(!Template.getAsDependentTemplateName() &&
3431 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003432
Douglas Gregore29139c2011-03-03 17:04:51 +00003433 // Look through qualified template names.
3434 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3435 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003436
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003437 // Build the canonical template specialization type.
3438 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003439 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003440 CanonArgs.reserve(NumArgs);
3441 for (unsigned I = 0; I != NumArgs; ++I)
3442 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3443
3444 // Determine whether this canonical template specialization type already
3445 // exists.
3446 llvm::FoldingSetNodeID ID;
3447 TemplateSpecializationType::Profile(ID, CanonTemplate,
3448 CanonArgs.data(), NumArgs, *this);
3449
Craig Topper36250ad2014-05-12 05:36:57 +00003450 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003451 TemplateSpecializationType *Spec
3452 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3453
3454 if (!Spec) {
3455 // Allocate a new canonical template specialization type.
3456 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3457 sizeof(TemplateArgument) * NumArgs),
3458 TypeAlignment);
3459 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3460 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003461 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003462 Types.push_back(Spec);
3463 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3464 }
3465
3466 assert(Spec->isDependentType() &&
3467 "Non-dependent template-id type must have a canonical type");
3468 return QualType(Spec, 0);
3469}
3470
3471QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003472ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3473 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003474 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003475 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003476 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003477
Craig Topper36250ad2014-05-12 05:36:57 +00003478 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003479 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003480 if (T)
3481 return QualType(T, 0);
3482
Douglas Gregorc42075a2010-02-04 18:10:26 +00003483 QualType Canon = NamedType;
3484 if (!Canon.isCanonical()) {
3485 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003486 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003488 (void)CheckT;
3489 }
3490
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003491 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003492 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003493 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003494 return QualType(T, 0);
3495}
3496
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003497QualType
Jay Foad39c79802011-01-12 09:06:06 +00003498ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003499 llvm::FoldingSetNodeID ID;
3500 ParenType::Profile(ID, InnerType);
3501
Craig Topper36250ad2014-05-12 05:36:57 +00003502 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003503 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3504 if (T)
3505 return QualType(T, 0);
3506
3507 QualType Canon = InnerType;
3508 if (!Canon.isCanonical()) {
3509 Canon = getCanonicalType(InnerType);
3510 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3511 assert(!CheckT && "Paren canonical type broken");
3512 (void)CheckT;
3513 }
3514
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003515 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003516 Types.push_back(T);
3517 ParenTypes.InsertNode(T, InsertPos);
3518 return QualType(T, 0);
3519}
3520
Douglas Gregor02085352010-03-31 20:19:30 +00003521QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3522 NestedNameSpecifier *NNS,
3523 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003524 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003525 if (Canon.isNull()) {
3526 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003527 ElaboratedTypeKeyword CanonKeyword = Keyword;
3528 if (Keyword == ETK_None)
3529 CanonKeyword = ETK_Typename;
3530
3531 if (CanonNNS != NNS || CanonKeyword != Keyword)
3532 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003533 }
3534
3535 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003536 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003537
Craig Topper36250ad2014-05-12 05:36:57 +00003538 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003539 DependentNameType *T
3540 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003541 if (T)
3542 return QualType(T, 0);
3543
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003544 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003545 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003546 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003547 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003548}
3549
Mike Stump11289f42009-09-09 15:08:12 +00003550QualType
John McCallc392f372010-06-11 00:33:02 +00003551ASTContext::getDependentTemplateSpecializationType(
3552 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003553 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003554 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003555 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003556 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003557 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003558 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3559 ArgCopy.push_back(Args[I].getArgument());
3560 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3561 ArgCopy.size(),
3562 ArgCopy.data());
3563}
3564
3565QualType
3566ASTContext::getDependentTemplateSpecializationType(
3567 ElaboratedTypeKeyword Keyword,
3568 NestedNameSpecifier *NNS,
3569 const IdentifierInfo *Name,
3570 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003571 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003572 assert((!NNS || NNS->isDependent()) &&
3573 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003574
Douglas Gregorc42075a2010-02-04 18:10:26 +00003575 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003576 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3577 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003578
Craig Topper36250ad2014-05-12 05:36:57 +00003579 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003580 DependentTemplateSpecializationType *T
3581 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003582 if (T)
3583 return QualType(T, 0);
3584
John McCallc392f372010-06-11 00:33:02 +00003585 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003586
John McCallc392f372010-06-11 00:33:02 +00003587 ElaboratedTypeKeyword CanonKeyword = Keyword;
3588 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3589
3590 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003591 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003592 for (unsigned I = 0; I != NumArgs; ++I) {
3593 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3594 if (!CanonArgs[I].structurallyEquals(Args[I]))
3595 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003596 }
3597
John McCallc392f372010-06-11 00:33:02 +00003598 QualType Canon;
3599 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3600 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3601 Name, NumArgs,
3602 CanonArgs.data());
3603
3604 // Find the insert position again.
3605 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3606 }
3607
3608 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3609 sizeof(TemplateArgument) * NumArgs),
3610 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003611 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003612 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003613 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003614 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003615 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003616}
3617
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003618QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003619 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003620 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003621 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003622
3623 assert(Pattern->containsUnexpandedParameterPack() &&
3624 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003625 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003626 PackExpansionType *T
3627 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3628 if (T)
3629 return QualType(T, 0);
3630
3631 QualType Canon;
3632 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003633 Canon = getCanonicalType(Pattern);
3634 // The canonical type might not contain an unexpanded parameter pack, if it
3635 // contains an alias template specialization which ignores one of its
3636 // parameters.
3637 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003638 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003639
Richard Smith68eea502012-07-16 00:20:35 +00003640 // Find the insert position again, in case we inserted an element into
3641 // PackExpansionTypes and invalidated our insert position.
3642 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3643 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003644 }
3645
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003646 T = new (*this, TypeAlignment)
3647 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003648 Types.push_back(T);
3649 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003650 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003651}
3652
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003653/// CmpProtocolNames - Comparison predicate for sorting protocols
3654/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003655static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3656 ObjCProtocolDecl *const *RHS) {
3657 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003658}
3659
John McCall8b07ec22010-05-15 11:32:37 +00003660static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003661 unsigned NumProtocols) {
3662 if (NumProtocols == 0) return true;
3663
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003664 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3665 return false;
3666
John McCallfc93cf92009-10-22 22:37:11 +00003667 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003668 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003669 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003670 return false;
3671 return true;
3672}
3673
Craig Topper6a8c1512015-10-22 01:56:18 +00003674static void
3675SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003676 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003677 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003678
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003679 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003680 for (ObjCProtocolDecl *&P : Protocols)
3681 P = P->getCanonicalDecl();
3682
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003683 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003684 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3685 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003686}
3687
John McCall8b07ec22010-05-15 11:32:37 +00003688QualType ASTContext::getObjCObjectType(QualType BaseType,
3689 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003690 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003691 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003692 llvm::makeArrayRef(Protocols, NumProtocols),
3693 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003694}
3695
3696QualType ASTContext::getObjCObjectType(
3697 QualType baseType,
3698 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003699 ArrayRef<ObjCProtocolDecl *> protocols,
3700 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003701 // If the base type is an interface and there aren't any protocols or
3702 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003703 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3704 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003705 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003706
3707 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003708 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003709 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003710 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003711 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3712 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003713
Douglas Gregore9d95f12015-07-07 03:57:35 +00003714 // Determine the type arguments to be used for canonicalization,
3715 // which may be explicitly specified here or written on the base
3716 // type.
3717 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3718 if (effectiveTypeArgs.empty()) {
3719 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3720 effectiveTypeArgs = baseObject->getTypeArgs();
3721 }
John McCallfc93cf92009-10-22 22:37:11 +00003722
Douglas Gregore9d95f12015-07-07 03:57:35 +00003723 // Build the canonical type, which has the canonical base type and a
3724 // sorted-and-uniqued list of protocols and the type arguments
3725 // canonicalized.
3726 QualType canonical;
3727 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3728 effectiveTypeArgs.end(),
3729 [&](QualType type) {
3730 return type.isCanonical();
3731 });
3732 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3733 protocols.size());
3734 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3735 // Determine the canonical type arguments.
3736 ArrayRef<QualType> canonTypeArgs;
3737 SmallVector<QualType, 4> canonTypeArgsVec;
3738 if (!typeArgsAreCanonical) {
3739 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3740 for (auto typeArg : effectiveTypeArgs)
3741 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3742 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003743 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003744 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003745 }
3746
Douglas Gregore9d95f12015-07-07 03:57:35 +00003747 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3748 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3749 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003750 canonProtocolsVec.append(protocols.begin(), protocols.end());
3751 SortAndUniqueProtocols(canonProtocolsVec);
3752 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003753 } else {
3754 canonProtocols = protocols;
3755 }
3756
3757 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003758 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003759
John McCallfc93cf92009-10-22 22:37:11 +00003760 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003761 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3762 }
3763
Douglas Gregore9d95f12015-07-07 03:57:35 +00003764 unsigned size = sizeof(ObjCObjectTypeImpl);
3765 size += typeArgs.size() * sizeof(QualType);
3766 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3767 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003768 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003769 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3770 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003771
3772 Types.push_back(T);
3773 ObjCObjectTypes.InsertNode(T, InsertPos);
3774 return QualType(T, 0);
3775}
3776
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003777/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3778/// protocol list adopt all protocols in QT's qualified-id protocol
3779/// list.
3780bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3781 ObjCInterfaceDecl *IC) {
3782 if (!QT->isObjCQualifiedIdType())
3783 return false;
3784
3785 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3786 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003787 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003788 if (!IC->ClassImplementsProtocol(Proto, false))
3789 return false;
3790 }
3791 return true;
3792 }
3793 return false;
3794}
3795
3796/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3797/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3798/// of protocols.
3799bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3800 ObjCInterfaceDecl *IDecl) {
3801 if (!QT->isObjCQualifiedIdType())
3802 return false;
3803 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3804 if (!OPT)
3805 return false;
3806 if (!IDecl->hasDefinition())
3807 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003808 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3809 CollectInheritedProtocols(IDecl, InheritedProtocols);
3810 if (InheritedProtocols.empty())
3811 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003812 // Check that if every protocol in list of id<plist> conforms to a protcol
3813 // of IDecl's, then bridge casting is ok.
3814 bool Conforms = false;
3815 for (auto *Proto : OPT->quals()) {
3816 Conforms = false;
3817 for (auto *PI : InheritedProtocols) {
3818 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3819 Conforms = true;
3820 break;
3821 }
3822 }
3823 if (!Conforms)
3824 break;
3825 }
3826 if (Conforms)
3827 return true;
3828
Aaron Ballman83731462014-03-17 16:14:00 +00003829 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003830 // If both the right and left sides have qualifiers.
3831 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003832 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003833 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003834 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003835 break;
3836 }
3837 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003838 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003839 }
3840 return true;
3841}
3842
John McCall8b07ec22010-05-15 11:32:37 +00003843/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3844/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003845QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003846 llvm::FoldingSetNodeID ID;
3847 ObjCObjectPointerType::Profile(ID, ObjectT);
3848
Craig Topper36250ad2014-05-12 05:36:57 +00003849 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003850 if (ObjCObjectPointerType *QT =
3851 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3852 return QualType(QT, 0);
3853
3854 // Find the canonical object type.
3855 QualType Canonical;
3856 if (!ObjectT.isCanonical()) {
3857 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3858
3859 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003860 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3861 }
3862
Douglas Gregorf85bee62010-02-08 22:59:26 +00003863 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003864 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3865 ObjCObjectPointerType *QType =
3866 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003867
Steve Narofffb4330f2009-06-17 22:40:22 +00003868 Types.push_back(QType);
3869 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003870 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003871}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003872
Douglas Gregor1c283312010-08-11 12:19:30 +00003873/// getObjCInterfaceType - Return the unique reference to the type for the
3874/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003875QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3876 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003877 if (Decl->TypeForDecl)
3878 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003879
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003880 if (PrevDecl) {
3881 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3882 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3883 return QualType(PrevDecl->TypeForDecl, 0);
3884 }
3885
Douglas Gregor7671e532011-12-16 16:34:57 +00003886 // Prefer the definition, if there is one.
3887 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3888 Decl = Def;
3889
Douglas Gregor1c283312010-08-11 12:19:30 +00003890 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3891 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3892 Decl->TypeForDecl = T;
3893 Types.push_back(T);
3894 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003895}
3896
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003897/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3898/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003899/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003900/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003901/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003902QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003903 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003904 if (tofExpr->isTypeDependent()) {
3905 llvm::FoldingSetNodeID ID;
3906 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003907
Craig Topper36250ad2014-05-12 05:36:57 +00003908 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003909 DependentTypeOfExprType *Canon
3910 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3911 if (Canon) {
3912 // We already have a "canonical" version of an identical, dependent
3913 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003914 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003915 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003916 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003917 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003918 Canon
3919 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003920 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3921 toe = Canon;
3922 }
3923 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003924 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003925 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003926 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003927 Types.push_back(toe);
3928 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003929}
3930
Steve Naroffa773cd52007-08-01 18:02:17 +00003931/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003932/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003933/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003934/// an issue. This doesn't affect the type checker, since it operates
3935/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003936QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003937 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003938 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003939 Types.push_back(tot);
3940 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003941}
3942
Richard Smith8eb1d322014-06-05 20:13:13 +00003943/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3944/// nodes. This would never be helpful, since each such type has its own
3945/// expression, and would not give a significant memory saving, since there
3946/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003947QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003948 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003949
3950 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003951 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003952 // unique dependent type. Two such decltype-specifiers refer to the same
3953 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003954 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003955 llvm::FoldingSetNodeID ID;
3956 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003957
Craig Topper36250ad2014-05-12 05:36:57 +00003958 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003959 DependentDecltypeType *Canon
3960 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003961 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003962 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003963 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003964 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003965 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003966 dt = new (*this, TypeAlignment)
3967 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003968 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003969 dt = new (*this, TypeAlignment)
3970 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003971 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003972 Types.push_back(dt);
3973 return QualType(dt, 0);
3974}
3975
Alexis Hunte852b102011-05-24 22:41:36 +00003976/// getUnaryTransformationType - We don't unique these, since the memory
3977/// savings are minimal and these are rare.
3978QualType ASTContext::getUnaryTransformType(QualType BaseType,
3979 QualType UnderlyingType,
3980 UnaryTransformType::UTTKind Kind)
3981 const {
3982 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003983 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3984 Kind,
3985 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003986 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003987 Types.push_back(Ty);
3988 return QualType(Ty, 0);
3989}
3990
Richard Smith2a7d4812013-05-04 07:00:32 +00003991/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3992/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3993/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00003994QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003995 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00003996 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003997 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003998
Richard Smith2a7d4812013-05-04 07:00:32 +00003999 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004000 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004001 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004002 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004003 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4004 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004005
Richard Smith74aeef52013-04-26 16:15:35 +00004006 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004007 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004008 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004009 Types.push_back(AT);
4010 if (InsertPos)
4011 AutoTypes.InsertNode(AT, InsertPos);
4012 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004013}
4014
Eli Friedman0dfb8892011-10-06 23:00:33 +00004015/// getAtomicType - Return the uniqued reference to the atomic type for
4016/// the given value type.
4017QualType ASTContext::getAtomicType(QualType T) const {
4018 // Unique pointers, to guarantee there is only one pointer of a particular
4019 // structure.
4020 llvm::FoldingSetNodeID ID;
4021 AtomicType::Profile(ID, T);
4022
Craig Topper36250ad2014-05-12 05:36:57 +00004023 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004024 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4025 return QualType(AT, 0);
4026
4027 // If the atomic value type isn't canonical, this won't be a canonical type
4028 // either, so fill in the canonical type field.
4029 QualType Canonical;
4030 if (!T.isCanonical()) {
4031 Canonical = getAtomicType(getCanonicalType(T));
4032
4033 // Get the new insert position for the node we care about.
4034 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004035 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004036 }
4037 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4038 Types.push_back(New);
4039 AtomicTypes.InsertNode(New, InsertPos);
4040 return QualType(New, 0);
4041}
4042
Richard Smith02e85f32011-04-14 22:09:26 +00004043/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4044QualType ASTContext::getAutoDeductType() const {
4045 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004046 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004047 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004048 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004049 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004050 return AutoDeductTy;
4051}
4052
4053/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4054QualType ASTContext::getAutoRRefDeductType() const {
4055 if (AutoRRefDeductTy.isNull())
4056 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4057 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4058 return AutoRRefDeductTy;
4059}
4060
Chris Lattnerfb072462007-01-23 05:45:31 +00004061/// getTagDeclType - Return the unique reference to the type for the
4062/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004063QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004064 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004065 // FIXME: What is the design on getTagDeclType when it requires casting
4066 // away const? mutable?
4067 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004068}
4069
Mike Stump11289f42009-09-09 15:08:12 +00004070/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4071/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4072/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004073CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004074 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004075}
Chris Lattnerfb072462007-01-23 05:45:31 +00004076
Hans Wennborg27541db2011-10-27 08:29:09 +00004077/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4078CanQualType ASTContext::getIntMaxType() const {
4079 return getFromTargetType(Target->getIntMaxType());
4080}
4081
4082/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4083CanQualType ASTContext::getUIntMaxType() const {
4084 return getFromTargetType(Target->getUIntMaxType());
4085}
4086
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004087/// getSignedWCharType - Return the type of "signed wchar_t".
4088/// Used when in C++, as a GCC extension.
4089QualType ASTContext::getSignedWCharType() const {
4090 // FIXME: derive from "Target" ?
4091 return WCharTy;
4092}
4093
4094/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4095/// Used when in C++, as a GCC extension.
4096QualType ASTContext::getUnsignedWCharType() const {
4097 // FIXME: derive from "Target" ?
4098 return UnsignedIntTy;
4099}
4100
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004101QualType ASTContext::getIntPtrType() const {
4102 return getFromTargetType(Target->getIntPtrType());
4103}
4104
4105QualType ASTContext::getUIntPtrType() const {
4106 return getCorrespondingUnsignedType(getIntPtrType());
4107}
4108
Hans Wennborg27541db2011-10-27 08:29:09 +00004109/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004110/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4111QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004112 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004113}
4114
Eli Friedman4e91899e2012-11-27 02:58:24 +00004115/// \brief Return the unique type for "pid_t" defined in
4116/// <sys/types.h>. We need this to compute the correct type for vfork().
4117QualType ASTContext::getProcessIDType() const {
4118 return getFromTargetType(Target->getProcessIDType());
4119}
4120
Chris Lattnera21ad802008-04-02 05:18:44 +00004121//===----------------------------------------------------------------------===//
4122// Type Operators
4123//===----------------------------------------------------------------------===//
4124
Jay Foad39c79802011-01-12 09:06:06 +00004125CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004126 // Push qualifiers into arrays, and then discard any remaining
4127 // qualifiers.
4128 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004129 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004130 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004131 QualType Result;
4132 if (isa<ArrayType>(Ty)) {
4133 Result = getArrayDecayedType(QualType(Ty,0));
4134 } else if (isa<FunctionType>(Ty)) {
4135 Result = getPointerType(QualType(Ty, 0));
4136 } else {
4137 Result = QualType(Ty, 0);
4138 }
4139
4140 return CanQualType::CreateUnsafe(Result);
4141}
4142
John McCall6c9dd522011-01-18 07:41:22 +00004143QualType ASTContext::getUnqualifiedArrayType(QualType type,
4144 Qualifiers &quals) {
4145 SplitQualType splitType = type.getSplitUnqualifiedType();
4146
4147 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4148 // the unqualified desugared type and then drops it on the floor.
4149 // We then have to strip that sugar back off with
4150 // getUnqualifiedDesugaredType(), which is silly.
4151 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004152 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004153
4154 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004155 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004156 quals = splitType.Quals;
4157 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004158 }
4159
John McCall6c9dd522011-01-18 07:41:22 +00004160 // Otherwise, recurse on the array's element type.
4161 QualType elementType = AT->getElementType();
4162 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4163
4164 // If that didn't change the element type, AT has no qualifiers, so we
4165 // can just use the results in splitType.
4166 if (elementType == unqualElementType) {
4167 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004168 quals = splitType.Quals;
4169 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004170 }
4171
4172 // Otherwise, add in the qualifiers from the outermost type, then
4173 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004174 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004175
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004176 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004177 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004178 CAT->getSizeModifier(), 0);
4179 }
4180
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004181 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004182 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004183 }
4184
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004185 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004186 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004187 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004188 VAT->getSizeModifier(),
4189 VAT->getIndexTypeCVRQualifiers(),
4190 VAT->getBracketsRange());
4191 }
4192
4193 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004194 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004195 DSAT->getSizeModifier(), 0,
4196 SourceRange());
4197}
4198
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004199/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4200/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4201/// they point to and return true. If T1 and T2 aren't pointer types
4202/// or pointer-to-member types, or if they are not similar at this
4203/// level, returns false and leaves T1 and T2 unchanged. Top-level
4204/// qualifiers on T1 and T2 are ignored. This function will typically
4205/// be called in a loop that successively "unwraps" pointer and
4206/// pointer-to-member types to compare them at each level.
4207bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4208 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4209 *T2PtrType = T2->getAs<PointerType>();
4210 if (T1PtrType && T2PtrType) {
4211 T1 = T1PtrType->getPointeeType();
4212 T2 = T2PtrType->getPointeeType();
4213 return true;
4214 }
4215
4216 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4217 *T2MPType = T2->getAs<MemberPointerType>();
4218 if (T1MPType && T2MPType &&
4219 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4220 QualType(T2MPType->getClass(), 0))) {
4221 T1 = T1MPType->getPointeeType();
4222 T2 = T2MPType->getPointeeType();
4223 return true;
4224 }
4225
David Blaikiebbafb8a2012-03-11 07:00:24 +00004226 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004227 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4228 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4229 if (T1OPType && T2OPType) {
4230 T1 = T1OPType->getPointeeType();
4231 T2 = T2OPType->getPointeeType();
4232 return true;
4233 }
4234 }
4235
4236 // FIXME: Block pointers, too?
4237
4238 return false;
4239}
4240
Jay Foad39c79802011-01-12 09:06:06 +00004241DeclarationNameInfo
4242ASTContext::getNameForTemplate(TemplateName Name,
4243 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004244 switch (Name.getKind()) {
4245 case TemplateName::QualifiedTemplate:
4246 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004247 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004248 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4249 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004250
John McCalld9dfe3a2011-06-30 08:33:18 +00004251 case TemplateName::OverloadedTemplate: {
4252 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4253 // DNInfo work in progress: CHECKME: what about DNLoc?
4254 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4255 }
4256
4257 case TemplateName::DependentTemplate: {
4258 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004259 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004260 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004261 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4262 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004263 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004264 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4265 // DNInfo work in progress: FIXME: source locations?
4266 DeclarationNameLoc DNLoc;
4267 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4268 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4269 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004270 }
4271 }
4272
John McCalld9dfe3a2011-06-30 08:33:18 +00004273 case TemplateName::SubstTemplateTemplateParm: {
4274 SubstTemplateTemplateParmStorage *subst
4275 = Name.getAsSubstTemplateTemplateParm();
4276 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4277 NameLoc);
4278 }
4279
4280 case TemplateName::SubstTemplateTemplateParmPack: {
4281 SubstTemplateTemplateParmPackStorage *subst
4282 = Name.getAsSubstTemplateTemplateParmPack();
4283 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4284 NameLoc);
4285 }
4286 }
4287
4288 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004289}
4290
Jay Foad39c79802011-01-12 09:06:06 +00004291TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004292 switch (Name.getKind()) {
4293 case TemplateName::QualifiedTemplate:
4294 case TemplateName::Template: {
4295 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004296 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004297 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004298 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4299
4300 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004301 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004302 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004303
John McCalld9dfe3a2011-06-30 08:33:18 +00004304 case TemplateName::OverloadedTemplate:
4305 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004306
John McCalld9dfe3a2011-06-30 08:33:18 +00004307 case TemplateName::DependentTemplate: {
4308 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4309 assert(DTN && "Non-dependent template names must refer to template decls.");
4310 return DTN->CanonicalTemplateName;
4311 }
4312
4313 case TemplateName::SubstTemplateTemplateParm: {
4314 SubstTemplateTemplateParmStorage *subst
4315 = Name.getAsSubstTemplateTemplateParm();
4316 return getCanonicalTemplateName(subst->getReplacement());
4317 }
4318
4319 case TemplateName::SubstTemplateTemplateParmPack: {
4320 SubstTemplateTemplateParmPackStorage *subst
4321 = Name.getAsSubstTemplateTemplateParmPack();
4322 TemplateTemplateParmDecl *canonParameter
4323 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4324 TemplateArgument canonArgPack
4325 = getCanonicalTemplateArgument(subst->getArgumentPack());
4326 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4327 }
4328 }
4329
4330 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004331}
4332
Douglas Gregoradee3e32009-11-11 23:06:43 +00004333bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4334 X = getCanonicalTemplateName(X);
4335 Y = getCanonicalTemplateName(Y);
4336 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4337}
4338
Mike Stump11289f42009-09-09 15:08:12 +00004339TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004340ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 switch (Arg.getKind()) {
4342 case TemplateArgument::Null:
4343 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004344
Douglas Gregora8e02e72009-07-28 23:00:59 +00004345 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004346 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004347
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004348 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004349 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004350 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004351 }
Mike Stump11289f42009-09-09 15:08:12 +00004352
Eli Friedmanb826a002012-09-26 02:36:12 +00004353 case TemplateArgument::NullPtr:
4354 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4355 /*isNullPtr*/true);
4356
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004357 case TemplateArgument::Template:
4358 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004359
4360 case TemplateArgument::TemplateExpansion:
4361 return TemplateArgument(getCanonicalTemplateName(
4362 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004363 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004364
Douglas Gregora8e02e72009-07-28 23:00:59 +00004365 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004366 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004367
Douglas Gregora8e02e72009-07-28 23:00:59 +00004368 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004369 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004370
Douglas Gregora8e02e72009-07-28 23:00:59 +00004371 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004372 if (Arg.pack_size() == 0)
4373 return Arg;
4374
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004375 TemplateArgument *CanonArgs
4376 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004377 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004378 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004379 AEnd = Arg.pack_end();
4380 A != AEnd; (void)++A, ++Idx)
4381 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004382
Benjamin Kramercce63472015-08-05 09:40:22 +00004383 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004384 }
4385 }
4386
4387 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004388 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004389}
4390
Douglas Gregor333489b2009-03-27 23:10:48 +00004391NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004392ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004393 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004394 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004395
4396 switch (NNS->getKind()) {
4397 case NestedNameSpecifier::Identifier:
4398 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004399 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004400 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4401 NNS->getAsIdentifier());
4402
4403 case NestedNameSpecifier::Namespace:
4404 // A namespace is canonical; build a nested-name-specifier with
4405 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004406 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004407 NNS->getAsNamespace()->getOriginalNamespace());
4408
4409 case NestedNameSpecifier::NamespaceAlias:
4410 // A namespace is canonical; build a nested-name-specifier with
4411 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004412 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004413 NNS->getAsNamespaceAlias()->getNamespace()
4414 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004415
4416 case NestedNameSpecifier::TypeSpec:
4417 case NestedNameSpecifier::TypeSpecWithTemplate: {
4418 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004419
4420 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4421 // break it apart into its prefix and identifier, then reconsititute those
4422 // as the canonical nested-name-specifier. This is required to canonicalize
4423 // a dependent nested-name-specifier involving typedefs of dependent-name
4424 // types, e.g.,
4425 // typedef typename T::type T1;
4426 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004427 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4428 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004429 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004430
Eli Friedman5358a0a2012-03-03 04:09:56 +00004431 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4432 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4433 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004434 return NestedNameSpecifier::Create(*this, nullptr, false,
4435 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004436 }
4437
4438 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004439 case NestedNameSpecifier::Super:
4440 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004441 return NNS;
4442 }
4443
David Blaikie8a40f702012-01-17 06:56:22 +00004444 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004445}
4446
Jay Foad39c79802011-01-12 09:06:06 +00004447const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004448 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004449 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004450 // Handle the common positive case fast.
4451 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4452 return AT;
4453 }
Mike Stump11289f42009-09-09 15:08:12 +00004454
John McCall8ccfcb52009-09-24 19:53:00 +00004455 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004456 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004457 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004458
John McCall8ccfcb52009-09-24 19:53:00 +00004459 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004460 // implements C99 6.7.3p8: "If the specification of an array type includes
4461 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004462
Chris Lattner7adf0762008-08-04 07:31:14 +00004463 // If we get here, we either have type qualifiers on the type, or we have
4464 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004465 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004466
John McCall33ddac02011-01-19 10:06:00 +00004467 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004468 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattner7adf0762008-08-04 07:31:14 +00004470 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004471 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004472 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004473 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004474
Chris Lattner7adf0762008-08-04 07:31:14 +00004475 // Otherwise, we have an array and we have qualifiers on it. Push the
4476 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004477 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004478
Chris Lattner7adf0762008-08-04 07:31:14 +00004479 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4480 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4481 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004482 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004483 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4484 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4485 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004486 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004487
Mike Stump11289f42009-09-09 15:08:12 +00004488 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004489 = dyn_cast<DependentSizedArrayType>(ATy))
4490 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004491 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004492 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004493 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004494 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004495 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004496
Chris Lattner7adf0762008-08-04 07:31:14 +00004497 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004498 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004499 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004500 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004501 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004502 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004503}
4504
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004505QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004506 if (T->isArrayType() || T->isFunctionType())
4507 return getDecayedType(T);
4508 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004509}
4510
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004511QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004512 T = getVariableArrayDecayedType(T);
4513 T = getAdjustedParameterType(T);
4514 return T.getUnqualifiedType();
4515}
4516
David Majnemerd09a51c2015-03-03 01:50:05 +00004517QualType ASTContext::getExceptionObjectType(QualType T) const {
4518 // C++ [except.throw]p3:
4519 // A throw-expression initializes a temporary object, called the exception
4520 // object, the type of which is determined by removing any top-level
4521 // cv-qualifiers from the static type of the operand of throw and adjusting
4522 // the type from "array of T" or "function returning T" to "pointer to T"
4523 // or "pointer to function returning T", [...]
4524 T = getVariableArrayDecayedType(T);
4525 if (T->isArrayType() || T->isFunctionType())
4526 T = getDecayedType(T);
4527 return T.getUnqualifiedType();
4528}
4529
Chris Lattnera21ad802008-04-02 05:18:44 +00004530/// getArrayDecayedType - Return the properly qualified result of decaying the
4531/// specified array type to a pointer. This operation is non-trivial when
4532/// handling typedefs etc. The canonical type of "T" must be an array type,
4533/// this returns a pointer to a properly qualified element of the array.
4534///
4535/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004536QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004537 // Get the element type with 'getAsArrayType' so that we don't lose any
4538 // typedefs in the element type of the array. This also handles propagation
4539 // of type qualifiers from the array type into the element type if present
4540 // (C99 6.7.3p8).
4541 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4542 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattner7adf0762008-08-04 07:31:14 +00004544 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004545
4546 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004547 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004548}
4549
John McCall33ddac02011-01-19 10:06:00 +00004550QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4551 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004552}
4553
John McCall33ddac02011-01-19 10:06:00 +00004554QualType ASTContext::getBaseElementType(QualType type) const {
4555 Qualifiers qs;
4556 while (true) {
4557 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004558 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004559 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall33ddac02011-01-19 10:06:00 +00004561 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004562 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004563 }
Mike Stump11289f42009-09-09 15:08:12 +00004564
John McCall33ddac02011-01-19 10:06:00 +00004565 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004566}
4567
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004568/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004569uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004570ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4571 uint64_t ElementCount = 1;
4572 do {
4573 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004574 CA = dyn_cast_or_null<ConstantArrayType>(
4575 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004576 } while (CA);
4577 return ElementCount;
4578}
4579
Steve Naroff0af91202007-04-27 21:51:21 +00004580/// getFloatingRank - Return a relative rank for floating point types.
4581/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004582static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004583 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004584 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004585
John McCall9dd450b2009-09-21 23:43:11 +00004586 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4587 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004588 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004589 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004590 case BuiltinType::Float: return FloatRank;
4591 case BuiltinType::Double: return DoubleRank;
4592 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004593 }
4594}
4595
Mike Stump11289f42009-09-09 15:08:12 +00004596/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4597/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004598/// 'typeDomain' is a real floating point or complex type.
4599/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004600QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4601 QualType Domain) const {
4602 FloatingRank EltRank = getFloatingRank(Size);
4603 if (Domain->isComplexType()) {
4604 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004605 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004606 case FloatRank: return FloatComplexTy;
4607 case DoubleRank: return DoubleComplexTy;
4608 case LongDoubleRank: return LongDoubleComplexTy;
4609 }
Steve Naroff0af91202007-04-27 21:51:21 +00004610 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004611
4612 assert(Domain->isRealFloatingType() && "Unknown domain!");
4613 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004614 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004615 case FloatRank: return FloatTy;
4616 case DoubleRank: return DoubleTy;
4617 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004618 }
David Blaikief47fa302012-01-17 02:30:50 +00004619 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004620}
4621
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004622/// getFloatingTypeOrder - Compare the rank of the two specified floating
4623/// point types, ignoring the domain of the type (i.e. 'double' ==
4624/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004625/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004626int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004627 FloatingRank LHSR = getFloatingRank(LHS);
4628 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004629
Chris Lattnerb90739d2008-04-06 23:38:49 +00004630 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004631 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004632 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004633 return 1;
4634 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004635}
4636
Chris Lattner76a00cf2008-04-06 22:59:24 +00004637/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4638/// routine will assert if passed a built-in type that isn't an integer or enum,
4639/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004640unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004641 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004642
Chris Lattner76a00cf2008-04-06 22:59:24 +00004643 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004644 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004645 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004646 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004647 case BuiltinType::Char_S:
4648 case BuiltinType::Char_U:
4649 case BuiltinType::SChar:
4650 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004651 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004652 case BuiltinType::Short:
4653 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004654 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004655 case BuiltinType::Int:
4656 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004657 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004658 case BuiltinType::Long:
4659 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004660 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004661 case BuiltinType::LongLong:
4662 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004663 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004664 case BuiltinType::Int128:
4665 case BuiltinType::UInt128:
4666 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004667 }
4668}
4669
Eli Friedman629ffb92009-08-20 04:21:42 +00004670/// \brief Whether this is a promotable bitfield reference according
4671/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4672///
4673/// \returns the type this bit-field will promote to, or NULL if no
4674/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004675QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004676 if (E->isTypeDependent() || E->isValueDependent())
4677 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004678
4679 // FIXME: We should not do this unless E->refersToBitField() is true. This
4680 // matters in C where getSourceBitField() will find bit-fields for various
4681 // cases where the source expression is not a bit-field designator.
4682
John McCalld25db7e2013-05-06 21:39:12 +00004683 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004684 if (!Field)
4685 return QualType();
4686
4687 QualType FT = Field->getType();
4688
Richard Smithcaf33902011-10-10 18:28:20 +00004689 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004690 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004691 // C++ [conv.prom]p5:
4692 // A prvalue for an integral bit-field can be converted to a prvalue of type
4693 // int if int can represent all the values of the bit-field; otherwise, it
4694 // can be converted to unsigned int if unsigned int can represent all the
4695 // values of the bit-field. If the bit-field is larger yet, no integral
4696 // promotion applies to it.
4697 // C11 6.3.1.1/2:
4698 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4699 // If an int can represent all values of the original type (as restricted by
4700 // the width, for a bit-field), the value is converted to an int; otherwise,
4701 // it is converted to an unsigned int.
4702 //
4703 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4704 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004705 if (BitWidth < IntSize)
4706 return IntTy;
4707
4708 if (BitWidth == IntSize)
4709 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4710
4711 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004712 // like the base type. GCC has some weird bugs in this area that we
4713 // deliberately do not follow (GCC follows a pre-standard resolution to
4714 // C's DR315 which treats bit-width as being part of the type, and this leaks
4715 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004716 return QualType();
4717}
4718
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004719/// getPromotedIntegerType - Returns the type that Promotable will
4720/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4721/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004722QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004723 assert(!Promotable.isNull());
4724 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004725 if (const EnumType *ET = Promotable->getAs<EnumType>())
4726 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004727
4728 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4729 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4730 // (3.9.1) can be converted to a prvalue of the first of the following
4731 // types that can represent all the values of its underlying type:
4732 // int, unsigned int, long int, unsigned long int, long long int, or
4733 // unsigned long long int [...]
4734 // FIXME: Is there some better way to compute this?
4735 if (BT->getKind() == BuiltinType::WChar_S ||
4736 BT->getKind() == BuiltinType::WChar_U ||
4737 BT->getKind() == BuiltinType::Char16 ||
4738 BT->getKind() == BuiltinType::Char32) {
4739 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4740 uint64_t FromSize = getTypeSize(BT);
4741 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4742 LongLongTy, UnsignedLongLongTy };
4743 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4744 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4745 if (FromSize < ToSize ||
4746 (FromSize == ToSize &&
4747 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4748 return PromoteTypes[Idx];
4749 }
4750 llvm_unreachable("char type should fit into long long");
4751 }
4752 }
4753
4754 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004755 if (Promotable->isSignedIntegerType())
4756 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004757 uint64_t PromotableSize = getIntWidth(Promotable);
4758 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004759 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4760 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4761}
4762
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004763/// \brief Recurses in pointer/array types until it finds an objc retainable
4764/// type and returns its ownership.
4765Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4766 while (!T.isNull()) {
4767 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4768 return T.getObjCLifetime();
4769 if (T->isArrayType())
4770 T = getBaseElementType(T);
4771 else if (const PointerType *PT = T->getAs<PointerType>())
4772 T = PT->getPointeeType();
4773 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004774 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004775 else
4776 break;
4777 }
4778
4779 return Qualifiers::OCL_None;
4780}
4781
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004782static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4783 // Incomplete enum types are not treated as integer types.
4784 // FIXME: In C++, enum types are never integer types.
4785 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4786 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004787 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004788}
4789
Mike Stump11289f42009-09-09 15:08:12 +00004790/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004791/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004792/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004793int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004794 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4795 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004796
4797 // Unwrap enums to their underlying type.
4798 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4799 LHSC = getIntegerTypeForEnum(ET);
4800 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4801 RHSC = getIntegerTypeForEnum(ET);
4802
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004803 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004804
Chris Lattner76a00cf2008-04-06 22:59:24 +00004805 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4806 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004807
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004808 unsigned LHSRank = getIntegerRank(LHSC);
4809 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004810
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004811 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4812 if (LHSRank == RHSRank) return 0;
4813 return LHSRank > RHSRank ? 1 : -1;
4814 }
Mike Stump11289f42009-09-09 15:08:12 +00004815
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004816 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4817 if (LHSUnsigned) {
4818 // If the unsigned [LHS] type is larger, return it.
4819 if (LHSRank >= RHSRank)
4820 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004822 // If the signed type can represent all values of the unsigned type, it
4823 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004824 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004825 return -1;
4826 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004827
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004828 // If the unsigned [RHS] type is larger, return it.
4829 if (RHSRank >= LHSRank)
4830 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004832 // If the signed type can represent all values of the unsigned type, it
4833 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004834 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004835 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004836}
Anders Carlsson98f07902007-08-17 05:31:46 +00004837
Mike Stump11289f42009-09-09 15:08:12 +00004838// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004839QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004840 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004841 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004842 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004843
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004844 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004845
Anders Carlsson98f07902007-08-17 05:31:46 +00004846 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004847 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004848 // int flags;
4849 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004850 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004851 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004852 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004853 FieldTypes[3] = LongTy;
4854
Anders Carlsson98f07902007-08-17 05:31:46 +00004855 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004856 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004857 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004858 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004859 SourceLocation(), nullptr,
4860 FieldTypes[i], /*TInfo=*/nullptr,
4861 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004862 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004863 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004864 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004865 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004866 }
4867
Douglas Gregord5058122010-02-11 01:19:42 +00004868 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004869 }
Mike Stump11289f42009-09-09 15:08:12 +00004870
Anders Carlsson98f07902007-08-17 05:31:46 +00004871 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004872}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004873
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004874QualType ASTContext::getObjCSuperType() const {
4875 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004876 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004877 TUDecl->addDecl(ObjCSuperTypeDecl);
4878 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4879 }
4880 return ObjCSuperType;
4881}
4882
Douglas Gregor512b0772009-04-23 22:29:11 +00004883void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004884 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004885 assert(Rec && "Invalid CFConstantStringType");
4886 CFConstantStringTypeDecl = Rec->getDecl();
4887}
4888
Jay Foad39c79802011-01-12 09:06:06 +00004889QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004890 if (BlockDescriptorType)
4891 return getTagDeclType(BlockDescriptorType);
4892
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004894 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004895 RD = buildImplicitRecord("__block_descriptor");
4896 RD->startDefinition();
4897
Mike Stumpd0153282009-10-20 02:12:22 +00004898 QualType FieldTypes[] = {
4899 UnsignedLongTy,
4900 UnsignedLongTy,
4901 };
4902
Craig Topperd6d31ac2013-07-15 08:24:27 +00004903 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004904 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004905 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004906 };
4907
4908 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004909 FieldDecl *Field = FieldDecl::Create(
4910 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004911 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4912 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004913 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004914 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004915 }
4916
Alp Toker2dea15b2013-12-17 01:22:38 +00004917 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004918
Alp Toker2dea15b2013-12-17 01:22:38 +00004919 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004920
4921 return getTagDeclType(BlockDescriptorType);
4922}
4923
Jay Foad39c79802011-01-12 09:06:06 +00004924QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004925 if (BlockDescriptorExtendedType)
4926 return getTagDeclType(BlockDescriptorExtendedType);
4927
Alp Toker2dea15b2013-12-17 01:22:38 +00004928 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004929 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004930 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4931 RD->startDefinition();
4932
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004933 QualType FieldTypes[] = {
4934 UnsignedLongTy,
4935 UnsignedLongTy,
4936 getPointerType(VoidPtrTy),
4937 getPointerType(VoidPtrTy)
4938 };
4939
Craig Topperd6d31ac2013-07-15 08:24:27 +00004940 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004941 "reserved",
4942 "Size",
4943 "CopyFuncPtr",
4944 "DestroyFuncPtr"
4945 };
4946
4947 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004948 FieldDecl *Field = FieldDecl::Create(
4949 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004950 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4951 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004952 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004953 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004954 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004955 }
4956
Alp Toker2dea15b2013-12-17 01:22:38 +00004957 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004958
Alp Toker2dea15b2013-12-17 01:22:38 +00004959 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004960 return getTagDeclType(BlockDescriptorExtendedType);
4961}
4962
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004963/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4964/// requires copy/dispose. Note that this must match the logic
4965/// in buildByrefHelpers.
4966bool ASTContext::BlockRequiresCopying(QualType Ty,
4967 const VarDecl *D) {
4968 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4969 const Expr *copyExpr = getBlockVarCopyInits(D);
4970 if (!copyExpr && record->hasTrivialDestructor()) return false;
4971
Mike Stump94967902009-10-21 18:16:27 +00004972 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004973 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004974
4975 if (!Ty->isObjCRetainableType()) return false;
4976
4977 Qualifiers qs = Ty.getQualifiers();
4978
4979 // If we have lifetime, that dominates.
4980 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004981 switch (lifetime) {
4982 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4983
4984 // These are just bits as far as the runtime is concerned.
4985 case Qualifiers::OCL_ExplicitNone:
4986 case Qualifiers::OCL_Autoreleasing:
4987 return false;
4988
4989 // Tell the runtime that this is ARC __weak, called by the
4990 // byref routines.
4991 case Qualifiers::OCL_Weak:
4992 // ARC __strong __block variables need to be retained.
4993 case Qualifiers::OCL_Strong:
4994 return true;
4995 }
4996 llvm_unreachable("fell out of lifetime switch!");
4997 }
4998 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4999 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005000}
5001
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005002bool ASTContext::getByrefLifetime(QualType Ty,
5003 Qualifiers::ObjCLifetime &LifeTime,
5004 bool &HasByrefExtendedLayout) const {
5005
5006 if (!getLangOpts().ObjC1 ||
5007 getLangOpts().getGC() != LangOptions::NonGC)
5008 return false;
5009
5010 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005011 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005012 HasByrefExtendedLayout = true;
5013 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005014 } else if ((LifeTime = Ty.getObjCLifetime())) {
5015 // Honor the ARC qualifiers.
5016 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5017 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005018 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005019 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005020 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005021 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005022 return true;
5023}
5024
Douglas Gregorbab8a962011-09-08 01:46:34 +00005025TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5026 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005027 ObjCInstanceTypeDecl =
5028 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005029 return ObjCInstanceTypeDecl;
5030}
5031
Anders Carlsson18acd442007-10-29 06:33:42 +00005032// This returns true if a type has been typedefed to BOOL:
5033// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005034static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005035 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005036 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5037 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005038
Anders Carlssond8499822007-10-29 05:01:08 +00005039 return false;
5040}
5041
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005042/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005043/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005044CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005045 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5046 return CharUnits::Zero();
5047
Ken Dyck40775002010-01-11 17:06:35 +00005048 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005049
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005050 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005051 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005052 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005053 // Treat arrays as pointers, since that's how they're passed in.
5054 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005055 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005056 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005057}
5058
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005059bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005060 return getTargetInfo().getCXXABI().isMicrosoft() &&
5061 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005062 VD->getType()->isIntegralOrEnumerationType() &&
5063 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005064}
5065
Ken Dyck40775002010-01-11 17:06:35 +00005066static inline
5067std::string charUnitsToString(const CharUnits &CU) {
5068 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005069}
5070
John McCall351762c2011-02-07 10:33:21 +00005071/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005072/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005073std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5074 std::string S;
5075
David Chisnall950a9512009-11-17 19:33:30 +00005076 const BlockDecl *Decl = Expr->getBlockDecl();
5077 QualType BlockTy =
5078 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5079 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005080 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005081 getObjCEncodingForMethodParameter(
5082 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5083 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005084 else
Alp Toker314cc812014-01-25 16:55:45 +00005085 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005086 // Compute size of all parameters.
5087 // Start with computing size of a pointer in number of bytes.
5088 // FIXME: There might(should) be a better way of doing this computation!
5089 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005090 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5091 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005092 for (auto PI : Decl->params()) {
5093 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005094 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005095 if (sz.isZero())
5096 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005097 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005098 ParmOffset += sz;
5099 }
5100 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005101 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005102 // Block pointer and offset.
5103 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005104
5105 // Argument types.
5106 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005107 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005108 QualType PType = PVDecl->getOriginalType();
5109 if (const ArrayType *AT =
5110 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5111 // Use array's original type only if it has known number of
5112 // elements.
5113 if (!isa<ConstantArrayType>(AT))
5114 PType = PVDecl->getType();
5115 } else if (PType->isFunctionType())
5116 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005117 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005118 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5119 S, true /*Extended*/);
5120 else
5121 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005122 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005123 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005124 }
John McCall351762c2011-02-07 10:33:21 +00005125
5126 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005127}
5128
Douglas Gregora9d84932011-05-27 01:19:52 +00005129bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005130 std::string& S) {
5131 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005132 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005133 CharUnits ParmOffset;
5134 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005135 for (auto PI : Decl->params()) {
5136 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005137 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005138 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005139 continue;
5140
David Chisnall50e4eba2010-12-30 14:05:53 +00005141 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005142 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005143 ParmOffset += sz;
5144 }
5145 S += charUnitsToString(ParmOffset);
5146 ParmOffset = CharUnits::Zero();
5147
5148 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005149 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005150 QualType PType = PVDecl->getOriginalType();
5151 if (const ArrayType *AT =
5152 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5153 // Use array's original type only if it has known number of
5154 // elements.
5155 if (!isa<ConstantArrayType>(AT))
5156 PType = PVDecl->getType();
5157 } else if (PType->isFunctionType())
5158 PType = PVDecl->getType();
5159 getObjCEncodingForType(PType, S);
5160 S += charUnitsToString(ParmOffset);
5161 ParmOffset += getObjCEncodingTypeSize(PType);
5162 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005163
5164 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005165}
5166
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005167/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5168/// method parameter or return type. If Extended, include class names and
5169/// block object types.
5170void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5171 QualType T, std::string& S,
5172 bool Extended) const {
5173 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5174 getObjCEncodingForTypeQualifier(QT, S);
5175 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005176 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005177 true /*OutermostType*/,
5178 false /*EncodingProperty*/,
5179 false /*StructField*/,
5180 Extended /*EncodeBlockParameters*/,
5181 Extended /*EncodeClassNames*/);
5182}
5183
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005184/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005185/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005186bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005187 std::string& S,
5188 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005189 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005190 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005191 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5192 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005193 // Compute size of all parameters.
5194 // Start with computing size of a pointer in number of bytes.
5195 // FIXME: There might(should) be a better way of doing this computation!
5196 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005197 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005198 // The first two arguments (self and _cmd) are pointers; account for
5199 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005200 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005201 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005202 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005203 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005204 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005205 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005206 continue;
5207
Ken Dyck40775002010-01-11 17:06:35 +00005208 assert (sz.isPositive() &&
5209 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005210 ParmOffset += sz;
5211 }
Ken Dyck40775002010-01-11 17:06:35 +00005212 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005213 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005214 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005215
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005216 // Argument types.
5217 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005218 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005219 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005220 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005221 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005222 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005223 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5224 // Use array's original type only if it has known number of
5225 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005226 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005227 PType = PVDecl->getType();
5228 } else if (PType->isFunctionType())
5229 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005230 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5231 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005232 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005233 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005234 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005235
5236 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005237}
5238
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005239ObjCPropertyImplDecl *
5240ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5241 const ObjCPropertyDecl *PD,
5242 const Decl *Container) const {
5243 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005244 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005245 if (const ObjCCategoryImplDecl *CID =
5246 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005247 for (auto *PID : CID->property_impls())
5248 if (PID->getPropertyDecl() == PD)
5249 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005250 } else {
5251 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5252 for (auto *PID : OID->property_impls())
5253 if (PID->getPropertyDecl() == PD)
5254 return PID;
5255 }
5256 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005257}
5258
Daniel Dunbar4932b362008-08-28 04:38:10 +00005259/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005260/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005261/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5262/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005263/// Property attributes are stored as a comma-delimited C string. The simple
5264/// attributes readonly and bycopy are encoded as single characters. The
5265/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5266/// encoded as single characters, followed by an identifier. Property types
5267/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005268/// these attributes are defined by the following enumeration:
5269/// @code
5270/// enum PropertyAttributes {
5271/// kPropertyReadOnly = 'R', // property is read-only.
5272/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5273/// kPropertyByref = '&', // property is a reference to the value last assigned
5274/// kPropertyDynamic = 'D', // property is dynamic
5275/// kPropertyGetter = 'G', // followed by getter selector name
5276/// kPropertySetter = 'S', // followed by setter selector name
5277/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005278/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005279/// kPropertyWeak = 'W' // 'weak' property
5280/// kPropertyStrong = 'P' // property GC'able
5281/// kPropertyNonAtomic = 'N' // property non-atomic
5282/// };
5283/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005284void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005285 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005286 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005287 // Collect information from the property implementation decl(s).
5288 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005289 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005290
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005291 if (ObjCPropertyImplDecl *PropertyImpDecl =
5292 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5293 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5294 Dynamic = true;
5295 else
5296 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005297 }
5298
5299 // FIXME: This is not very efficient.
5300 S = "T";
5301
5302 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005303 // GCC has some special rules regarding encoding of properties which
5304 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005305 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005306
5307 if (PD->isReadOnly()) {
5308 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005309 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5310 S += ",C";
5311 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5312 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005313 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5314 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005315 } else {
5316 switch (PD->getSetterKind()) {
5317 case ObjCPropertyDecl::Assign: break;
5318 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005319 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005320 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005321 }
5322 }
5323
5324 // It really isn't clear at all what this means, since properties
5325 // are "dynamic by default".
5326 if (Dynamic)
5327 S += ",D";
5328
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005329 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5330 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005331
Daniel Dunbar4932b362008-08-28 04:38:10 +00005332 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5333 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005334 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005335 }
5336
5337 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5338 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005339 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005340 }
5341
5342 if (SynthesizePID) {
5343 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5344 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005345 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005346 }
5347
5348 // FIXME: OBJCGC: weak & strong
5349}
5350
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005351/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005352/// Another legacy compatibility encoding: 32-bit longs are encoded as
5353/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005354/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5355///
5356void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005357 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005358 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005359 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005360 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005361 else
Jay Foad39c79802011-01-12 09:06:06 +00005362 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005363 PointeeTy = IntTy;
5364 }
5365 }
5366}
5367
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005368void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005369 const FieldDecl *Field,
5370 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005371 // We follow the behavior of gcc, expanding structures which are
5372 // directly pointed to, and expanding embedded structures. Note that
5373 // these rules are sufficient to prevent recursive encoding of the
5374 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005375 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005376 true /* outermost type */, false, false,
5377 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005378}
5379
Joe Groff98ac7d22014-07-07 22:25:15 +00005380void ASTContext::getObjCEncodingForPropertyType(QualType T,
5381 std::string& S) const {
5382 // Encode result type.
5383 // GCC has some special rules regarding encoding of properties which
5384 // closely resembles encoding of ivars.
5385 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5386 true /* outermost type */,
5387 true /* encoding property */);
5388}
5389
John McCall393a78d2012-12-20 02:45:14 +00005390static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5391 BuiltinType::Kind kind) {
5392 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005393 case BuiltinType::Void: return 'v';
5394 case BuiltinType::Bool: return 'B';
5395 case BuiltinType::Char_U:
5396 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005397 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005398 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005399 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005400 case BuiltinType::UInt: return 'I';
5401 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005402 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005403 case BuiltinType::UInt128: return 'T';
5404 case BuiltinType::ULongLong: return 'Q';
5405 case BuiltinType::Char_S:
5406 case BuiltinType::SChar: return 'c';
5407 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005408 case BuiltinType::WChar_S:
5409 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005410 case BuiltinType::Int: return 'i';
5411 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005412 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005413 case BuiltinType::LongLong: return 'q';
5414 case BuiltinType::Int128: return 't';
5415 case BuiltinType::Float: return 'f';
5416 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005417 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005418 case BuiltinType::NullPtr: return '*'; // like char*
5419
5420 case BuiltinType::Half:
5421 // FIXME: potentially need @encodes for these!
5422 return ' ';
5423
5424 case BuiltinType::ObjCId:
5425 case BuiltinType::ObjCClass:
5426 case BuiltinType::ObjCSel:
5427 llvm_unreachable("@encoding ObjC primitive type");
5428
5429 // OpenCL and placeholder types don't need @encodings.
5430 case BuiltinType::OCLImage1d:
5431 case BuiltinType::OCLImage1dArray:
5432 case BuiltinType::OCLImage1dBuffer:
5433 case BuiltinType::OCLImage2d:
5434 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005435 case BuiltinType::OCLImage2dDepth:
5436 case BuiltinType::OCLImage2dArrayDepth:
5437 case BuiltinType::OCLImage2dMSAA:
5438 case BuiltinType::OCLImage2dArrayMSAA:
5439 case BuiltinType::OCLImage2dMSAADepth:
5440 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005441 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005442 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005443 case BuiltinType::OCLClkEvent:
5444 case BuiltinType::OCLQueue:
5445 case BuiltinType::OCLNDRange:
5446 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005447 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005448 case BuiltinType::Dependent:
5449#define BUILTIN_TYPE(KIND, ID)
5450#define PLACEHOLDER_TYPE(KIND, ID) \
5451 case BuiltinType::KIND:
5452#include "clang/AST/BuiltinTypes.def"
5453 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005454 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005455 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005456}
5457
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005458static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5459 EnumDecl *Enum = ET->getDecl();
5460
5461 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5462 if (!Enum->isFixed())
5463 return 'i';
5464
5465 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005466 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5467 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005468}
5469
Jay Foad39c79802011-01-12 09:06:06 +00005470static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005471 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005472 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005473 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005474 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5475 // The GNU runtime requires more information; bitfields are encoded as b,
5476 // then the offset (in bits) of the first element, then the type of the
5477 // bitfield, then the size in bits. For example, in this structure:
5478 //
5479 // struct
5480 // {
5481 // int integer;
5482 // int flags:2;
5483 // };
5484 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5485 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5486 // information is not especially sensible, but we're stuck with it for
5487 // compatibility with GCC, although providing it breaks anything that
5488 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005489 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005490 const RecordDecl *RD = FD->getParent();
5491 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005492 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005493 if (const EnumType *ET = T->getAs<EnumType>())
5494 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005495 else {
5496 const BuiltinType *BT = T->castAs<BuiltinType>();
5497 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5498 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005499 }
Richard Smithcaf33902011-10-10 18:28:20 +00005500 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005501}
5502
Daniel Dunbar07d07852009-10-18 21:17:35 +00005503// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005504void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5505 bool ExpandPointedToStructures,
5506 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005507 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005508 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005509 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005510 bool StructField,
5511 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005512 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005513 bool EncodePointerToObjCTypedef,
5514 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005515 CanQualType CT = getCanonicalType(T);
5516 switch (CT->getTypeClass()) {
5517 case Type::Builtin:
5518 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005519 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005520 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005521 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5522 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5523 else
5524 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005525 return;
Mike Stump11289f42009-09-09 15:08:12 +00005526
John McCall393a78d2012-12-20 02:45:14 +00005527 case Type::Complex: {
5528 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005529 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005530 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005531 return;
5532 }
John McCall393a78d2012-12-20 02:45:14 +00005533
5534 case Type::Atomic: {
5535 const AtomicType *AT = T->castAs<AtomicType>();
5536 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005537 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005538 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005539 }
John McCall393a78d2012-12-20 02:45:14 +00005540
5541 // encoding for pointer or reference types.
5542 case Type::Pointer:
5543 case Type::LValueReference:
5544 case Type::RValueReference: {
5545 QualType PointeeTy;
5546 if (isa<PointerType>(CT)) {
5547 const PointerType *PT = T->castAs<PointerType>();
5548 if (PT->isObjCSelType()) {
5549 S += ':';
5550 return;
5551 }
5552 PointeeTy = PT->getPointeeType();
5553 } else {
5554 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5555 }
5556
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005557 bool isReadOnly = false;
5558 // For historical/compatibility reasons, the read-only qualifier of the
5559 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5560 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005561 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005562 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005563 if (OutermostType && T.isConstQualified()) {
5564 isReadOnly = true;
5565 S += 'r';
5566 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005567 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005568 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005569 while (P->getAs<PointerType>())
5570 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005571 if (P.isConstQualified()) {
5572 isReadOnly = true;
5573 S += 'r';
5574 }
5575 }
5576 if (isReadOnly) {
5577 // Another legacy compatibility encoding. Some ObjC qualifier and type
5578 // combinations need to be rearranged.
5579 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005580 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005581 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005582 }
Mike Stump11289f42009-09-09 15:08:12 +00005583
Anders Carlssond8499822007-10-29 05:01:08 +00005584 if (PointeeTy->isCharType()) {
5585 // char pointer types should be encoded as '*' unless it is a
5586 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005587 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005588 S += '*';
5589 return;
5590 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005591 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005592 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5593 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5594 S += '#';
5595 return;
5596 }
5597 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5598 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5599 S += '@';
5600 return;
5601 }
5602 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005603 }
Anders Carlssond8499822007-10-29 05:01:08 +00005604 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005605 getLegacyIntegralTypeEncoding(PointeeTy);
5606
Mike Stump11289f42009-09-09 15:08:12 +00005607 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005608 nullptr, false, false, false, false, false, false,
5609 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005610 return;
5611 }
John McCall393a78d2012-12-20 02:45:14 +00005612
5613 case Type::ConstantArray:
5614 case Type::IncompleteArray:
5615 case Type::VariableArray: {
5616 const ArrayType *AT = cast<ArrayType>(CT);
5617
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005618 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005619 // Incomplete arrays are encoded as a pointer to the array element.
5620 S += '^';
5621
Mike Stump11289f42009-09-09 15:08:12 +00005622 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005623 false, ExpandStructures, FD);
5624 } else {
5625 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005626
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005627 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5628 S += llvm::utostr(CAT->getSize().getZExtValue());
5629 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005630 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005631 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5632 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005633 S += '0';
5634 }
Mike Stump11289f42009-09-09 15:08:12 +00005635
5636 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005637 false, ExpandStructures, FD,
5638 false, false, false, false, false, false,
5639 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005640 S += ']';
5641 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005642 return;
5643 }
Mike Stump11289f42009-09-09 15:08:12 +00005644
John McCall393a78d2012-12-20 02:45:14 +00005645 case Type::FunctionNoProto:
5646 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005647 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005648 return;
Mike Stump11289f42009-09-09 15:08:12 +00005649
John McCall393a78d2012-12-20 02:45:14 +00005650 case Type::Record: {
5651 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005652 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005653 // Anonymous structures print as '?'
5654 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5655 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005656 if (ClassTemplateSpecializationDecl *Spec
5657 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5658 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005659 llvm::raw_string_ostream OS(S);
5660 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005661 TemplateArgs.data(),
5662 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005663 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005664 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005665 } else {
5666 S += '?';
5667 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005668 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005669 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005670 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005671 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005672 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005673 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005674 if (FD) {
5675 S += '"';
5676 S += Field->getNameAsString();
5677 S += '"';
5678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005680 // Special case bit-fields.
5681 if (Field->isBitField()) {
5682 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005683 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005684 } else {
5685 QualType qt = Field->getType();
5686 getLegacyIntegralTypeEncoding(qt);
5687 getObjCEncodingForTypeImpl(qt, S, false, true,
5688 FD, /*OutermostType*/false,
5689 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005690 /*StructField*/true,
5691 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005692 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005693 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005694 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005695 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005696 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005697 return;
5698 }
Mike Stump11289f42009-09-09 15:08:12 +00005699
John McCall393a78d2012-12-20 02:45:14 +00005700 case Type::BlockPointer: {
5701 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005702 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005703 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005704 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005705
5706 S += '<';
5707 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005708 getObjCEncodingForTypeImpl(
5709 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5710 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005711 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5712 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005713 // Block self
5714 S += "@?";
5715 // Block parameters
5716 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005717 for (const auto &I : FPT->param_types())
5718 getObjCEncodingForTypeImpl(
5719 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5720 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005721 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5722 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005723 }
5724 S += '>';
5725 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005726 return;
5727 }
Mike Stump11289f42009-09-09 15:08:12 +00005728
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005729 case Type::ObjCObject: {
5730 // hack to match legacy encoding of *id and *Class
5731 QualType Ty = getObjCObjectPointerType(CT);
5732 if (Ty->isObjCIdType()) {
5733 S += "{objc_object=}";
5734 return;
5735 }
5736 else if (Ty->isObjCClassType()) {
5737 S += "{objc_class=}";
5738 return;
5739 }
5740 }
5741
John McCall393a78d2012-12-20 02:45:14 +00005742 case Type::ObjCInterface: {
5743 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005744 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005745 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005746 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005747 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005748 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005749 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005750 DeepCollectObjCIvars(OI, true, Ivars);
5751 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005752 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005753 if (Field->isBitField())
5754 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005755 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005756 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5757 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005758 EncodePointerToObjCTypedef,
5759 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005760 }
5761 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005762 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005763 }
Mike Stump11289f42009-09-09 15:08:12 +00005764
John McCall393a78d2012-12-20 02:45:14 +00005765 case Type::ObjCObjectPointer: {
5766 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005767 if (OPT->isObjCIdType()) {
5768 S += '@';
5769 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005770 }
Mike Stump11289f42009-09-09 15:08:12 +00005771
Steve Narofff0c86112009-10-28 22:03:49 +00005772 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5773 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5774 // Since this is a binary compatibility issue, need to consult with runtime
5775 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005776 S += '#';
5777 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005778 }
Mike Stump11289f42009-09-09 15:08:12 +00005779
Chris Lattnere7cabb92009-07-13 00:10:46 +00005780 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005781 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005782 ExpandPointedToStructures,
5783 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005784 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005785 // Note that we do extended encoding of protocol qualifer list
5786 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005787 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005788 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005789 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005790 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005791 S += '>';
5792 }
5793 S += '"';
5794 }
5795 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
Chris Lattnere7cabb92009-07-13 00:10:46 +00005798 QualType PointeeTy = OPT->getPointeeType();
5799 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005800 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5801 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005802 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005803 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005804 // {...};
5805 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005806 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005807 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005808 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5809 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5810 DeepCollectObjCIvars(OI, true, Ivars);
5811 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5812 if (cast<FieldDecl>(Ivars[i]) == FD) {
5813 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005814 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005815 S += '}';
5816 return;
5817 }
5818 }
5819 }
Mike Stump11289f42009-09-09 15:08:12 +00005820 getObjCEncodingForTypeImpl(PointeeTy, S,
5821 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005822 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005823 false, false, false, false, false,
5824 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005825 return;
5826 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005827
5828 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005829 if (OPT->getInterfaceDecl() &&
5830 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005831 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005832 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005833 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005834 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005835 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005836 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005837 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005838 S += '"';
5839 }
5840 return;
5841 }
Mike Stump11289f42009-09-09 15:08:12 +00005842
John McCalla9e6e8d2010-05-17 23:56:34 +00005843 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005844 // FIXME: we shoul do better than that. 'M' is available.
5845 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005846 // This matches gcc's encoding, even though technically it is insufficient.
5847 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005848 case Type::Vector:
5849 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005850 // Until we have a coherent encoding of these three types, issue warning.
5851 { if (NotEncodedT)
5852 *NotEncodedT = T;
5853 return;
5854 }
5855
5856 // We could see an undeduced auto type here during error recovery.
5857 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005858 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005859 return;
5860
John McCall393a78d2012-12-20 02:45:14 +00005861#define ABSTRACT_TYPE(KIND, BASE)
5862#define TYPE(KIND, BASE)
5863#define DEPENDENT_TYPE(KIND, BASE) \
5864 case Type::KIND:
5865#define NON_CANONICAL_TYPE(KIND, BASE) \
5866 case Type::KIND:
5867#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5868 case Type::KIND:
5869#include "clang/AST/TypeNodes.def"
5870 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005871 }
John McCall393a78d2012-12-20 02:45:14 +00005872 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005873}
5874
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005875void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5876 std::string &S,
5877 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005878 bool includeVBases,
5879 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005880 assert(RDecl && "Expected non-null RecordDecl");
5881 assert(!RDecl->isUnion() && "Should not be called for unions");
5882 if (!RDecl->getDefinition())
5883 return;
5884
5885 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5886 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5887 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5888
5889 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005890 for (const auto &BI : CXXRec->bases()) {
5891 if (!BI.isVirtual()) {
5892 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005893 if (base->isEmpty())
5894 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005895 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005896 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5897 std::make_pair(offs, base));
5898 }
5899 }
5900 }
5901
5902 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005903 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005904 uint64_t offs = layout.getFieldOffset(i);
5905 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005906 std::make_pair(offs, Field));
5907 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005908 }
5909
5910 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005911 for (const auto &BI : CXXRec->vbases()) {
5912 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005913 if (base->isEmpty())
5914 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005915 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005916 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5917 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005918 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5919 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005920 }
5921 }
5922
5923 CharUnits size;
5924 if (CXXRec) {
5925 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5926 } else {
5927 size = layout.getSize();
5928 }
5929
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005930#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005931 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005932#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005933 std::multimap<uint64_t, NamedDecl *>::iterator
5934 CurLayObj = FieldOrBaseOffsets.begin();
5935
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005936 if (CXXRec && CXXRec->isDynamicClass() &&
5937 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005938 if (FD) {
5939 S += "\"_vptr$";
5940 std::string recname = CXXRec->getNameAsString();
5941 if (recname.empty()) recname = "?";
5942 S += recname;
5943 S += '"';
5944 }
5945 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005946#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005947 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005948#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005949 }
5950
5951 if (!RDecl->hasFlexibleArrayMember()) {
5952 // Mark the end of the structure.
5953 uint64_t offs = toBits(size);
5954 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005955 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005956 }
5957
5958 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005959#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005960 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005961 if (CurOffs < CurLayObj->first) {
5962 uint64_t padding = CurLayObj->first - CurOffs;
5963 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5964 // packing/alignment of members is different that normal, in which case
5965 // the encoding will be out-of-sync with the real layout.
5966 // If the runtime switches to just consider the size of types without
5967 // taking into account alignment, we could make padding explicit in the
5968 // encoding (e.g. using arrays of chars). The encoding strings would be
5969 // longer then though.
5970 CurOffs += padding;
5971 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005972#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005973
5974 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005975 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005976 break; // reached end of structure.
5977
5978 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5979 // We expand the bases without their virtual bases since those are going
5980 // in the initial structure. Note that this differs from gcc which
5981 // expands virtual bases each time one is encountered in the hierarchy,
5982 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005983 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5984 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005985 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005986#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005987 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005988#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005989 } else {
5990 FieldDecl *field = cast<FieldDecl>(dcl);
5991 if (FD) {
5992 S += '"';
5993 S += field->getNameAsString();
5994 S += '"';
5995 }
5996
5997 if (field->isBitField()) {
5998 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005999#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006000 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006001#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006002 } else {
6003 QualType qt = field->getType();
6004 getLegacyIntegralTypeEncoding(qt);
6005 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6006 /*OutermostType*/false,
6007 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006008 /*StructField*/true,
6009 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006010#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006011 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006012#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006013 }
6014 }
6015 }
6016}
6017
Mike Stump11289f42009-09-09 15:08:12 +00006018void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006019 std::string& S) const {
6020 if (QT & Decl::OBJC_TQ_In)
6021 S += 'n';
6022 if (QT & Decl::OBJC_TQ_Inout)
6023 S += 'N';
6024 if (QT & Decl::OBJC_TQ_Out)
6025 S += 'o';
6026 if (QT & Decl::OBJC_TQ_Bycopy)
6027 S += 'O';
6028 if (QT & Decl::OBJC_TQ_Byref)
6029 S += 'R';
6030 if (QT & Decl::OBJC_TQ_Oneway)
6031 S += 'V';
6032}
6033
Douglas Gregor3ea72692011-08-12 05:46:01 +00006034TypedefDecl *ASTContext::getObjCIdDecl() const {
6035 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006036 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006037 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006038 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006039 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006040 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006041}
6042
Douglas Gregor52e02802011-08-12 06:17:30 +00006043TypedefDecl *ASTContext::getObjCSelDecl() const {
6044 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006045 QualType T = getPointerType(ObjCBuiltinSelTy);
6046 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006047 }
6048 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006049}
6050
Douglas Gregor0a586182011-08-12 05:59:41 +00006051TypedefDecl *ASTContext::getObjCClassDecl() const {
6052 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006053 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006054 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006055 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006056 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006057 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006058}
6059
Douglas Gregord53ae832012-01-17 18:09:05 +00006060ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6061 if (!ObjCProtocolClassDecl) {
6062 ObjCProtocolClassDecl
6063 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6064 SourceLocation(),
6065 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006066 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006067 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006068 SourceLocation(), true);
6069 }
6070
6071 return ObjCProtocolClassDecl;
6072}
6073
Meador Inge5d3fb222012-06-16 03:34:49 +00006074//===----------------------------------------------------------------------===//
6075// __builtin_va_list Construction Functions
6076//===----------------------------------------------------------------------===//
6077
Charles Davisc7d5c942015-09-17 20:55:33 +00006078static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6079 StringRef Name) {
6080 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006081 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006082 return Context->buildImplicitTypedef(T, Name);
6083}
6084
6085static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6086 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6087}
6088
6089static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6090 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006091}
6092
6093static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6094 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006095 QualType T = Context->getPointerType(Context->VoidTy);
6096 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006097}
6098
Tim Northover9bb857a2013-01-31 12:13:10 +00006099static TypedefDecl *
6100CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006101 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006102 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006103 if (Context->getLangOpts().CPlusPlus) {
6104 // namespace std { struct __va_list {
6105 NamespaceDecl *NS;
6106 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6107 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006108 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006109 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006110 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006111 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006112 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006113 }
6114
6115 VaListTagDecl->startDefinition();
6116
6117 const size_t NumFields = 5;
6118 QualType FieldTypes[NumFields];
6119 const char *FieldNames[NumFields];
6120
6121 // void *__stack;
6122 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6123 FieldNames[0] = "__stack";
6124
6125 // void *__gr_top;
6126 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6127 FieldNames[1] = "__gr_top";
6128
6129 // void *__vr_top;
6130 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6131 FieldNames[2] = "__vr_top";
6132
6133 // int __gr_offs;
6134 FieldTypes[3] = Context->IntTy;
6135 FieldNames[3] = "__gr_offs";
6136
6137 // int __vr_offs;
6138 FieldTypes[4] = Context->IntTy;
6139 FieldNames[4] = "__vr_offs";
6140
6141 // Create fields
6142 for (unsigned i = 0; i < NumFields; ++i) {
6143 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6144 VaListTagDecl,
6145 SourceLocation(),
6146 SourceLocation(),
6147 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006148 FieldTypes[i], /*TInfo=*/nullptr,
6149 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006150 /*Mutable=*/false,
6151 ICIS_NoInit);
6152 Field->setAccess(AS_public);
6153 VaListTagDecl->addDecl(Field);
6154 }
6155 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006156 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006157 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006158
6159 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006160 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006161}
6162
Meador Inge5d3fb222012-06-16 03:34:49 +00006163static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6164 // typedef struct __va_list_tag {
6165 RecordDecl *VaListTagDecl;
6166
Alp Toker2dea15b2013-12-17 01:22:38 +00006167 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006168 VaListTagDecl->startDefinition();
6169
6170 const size_t NumFields = 5;
6171 QualType FieldTypes[NumFields];
6172 const char *FieldNames[NumFields];
6173
6174 // unsigned char gpr;
6175 FieldTypes[0] = Context->UnsignedCharTy;
6176 FieldNames[0] = "gpr";
6177
6178 // unsigned char fpr;
6179 FieldTypes[1] = Context->UnsignedCharTy;
6180 FieldNames[1] = "fpr";
6181
6182 // unsigned short reserved;
6183 FieldTypes[2] = Context->UnsignedShortTy;
6184 FieldNames[2] = "reserved";
6185
6186 // void* overflow_arg_area;
6187 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6188 FieldNames[3] = "overflow_arg_area";
6189
6190 // void* reg_save_area;
6191 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6192 FieldNames[4] = "reg_save_area";
6193
6194 // Create fields
6195 for (unsigned i = 0; i < NumFields; ++i) {
6196 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6197 SourceLocation(),
6198 SourceLocation(),
6199 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006200 FieldTypes[i], /*TInfo=*/nullptr,
6201 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006202 /*Mutable=*/false,
6203 ICIS_NoInit);
6204 Field->setAccess(AS_public);
6205 VaListTagDecl->addDecl(Field);
6206 }
6207 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006208 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006209 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6210
6211 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006212 TypedefDecl *VaListTagTypedefDecl =
6213 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6214
Meador Inge5d3fb222012-06-16 03:34:49 +00006215 QualType VaListTagTypedefType =
6216 Context->getTypedefType(VaListTagTypedefDecl);
6217
6218 // typedef __va_list_tag __builtin_va_list[1];
6219 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6220 QualType VaListTagArrayType
6221 = Context->getConstantArrayType(VaListTagTypedefType,
6222 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006223 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006224}
6225
6226static TypedefDecl *
6227CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006228 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006229 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006230 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006231 VaListTagDecl->startDefinition();
6232
6233 const size_t NumFields = 4;
6234 QualType FieldTypes[NumFields];
6235 const char *FieldNames[NumFields];
6236
6237 // unsigned gp_offset;
6238 FieldTypes[0] = Context->UnsignedIntTy;
6239 FieldNames[0] = "gp_offset";
6240
6241 // unsigned fp_offset;
6242 FieldTypes[1] = Context->UnsignedIntTy;
6243 FieldNames[1] = "fp_offset";
6244
6245 // void* overflow_arg_area;
6246 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6247 FieldNames[2] = "overflow_arg_area";
6248
6249 // void* reg_save_area;
6250 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6251 FieldNames[3] = "reg_save_area";
6252
6253 // Create fields
6254 for (unsigned i = 0; i < NumFields; ++i) {
6255 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6256 VaListTagDecl,
6257 SourceLocation(),
6258 SourceLocation(),
6259 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006260 FieldTypes[i], /*TInfo=*/nullptr,
6261 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006262 /*Mutable=*/false,
6263 ICIS_NoInit);
6264 Field->setAccess(AS_public);
6265 VaListTagDecl->addDecl(Field);
6266 }
6267 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006268 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006269 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6270
Richard Smith9b88a4c2015-07-27 05:40:23 +00006271 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006272
Richard Smith9b88a4c2015-07-27 05:40:23 +00006273 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006274 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006275 QualType VaListTagArrayType =
6276 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006277 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006278}
6279
6280static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6281 // typedef int __builtin_va_list[4];
6282 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6283 QualType IntArrayType
6284 = Context->getConstantArrayType(Context->IntTy,
6285 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006286 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006287}
6288
Logan Chien57086ce2012-10-10 06:56:20 +00006289static TypedefDecl *
6290CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006291 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006292 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006293 if (Context->getLangOpts().CPlusPlus) {
6294 // namespace std { struct __va_list {
6295 NamespaceDecl *NS;
6296 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6297 Context->getTranslationUnitDecl(),
6298 /*Inline*/false, SourceLocation(),
6299 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006300 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006301 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006302 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006303 }
6304
6305 VaListDecl->startDefinition();
6306
6307 // void * __ap;
6308 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6309 VaListDecl,
6310 SourceLocation(),
6311 SourceLocation(),
6312 &Context->Idents.get("__ap"),
6313 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006314 /*TInfo=*/nullptr,
6315 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006316 /*Mutable=*/false,
6317 ICIS_NoInit);
6318 Field->setAccess(AS_public);
6319 VaListDecl->addDecl(Field);
6320
6321 // };
6322 VaListDecl->completeDefinition();
6323
6324 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006325 QualType T = Context->getRecordType(VaListDecl);
6326 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006327}
6328
Ulrich Weigand47445072013-05-06 16:26:41 +00006329static TypedefDecl *
6330CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006331 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006332 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006333 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006334 VaListTagDecl->startDefinition();
6335
6336 const size_t NumFields = 4;
6337 QualType FieldTypes[NumFields];
6338 const char *FieldNames[NumFields];
6339
6340 // long __gpr;
6341 FieldTypes[0] = Context->LongTy;
6342 FieldNames[0] = "__gpr";
6343
6344 // long __fpr;
6345 FieldTypes[1] = Context->LongTy;
6346 FieldNames[1] = "__fpr";
6347
6348 // void *__overflow_arg_area;
6349 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6350 FieldNames[2] = "__overflow_arg_area";
6351
6352 // void *__reg_save_area;
6353 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6354 FieldNames[3] = "__reg_save_area";
6355
6356 // Create fields
6357 for (unsigned i = 0; i < NumFields; ++i) {
6358 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6359 VaListTagDecl,
6360 SourceLocation(),
6361 SourceLocation(),
6362 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006363 FieldTypes[i], /*TInfo=*/nullptr,
6364 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006365 /*Mutable=*/false,
6366 ICIS_NoInit);
6367 Field->setAccess(AS_public);
6368 VaListTagDecl->addDecl(Field);
6369 }
6370 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006371 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006372 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006373
Richard Smith9b88a4c2015-07-27 05:40:23 +00006374 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006375
6376 // typedef __va_list_tag __builtin_va_list[1];
6377 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006378 QualType VaListTagArrayType =
6379 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006380
Alp Toker56b5cc92013-12-15 10:36:26 +00006381 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006382}
6383
Meador Inge5d3fb222012-06-16 03:34:49 +00006384static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6385 TargetInfo::BuiltinVaListKind Kind) {
6386 switch (Kind) {
6387 case TargetInfo::CharPtrBuiltinVaList:
6388 return CreateCharPtrBuiltinVaListDecl(Context);
6389 case TargetInfo::VoidPtrBuiltinVaList:
6390 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006391 case TargetInfo::AArch64ABIBuiltinVaList:
6392 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006393 case TargetInfo::PowerABIBuiltinVaList:
6394 return CreatePowerABIBuiltinVaListDecl(Context);
6395 case TargetInfo::X86_64ABIBuiltinVaList:
6396 return CreateX86_64ABIBuiltinVaListDecl(Context);
6397 case TargetInfo::PNaClABIBuiltinVaList:
6398 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006399 case TargetInfo::AAPCSABIBuiltinVaList:
6400 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006401 case TargetInfo::SystemZBuiltinVaList:
6402 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006403 }
6404
6405 llvm_unreachable("Unhandled __builtin_va_list type kind");
6406}
6407
6408TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006409 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006410 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006411 assert(BuiltinVaListDecl->isImplicit());
6412 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006413
6414 return BuiltinVaListDecl;
6415}
6416
Richard Smith9b88a4c2015-07-27 05:40:23 +00006417Decl *ASTContext::getVaListTagDecl() const {
6418 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006419 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006420 if (!VaListTagDecl)
6421 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006422
Richard Smith9b88a4c2015-07-27 05:40:23 +00006423 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006424}
6425
Charles Davisc7d5c942015-09-17 20:55:33 +00006426TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6427 if (!BuiltinMSVaListDecl)
6428 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6429
6430 return BuiltinMSVaListDecl;
6431}
6432
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006433void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006434 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006435 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006436
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006437 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006438}
6439
John McCalld28ae272009-12-02 08:04:21 +00006440/// \brief Retrieve the template name that corresponds to a non-empty
6441/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006442TemplateName
6443ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6444 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006445 unsigned size = End - Begin;
6446 assert(size > 1 && "set is not overloaded!");
6447
6448 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6449 size * sizeof(FunctionTemplateDecl*));
6450 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6451
6452 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006453 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006454 NamedDecl *D = *I;
6455 assert(isa<FunctionTemplateDecl>(D) ||
6456 (isa<UsingShadowDecl>(D) &&
6457 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6458 *Storage++ = D;
6459 }
6460
6461 return TemplateName(OT);
6462}
6463
Douglas Gregordc572a32009-03-30 22:58:21 +00006464/// \brief Retrieve the template name that represents a qualified
6465/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006466TemplateName
6467ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6468 bool TemplateKeyword,
6469 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006470 assert(NNS && "Missing nested-name-specifier in qualified template name");
6471
Douglas Gregorc42075a2010-02-04 18:10:26 +00006472 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006473 llvm::FoldingSetNodeID ID;
6474 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6475
Craig Topper36250ad2014-05-12 05:36:57 +00006476 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006477 QualifiedTemplateName *QTN =
6478 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6479 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006480 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6481 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006482 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6483 }
6484
6485 return TemplateName(QTN);
6486}
6487
6488/// \brief Retrieve the template name that represents a dependent
6489/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006490TemplateName
6491ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6492 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006493 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006494 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006495
6496 llvm::FoldingSetNodeID ID;
6497 DependentTemplateName::Profile(ID, NNS, Name);
6498
Craig Topper36250ad2014-05-12 05:36:57 +00006499 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006500 DependentTemplateName *QTN =
6501 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6502
6503 if (QTN)
6504 return TemplateName(QTN);
6505
6506 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6507 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006508 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6509 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006510 } else {
6511 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006512 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6513 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006514 DependentTemplateName *CheckQTN =
6515 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6516 assert(!CheckQTN && "Dependent type name canonicalization broken");
6517 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006518 }
6519
6520 DependentTemplateNames.InsertNode(QTN, InsertPos);
6521 return TemplateName(QTN);
6522}
6523
Douglas Gregor71395fa2009-11-04 00:56:37 +00006524/// \brief Retrieve the template name that represents a dependent
6525/// template name such as \c MetaFun::template operator+.
6526TemplateName
6527ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006528 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006529 assert((!NNS || NNS->isDependent()) &&
6530 "Nested name specifier must be dependent");
6531
6532 llvm::FoldingSetNodeID ID;
6533 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006534
6535 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006536 DependentTemplateName *QTN
6537 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006538
6539 if (QTN)
6540 return TemplateName(QTN);
6541
6542 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6543 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006544 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6545 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006546 } else {
6547 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006548 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6549 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006550
6551 DependentTemplateName *CheckQTN
6552 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6553 assert(!CheckQTN && "Dependent template name canonicalization broken");
6554 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006555 }
6556
6557 DependentTemplateNames.InsertNode(QTN, InsertPos);
6558 return TemplateName(QTN);
6559}
6560
Douglas Gregor5590be02011-01-15 06:45:20 +00006561TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006562ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6563 TemplateName replacement) const {
6564 llvm::FoldingSetNodeID ID;
6565 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006566
6567 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006568 SubstTemplateTemplateParmStorage *subst
6569 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6570
6571 if (!subst) {
6572 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6573 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6574 }
6575
6576 return TemplateName(subst);
6577}
6578
6579TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006580ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6581 const TemplateArgument &ArgPack) const {
6582 ASTContext &Self = const_cast<ASTContext &>(*this);
6583 llvm::FoldingSetNodeID ID;
6584 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006585
6586 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006587 SubstTemplateTemplateParmPackStorage *Subst
6588 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6589
6590 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006591 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006592 ArgPack.pack_size(),
6593 ArgPack.pack_begin());
6594 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6595 }
6596
6597 return TemplateName(Subst);
6598}
6599
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006600/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006601/// TargetInfo, produce the corresponding type. The unsigned @p Type
6602/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006603CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006604 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006605 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006606 case TargetInfo::SignedChar: return SignedCharTy;
6607 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006608 case TargetInfo::SignedShort: return ShortTy;
6609 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6610 case TargetInfo::SignedInt: return IntTy;
6611 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6612 case TargetInfo::SignedLong: return LongTy;
6613 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6614 case TargetInfo::SignedLongLong: return LongLongTy;
6615 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6616 }
6617
David Blaikie83d382b2011-09-23 05:06:16 +00006618 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006619}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006620
6621//===----------------------------------------------------------------------===//
6622// Type Predicates.
6623//===----------------------------------------------------------------------===//
6624
Fariborz Jahanian96207692009-02-18 21:49:28 +00006625/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6626/// garbage collection attribute.
6627///
John McCall553d45a2011-01-12 00:34:59 +00006628Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006629 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006630 return Qualifiers::GCNone;
6631
David Blaikiebbafb8a2012-03-11 07:00:24 +00006632 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006633 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6634
6635 // Default behaviour under objective-C's gc is for ObjC pointers
6636 // (or pointers to them) be treated as though they were declared
6637 // as __strong.
6638 if (GCAttrs == Qualifiers::GCNone) {
6639 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6640 return Qualifiers::Strong;
6641 else if (Ty->isPointerType())
6642 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6643 } else {
6644 // It's not valid to set GC attributes on anything that isn't a
6645 // pointer.
6646#ifndef NDEBUG
6647 QualType CT = Ty->getCanonicalTypeInternal();
6648 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6649 CT = AT->getElementType();
6650 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6651#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006652 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006653 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006654}
6655
Chris Lattner49af6a42008-04-07 06:51:04 +00006656//===----------------------------------------------------------------------===//
6657// Type Compatibility Testing
6658//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006659
Mike Stump11289f42009-09-09 15:08:12 +00006660/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006661/// compatible.
6662static bool areCompatVectorTypes(const VectorType *LHS,
6663 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006664 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006665 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006666 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006667}
6668
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006669bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6670 QualType SecondVec) {
6671 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6672 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6673
6674 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6675 return true;
6676
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006677 // Treat Neon vector types and most AltiVec vector types as if they are the
6678 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006679 const VectorType *First = FirstVec->getAs<VectorType>();
6680 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006681 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006682 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006683 First->getVectorKind() != VectorType::AltiVecPixel &&
6684 First->getVectorKind() != VectorType::AltiVecBool &&
6685 Second->getVectorKind() != VectorType::AltiVecPixel &&
6686 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006687 return true;
6688
6689 return false;
6690}
6691
Steve Naroff8e6aee52009-07-23 01:01:38 +00006692//===----------------------------------------------------------------------===//
6693// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6694//===----------------------------------------------------------------------===//
6695
6696/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6697/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006698bool
6699ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6700 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006701 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006702 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006703 for (auto *PI : rProto->protocols())
6704 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006705 return true;
6706 return false;
6707}
6708
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006709/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6710/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006711bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6712 QualType rhs) {
6713 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6714 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6715 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6716
Aaron Ballman83731462014-03-17 16:14:00 +00006717 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006718 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006719 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006720 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6721 match = true;
6722 break;
6723 }
6724 }
6725 if (!match)
6726 return false;
6727 }
6728 return true;
6729}
6730
Steve Naroff8e6aee52009-07-23 01:01:38 +00006731/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6732/// ObjCQualifiedIDType.
6733bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6734 bool compare) {
6735 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006736 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006737 lhs->isObjCIdType() || lhs->isObjCClassType())
6738 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006739 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006740 rhs->isObjCIdType() || rhs->isObjCClassType())
6741 return true;
6742
6743 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006744 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006745
Steve Naroff8e6aee52009-07-23 01:01:38 +00006746 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006747
Steve Naroff8e6aee52009-07-23 01:01:38 +00006748 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006749 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006750 // make sure we check the class hierarchy.
6751 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006752 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006753 // when comparing an id<P> on lhs with a static type on rhs,
6754 // see if static class implements all of id's protocols, directly or
6755 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006756 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 return false;
6758 }
6759 }
6760 // If there are no qualifiers and no interface, we have an 'id'.
6761 return true;
6762 }
Mike Stump11289f42009-09-09 15:08:12 +00006763 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006764 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006765 bool match = false;
6766
6767 // when comparing an id<P> on lhs with a static type on rhs,
6768 // see if static class implements all of id's protocols, directly or
6769 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006770 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006771 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6772 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6773 match = true;
6774 break;
6775 }
6776 }
Mike Stump11289f42009-09-09 15:08:12 +00006777 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006778 // make sure we check the class hierarchy.
6779 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006780 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006781 // when comparing an id<P> on lhs with a static type on rhs,
6782 // see if static class implements all of id's protocols, directly or
6783 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006784 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006785 match = true;
6786 break;
6787 }
6788 }
6789 }
6790 if (!match)
6791 return false;
6792 }
Mike Stump11289f42009-09-09 15:08:12 +00006793
Steve Naroff8e6aee52009-07-23 01:01:38 +00006794 return true;
6795 }
Mike Stump11289f42009-09-09 15:08:12 +00006796
Steve Naroff8e6aee52009-07-23 01:01:38 +00006797 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6798 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6799
Mike Stump11289f42009-09-09 15:08:12 +00006800 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006801 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006802 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006803 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006804 bool match = false;
6805
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006806 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006807 // see if static class implements all of id's protocols, directly or
6808 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006809 // First, lhs protocols in the qualifier list must be found, direct
6810 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006811 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006812 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6813 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6814 match = true;
6815 break;
6816 }
6817 }
6818 if (!match)
6819 return false;
6820 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006821
6822 // Static class's protocols, or its super class or category protocols
6823 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6824 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6825 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6826 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6827 // This is rather dubious but matches gcc's behavior. If lhs has
6828 // no type qualifier and its class has no static protocol(s)
6829 // assume that it is mismatch.
6830 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6831 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006832 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006833 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006834 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006835 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6836 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6837 match = true;
6838 break;
6839 }
6840 }
6841 if (!match)
6842 return false;
6843 }
6844 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006845 return true;
6846 }
6847 return false;
6848}
6849
Eli Friedman47f77112008-08-22 00:56:42 +00006850/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006851/// compatible for assignment from RHS to LHS. This handles validation of any
6852/// protocol qualifiers on the LHS or RHS.
6853///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006854bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6855 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006856 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6857 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6858
Steve Naroff1329fa02009-07-15 18:40:39 +00006859 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006860 if (LHS->isObjCUnqualifiedIdOrClass() ||
6861 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006862 return true;
6863
Douglas Gregorab209d82015-07-07 03:58:42 +00006864 // Function object that propagates a successful result or handles
6865 // __kindof types.
6866 auto finish = [&](bool succeeded) -> bool {
6867 if (succeeded)
6868 return true;
6869
6870 if (!RHS->isKindOfType())
6871 return false;
6872
6873 // Strip off __kindof and protocol qualifiers, then check whether
6874 // we can assign the other way.
6875 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6876 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6877 };
6878
6879 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6880 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6881 QualType(RHSOPT,0),
6882 false));
6883 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006884
Douglas Gregorab209d82015-07-07 03:58:42 +00006885 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6886 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6887 QualType(RHSOPT,0)));
6888 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006889
John McCall8b07ec22010-05-15 11:32:37 +00006890 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006891 if (LHS->getInterface() && RHS->getInterface()) {
6892 return finish(canAssignObjCInterfaces(LHS, RHS));
6893 }
Mike Stump11289f42009-09-09 15:08:12 +00006894
Steve Naroff8e6aee52009-07-23 01:01:38 +00006895 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006896}
6897
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006898/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006899/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006900/// arguments in block literals. When passed as arguments, passing 'A*' where
6901/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6902/// not OK. For the return type, the opposite is not OK.
6903bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6904 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006905 const ObjCObjectPointerType *RHSOPT,
6906 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006907
6908 // Function object that propagates a successful result or handles
6909 // __kindof types.
6910 auto finish = [&](bool succeeded) -> bool {
6911 if (succeeded)
6912 return true;
6913
6914 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6915 if (!Expected->isKindOfType())
6916 return false;
6917
6918 // Strip off __kindof and protocol qualifiers, then check whether
6919 // we can assign the other way.
6920 return canAssignObjCInterfacesInBlockPointer(
6921 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6922 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6923 BlockReturnType);
6924 };
6925
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006926 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006927 return true;
6928
6929 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006930 return finish(RHSOPT->isObjCBuiltinType() ||
6931 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006932 }
6933
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006934 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006935 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6936 QualType(RHSOPT,0),
6937 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006938
6939 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6940 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6941 if (LHS && RHS) { // We have 2 user-defined types.
6942 if (LHS != RHS) {
6943 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006944 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006945 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006946 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006947 }
6948 else
6949 return true;
6950 }
6951 return false;
6952}
6953
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006954/// Comparison routine for Objective-C protocols to be used with
6955/// llvm::array_pod_sort.
6956static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6957 ObjCProtocolDecl * const *rhs) {
6958 return (*lhs)->getName().compare((*rhs)->getName());
6959
6960}
6961
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006962/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006963/// of protocols inherited from two distinct objective-c pointer objects with
6964/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006965/// It is used to build composite qualifier list of the composite type of
6966/// the conditional expression involving two objective-c pointer objects.
6967static
6968void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006969 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006970 const ObjCObjectPointerType *LHSOPT,
6971 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006972 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006973
John McCall8b07ec22010-05-15 11:32:37 +00006974 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6975 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6976 assert(LHS->getInterface() && "LHS must have an interface base");
6977 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006978
6979 // Add all of the protocols for the LHS.
6980 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6981
6982 // Start with the protocol qualifiers.
6983 for (auto proto : LHS->quals()) {
6984 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006985 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006986
6987 // Also add the protocols associated with the LHS interface.
6988 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6989
6990 // Add all of the protocls for the RHS.
6991 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6992
6993 // Start with the protocol qualifiers.
6994 for (auto proto : RHS->quals()) {
6995 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006996 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006997
6998 // Also add the protocols associated with the RHS interface.
6999 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7000
7001 // Compute the intersection of the collected protocol sets.
7002 for (auto proto : LHSProtocolSet) {
7003 if (RHSProtocolSet.count(proto))
7004 IntersectionSet.push_back(proto);
7005 }
7006
7007 // Compute the set of protocols that is implied by either the common type or
7008 // the protocols within the intersection.
7009 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7010 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7011
7012 // Remove any implied protocols from the list of inherited protocols.
7013 if (!ImpliedProtocols.empty()) {
7014 IntersectionSet.erase(
7015 std::remove_if(IntersectionSet.begin(),
7016 IntersectionSet.end(),
7017 [&](ObjCProtocolDecl *proto) -> bool {
7018 return ImpliedProtocols.count(proto) > 0;
7019 }),
7020 IntersectionSet.end());
7021 }
7022
7023 // Sort the remaining protocols by name.
7024 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7025 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007026}
7027
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007028/// Determine whether the first type is a subtype of the second.
7029static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7030 QualType rhs) {
7031 // Common case: two object pointers.
7032 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7033 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7034 if (lhsOPT && rhsOPT)
7035 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7036
7037 // Two block pointers.
7038 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7039 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7040 if (lhsBlock && rhsBlock)
7041 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7042
7043 // If either is an unqualified 'id' and the other is a block, it's
7044 // acceptable.
7045 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7046 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7047 return true;
7048
7049 return false;
7050}
7051
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007052// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007053static bool sameObjCTypeArgs(ASTContext &ctx,
7054 const ObjCInterfaceDecl *iface,
7055 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007056 ArrayRef<QualType> rhsArgs,
7057 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007058 if (lhsArgs.size() != rhsArgs.size())
7059 return false;
7060
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007061 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007062 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007063 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7064 continue;
7065
7066 switch (typeParams->begin()[i]->getVariance()) {
7067 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007068 if (!stripKindOf ||
7069 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7070 rhsArgs[i].stripObjCKindOfType(ctx))) {
7071 return false;
7072 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007073 break;
7074
7075 case ObjCTypeParamVariance::Covariant:
7076 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7077 return false;
7078 break;
7079
7080 case ObjCTypeParamVariance::Contravariant:
7081 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7082 return false;
7083 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007084 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007085 }
7086
7087 return true;
7088}
7089
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007090QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007091 const ObjCObjectPointerType *Lptr,
7092 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007093 const ObjCObjectType *LHS = Lptr->getObjectType();
7094 const ObjCObjectType *RHS = Rptr->getObjectType();
7095 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7096 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007097
7098 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007099 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007100
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007101 // Follow the left-hand side up the class hierarchy until we either hit a
7102 // root or find the RHS. Record the ancestors in case we don't find it.
7103 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7104 LHSAncestors;
7105 while (true) {
7106 // Record this ancestor. We'll need this if the common type isn't in the
7107 // path from the LHS to the root.
7108 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007109
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007110 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7111 // Get the type arguments.
7112 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7113 bool anyChanges = false;
7114 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7115 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007116 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7117 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007118 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007119 return QualType();
7120 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7121 // If only one has type arguments, the result will not have type
7122 // arguments.
7123 LHSTypeArgs = { };
7124 anyChanges = true;
7125 }
7126
7127 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007128 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007129 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7130 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007131 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007132 anyChanges = true;
7133
7134 // If anything in the LHS will have changed, build a new result type.
7135 if (anyChanges) {
7136 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007137 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7138 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007139 return getObjCObjectPointerType(Result);
7140 }
7141
7142 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007143 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007144
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007145 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007146 QualType LHSSuperType = LHS->getSuperClassType();
7147 if (LHSSuperType.isNull())
7148 break;
7149
7150 LHS = LHSSuperType->castAs<ObjCObjectType>();
7151 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007152
7153 // We didn't find anything by following the LHS to its root; now check
7154 // the RHS against the cached set of ancestors.
7155 while (true) {
7156 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7157 if (KnownLHS != LHSAncestors.end()) {
7158 LHS = KnownLHS->second;
7159
7160 // Get the type arguments.
7161 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7162 bool anyChanges = false;
7163 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7164 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007165 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7166 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007167 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007168 return QualType();
7169 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7170 // If only one has type arguments, the result will not have type
7171 // arguments.
7172 RHSTypeArgs = { };
7173 anyChanges = true;
7174 }
7175
7176 // Compute the intersection of protocols.
7177 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7178 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7179 Protocols);
7180 if (!Protocols.empty())
7181 anyChanges = true;
7182
7183 if (anyChanges) {
7184 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007185 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7186 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007187 return getObjCObjectPointerType(Result);
7188 }
7189
7190 return getObjCObjectPointerType(QualType(RHS, 0));
7191 }
7192
7193 // Find the superclass of the RHS.
7194 QualType RHSSuperType = RHS->getSuperClassType();
7195 if (RHSSuperType.isNull())
7196 break;
7197
7198 RHS = RHSSuperType->castAs<ObjCObjectType>();
7199 }
7200
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007201 return QualType();
7202}
7203
John McCall8b07ec22010-05-15 11:32:37 +00007204bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7205 const ObjCObjectType *RHS) {
7206 assert(LHS->getInterface() && "LHS is not an interface type");
7207 assert(RHS->getInterface() && "RHS is not an interface type");
7208
Chris Lattner49af6a42008-04-07 06:51:04 +00007209 // Verify that the base decls are compatible: the RHS must be a subclass of
7210 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007211 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7212 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7213 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007214 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007215
Douglas Gregore83b9562015-07-07 03:57:53 +00007216 // If the LHS has protocol qualifiers, determine whether all of them are
7217 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7218 // LHS).
7219 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007220 // OK if conversion of LHS to SuperClass results in narrowing of types
7221 // ; i.e., SuperClass may implement at least one of the protocols
7222 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7223 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7224 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7225 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7226 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7227 // qualifiers.
7228 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007229 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007230 // If there is no protocols associated with RHS, it is not a match.
7231 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007232 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007233
7234 for (const auto *LHSProto : LHS->quals()) {
7235 bool SuperImplementsProtocol = false;
7236 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7237 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7238 SuperImplementsProtocol = true;
7239 break;
7240 }
7241 if (!SuperImplementsProtocol)
7242 return false;
7243 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007244 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007245
7246 // If the LHS is specialized, we may need to check type arguments.
7247 if (LHS->isSpecialized()) {
7248 // Follow the superclass chain until we've matched the LHS class in the
7249 // hierarchy. This substitutes type arguments through.
7250 const ObjCObjectType *RHSSuper = RHS;
7251 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7252 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7253
7254 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007255 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007256 !sameObjCTypeArgs(*this, LHS->getInterface(),
7257 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007258 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007259 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007260 }
7261 }
7262
7263 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007264}
7265
Steve Naroffb7605152009-02-12 17:52:19 +00007266bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7267 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007268 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7269 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007270
Steve Naroff7cae42b2009-07-10 23:34:53 +00007271 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007272 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007273
7274 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7275 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007276}
7277
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007278bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7279 return canAssignObjCInterfaces(
7280 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7281 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7282}
7283
Mike Stump11289f42009-09-09 15:08:12 +00007284/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007285/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007286/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007287/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007288bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7289 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007290 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007291 return hasSameType(LHS, RHS);
7292
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007293 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007294}
7295
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007296bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007297 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007298}
7299
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007300bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7301 return !mergeTypes(LHS, RHS, true).isNull();
7302}
7303
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007304/// mergeTransparentUnionType - if T is a transparent union type and a member
7305/// of T is compatible with SubType, return the merged type, else return
7306/// QualType()
7307QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7308 bool OfBlockPointer,
7309 bool Unqualified) {
7310 if (const RecordType *UT = T->getAsUnionType()) {
7311 RecordDecl *UD = UT->getDecl();
7312 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007313 for (const auto *I : UD->fields()) {
7314 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007315 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7316 if (!MT.isNull())
7317 return MT;
7318 }
7319 }
7320 }
7321
7322 return QualType();
7323}
7324
Alp Toker9cacbab2014-01-20 20:26:09 +00007325/// mergeFunctionParameterTypes - merge two types which appear as function
7326/// parameter types
7327QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7328 bool OfBlockPointer,
7329 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007330 // GNU extension: two types are compatible if they appear as a function
7331 // argument, one of the types is a transparent union type and the other
7332 // type is compatible with a union member
7333 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7334 Unqualified);
7335 if (!lmerge.isNull())
7336 return lmerge;
7337
7338 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7339 Unqualified);
7340 if (!rmerge.isNull())
7341 return rmerge;
7342
7343 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7344}
7345
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007346QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007347 bool OfBlockPointer,
7348 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007349 const FunctionType *lbase = lhs->getAs<FunctionType>();
7350 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007351 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7352 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007353 bool allLTypes = true;
7354 bool allRTypes = true;
7355
7356 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007357 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007358 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007359 QualType RHS = rbase->getReturnType();
7360 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007361 bool UnqualifiedResult = Unqualified;
7362 if (!UnqualifiedResult)
7363 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007364 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007365 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007366 else
Alp Toker314cc812014-01-25 16:55:45 +00007367 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007368 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007369 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007370
7371 if (Unqualified)
7372 retType = retType.getUnqualifiedType();
7373
Alp Toker314cc812014-01-25 16:55:45 +00007374 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7375 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007376 if (Unqualified) {
7377 LRetType = LRetType.getUnqualifiedType();
7378 RRetType = RRetType.getUnqualifiedType();
7379 }
7380
7381 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007382 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007383 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007384 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007385
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007386 // FIXME: double check this
7387 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7388 // rbase->getRegParmAttr() != 0 &&
7389 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007390 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7391 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007392
Douglas Gregor8c940862010-01-18 17:14:39 +00007393 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007394 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007395 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007396
John McCall8c6b56f2010-12-15 01:06:38 +00007397 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007398 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7399 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007400 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7401 return QualType();
7402
John McCall31168b02011-06-15 23:02:42 +00007403 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7404 return QualType();
7405
John McCall8c6b56f2010-12-15 01:06:38 +00007406 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7407 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007408
Rafael Espindola8778c282012-11-29 16:09:03 +00007409 if (lbaseInfo.getNoReturn() != NoReturn)
7410 allLTypes = false;
7411 if (rbaseInfo.getNoReturn() != NoReturn)
7412 allRTypes = false;
7413
John McCall31168b02011-06-15 23:02:42 +00007414 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007415
Eli Friedman47f77112008-08-22 00:56:42 +00007416 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007417 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7418 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007419 // Compatible functions must have the same number of parameters
7420 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007421 return QualType();
7422
7423 // Variadic and non-variadic functions aren't compatible
7424 if (lproto->isVariadic() != rproto->isVariadic())
7425 return QualType();
7426
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007427 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7428 return QualType();
7429
Fariborz Jahanian97676972011-09-28 21:52:05 +00007430 if (LangOpts.ObjCAutoRefCount &&
7431 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7432 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007433
7434 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007435 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007436 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7437 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7438 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7439 QualType paramType = mergeFunctionParameterTypes(
7440 lParamType, rParamType, OfBlockPointer, Unqualified);
7441 if (paramType.isNull())
7442 return QualType();
7443
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007444 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007445 paramType = paramType.getUnqualifiedType();
7446
7447 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007448 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007449 lParamType = lParamType.getUnqualifiedType();
7450 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007451 }
Alp Toker601b22c2014-01-21 23:35:24 +00007452
7453 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007454 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007455 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007456 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007457 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007458
Eli Friedman47f77112008-08-22 00:56:42 +00007459 if (allLTypes) return lhs;
7460 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007461
7462 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7463 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007464 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007465 }
7466
7467 if (lproto) allRTypes = false;
7468 if (rproto) allLTypes = false;
7469
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007470 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007471 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007472 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007473 if (proto->isVariadic()) return QualType();
7474 // Check that the types are compatible with the types that
7475 // would result from default argument promotions (C99 6.7.5.3p15).
7476 // The only types actually affected are promotable integer
7477 // types and floats, which would be passed as a different
7478 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007479 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7480 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007481
Eli Friedman448ce402012-08-30 00:44:15 +00007482 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007483 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007484 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7485 paramTy = Enum->getDecl()->getIntegerType();
7486 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007487 return QualType();
7488 }
Alp Toker601b22c2014-01-21 23:35:24 +00007489
7490 if (paramTy->isPromotableIntegerType() ||
7491 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007492 return QualType();
7493 }
7494
7495 if (allLTypes) return lhs;
7496 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007497
7498 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7499 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007500 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007501 }
7502
7503 if (allLTypes) return lhs;
7504 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007505 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007506}
7507
John McCall433c2e62013-03-21 00:10:07 +00007508/// Given that we have an enum type and a non-enum type, try to merge them.
7509static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7510 QualType other, bool isBlockReturnType) {
7511 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7512 // a signed integer type, or an unsigned integer type.
7513 // Compatibility is based on the underlying type, not the promotion
7514 // type.
7515 QualType underlyingType = ET->getDecl()->getIntegerType();
7516 if (underlyingType.isNull()) return QualType();
7517 if (Context.hasSameType(underlyingType, other))
7518 return other;
7519
7520 // In block return types, we're more permissive and accept any
7521 // integral type of the same size.
7522 if (isBlockReturnType && other->isIntegerType() &&
7523 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7524 return other;
7525
7526 return QualType();
7527}
7528
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007529QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007530 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007531 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007532 // C++ [expr]: If an expression initially has the type "reference to T", the
7533 // type is adjusted to "T" prior to any further analysis, the expression
7534 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007535 // expression is an lvalue unless the reference is an rvalue reference and
7536 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007537 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7538 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007539
7540 if (Unqualified) {
7541 LHS = LHS.getUnqualifiedType();
7542 RHS = RHS.getUnqualifiedType();
7543 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007544
Eli Friedman47f77112008-08-22 00:56:42 +00007545 QualType LHSCan = getCanonicalType(LHS),
7546 RHSCan = getCanonicalType(RHS);
7547
7548 // If two types are identical, they are compatible.
7549 if (LHSCan == RHSCan)
7550 return LHS;
7551
John McCall8ccfcb52009-09-24 19:53:00 +00007552 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007553 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7554 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007555 if (LQuals != RQuals) {
7556 // If any of these qualifiers are different, we have a type
7557 // mismatch.
7558 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007559 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7560 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007561 return QualType();
7562
7563 // Exactly one GC qualifier difference is allowed: __strong is
7564 // okay if the other type has no GC qualifier but is an Objective
7565 // C object pointer (i.e. implicitly strong by default). We fix
7566 // this by pretending that the unqualified type was actually
7567 // qualified __strong.
7568 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7569 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7570 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7571
7572 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7573 return QualType();
7574
7575 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7576 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7577 }
7578 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7579 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7580 }
Eli Friedman47f77112008-08-22 00:56:42 +00007581 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007582 }
7583
7584 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007585
Eli Friedmandcca6332009-06-01 01:22:52 +00007586 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7587 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007588
Chris Lattnerfd652912008-01-14 05:45:46 +00007589 // We want to consider the two function types to be the same for these
7590 // comparisons, just force one to the other.
7591 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7592 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007593
7594 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007595 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7596 LHSClass = Type::ConstantArray;
7597 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7598 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007599
John McCall8b07ec22010-05-15 11:32:37 +00007600 // ObjCInterfaces are just specialized ObjCObjects.
7601 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7602 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7603
Nate Begemance4d7fc2008-04-18 23:10:10 +00007604 // Canonicalize ExtVector -> Vector.
7605 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7606 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007607
Chris Lattner95554662008-04-07 05:43:21 +00007608 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007609 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007610 // Note that we only have special rules for turning block enum
7611 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007612 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007613 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007614 }
John McCall9dd450b2009-09-21 23:43:11 +00007615 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007616 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007617 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007618 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007619 if (OfBlockPointer && !BlockReturnType) {
7620 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7621 return LHS;
7622 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7623 return RHS;
7624 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007625
Eli Friedman47f77112008-08-22 00:56:42 +00007626 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007627 }
Eli Friedman47f77112008-08-22 00:56:42 +00007628
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007629 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007630 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007631#define TYPE(Class, Base)
7632#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007633#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007634#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7635#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7636#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007637 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007638
Richard Smith27d807c2013-04-30 13:56:41 +00007639 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007640 case Type::LValueReference:
7641 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007642 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007643 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007644
John McCall8b07ec22010-05-15 11:32:37 +00007645 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007646 case Type::IncompleteArray:
7647 case Type::VariableArray:
7648 case Type::FunctionProto:
7649 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007650 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007651
Chris Lattnerfd652912008-01-14 05:45:46 +00007652 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007653 {
7654 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007655 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7656 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007657 if (Unqualified) {
7658 LHSPointee = LHSPointee.getUnqualifiedType();
7659 RHSPointee = RHSPointee.getUnqualifiedType();
7660 }
7661 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7662 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007663 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007664 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007665 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007666 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007667 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007668 return getPointerType(ResultType);
7669 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007670 case Type::BlockPointer:
7671 {
7672 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007673 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7674 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007675 if (Unqualified) {
7676 LHSPointee = LHSPointee.getUnqualifiedType();
7677 RHSPointee = RHSPointee.getUnqualifiedType();
7678 }
7679 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7680 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007681 if (ResultType.isNull()) return QualType();
7682 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7683 return LHS;
7684 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7685 return RHS;
7686 return getBlockPointerType(ResultType);
7687 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007688 case Type::Atomic:
7689 {
7690 // Merge two pointer types, while trying to preserve typedef info
7691 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7692 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7693 if (Unqualified) {
7694 LHSValue = LHSValue.getUnqualifiedType();
7695 RHSValue = RHSValue.getUnqualifiedType();
7696 }
7697 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7698 Unqualified);
7699 if (ResultType.isNull()) return QualType();
7700 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7701 return LHS;
7702 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7703 return RHS;
7704 return getAtomicType(ResultType);
7705 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007706 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007707 {
7708 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7709 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7710 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7711 return QualType();
7712
7713 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7714 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007715 if (Unqualified) {
7716 LHSElem = LHSElem.getUnqualifiedType();
7717 RHSElem = RHSElem.getUnqualifiedType();
7718 }
7719
7720 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007721 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007722 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7723 return LHS;
7724 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7725 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007726 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7727 ArrayType::ArraySizeModifier(), 0);
7728 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7729 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007730 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7731 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007732 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7733 return LHS;
7734 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7735 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007736 if (LVAT) {
7737 // FIXME: This isn't correct! But tricky to implement because
7738 // the array's size has to be the size of LHS, but the type
7739 // has to be different.
7740 return LHS;
7741 }
7742 if (RVAT) {
7743 // FIXME: This isn't correct! But tricky to implement because
7744 // the array's size has to be the size of RHS, but the type
7745 // has to be different.
7746 return RHS;
7747 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007748 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7749 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007750 return getIncompleteArrayType(ResultType,
7751 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007752 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007753 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007754 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007755 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007756 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007757 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007758 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007759 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007760 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007761 case Type::Complex:
7762 // Distinct complex types are incompatible.
7763 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007764 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007765 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007766 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7767 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007768 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007769 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007770 case Type::ObjCObject: {
7771 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007772 // FIXME: This should be type compatibility, e.g. whether
7773 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007774 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7775 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7776 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007777 return LHS;
7778
Eli Friedman47f77112008-08-22 00:56:42 +00007779 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007780 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007781 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007782 if (OfBlockPointer) {
7783 if (canAssignObjCInterfacesInBlockPointer(
7784 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007785 RHS->getAs<ObjCObjectPointerType>(),
7786 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007787 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007788 return QualType();
7789 }
John McCall9dd450b2009-09-21 23:43:11 +00007790 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7791 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007792 return LHS;
7793
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007794 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007795 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007796 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007797
David Blaikie8a40f702012-01-17 06:56:22 +00007798 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007799}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007800
Fariborz Jahanian97676972011-09-28 21:52:05 +00007801bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7802 const FunctionProtoType *FromFunctionType,
7803 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007804 if (FromFunctionType->hasAnyConsumedParams() !=
7805 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007806 return false;
7807 FunctionProtoType::ExtProtoInfo FromEPI =
7808 FromFunctionType->getExtProtoInfo();
7809 FunctionProtoType::ExtProtoInfo ToEPI =
7810 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007811 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007812 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7813 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007814 return false;
7815 }
7816 return true;
7817}
7818
Chandler Carruth21c90602015-12-30 03:24:14 +00007819void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7820 ObjCLayouts[CD] = nullptr;
7821}
7822
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007823/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7824/// 'RHS' attributes and returns the merged version; including for function
7825/// return types.
7826QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7827 QualType LHSCan = getCanonicalType(LHS),
7828 RHSCan = getCanonicalType(RHS);
7829 // If two types are identical, they are compatible.
7830 if (LHSCan == RHSCan)
7831 return LHS;
7832 if (RHSCan->isFunctionType()) {
7833 if (!LHSCan->isFunctionType())
7834 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007835 QualType OldReturnType =
7836 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007837 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007838 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007839 QualType ResReturnType =
7840 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7841 if (ResReturnType.isNull())
7842 return QualType();
7843 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7844 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7845 // In either case, use OldReturnType to build the new function type.
7846 const FunctionType *F = LHS->getAs<FunctionType>();
7847 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007848 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7849 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007850 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007851 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007852 return ResultType;
7853 }
7854 }
7855 return QualType();
7856 }
7857
7858 // If the qualifiers are different, the types can still be merged.
7859 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7860 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7861 if (LQuals != RQuals) {
7862 // If any of these qualifiers are different, we have a type mismatch.
7863 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7864 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7865 return QualType();
7866
7867 // Exactly one GC qualifier difference is allowed: __strong is
7868 // okay if the other type has no GC qualifier but is an Objective
7869 // C object pointer (i.e. implicitly strong by default). We fix
7870 // this by pretending that the unqualified type was actually
7871 // qualified __strong.
7872 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7873 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7874 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7875
7876 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7877 return QualType();
7878
7879 if (GC_L == Qualifiers::Strong)
7880 return LHS;
7881 if (GC_R == Qualifiers::Strong)
7882 return RHS;
7883 return QualType();
7884 }
7885
7886 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7887 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7888 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7889 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7890 if (ResQT == LHSBaseQT)
7891 return LHS;
7892 if (ResQT == RHSBaseQT)
7893 return RHS;
7894 }
7895 return QualType();
7896}
7897
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007898//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007899// Integer Predicates
7900//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007901
Jay Foad39c79802011-01-12 09:06:06 +00007902unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007903 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007904 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007905 if (T->isBooleanType())
7906 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007907 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007908 return (unsigned)getTypeSize(T);
7909}
7910
Abramo Bagnara13640492012-09-09 10:21:24 +00007911QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007912 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007913
7914 // Turn <4 x signed int> -> <4 x unsigned int>
7915 if (const VectorType *VTy = T->getAs<VectorType>())
7916 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007917 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007918
7919 // For enums, we return the unsigned version of the base type.
7920 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007921 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007922
7923 const BuiltinType *BTy = T->getAs<BuiltinType>();
7924 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007925 switch (BTy->getKind()) {
7926 case BuiltinType::Char_S:
7927 case BuiltinType::SChar:
7928 return UnsignedCharTy;
7929 case BuiltinType::Short:
7930 return UnsignedShortTy;
7931 case BuiltinType::Int:
7932 return UnsignedIntTy;
7933 case BuiltinType::Long:
7934 return UnsignedLongTy;
7935 case BuiltinType::LongLong:
7936 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007937 case BuiltinType::Int128:
7938 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007939 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007940 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007941 }
7942}
7943
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007944ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007945
Richard Smith1fa5d642013-05-11 05:45:24 +00007946void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7947 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007948
7949//===----------------------------------------------------------------------===//
7950// Builtin Type Computation
7951//===----------------------------------------------------------------------===//
7952
7953/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007954/// pointer over the consumed characters. This returns the resultant type. If
7955/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7956/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7957/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007958///
7959/// RequiresICE is filled in on return to indicate whether the value is required
7960/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007961static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007962 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007963 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007964 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007965 // Modifiers.
7966 int HowLong = 0;
7967 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007968 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007969
Chris Lattnerdc226c22010-10-01 22:42:38 +00007970 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007971 bool Done = false;
7972 while (!Done) {
7973 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007974 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007975 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007976 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007977 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007978 case 'S':
7979 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7980 assert(!Signed && "Can't use 'S' modifier multiple times!");
7981 Signed = true;
7982 break;
7983 case 'U':
7984 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007985 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007986 Unsigned = true;
7987 break;
7988 case 'L':
7989 assert(HowLong <= 2 && "Can't have LLLL modifier");
7990 ++HowLong;
7991 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007992 case 'W':
7993 // This modifier represents int64 type.
7994 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7995 switch (Context.getTargetInfo().getInt64Type()) {
7996 default:
7997 llvm_unreachable("Unexpected integer type");
7998 case TargetInfo::SignedLong:
7999 HowLong = 1;
8000 break;
8001 case TargetInfo::SignedLongLong:
8002 HowLong = 2;
8003 break;
8004 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008005 }
8006 }
8007
8008 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008009
Chris Lattnerecd79c62009-06-14 00:45:47 +00008010 // Read the base type.
8011 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008012 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008013 case 'v':
8014 assert(HowLong == 0 && !Signed && !Unsigned &&
8015 "Bad modifiers used with 'v'!");
8016 Type = Context.VoidTy;
8017 break;
Jack Carter24bef982013-08-15 15:16:57 +00008018 case 'h':
8019 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008020 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008021 Type = Context.HalfTy;
8022 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008023 case 'f':
8024 assert(HowLong == 0 && !Signed && !Unsigned &&
8025 "Bad modifiers used with 'f'!");
8026 Type = Context.FloatTy;
8027 break;
8028 case 'd':
8029 assert(HowLong < 2 && !Signed && !Unsigned &&
8030 "Bad modifiers used with 'd'!");
8031 if (HowLong)
8032 Type = Context.LongDoubleTy;
8033 else
8034 Type = Context.DoubleTy;
8035 break;
8036 case 's':
8037 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8038 if (Unsigned)
8039 Type = Context.UnsignedShortTy;
8040 else
8041 Type = Context.ShortTy;
8042 break;
8043 case 'i':
8044 if (HowLong == 3)
8045 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8046 else if (HowLong == 2)
8047 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8048 else if (HowLong == 1)
8049 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8050 else
8051 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8052 break;
8053 case 'c':
8054 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8055 if (Signed)
8056 Type = Context.SignedCharTy;
8057 else if (Unsigned)
8058 Type = Context.UnsignedCharTy;
8059 else
8060 Type = Context.CharTy;
8061 break;
8062 case 'b': // boolean
8063 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8064 Type = Context.BoolTy;
8065 break;
8066 case 'z': // size_t.
8067 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8068 Type = Context.getSizeType();
8069 break;
8070 case 'F':
8071 Type = Context.getCFConstantStringType();
8072 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008073 case 'G':
8074 Type = Context.getObjCIdType();
8075 break;
8076 case 'H':
8077 Type = Context.getObjCSelType();
8078 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008079 case 'M':
8080 Type = Context.getObjCSuperType();
8081 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008082 case 'a':
8083 Type = Context.getBuiltinVaListType();
8084 assert(!Type.isNull() && "builtin va list type not initialized!");
8085 break;
8086 case 'A':
8087 // This is a "reference" to a va_list; however, what exactly
8088 // this means depends on how va_list is defined. There are two
8089 // different kinds of va_list: ones passed by value, and ones
8090 // passed by reference. An example of a by-value va_list is
8091 // x86, where va_list is a char*. An example of by-ref va_list
8092 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8093 // we want this argument to be a char*&; for x86-64, we want
8094 // it to be a __va_list_tag*.
8095 Type = Context.getBuiltinVaListType();
8096 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008097 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008098 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008099 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008100 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008101 break;
8102 case 'V': {
8103 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008104 unsigned NumElements = strtoul(Str, &End, 10);
8105 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008106 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008107
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008108 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8109 RequiresICE, false);
8110 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008111
8112 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008113 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008114 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008115 break;
8116 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008117 case 'E': {
8118 char *End;
8119
8120 unsigned NumElements = strtoul(Str, &End, 10);
8121 assert(End != Str && "Missing vector size");
8122
8123 Str = End;
8124
8125 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8126 false);
8127 Type = Context.getExtVectorType(ElementType, NumElements);
8128 break;
8129 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008130 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008131 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8132 false);
8133 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008134 Type = Context.getComplexType(ElementType);
8135 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008136 }
8137 case 'Y' : {
8138 Type = Context.getPointerDiffType();
8139 break;
8140 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008141 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008142 Type = Context.getFILEType();
8143 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008144 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008145 return QualType();
8146 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008147 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008148 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008149 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008150 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008151 else
8152 Type = Context.getjmp_bufType();
8153
Mike Stump2adb4da2009-07-28 23:47:15 +00008154 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008155 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008156 return QualType();
8157 }
8158 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008159 case 'K':
8160 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8161 Type = Context.getucontext_tType();
8162
8163 if (Type.isNull()) {
8164 Error = ASTContext::GE_Missing_ucontext;
8165 return QualType();
8166 }
8167 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008168 case 'p':
8169 Type = Context.getProcessIDType();
8170 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008171 }
Mike Stump11289f42009-09-09 15:08:12 +00008172
Chris Lattnerdc226c22010-10-01 22:42:38 +00008173 // If there are modifiers and if we're allowed to parse them, go for it.
8174 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008175 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008176 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008177 default: Done = true; --Str; break;
8178 case '*':
8179 case '&': {
8180 // Both pointers and references can have their pointee types
8181 // qualified with an address space.
8182 char *End;
8183 unsigned AddrSpace = strtoul(Str, &End, 10);
8184 if (End != Str && AddrSpace != 0) {
8185 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8186 Str = End;
8187 }
8188 if (c == '*')
8189 Type = Context.getPointerType(Type);
8190 else
8191 Type = Context.getLValueReferenceType(Type);
8192 break;
8193 }
8194 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8195 case 'C':
8196 Type = Type.withConst();
8197 break;
8198 case 'D':
8199 Type = Context.getVolatileType(Type);
8200 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008201 case 'R':
8202 Type = Type.withRestrict();
8203 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008204 }
8205 }
Chris Lattner84733392010-10-01 07:13:18 +00008206
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008207 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008208 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008209
Chris Lattnerecd79c62009-06-14 00:45:47 +00008210 return Type;
8211}
8212
8213/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008214QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008215 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008216 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008217 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008218
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008219 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008220
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008221 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008222 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008223 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8224 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008225 if (Error != GE_None)
8226 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008227
8228 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8229
Chris Lattnerecd79c62009-06-14 00:45:47 +00008230 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008231 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008232 if (Error != GE_None)
8233 return QualType();
8234
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008235 // If this argument is required to be an IntegerConstantExpression and the
8236 // caller cares, fill in the bitmask we return.
8237 if (RequiresICE && IntegerConstantArgs)
8238 *IntegerConstantArgs |= 1 << ArgTypes.size();
8239
Chris Lattnerecd79c62009-06-14 00:45:47 +00008240 // Do array -> pointer decay. The builtin should use the decayed type.
8241 if (Ty->isArrayType())
8242 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008243
Chris Lattnerecd79c62009-06-14 00:45:47 +00008244 ArgTypes.push_back(Ty);
8245 }
8246
David Majnemerba3e5ec2015-03-13 18:26:17 +00008247 if (Id == Builtin::BI__GetExceptionInfo)
8248 return QualType();
8249
Chris Lattnerecd79c62009-06-14 00:45:47 +00008250 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8251 "'.' should only occur at end of builtin type list!");
8252
Reid Kleckner78af0702013-08-27 23:08:25 +00008253 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008254 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8255
8256 bool Variadic = (TypeStr[0] == '.');
8257
8258 // We really shouldn't be making a no-proto type here, especially in C++.
8259 if (ArgTypes.empty() && Variadic)
8260 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008261
John McCalldb40c7f2010-12-14 08:05:40 +00008262 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008263 EPI.ExtInfo = EI;
8264 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008265
Jordan Rose5c382722013-03-08 21:51:21 +00008266 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008267}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008268
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008269static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8270 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008271 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008272 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008273
Rafael Espindola3ae00052013-05-13 00:12:11 +00008274 GVALinkage External = GVA_StrongExternal;
8275 switch (FD->getTemplateSpecializationKind()) {
8276 case TSK_Undeclared:
8277 case TSK_ExplicitSpecialization:
8278 External = GVA_StrongExternal;
8279 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008280
Rafael Espindola3ae00052013-05-13 00:12:11 +00008281 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008282 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008283
David Majnemerc3d07332014-05-15 06:25:57 +00008284 // C++11 [temp.explicit]p10:
8285 // [ Note: The intent is that an inline function that is the subject of
8286 // an explicit instantiation declaration will still be implicitly
8287 // instantiated when used so that the body can be considered for
8288 // inlining, but that no out-of-line copy of the inline function would be
8289 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008290 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008291 return GVA_AvailableExternally;
8292
Rafael Espindola3ae00052013-05-13 00:12:11 +00008293 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008294 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008295 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008296 }
8297
8298 if (!FD->isInlined())
8299 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008300
David Majnemer3f021502015-10-08 04:53:31 +00008301 if ((!Context.getLangOpts().CPlusPlus &&
8302 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008303 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008304 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008305 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8306
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008307 // GNU or C99 inline semantics. Determine whether this symbol should be
8308 // externally visible.
8309 if (FD->isInlineDefinitionExternallyVisible())
8310 return External;
8311
8312 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008313 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008314 }
8315
David Majnemer54e3ba52014-04-02 23:17:29 +00008316 // Functions specified with extern and inline in -fms-compatibility mode
8317 // forcibly get emitted. While the body of the function cannot be later
8318 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008319 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008320 return GVA_StrongODR;
8321
David Majnemer27d69db2014-04-28 22:17:59 +00008322 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008323}
8324
Artem Belevich7b41f702015-09-23 17:44:53 +00008325static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008326 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8327 // dllexport/dllimport on inline functions.
8328 if (D->hasAttr<DLLImportAttr>()) {
8329 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8330 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008331 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008332 if (L == GVA_DiscardableODR)
8333 return GVA_StrongODR;
8334 }
8335 return L;
8336}
8337
8338GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008339 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8340 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008341}
8342
8343static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8344 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008345 if (!VD->isExternallyVisible())
8346 return GVA_Internal;
8347
David Majnemer27d69db2014-04-28 22:17:59 +00008348 if (VD->isStaticLocal()) {
8349 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8350 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8351 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8352 LexicalContext = LexicalContext->getLexicalParent();
8353
Richard Smith9e2341d2015-03-23 03:25:59 +00008354 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008355 // enclosing function.
8356 if (LexicalContext)
8357 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008358 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008359
8360 // GVA_StrongODR function linkage is stronger than what we need,
8361 // downgrade to GVA_DiscardableODR.
8362 // This allows us to discard the variable if we never end up needing it.
8363 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8364 : StaticLocalLinkage;
8365 }
8366
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008367 // MSVC treats in-class initialized static data members as definitions.
8368 // By giving them non-strong linkage, out-of-line definitions won't
8369 // cause link errors.
8370 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8371 return GVA_DiscardableODR;
8372
Richard Smith8809a0c2013-09-27 20:14:12 +00008373 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008374 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008375 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008376
David Majnemer6d1780c2015-07-17 23:36:49 +00008377 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008378 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8379 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008380 ? GVA_StrongODR
8381 : GVA_StrongExternal;
8382
Rafael Espindola3ae00052013-05-13 00:12:11 +00008383 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008384 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008385
David Majnemer27d69db2014-04-28 22:17:59 +00008386 case TSK_ExplicitInstantiationDeclaration:
8387 return GVA_AvailableExternally;
8388
Rafael Espindola3ae00052013-05-13 00:12:11 +00008389 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008390 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008391 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008392
8393 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008394}
8395
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008396GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008397 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8398 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008399}
8400
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008401bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008402 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8403 if (!VD->isFileVarDecl())
8404 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008405 // Global named register variables (GNU extension) are never emitted.
8406 if (VD->getStorageClass() == SC_Register)
8407 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008408 if (VD->getDescribedVarTemplate() ||
8409 isa<VarTemplatePartialSpecializationDecl>(VD))
8410 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008411 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8412 // We never need to emit an uninstantiated function template.
8413 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8414 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008415 } else if (isa<OMPThreadPrivateDecl>(D))
8416 return true;
8417 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008418 return false;
8419
8420 // If this is a member of a class template, we do not need to emit it.
8421 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008422 return false;
8423
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008424 // Weak references don't produce any output by themselves.
8425 if (D->hasAttr<WeakRefAttr>())
8426 return false;
8427
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008428 // Aliases and used decls are required.
8429 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8430 return true;
8431
8432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8433 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008434 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008435 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008436
8437 // Constructors and destructors are required.
8438 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8439 return true;
8440
John McCall6bd2a892013-01-25 22:31:03 +00008441 // The key function for a class is required. This rule only comes
8442 // into play when inline functions can be key functions, though.
8443 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8444 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8445 const CXXRecordDecl *RD = MD->getParent();
8446 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8447 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8448 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8449 return true;
8450 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008451 }
8452 }
8453
8454 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8455
8456 // static, static inline, always_inline, and extern inline functions can
8457 // always be deferred. Normal inline functions can be deferred in C99/C++.
8458 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008459 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8460 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008461 return false;
8462 return true;
8463 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008464
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008465 const VarDecl *VD = cast<VarDecl>(D);
8466 assert(VD->isFileVarDecl() && "Expected file scoped var");
8467
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008468 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8469 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008470 return false;
8471
Richard Smitha0e5e542012-11-12 21:38:00 +00008472 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008473 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008474 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8475 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008476 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008477
Richard Smitha0e5e542012-11-12 21:38:00 +00008478 // Variables that have destruction with side-effects are required.
8479 if (VD->getType().isDestructedType())
8480 return true;
8481
8482 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008483 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8484 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008485 return true;
8486
8487 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008488}
Charles Davis53c59df2010-08-16 03:33:14 +00008489
Reid Kleckner78af0702013-08-27 23:08:25 +00008490CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8491 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008492 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008493 if (IsCXXMethod)
8494 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008495
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008496 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8497
8498 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008499}
8500
Jay Foad39c79802011-01-12 09:06:06 +00008501bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008502 // Pass through to the C++ ABI object
8503 return ABI->isNearlyEmpty(RD);
8504}
8505
Reid Kleckner96f8f932014-02-05 17:27:08 +00008506VTableContextBase *ASTContext::getVTableContext() {
8507 if (!VTContext.get()) {
8508 if (Target->getCXXABI().isMicrosoft())
8509 VTContext.reset(new MicrosoftVTableContext(*this));
8510 else
8511 VTContext.reset(new ItaniumVTableContext(*this));
8512 }
8513 return VTContext.get();
8514}
8515
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008516MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008517 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008518 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008519 case TargetCXXABI::GenericItanium:
8520 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008521 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008522 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008523 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008524 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008525 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008526 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008527 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008528 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008529 }
David Blaikie83d382b2011-09-23 05:06:16 +00008530 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008531}
8532
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008533CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008534
8535size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008536 return ASTRecordLayouts.getMemorySize() +
8537 llvm::capacity_in_bytes(ObjCLayouts) +
8538 llvm::capacity_in_bytes(KeyFunctions) +
8539 llvm::capacity_in_bytes(ObjCImpls) +
8540 llvm::capacity_in_bytes(BlockVarCopyInits) +
8541 llvm::capacity_in_bytes(DeclAttrs) +
8542 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8543 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8544 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8545 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8546 llvm::capacity_in_bytes(OverriddenMethods) +
8547 llvm::capacity_in_bytes(Types) +
8548 llvm::capacity_in_bytes(VariableArrayTypes) +
8549 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008550}
Ted Kremenek540017e2011-10-06 05:00:56 +00008551
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008552/// getIntTypeForBitwidth -
8553/// sets integer QualTy according to specified details:
8554/// bitwidth, signed/unsigned.
8555/// Returns empty type if there is no appropriate target types.
8556QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8557 unsigned Signed) const {
8558 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8559 CanQualType QualTy = getFromTargetType(Ty);
8560 if (!QualTy && DestWidth == 128)
8561 return Signed ? Int128Ty : UnsignedInt128Ty;
8562 return QualTy;
8563}
8564
8565/// getRealTypeForBitwidth -
8566/// sets floating point QualTy according to specified bitwidth.
8567/// Returns empty type if there is no appropriate target types.
8568QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8569 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8570 switch (Ty) {
8571 case TargetInfo::Float:
8572 return FloatTy;
8573 case TargetInfo::Double:
8574 return DoubleTy;
8575 case TargetInfo::LongDouble:
8576 return LongDoubleTy;
8577 case TargetInfo::NoFloat:
8578 return QualType();
8579 }
8580
8581 llvm_unreachable("Unhandled TargetInfo::RealType value");
8582}
8583
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008584void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8585 if (Number > 1)
8586 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008587}
8588
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008589unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8590 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8591 MangleNumbers.find(ND);
8592 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008593}
8594
David Majnemer2206bf52014-03-05 08:57:59 +00008595void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8596 if (Number > 1)
8597 StaticLocalNumbers[VD] = Number;
8598}
8599
8600unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8601 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8602 StaticLocalNumbers.find(VD);
8603 return I != StaticLocalNumbers.end() ? I->second : 1;
8604}
8605
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008606MangleNumberingContext &
8607ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008608 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8609 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8610 if (!MCtx)
8611 MCtx = createMangleNumberingContext();
8612 return *MCtx;
8613}
8614
8615MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8616 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008617}
8618
David Majnemere7a818f2015-03-06 18:53:55 +00008619const CXXConstructorDecl *
8620ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8621 return ABI->getCopyConstructorForExceptionObject(
8622 cast<CXXRecordDecl>(RD->getFirstDecl()));
8623}
8624
8625void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8626 CXXConstructorDecl *CD) {
8627 return ABI->addCopyConstructorForExceptionObject(
8628 cast<CXXRecordDecl>(RD->getFirstDecl()),
8629 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8630}
8631
David Majnemerdfa6d202015-03-11 18:36:39 +00008632void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8633 unsigned ParmIdx, Expr *DAE) {
8634 ABI->addDefaultArgExprForConstructor(
8635 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8636}
8637
8638Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8639 unsigned ParmIdx) {
8640 return ABI->getDefaultArgExprForConstructor(
8641 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8642}
8643
David Majnemer00350522015-08-31 18:48:39 +00008644void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8645 TypedefNameDecl *DD) {
8646 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8647}
8648
8649TypedefNameDecl *
8650ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8651 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8652}
8653
8654void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8655 DeclaratorDecl *DD) {
8656 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8657}
8658
8659DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8660 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8661}
8662
Ted Kremenek540017e2011-10-06 05:00:56 +00008663void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8664 ParamIndices[D] = index;
8665}
8666
8667unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8668 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8669 assert(I != ParamIndices.end() &&
8670 "ParmIndices lacks entry set by ParmVarDecl");
8671 return I->second;
8672}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008673
Richard Smithe6c01442013-06-05 00:46:14 +00008674APValue *
8675ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8676 bool MayCreate) {
8677 assert(E && E->getStorageDuration() == SD_Static &&
8678 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008679 if (MayCreate) {
8680 APValue *&MTVI = MaterializedTemporaryValues[E];
8681 if (!MTVI)
8682 MTVI = new (*this) APValue;
8683 return MTVI;
8684 }
Richard Smithe6c01442013-06-05 00:46:14 +00008685
David Majnemer2dcef9e2015-08-13 23:50:15 +00008686 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008687}
8688
Fariborz Jahanian615de762013-05-28 17:37:39 +00008689bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8690 const llvm::Triple &T = getTargetInfo().getTriple();
8691 if (!T.isOSDarwin())
8692 return false;
8693
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008694 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8695 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8696 return false;
8697
Fariborz Jahanian615de762013-05-28 17:37:39 +00008698 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8699 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8700 uint64_t Size = sizeChars.getQuantity();
8701 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8702 unsigned Align = alignChars.getQuantity();
8703 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8704 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8705}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008706
8707namespace {
8708
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008709ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8710 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008711 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008712 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008713 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008714 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008715 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008716}
8717
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008718/// Template specializations to abstract away from pointers and TypeLocs.
8719/// @{
8720template <typename T>
8721ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8722 return ast_type_traits::DynTypedNode::create(*Node);
8723}
8724template <>
8725ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8726 return ast_type_traits::DynTypedNode::create(Node);
8727}
8728template <>
8729ast_type_traits::DynTypedNode
8730createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8731 return ast_type_traits::DynTypedNode::create(Node);
8732}
8733/// @}
8734
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008735 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8736 /// parents as defined by the \c RecursiveASTVisitor.
8737 ///
8738 /// Note that the relationship described here is purely in terms of AST
8739 /// traversal - there are other relationships (for example declaration context)
8740 /// in the AST that are better modeled by special matchers.
8741 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008742 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008743 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008744 public:
8745 /// \brief Builds and returns the translation unit's parent map.
8746 ///
8747 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008748 static std::pair<ASTContext::ParentMapPointers *,
8749 ASTContext::ParentMapOtherNodes *>
8750 buildMap(TranslationUnitDecl &TU) {
8751 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8752 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008753 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008754 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008755 }
8756
8757 private:
8758 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8759
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008760 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8761 ASTContext::ParentMapOtherNodes *OtherParents)
8762 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008763
8764 bool shouldVisitTemplateInstantiations() const {
8765 return true;
8766 }
8767 bool shouldVisitImplicitCode() const {
8768 return true;
8769 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008770
Richard Smith85838722015-11-24 03:09:01 +00008771 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8772 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008773 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008774 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008775 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008776 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008777 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008778 // FIXME: Currently we add the same parent multiple times, but only
8779 // when no memoization data is available for the type.
8780 // For example when we visit all subexpressions of template
8781 // instantiations; this is suboptimal, but benign: the only way to
8782 // visit those is with hasAncestor / hasParent, and those do not create
8783 // new matches.
8784 // The plan is to enable DynTypedNode to be storable in a map or hash
8785 // map. The main problem there is to implement hash functions /
8786 // comparison operators for all types that DynTypedNode supports that
8787 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008788 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008789 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008790 if (const auto *D = ParentStack.back().get<Decl>())
8791 NodeOrVector = D;
8792 else if (const auto *S = ParentStack.back().get<Stmt>())
8793 NodeOrVector = S;
8794 else
8795 NodeOrVector =
8796 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008797 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008798 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8799 auto *Vector = new ASTContext::ParentVector(
8800 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008801 if (auto *Node =
8802 NodeOrVector
8803 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8804 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008805 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008806 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008807
8808 auto *Vector =
8809 NodeOrVector.template get<ASTContext::ParentVector *>();
8810 // Skip duplicates for types that have memoization data.
8811 // We must check that the type has memoization data before calling
8812 // std::find() because DynTypedNode::operator== can't compare all
8813 // types.
8814 bool Found = ParentStack.back().getMemoizationData() &&
8815 std::find(Vector->begin(), Vector->end(),
8816 ParentStack.back()) != Vector->end();
8817 if (!Found)
8818 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008819 }
8820 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008821 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00008822 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008823 ParentStack.pop_back();
8824 return Result;
8825 }
8826
8827 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00008828 return TraverseNode(DeclNode, DeclNode,
8829 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008830 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008831 }
8832
8833 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00008834 return TraverseNode(StmtNode, StmtNode,
8835 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008836 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008837 }
8838
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008839 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00008840 return TraverseNode(
8841 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8842 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8843 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008844 }
8845
8846 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8847 return TraverseNode(
8848 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00008849 [&] {
8850 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8851 },
8852 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008853 }
8854
8855 ASTContext::ParentMapPointers *Parents;
8856 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008857 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8858
8859 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8860 };
8861
Eugene Zelenkod4304d22015-11-04 21:37:17 +00008862} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008863
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008864template <typename NodeTy, typename MapTy>
8865static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8866 const MapTy &Map) {
8867 auto I = Map.find(Node);
8868 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008869 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008870 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008871 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008872 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008873 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008874 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008875}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008876
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008877ASTContext::DynTypedNodeList
8878ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8879 if (!PointerParents) {
8880 // We always need to run over the whole translation unit, as
8881 // hasAncestor can escape any subtree.
8882 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8883 PointerParents.reset(Maps.first);
8884 OtherParents.reset(Maps.second);
8885 }
8886 if (Node.getNodeKind().hasPointerIdentity())
8887 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8888 return getDynNodeFromMap(Node, *OtherParents);
8889}
8890
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008891bool
8892ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8893 const ObjCMethodDecl *MethodImpl) {
8894 // No point trying to match an unavailable/deprecated mothod.
8895 if (MethodDecl->hasAttr<UnavailableAttr>()
8896 || MethodDecl->hasAttr<DeprecatedAttr>())
8897 return false;
8898 if (MethodDecl->getObjCDeclQualifier() !=
8899 MethodImpl->getObjCDeclQualifier())
8900 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008901 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008902 return false;
8903
8904 if (MethodDecl->param_size() != MethodImpl->param_size())
8905 return false;
8906
8907 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8908 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8909 EF = MethodDecl->param_end();
8910 IM != EM && IF != EF; ++IM, ++IF) {
8911 const ParmVarDecl *DeclVar = (*IF);
8912 const ParmVarDecl *ImplVar = (*IM);
8913 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8914 return false;
8915 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8916 return false;
8917 }
8918 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8919
8920}
Richard Smith053f6c62014-05-16 23:01:30 +00008921
8922// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8923// doesn't include ASTContext.h
8924template
8925clang::LazyGenerationalUpdatePtr<
8926 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8927clang::LazyGenerationalUpdatePtr<
8928 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8929 const clang::ASTContext &Ctx, Decl *Value);