blob: fd9c7cf11329c4a538b3b79e7608a1780ab95521 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000037#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000038#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000039#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000040#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000041
Reid Spencer5f016e22007-07-11 17:01:13 +000042using namespace clang;
43
Douglas Gregor18274032010-07-03 00:47:00 +000044unsigned ASTContext::NumImplicitDefaultConstructors;
45unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000046unsigned ASTContext::NumImplicitCopyConstructors;
47unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveConstructors;
49unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000050unsigned ASTContext::NumImplicitCopyAssignmentOperators;
51unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000052unsigned ASTContext::NumImplicitMoveAssignmentOperators;
53unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000054unsigned ASTContext::NumImplicitDestructors;
55unsigned ASTContext::NumImplicitDestructorsDeclared;
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000058 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000059};
60
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000061RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000062 if (!CommentsLoaded && ExternalSource) {
63 ExternalSource->ReadComments();
64 CommentsLoaded = true;
65 }
66
67 assert(D);
68
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000069 // User can not attach documentation to implicit declarations.
70 if (D->isImplicit())
71 return NULL;
72
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000073 // User can not attach documentation to implicit instantiations.
74 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
76 return NULL;
77 }
78
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000079 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->isStaticDataMember() &&
81 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
82 return NULL;
83 }
84
85 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
86 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
87 return NULL;
88 }
89
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000090 if (const ClassTemplateSpecializationDecl *CTSD =
91 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
92 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
93 if (TSK == TSK_ImplicitInstantiation ||
94 TSK == TSK_Undeclared)
95 return NULL;
96 }
97
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000098 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
99 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 return NULL;
101 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000102 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // When tag declaration (but not definition!) is part of the
104 // decl-specifier-seq of some other declaration, it doesn't get comment
105 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
106 return NULL;
107 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000108 // TODO: handle comments for function parameters properly.
109 if (isa<ParmVarDecl>(D))
110 return NULL;
111
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000112 // TODO: we could look up template parameter documentation in the template
113 // documentation.
114 if (isa<TemplateTypeParmDecl>(D) ||
115 isa<NonTypeTemplateParmDecl>(D) ||
116 isa<TemplateTemplateParmDecl>(D))
117 return NULL;
118
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000119 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000120
121 // If there are no comments anywhere, we won't find anything.
122 if (RawComments.empty())
123 return NULL;
124
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000125 // Find declaration location.
126 // For Objective-C declarations we generally don't expect to have multiple
127 // declarators, thus use declaration starting location as the "declaration
128 // location".
129 // For all other declarations multiple declarators are used quite frequently,
130 // so we use the location of the identifier as the "declaration location".
131 SourceLocation DeclLoc;
132 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000133 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000134 isa<RedeclarableTemplateDecl>(D) ||
135 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000136 DeclLoc = D->getLocStart();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000137 else {
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000138 DeclLoc = D->getLocation();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000139 // If location of the typedef name is in a macro, it is because being
140 // declared via a macro. Try using declaration's starting location
141 // as the "declaration location".
142 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
143 DeclLoc = D->getLocStart();
144 }
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000145
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000146 // If the declaration doesn't map directly to a location in a file, we
147 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000148 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
149 return NULL;
150
151 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000152 ArrayRef<RawComment *>::iterator Comment;
153 {
154 // When searching for comments during parsing, the comment we are looking
155 // for is usually among the last two comments we parsed -- check them
156 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000157 RawComment CommentAtDeclLoc(
158 SourceMgr, SourceRange(DeclLoc), false,
159 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000160 BeforeThanCompare<RawComment> Compare(SourceMgr);
161 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
162 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
163 if (!Found && RawComments.size() >= 2) {
164 MaybeBeforeDecl--;
165 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
166 }
167
168 if (Found) {
169 Comment = MaybeBeforeDecl + 1;
170 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
171 &CommentAtDeclLoc, Compare));
172 } else {
173 // Slow path.
174 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
175 &CommentAtDeclLoc, Compare);
176 }
177 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000178
179 // Decompose the location for the declaration and find the beginning of the
180 // file buffer.
181 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
182
183 // First check whether we have a trailing comment.
184 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000185 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanian8c238be2013-08-06 23:29:00 +0000186 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian15c8e562013-08-07 16:40:29 +0000187 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000188 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000189 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000190 // Check that Doxygen trailing comment comes after the declaration, starts
191 // on the same line and in the same file as the declaration.
192 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
193 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
194 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
195 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000196 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000197 }
198 }
199
200 // The comment just after the declaration was not a trailing comment.
201 // Let's look at the previous comment.
202 if (Comment == RawComments.begin())
203 return NULL;
204 --Comment;
205
206 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000207 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000208 return NULL;
209
210 // Decompose the end of the comment.
211 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000212 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000213
214 // If the comment and the declaration aren't in the same file, then they
215 // aren't related.
216 if (DeclLocDecomp.first != CommentEndDecomp.first)
217 return NULL;
218
219 // Get the corresponding buffer.
220 bool Invalid = false;
221 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
222 &Invalid).data();
223 if (Invalid)
224 return NULL;
225
226 // Extract text between the comment and declaration.
227 StringRef Text(Buffer + CommentEndDecomp.second,
228 DeclLocDecomp.second - CommentEndDecomp.second);
229
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000230 // There should be no other declarations or preprocessor directives between
231 // comment and declaration.
Argyrios Kyrtzidisdc663262013-07-26 18:38:12 +0000232 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000233 return NULL;
234
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000235 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000236}
237
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000238namespace {
239/// If we have a 'templated' declaration for a template, adjust 'D' to
240/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000241/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000242const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000244 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000245 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000246 return FTD;
247
248 // Nothing to do if function is not an implicit instantiation.
249 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
250 return D;
251
252 // Function is an implicit instantiation of a function template?
253 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
254 return FTD;
255
256 // Function is instantiated from a member definition of a class template?
257 if (const FunctionDecl *MemberDecl =
258 FD->getInstantiatedFromMemberFunction())
259 return MemberDecl;
260
261 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000262 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000263 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
264 // Static data member is instantiated from a member definition of a class
265 // template?
266 if (VD->isStaticDataMember())
267 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
268 return MemberDecl;
269
270 return D;
271 }
272 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
273 // Is this class declaration part of a class template?
274 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
275 return CTD;
276
277 // Class is an implicit instantiation of a class template or partial
278 // specialization?
279 if (const ClassTemplateSpecializationDecl *CTSD =
280 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
281 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
282 return D;
283 llvm::PointerUnion<ClassTemplateDecl *,
284 ClassTemplatePartialSpecializationDecl *>
285 PU = CTSD->getSpecializedTemplateOrPartial();
286 return PU.is<ClassTemplateDecl*>() ?
287 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
288 static_cast<const Decl*>(
289 PU.get<ClassTemplatePartialSpecializationDecl *>());
290 }
291
292 // Class is instantiated from a member definition of a class template?
293 if (const MemberSpecializationInfo *Info =
294 CRD->getMemberSpecializationInfo())
295 return Info->getInstantiatedFrom();
296
297 return D;
298 }
299 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
300 // Enum is instantiated from a member definition of a class template?
301 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
302 return MemberDecl;
303
304 return D;
305 }
306 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000307 return D;
308}
309} // unnamed namespace
310
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000311const RawComment *ASTContext::getRawCommentForAnyRedecl(
312 const Decl *D,
313 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000314 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000315
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000316 // Check whether we have cached a comment for this declaration already.
317 {
318 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
319 RedeclComments.find(D);
320 if (Pos != RedeclComments.end()) {
321 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000322 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
323 if (OriginalDecl)
324 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000326 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000327 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000328 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000329
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000330 // Search for comments attached to declarations in the redeclaration chain.
331 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000332 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000333 for (Decl::redecl_iterator I = D->redecls_begin(),
334 E = D->redecls_end();
335 I != E; ++I) {
336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
337 RedeclComments.find(*I);
338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
346 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000347 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000354 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355 RedeclComments[*I] = Raw;
356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000363
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000372
373 for (Decl::redecl_iterator I = D->redecls_begin(),
374 E = D->redecls_end();
375 I != E; ++I) {
376 RawCommentAndCacheFlags &R = RedeclComments[*I];
377 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
378 R = Raw;
379 }
380
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000381 return RC;
382}
383
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000384static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
385 SmallVectorImpl<const NamedDecl *> &Redeclared) {
386 const DeclContext *DC = ObjCMethod->getDeclContext();
387 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
388 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
389 if (!ID)
390 return;
391 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000392 for (ObjCInterfaceDecl::known_extensions_iterator
393 Ext = ID->known_extensions_begin(),
394 ExtEnd = ID->known_extensions_end();
395 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000396 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000397 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000398 ObjCMethod->isInstanceMethod()))
399 Redeclared.push_back(RedeclaredMethod);
400 }
401 }
402}
403
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000404comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
405 const Decl *D) const {
406 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
407 ThisDeclInfo->CommentDecl = D;
408 ThisDeclInfo->IsFilled = false;
409 ThisDeclInfo->fill();
410 ThisDeclInfo->CommentDecl = FC->getDecl();
411 comments::FullComment *CFC =
412 new (*this) comments::FullComment(FC->getBlocks(),
413 ThisDeclInfo);
414 return CFC;
415
416}
417
Richard Smith0a74a4c2013-05-21 05:24:00 +0000418comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
419 const RawComment *RC = getRawCommentForDeclNoCache(D);
420 return RC ? RC->parse(*this, 0, D) : 0;
421}
422
Dmitri Gribenko19523542012-09-29 11:40:46 +0000423comments::FullComment *ASTContext::getCommentForDecl(
424 const Decl *D,
425 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000426 if (D->isInvalidDecl())
427 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000428 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000429
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000430 const Decl *Canonical = D->getCanonicalDecl();
431 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
432 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433
434 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000435 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000437 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 return CFC;
439 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000440 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000441 }
442
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000443 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000444
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000445 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000446 if (!RC) {
447 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000448 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000449 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000450 if (OMD && OMD->isPropertyAccessor())
451 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
452 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
453 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000454 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000455 addRedeclaredMethods(OMD, Overridden);
456 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000457 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
458 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
459 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000460 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000461 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000462 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000463 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000464 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000465 if (const TagType *TT = QT->getAs<TagType>())
466 if (const Decl *TD = TT->getDecl())
467 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000468 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000469 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000470 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
471 while (IC->getSuperClass()) {
472 IC = IC->getSuperClass();
473 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
474 return cloneFullComment(FC, D);
475 }
476 }
477 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
478 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
479 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
480 return cloneFullComment(FC, D);
481 }
482 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
483 if (!(RD = RD->getDefinition()))
484 return NULL;
485 // Check non-virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000488 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000489 continue;
490 QualType Ty = I->getType();
491 if (Ty.isNull())
492 continue;
493 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
495 continue;
496
497 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
498 return cloneFullComment(FC, D);
499 }
500 }
501 // Check virtual bases.
502 for (CXXRecordDecl::base_class_const_iterator I =
503 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000504 if (I->getAccessSpecifier() != AS_public)
505 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000506 QualType Ty = I->getType();
507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(VirtualBase= VirtualBase->getDefinition()))
511 continue;
512 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000517 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000518 }
519
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000520 // If the RawComment was attached to other redeclaration of this Decl, we
521 // should parse the comment in context of that other Decl. This is important
522 // because comments can contain references to parameter names which can be
523 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000524 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000525 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000526
Dmitri Gribenko19523542012-09-29 11:40:46 +0000527 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000528 ParsedComments[Canonical] = FC;
529 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000530}
531
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000532void
533ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
534 TemplateTemplateParmDecl *Parm) {
535 ID.AddInteger(Parm->getDepth());
536 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000537 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000538
539 TemplateParameterList *Params = Parm->getTemplateParameters();
540 ID.AddInteger(Params->size());
541 for (TemplateParameterList::const_iterator P = Params->begin(),
542 PEnd = Params->end();
543 P != PEnd; ++P) {
544 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
545 ID.AddInteger(0);
546 ID.AddBoolean(TTP->isParameterPack());
547 continue;
548 }
549
550 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
551 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000552 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000553 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000554 if (NTTP->isExpandedParameterPack()) {
555 ID.AddBoolean(true);
556 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000557 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
558 QualType T = NTTP->getExpansionType(I);
559 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
560 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000561 } else
562 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000563 continue;
564 }
565
566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
567 ID.AddInteger(2);
568 Profile(ID, TTP);
569 }
570}
571
572TemplateTemplateParmDecl *
573ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000574 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000575 // Check if we already have a canonical template template parameter.
576 llvm::FoldingSetNodeID ID;
577 CanonicalTemplateTemplateParm::Profile(ID, TTP);
578 void *InsertPos = 0;
579 CanonicalTemplateTemplateParm *Canonical
580 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
581 if (Canonical)
582 return Canonical->getParam();
583
584 // Build a canonical template parameter list.
585 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000586 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000587 CanonParams.reserve(Params->size());
588 for (TemplateParameterList::const_iterator P = Params->begin(),
589 PEnd = Params->end();
590 P != PEnd; ++P) {
591 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
592 CanonParams.push_back(
593 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000594 SourceLocation(),
595 SourceLocation(),
596 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000597 TTP->getIndex(), 0, false,
598 TTP->isParameterPack()));
599 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000600 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
601 QualType T = getCanonicalType(NTTP->getType());
602 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
603 NonTypeTemplateParmDecl *Param;
604 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000605 SmallVector<QualType, 2> ExpandedTypes;
606 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000607 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
608 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
609 ExpandedTInfos.push_back(
610 getTrivialTypeSourceInfo(ExpandedTypes.back()));
611 }
612
613 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000614 SourceLocation(),
615 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000616 NTTP->getDepth(),
617 NTTP->getPosition(), 0,
618 T,
619 TInfo,
620 ExpandedTypes.data(),
621 ExpandedTypes.size(),
622 ExpandedTInfos.data());
623 } else {
624 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000625 SourceLocation(),
626 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000627 NTTP->getDepth(),
628 NTTP->getPosition(), 0,
629 T,
630 NTTP->isParameterPack(),
631 TInfo);
632 }
633 CanonParams.push_back(Param);
634
635 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000636 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
637 cast<TemplateTemplateParmDecl>(*P)));
638 }
639
640 TemplateTemplateParmDecl *CanonTTP
641 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000643 TTP->getPosition(),
644 TTP->isParameterPack(),
645 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000646 TemplateParameterList::Create(*this, SourceLocation(),
647 SourceLocation(),
648 CanonParams.data(),
649 CanonParams.size(),
650 SourceLocation()));
651
652 // Get the new insert position for the node we care about.
653 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
654 assert(Canonical == 0 && "Shouldn't be in the map!");
655 (void)Canonical;
656
657 // Create the canonical template template parameter entry.
658 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
659 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
660 return CanonTTP;
661}
662
Charles Davis071cc7d2010-08-16 03:33:14 +0000663CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000664 if (!LangOpts.CPlusPlus) return 0;
665
John McCallb8b2c9d2013-01-25 22:30:49 +0000666 switch (T.getCXXABI().getKind()) {
667 case TargetCXXABI::GenericARM:
668 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000669 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000670 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000671 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000672 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000673 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000674 return CreateMicrosoftCXXABI(*this);
675 }
David Blaikie7530c032012-01-17 06:56:22 +0000676 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000677}
678
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000679static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000680 const LangOptions &LOpts) {
681 if (LOpts.FakeAddressSpaceMap) {
682 // The fake address space map must have a distinct entry for each
683 // language-specific address space.
684 static const unsigned FakeAddrSpaceMap[] = {
685 1, // opencl_global
686 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000687 3, // opencl_constant
688 4, // cuda_device
689 5, // cuda_constant
690 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000691 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000692 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000693 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000695 }
696}
697
David Tweed1eef8522013-09-13 12:04:22 +0000698static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
699 const LangOptions &LangOpts) {
700 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed1eef8522013-09-13 12:04:22 +0000701 case LangOptions::ASMM_Target:
702 return TI.useAddressSpaceMapMangling();
703 case LangOptions::ASMM_On:
704 return true;
705 case LangOptions::ASMM_Off:
706 return false;
707 }
NAKAMURA Takumicb3b4002013-09-13 17:12:09 +0000708 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed1eef8522013-09-13 12:04:22 +0000709}
710
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000711ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000713 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000714 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000715 unsigned size_reserve,
716 bool DelayInitialization)
717 : FunctionProtoTypes(this_()),
718 TemplateSpecializationTypes(this_()),
719 DependentTemplateSpecializationTypes(this_()),
720 SubstTemplateTemplateParmPacks(this_()),
721 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000722 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000723 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000724 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000725 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000726 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000727 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000728 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
729 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
730 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000731 NullTypeSourceInfo(QualType()),
732 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000733 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000734 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000735 Idents(idents), Selectors(sels),
736 BuiltinInfo(builtins),
737 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000738 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000739 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000740 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000741 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000742{
Mike Stump1eb44332009-09-09 15:08:12 +0000743 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000744 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000745
746 if (!DelayInitialization) {
747 assert(t && "No target supplied for ASTContext initialization");
748 InitBuiltinTypes(*t);
749 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000750}
751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000753 // Release the DenseMaps associated with DeclContext objects.
754 // FIXME: Is this the ideal solution?
755 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000756
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000757 // Call all of the deallocation functions on all of their targets.
758 for (DeallocationMap::const_iterator I = Deallocations.begin(),
759 E = Deallocations.end(); I != E; ++I)
760 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
761 (I->first)((I->second)[J]);
762
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000763 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000764 // because they can contain DenseMaps.
765 for (llvm::DenseMap<const ObjCContainerDecl*,
766 const ASTRecordLayout*>::iterator
767 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
768 // Increment in loop to prevent using deallocated memory.
769 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
770 R->Destroy(*this);
771
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000772 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
773 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
774 // Increment in loop to prevent using deallocated memory.
775 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776 R->Destroy(*this);
777 }
Douglas Gregor63200642010-08-30 16:49:28 +0000778
779 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
780 AEnd = DeclAttrs.end();
781 A != AEnd; ++A)
782 A->second->~AttrVec();
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000783
784 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
785 I = MangleNumberingContexts.begin(),
786 E = MangleNumberingContexts.end();
787 I != E; ++I)
788 delete I->second;
Douglas Gregor63200642010-08-30 16:49:28 +0000789}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000790
Douglas Gregor00545312010-05-23 18:26:36 +0000791void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000792 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000793}
794
Mike Stump1eb44332009-09-09 15:08:12 +0000795void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000796ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000797 ExternalSource.reset(Source.take());
798}
799
Reid Spencer5f016e22007-07-11 17:01:13 +0000800void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000801 llvm::errs() << "\n*** AST Context Stats:\n";
802 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000803
Douglas Gregordbe833d2009-05-26 14:40:08 +0000804 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000805#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000806#define ABSTRACT_TYPE(Name, Parent)
807#include "clang/AST/TypeNodes.def"
808 0 // Extra
809 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000810
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
812 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000813 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 }
815
Douglas Gregordbe833d2009-05-26 14:40:08 +0000816 unsigned Idx = 0;
817 unsigned TotalBytes = 0;
818#define TYPE(Name, Parent) \
819 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000820 llvm::errs() << " " << counts[Idx] << " " << #Name \
821 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000822 TotalBytes += counts[Idx] * sizeof(Name##Type); \
823 ++Idx;
824#define ABSTRACT_TYPE(Name, Parent)
825#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chandler Carruthcd92a652011-07-04 05:32:14 +0000827 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
828
Douglas Gregor4923aa22010-07-02 20:37:36 +0000829 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000830 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
831 << NumImplicitDefaultConstructors
832 << " implicit default constructors created\n";
833 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
834 << NumImplicitCopyConstructors
835 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000836 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000837 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
838 << NumImplicitMoveConstructors
839 << " implicit move constructors created\n";
840 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
841 << NumImplicitCopyAssignmentOperators
842 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000843 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000844 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
845 << NumImplicitMoveAssignmentOperators
846 << " implicit move assignment operators created\n";
847 llvm::errs() << NumImplicitDestructorsDeclared << "/"
848 << NumImplicitDestructors
849 << " implicit destructors created\n";
850
Douglas Gregor2cf26342009-04-09 22:27:44 +0000851 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000852 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000853 ExternalSource->PrintStats();
854 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000855
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000856 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
Douglas Gregor772eeae2011-08-12 06:49:56 +0000859TypedefDecl *ASTContext::getInt128Decl() const {
860 if (!Int128Decl) {
861 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
862 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
863 getTranslationUnitDecl(),
864 SourceLocation(),
865 SourceLocation(),
866 &Idents.get("__int128_t"),
867 TInfo);
868 }
869
870 return Int128Decl;
871}
872
873TypedefDecl *ASTContext::getUInt128Decl() const {
874 if (!UInt128Decl) {
875 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
876 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
877 getTranslationUnitDecl(),
878 SourceLocation(),
879 SourceLocation(),
880 &Idents.get("__uint128_t"),
881 TInfo);
882 }
883
884 return UInt128Decl;
885}
Reid Spencer5f016e22007-07-11 17:01:13 +0000886
Nico Webercac18ad2013-06-20 21:44:55 +0000887TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000888 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000889 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000890 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
891 TTK_Struct,
892 getTranslationUnitDecl(),
893 SourceLocation(),
894 SourceLocation(),
895 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000896 }
897
898 return Float128StubDecl;
899}
900
John McCalle27ec8a2009-10-23 23:03:21 +0000901void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000902 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000903 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000904 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000905}
906
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000907void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
908 assert((!this->Target || this->Target == &Target) &&
909 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000912 this->Target = &Target;
913
914 ABI.reset(createCXXABI(Target));
915 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed1eef8522013-09-13 12:04:22 +0000916 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 // C99 6.2.5p19.
919 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 // C99 6.2.5p2.
922 InitBuiltinType(BoolTy, BuiltinType::Bool);
923 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000924 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 InitBuiltinType(CharTy, BuiltinType::Char_S);
926 else
927 InitBuiltinType(CharTy, BuiltinType::Char_U);
928 // C99 6.2.5p4.
929 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
930 InitBuiltinType(ShortTy, BuiltinType::Short);
931 InitBuiltinType(IntTy, BuiltinType::Int);
932 InitBuiltinType(LongTy, BuiltinType::Long);
933 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 // C99 6.2.5p6.
936 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
937 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
938 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
939 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
940 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 // C99 6.2.5p10.
943 InitBuiltinType(FloatTy, BuiltinType::Float);
944 InitBuiltinType(DoubleTy, BuiltinType::Double);
945 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000946
Chris Lattner2df9ced2009-04-30 02:43:43 +0000947 // GNU extension, 128-bit integers.
948 InitBuiltinType(Int128Ty, BuiltinType::Int128);
949 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
950
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000951 // C++ 3.9.1p5
952 if (TargetInfo::isTypeSigned(Target.getWCharType()))
953 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
954 else // -fshort-wchar makes wchar_t be unsigned.
955 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
956 if (LangOpts.CPlusPlus && LangOpts.WChar)
957 WideCharTy = WCharTy;
958 else {
959 // C99 (or C++ using -fno-wchar).
960 WideCharTy = getFromTargetType(Target.getWCharType());
961 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000962
James Molloy392da482012-05-04 10:55:22 +0000963 WIntTy = getFromTargetType(Target.getWIntType());
964
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000965 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
966 InitBuiltinType(Char16Ty, BuiltinType::Char16);
967 else // C99
968 Char16Ty = getFromTargetType(Target.getChar16Type());
969
970 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
971 InitBuiltinType(Char32Ty, BuiltinType::Char32);
972 else // C99
973 Char32Ty = getFromTargetType(Target.getChar32Type());
974
Douglas Gregor898574e2008-12-05 23:32:09 +0000975 // Placeholder type for type-dependent expressions whose type is
976 // completely unknown. No code should ever check a type against
977 // DependentTy and users should never see it; however, it is here to
978 // help diagnose failures to properly check for type-dependent
979 // expressions.
980 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000981
John McCall2a984ca2010-10-12 00:20:44 +0000982 // Placeholder type for functions.
983 InitBuiltinType(OverloadTy, BuiltinType::Overload);
984
John McCall864c0412011-04-26 20:42:42 +0000985 // Placeholder type for bound members.
986 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
987
John McCall3c3b7f92011-10-25 17:37:35 +0000988 // Placeholder type for pseudo-objects.
989 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
990
John McCall1de4d4e2011-04-07 08:22:57 +0000991 // "any" type; useful for debugger-like clients.
992 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
993
John McCall0ddaeb92011-10-17 18:09:15 +0000994 // Placeholder type for unbridged ARC casts.
995 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
996
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000997 // Placeholder type for builtin functions.
998 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
999
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 // C99 6.2.5p11.
1001 FloatComplexTy = getComplexType(FloatTy);
1002 DoubleComplexTy = getComplexType(DoubleTy);
1003 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001004
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001005 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001006 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1007 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001008 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +00001009
1010 if (LangOpts.OpenCL) {
1011 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1012 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1013 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1014 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1015 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1016 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001017
Guy Benyei21f18c42013-02-07 10:55:47 +00001018 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001019 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +00001020 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001021
1022 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001023 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1024 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001025
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001027
1028 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001030 // void * type
1031 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001032
1033 // nullptr type (C++0x 2.14.7)
1034 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001035
1036 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1037 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001038
1039 // Builtin type used to help define __builtin_va_list.
1040 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001041}
1042
David Blaikied6471f72011-09-25 23:23:43 +00001043DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001044 return SourceMgr.getDiagnostics();
1045}
1046
Douglas Gregor63200642010-08-30 16:49:28 +00001047AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1048 AttrVec *&Result = DeclAttrs[D];
1049 if (!Result) {
1050 void *Mem = Allocate(sizeof(AttrVec));
1051 Result = new (Mem) AttrVec;
1052 }
1053
1054 return *Result;
1055}
1056
1057/// \brief Erase the attributes corresponding to the given declaration.
1058void ASTContext::eraseDeclAttrs(const Decl *D) {
1059 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1060 if (Pos != DeclAttrs.end()) {
1061 Pos->second->~AttrVec();
1062 DeclAttrs.erase(Pos);
1063 }
1064}
1065
Larisse Voufoef4579c2013-08-06 01:03:05 +00001066// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001067MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001068ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001069 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001070 return getTemplateOrSpecializationInfo(Var)
1071 .dyn_cast<MemberSpecializationInfo *>();
1072}
1073
1074ASTContext::TemplateOrSpecializationInfo
1075ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1076 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1077 TemplateOrInstantiation.find(Var);
1078 if (Pos == TemplateOrInstantiation.end())
1079 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregor7caa6822009-07-24 20:34:43 +00001081 return Pos->second;
1082}
1083
Mike Stump1eb44332009-09-09 15:08:12 +00001084void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001085ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001086 TemplateSpecializationKind TSK,
1087 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001088 assert(Inst->isStaticDataMember() && "Not a static data member");
1089 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001090 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1091 Tmpl, TSK, PointOfInstantiation));
1092}
1093
1094void
1095ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1096 TemplateOrSpecializationInfo TSI) {
1097 assert(!TemplateOrInstantiation[Inst] &&
1098 "Already noted what the variable was instantiated from");
1099 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001100}
1101
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001102FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1103 const FunctionDecl *FD){
1104 assert(FD && "Specialization is 0");
1105 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001106 = ClassScopeSpecializationPattern.find(FD);
1107 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001108 return 0;
1109
1110 return Pos->second;
1111}
1112
1113void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1114 FunctionDecl *Pattern) {
1115 assert(FD && "Specialization is 0");
1116 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001117 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001118}
1119
John McCall7ba107a2009-11-18 02:36:19 +00001120NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001121ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001122 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001123 = InstantiatedFromUsingDecl.find(UUD);
1124 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001125 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Anders Carlsson0d8df782009-08-29 19:37:28 +00001127 return Pos->second;
1128}
1129
1130void
John McCalled976492009-12-04 22:46:56 +00001131ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1132 assert((isa<UsingDecl>(Pattern) ||
1133 isa<UnresolvedUsingValueDecl>(Pattern) ||
1134 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1135 "pattern decl is not a using decl");
1136 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1137 InstantiatedFromUsingDecl[Inst] = Pattern;
1138}
1139
1140UsingShadowDecl *
1141ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1142 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1143 = InstantiatedFromUsingShadowDecl.find(Inst);
1144 if (Pos == InstantiatedFromUsingShadowDecl.end())
1145 return 0;
1146
1147 return Pos->second;
1148}
1149
1150void
1151ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1152 UsingShadowDecl *Pattern) {
1153 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001155}
1156
Anders Carlssond8b285f2009-09-01 04:26:58 +00001157FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1158 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1159 = InstantiatedFromUnnamedFieldDecl.find(Field);
1160 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1161 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Anders Carlssond8b285f2009-09-01 04:26:58 +00001163 return Pos->second;
1164}
1165
1166void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1167 FieldDecl *Tmpl) {
1168 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1169 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1170 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1171 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Anders Carlssond8b285f2009-09-01 04:26:58 +00001173 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1174}
1175
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001176ASTContext::overridden_cxx_method_iterator
1177ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1178 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001179 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001180 if (Pos == OverriddenMethods.end())
1181 return 0;
1182
1183 return Pos->second.begin();
1184}
1185
1186ASTContext::overridden_cxx_method_iterator
1187ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001189 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001190 if (Pos == OverriddenMethods.end())
1191 return 0;
1192
1193 return Pos->second.end();
1194}
1195
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001196unsigned
1197ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1198 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001199 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001200 if (Pos == OverriddenMethods.end())
1201 return 0;
1202
1203 return Pos->second.size();
1204}
1205
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001206void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1207 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001208 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001209 OverriddenMethods[Method].push_back(Overridden);
1210}
1211
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001212void ASTContext::getOverriddenMethods(
1213 const NamedDecl *D,
1214 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001215 assert(D);
1216
1217 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001218 Overridden.append(overridden_methods_begin(CXXMethod),
1219 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001220 return;
1221 }
1222
1223 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1224 if (!Method)
1225 return;
1226
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001227 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1228 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001229 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001230}
1231
Douglas Gregore6649772011-12-03 00:30:27 +00001232void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1233 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1234 assert(!Import->isFromASTFile() && "Non-local import declaration");
1235 if (!FirstLocalImport) {
1236 FirstLocalImport = Import;
1237 LastLocalImport = Import;
1238 return;
1239 }
1240
1241 LastLocalImport->NextLocalImport = Import;
1242 LastLocalImport = Import;
1243}
1244
Chris Lattner464175b2007-07-18 17:52:12 +00001245//===----------------------------------------------------------------------===//
1246// Type Sizing and Analysis
1247//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001248
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001249/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1250/// scalar floating point type.
1251const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001252 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001253 assert(BT && "Not a floating point type!");
1254 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001255 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001256 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001257 case BuiltinType::Float: return Target->getFloatFormat();
1258 case BuiltinType::Double: return Target->getDoubleFormat();
1259 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001260 }
1261}
1262
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001263CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001264 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001265
John McCall4081a5c2010-10-08 18:24:19 +00001266 bool UseAlignAttrOnly = false;
1267 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1268 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001269
John McCall4081a5c2010-10-08 18:24:19 +00001270 // __attribute__((aligned)) can increase or decrease alignment
1271 // *except* on a struct or struct member, where it only increases
1272 // alignment unless 'packed' is also specified.
1273 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001274 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001275 // ignore that possibility; Sema should diagnose it.
1276 if (isa<FieldDecl>(D)) {
1277 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1278 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1279 } else {
1280 UseAlignAttrOnly = true;
1281 }
1282 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001283 else if (isa<FieldDecl>(D))
1284 UseAlignAttrOnly =
1285 D->hasAttr<PackedAttr>() ||
1286 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001287
John McCallba4f5d52011-01-20 07:57:12 +00001288 // If we're using the align attribute only, just ignore everything
1289 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001290 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001291 // do nothing
1292
John McCall4081a5c2010-10-08 18:24:19 +00001293 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001294 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001295 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001296 if (ForAlignof)
Sebastian Redl5d484e82009-11-23 17:18:46 +00001297 T = RT->getPointeeType();
1298 else
1299 T = getPointerType(RT->getPointeeType());
1300 }
1301 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001302 // Adjust alignments of declarations with array type by the
1303 // large-array alignment on the target.
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001304 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001305 unsigned MinWidth = Target->getLargeArrayMinWidth();
1306 if (!ForAlignof && MinWidth) {
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001307 if (isa<VariableArrayType>(arrayType))
1308 Align = std::max(Align, Target->getLargeArrayAlign());
1309 else if (isa<ConstantArrayType>(arrayType) &&
1310 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1311 Align = std::max(Align, Target->getLargeArrayAlign());
1312 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001313
John McCall3b657512011-01-19 10:06:00 +00001314 // Walk through any array types while we're at it.
1315 T = getBaseElementType(arrayType);
1316 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001317 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1319 if (VD->hasGlobalStorage())
1320 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1321 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001322 }
John McCallba4f5d52011-01-20 07:57:12 +00001323
1324 // Fields can be subject to extra alignment constraints, like if
1325 // the field is packed, the struct is packed, or the struct has a
1326 // a max-field-alignment constraint (#pragma pack). So calculate
1327 // the actual alignment of the field within the struct, and then
1328 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001329 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1330 const RecordDecl *Parent = Field->getParent();
1331 // We can only produce a sensible answer if the record is valid.
1332 if (!Parent->isInvalidDecl()) {
1333 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001334
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001335 // Start with the record's overall alignment.
1336 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001337
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001338 // Use the GCD of that and the offset within the record.
1339 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1340 if (Offset > 0) {
1341 // Alignment is always a power of 2, so the GCD will be a power of 2,
1342 // which means we get to do this crazy thing instead of Euclid's.
1343 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1344 if (LowBitOfOffset < FieldAlign)
1345 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1346 }
1347
1348 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001349 }
Charles Davis05f62472010-02-23 04:52:00 +00001350 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001351 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001352
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001353 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001354}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001355
John McCall929bbfb2012-08-21 04:10:00 +00001356// getTypeInfoDataSizeInChars - Return the size of a type, in
1357// chars. If the type is a record, its data size is returned. This is
1358// the size of the memcpy that's performed when assigning this type
1359// using a trivial copy/move assignment operator.
1360std::pair<CharUnits, CharUnits>
1361ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1362 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1363
1364 // In C++, objects can sometimes be allocated into the tail padding
1365 // of a base-class subobject. We decide whether that's possible
1366 // during class layout, so here we can just trust the layout results.
1367 if (getLangOpts().CPlusPlus) {
1368 if (const RecordType *RT = T->getAs<RecordType>()) {
1369 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1370 sizeAndAlign.first = layout.getDataSize();
1371 }
1372 }
1373
1374 return sizeAndAlign;
1375}
1376
Richard Trieu910f17e2013-05-14 21:59:17 +00001377/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1378/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1379std::pair<CharUnits, CharUnits>
1380static getConstantArrayInfoInChars(const ASTContext &Context,
1381 const ConstantArrayType *CAT) {
1382 std::pair<CharUnits, CharUnits> EltInfo =
1383 Context.getTypeInfoInChars(CAT->getElementType());
1384 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001385 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1386 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001387 "Overflow in array type char size evaluation");
1388 uint64_t Width = EltInfo.first.getQuantity() * Size;
1389 unsigned Align = EltInfo.second.getQuantity();
1390 Width = llvm::RoundUpToAlignment(Width, Align);
1391 return std::make_pair(CharUnits::fromQuantity(Width),
1392 CharUnits::fromQuantity(Align));
1393}
1394
John McCallea1471e2010-05-20 01:18:31 +00001395std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001396ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001397 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1398 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001399 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001400 return std::make_pair(toCharUnitsFromBits(Info.first),
1401 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001402}
1403
1404std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001405ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001406 return getTypeInfoInChars(T.getTypePtr());
1407}
1408
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001409std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1410 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1411 if (it != MemoizedTypeInfo.end())
1412 return it->second;
1413
1414 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1415 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1416 return Info;
1417}
1418
1419/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1420/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001421///
1422/// FIXME: Pointers into different addr spaces could have different sizes and
1423/// alignment requirements: getPointerInfo should take an AddrSpace, this
1424/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001425std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001426ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001427 uint64_t Width=0;
1428 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001429 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001430#define TYPE(Class, Base)
1431#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001432#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001433#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001434#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1435 case Type::Class: \
1436 assert(!T->isDependentType() && "should not see dependent types here"); \
1437 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001438#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001439 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001440
Chris Lattner692233e2007-07-13 22:27:08 +00001441 case Type::FunctionNoProto:
1442 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001443 // GCC extension: alignof(function) = 32 bits
1444 Width = 0;
1445 Align = 32;
1446 break;
1447
Douglas Gregor72564e72009-02-26 23:50:07 +00001448 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001449 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001450 Width = 0;
1451 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1452 break;
1453
Steve Narofffb22d962007-08-30 01:06:46 +00001454 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001455 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Chris Lattner98be4942008-03-05 18:54:05 +00001457 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001458 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001459 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1460 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001461 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001462 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001463 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001464 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001465 }
Nate Begeman213541a2008-04-18 23:10:10 +00001466 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001467 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001468 const VectorType *VT = cast<VectorType>(T);
1469 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1470 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001471 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001472 // If the alignment is not a power of 2, round up to the next power of 2.
1473 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001474 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001475 Align = llvm::NextPowerOf2(Align);
1476 Width = llvm::RoundUpToAlignment(Width, Align);
1477 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001478 // Adjust the alignment based on the target max.
1479 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1480 if (TargetVectorAlign && TargetVectorAlign < Align)
1481 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001482 break;
1483 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001484
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001485 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001486 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001487 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001488 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001489 // GCC extension: alignof(void) = 8 bits.
1490 Width = 0;
1491 Align = 8;
1492 break;
1493
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001494 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001495 Width = Target->getBoolWidth();
1496 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001497 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001498 case BuiltinType::Char_S:
1499 case BuiltinType::Char_U:
1500 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001502 Width = Target->getCharWidth();
1503 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001504 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001505 case BuiltinType::WChar_S:
1506 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001507 Width = Target->getWCharWidth();
1508 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001509 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001510 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001511 Width = Target->getChar16Width();
1512 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001513 break;
1514 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001515 Width = Target->getChar32Width();
1516 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001517 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001518 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001519 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001520 Width = Target->getShortWidth();
1521 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001522 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001523 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001524 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001525 Width = Target->getIntWidth();
1526 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001527 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001528 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001529 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001530 Width = Target->getLongWidth();
1531 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001532 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001533 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001534 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getLongLongWidth();
1536 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001537 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001538 case BuiltinType::Int128:
1539 case BuiltinType::UInt128:
1540 Width = 128;
1541 Align = 128; // int128_t is 128-bit aligned on all targets.
1542 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001543 case BuiltinType::Half:
1544 Width = Target->getHalfWidth();
1545 Align = Target->getHalfAlign();
1546 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001547 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001548 Width = Target->getFloatWidth();
1549 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001550 break;
1551 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001552 Width = Target->getDoubleWidth();
1553 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001554 break;
1555 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001556 Width = Target->getLongDoubleWidth();
1557 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001558 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001559 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001560 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1561 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001562 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001563 case BuiltinType::ObjCId:
1564 case BuiltinType::ObjCClass:
1565 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001566 Width = Target->getPointerWidth(0);
1567 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001568 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001569 case BuiltinType::OCLSampler:
1570 // Samplers are modeled as integers.
1571 Width = Target->getIntWidth();
1572 Align = Target->getIntAlign();
1573 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001574 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001575 case BuiltinType::OCLImage1d:
1576 case BuiltinType::OCLImage1dArray:
1577 case BuiltinType::OCLImage1dBuffer:
1578 case BuiltinType::OCLImage2d:
1579 case BuiltinType::OCLImage2dArray:
1580 case BuiltinType::OCLImage3d:
1581 // Currently these types are pointers to opaque types.
1582 Width = Target->getPointerWidth(0);
1583 Align = Target->getPointerAlign(0);
1584 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001585 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001586 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001587 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001588 Width = Target->getPointerWidth(0);
1589 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001590 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001591 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001592 unsigned AS = getTargetAddressSpace(
1593 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001594 Width = Target->getPointerWidth(AS);
1595 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001596 break;
1597 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001598 case Type::LValueReference:
1599 case Type::RValueReference: {
1600 // alignof and sizeof should never enter this code path here, so we go
1601 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001602 unsigned AS = getTargetAddressSpace(
1603 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001604 Width = Target->getPointerWidth(AS);
1605 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001606 break;
1607 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001608 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001609 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001610 Width = Target->getPointerWidth(AS);
1611 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001612 break;
1613 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001614 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001615 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001616 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001617 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001618 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001619 case Type::Complex: {
1620 // Complex types have the same alignment as their elements, but twice the
1621 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001622 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001623 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001624 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001625 Align = EltInfo.second;
1626 break;
1627 }
John McCallc12c5bb2010-05-15 11:32:37 +00001628 case Type::ObjCObject:
1629 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001630 case Type::Decayed:
1631 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001632 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001633 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001634 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001635 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001636 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001637 break;
1638 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001639 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001640 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001641 const TagType *TT = cast<TagType>(T);
1642
1643 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001644 Width = 8;
1645 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001646 break;
1647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Daniel Dunbar1d751182008-11-08 05:48:37 +00001649 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001650 return getTypeInfo(ET->getDecl()->getIntegerType());
1651
Daniel Dunbar1d751182008-11-08 05:48:37 +00001652 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001653 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001654 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001655 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001656 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001657 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001658
Chris Lattner9fcfe922009-10-22 05:17:15 +00001659 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001660 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1661 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001662
Richard Smith34b41d92011-02-20 03:19:35 +00001663 case Type::Auto: {
1664 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001665 assert(!A->getDeducedType().isNull() &&
1666 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001667 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001668 }
1669
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001670 case Type::Paren:
1671 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1672
Douglas Gregor18857642009-04-30 17:32:17 +00001673 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001674 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001675 std::pair<uint64_t, unsigned> Info
1676 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001677 // If the typedef has an aligned attribute on it, it overrides any computed
1678 // alignment we have. This violates the GCC documentation (which says that
1679 // attribute(aligned) can only round up) but matches its implementation.
1680 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1681 Align = AttrAlign;
1682 else
1683 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001684 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001685 break;
Chris Lattner71763312008-04-06 22:05:18 +00001686 }
Douglas Gregor18857642009-04-30 17:32:17 +00001687
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001688 case Type::Elaborated:
1689 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCall9d156a72011-01-06 01:58:22 +00001691 case Type::Attributed:
1692 return getTypeInfo(
1693 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1694
Eli Friedmanb001de72011-10-06 23:00:33 +00001695 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001696 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001697 std::pair<uint64_t, unsigned> Info
1698 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1699 Width = Info.first;
1700 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001701
1702 // If the size of the type doesn't exceed the platform's max
1703 // atomic promotion width, make the size and alignment more
1704 // favorable to atomic operations:
1705 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1706 // Round the size up to a power of 2.
1707 if (!llvm::isPowerOf2_64(Width))
1708 Width = llvm::NextPowerOf2(Width);
1709
1710 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001711 Align = static_cast<unsigned>(Width);
1712 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001713 }
1714
Douglas Gregor18857642009-04-30 17:32:17 +00001715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Eli Friedman2be46072011-10-14 20:59:01 +00001717 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001718 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001719}
1720
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001721/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1722CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1723 return CharUnits::fromQuantity(BitSize / getCharWidth());
1724}
1725
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001726/// toBits - Convert a size in characters to a size in characters.
1727int64_t ASTContext::toBits(CharUnits CharSize) const {
1728 return CharSize.getQuantity() * getCharWidth();
1729}
1730
Ken Dyckbdc601b2009-12-22 14:23:30 +00001731/// getTypeSizeInChars - Return the size of the specified type, in characters.
1732/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001733CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001734 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001735}
Jay Foad4ba2a172011-01-12 09:06:06 +00001736CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001737 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001738}
1739
Ken Dyck16e20cc2010-01-26 17:25:18 +00001740/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001741/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001742CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001743 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001744}
Jay Foad4ba2a172011-01-12 09:06:06 +00001745CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001746 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001747}
1748
Chris Lattner34ebde42009-01-27 18:08:34 +00001749/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1750/// type for the current target in bits. This can be different than the ABI
1751/// alignment in cases where it is beneficial for performance to overalign
1752/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001753unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001754 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001755
1756 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001757 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001758 T = CT->getElementType().getTypePtr();
1759 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001760 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1761 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001762 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1763
Chris Lattner34ebde42009-01-27 18:08:34 +00001764 return ABIAlign;
1765}
1766
Ulrich Weigand6b203512013-05-06 16:23:57 +00001767/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1768/// to a global variable of the specified type.
1769unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1770 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1771}
1772
1773/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1774/// should be given to a global variable of the specified type.
1775CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1776 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1777}
1778
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001779/// DeepCollectObjCIvars -
1780/// This routine first collects all declared, but not synthesized, ivars in
1781/// super class and then collects all ivars, including those synthesized for
1782/// current class. This routine is used for implementation of current class
1783/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001784///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001785void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1786 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001787 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001788 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1789 DeepCollectObjCIvars(SuperClass, false, Ivars);
1790 if (!leafClass) {
1791 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1792 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001793 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001794 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001795 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001796 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001797 Iv= Iv->getNextIvar())
1798 Ivars.push_back(Iv);
1799 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001800}
1801
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001802/// CollectInheritedProtocols - Collect all protocols in current class and
1803/// those inherited by it.
1804void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001805 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001806 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001807 // We can use protocol_iterator here instead of
1808 // all_referenced_protocol_iterator since we are walking all categories.
1809 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1810 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001811 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001812 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001813 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001814 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001815 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001816 CollectInheritedProtocols(*P, Protocols);
1817 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001818 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001819
1820 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001821 for (ObjCInterfaceDecl::visible_categories_iterator
1822 Cat = OI->visible_categories_begin(),
1823 CatEnd = OI->visible_categories_end();
1824 Cat != CatEnd; ++Cat) {
1825 CollectInheritedProtocols(*Cat, Protocols);
1826 }
1827
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001828 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1829 while (SD) {
1830 CollectInheritedProtocols(SD, Protocols);
1831 SD = SD->getSuperClass();
1832 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001833 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001834 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001835 PE = OC->protocol_end(); P != PE; ++P) {
1836 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001837 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001838 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1839 PE = Proto->protocol_end(); P != PE; ++P)
1840 CollectInheritedProtocols(*P, Protocols);
1841 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001842 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001843 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1844 PE = OP->protocol_end(); P != PE; ++P) {
1845 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001846 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1848 PE = Proto->protocol_end(); P != PE; ++P)
1849 CollectInheritedProtocols(*P, Protocols);
1850 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001851 }
1852}
1853
Jay Foad4ba2a172011-01-12 09:06:06 +00001854unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001855 unsigned count = 0;
1856 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001857 for (ObjCInterfaceDecl::known_extensions_iterator
1858 Ext = OI->known_extensions_begin(),
1859 ExtEnd = OI->known_extensions_end();
1860 Ext != ExtEnd; ++Ext) {
1861 count += Ext->ivar_size();
1862 }
1863
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001864 // Count ivar defined in this class's implementation. This
1865 // includes synthesized ivars.
1866 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001867 count += ImplDecl->ivar_size();
1868
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001869 return count;
1870}
1871
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001872bool ASTContext::isSentinelNullExpr(const Expr *E) {
1873 if (!E)
1874 return false;
1875
1876 // nullptr_t is always treated as null.
1877 if (E->getType()->isNullPtrType()) return true;
1878
1879 if (E->getType()->isAnyPointerType() &&
1880 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1881 Expr::NPC_ValueDependentIsNull))
1882 return true;
1883
1884 // Unfortunately, __null has type 'int'.
1885 if (isa<GNUNullExpr>(E)) return true;
1886
1887 return false;
1888}
1889
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001890/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1891ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1892 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1893 I = ObjCImpls.find(D);
1894 if (I != ObjCImpls.end())
1895 return cast<ObjCImplementationDecl>(I->second);
1896 return 0;
1897}
1898/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1899ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCCategoryImplDecl>(I->second);
1904 return 0;
1905}
1906
1907/// \brief Set the implementation of ObjCInterfaceDecl.
1908void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1909 ObjCImplementationDecl *ImplD) {
1910 assert(IFaceD && ImplD && "Passed null params");
1911 ObjCImpls[IFaceD] = ImplD;
1912}
1913/// \brief Set the implementation of ObjCCategoryDecl.
1914void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1915 ObjCCategoryImplDecl *ImplD) {
1916 assert(CatD && ImplD && "Passed null params");
1917 ObjCImpls[CatD] = ImplD;
1918}
1919
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001920const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1921 const NamedDecl *ND) const {
1922 if (const ObjCInterfaceDecl *ID =
1923 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001924 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001925 if (const ObjCCategoryDecl *CD =
1926 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001927 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001928 if (const ObjCImplDecl *IMD =
1929 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001930 return IMD->getClassInterface();
1931
1932 return 0;
1933}
1934
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001935/// \brief Get the copy initialization expression of VarDecl,or NULL if
1936/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001937Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001938 assert(VD && "Passed null params");
1939 assert(VD->hasAttr<BlocksAttr>() &&
1940 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001941 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001942 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001943 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1944}
1945
1946/// \brief Set the copy inialization expression of a block var decl.
1947void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1948 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001949 assert(VD->hasAttr<BlocksAttr>() &&
1950 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001951 BlockVarCopyInits[VD] = Init;
1952}
1953
John McCalla93c9342009-12-07 02:54:59 +00001954TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001955 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001956 if (!DataSize)
1957 DataSize = TypeLoc::getFullDataSizeForType(T);
1958 else
1959 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001960 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001961
John McCalla93c9342009-12-07 02:54:59 +00001962 TypeSourceInfo *TInfo =
1963 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1964 new (TInfo) TypeSourceInfo(T);
1965 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001966}
1967
John McCalla93c9342009-12-07 02:54:59 +00001968TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001969 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001970 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001971 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001972 return DI;
1973}
1974
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001975const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001976ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001977 return getObjCLayout(D, 0);
1978}
1979
1980const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001981ASTContext::getASTObjCImplementationLayout(
1982 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001983 return getObjCLayout(D->getClassInterface(), D);
1984}
1985
Chris Lattnera7674d82007-07-13 22:13:22 +00001986//===----------------------------------------------------------------------===//
1987// Type creation/memoization methods
1988//===----------------------------------------------------------------------===//
1989
Jay Foad4ba2a172011-01-12 09:06:06 +00001990QualType
John McCall3b657512011-01-19 10:06:00 +00001991ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1992 unsigned fastQuals = quals.getFastQualifiers();
1993 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001994
1995 // Check if we've already instantiated this type.
1996 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001997 ExtQuals::Profile(ID, baseType, quals);
1998 void *insertPos = 0;
1999 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2000 assert(eq->getQualifiers() == quals);
2001 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002002 }
2003
John McCall3b657512011-01-19 10:06:00 +00002004 // If the base type is not canonical, make the appropriate canonical type.
2005 QualType canon;
2006 if (!baseType->isCanonicalUnqualified()) {
2007 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002008 canonSplit.Quals.addConsistentQualifiers(quals);
2009 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002010
2011 // Re-find the insert position.
2012 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2013 }
2014
2015 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2016 ExtQualNodes.InsertNode(eq, insertPos);
2017 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002018}
2019
Jay Foad4ba2a172011-01-12 09:06:06 +00002020QualType
2021ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002022 QualType CanT = getCanonicalType(T);
2023 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002024 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002025
John McCall0953e762009-09-24 19:53:00 +00002026 // If we are composing extended qualifiers together, merge together
2027 // into one ExtQuals node.
2028 QualifierCollector Quals;
2029 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCall0953e762009-09-24 19:53:00 +00002031 // If this type already has an address space specified, it cannot get
2032 // another one.
2033 assert(!Quals.hasAddressSpace() &&
2034 "Type cannot be in multiple addr spaces!");
2035 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002036
John McCall0953e762009-09-24 19:53:00 +00002037 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002038}
2039
Chris Lattnerb7d25532009-02-18 22:53:11 +00002040QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002041 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002042 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002043 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002044 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002045
John McCall7f040a92010-12-24 02:08:15 +00002046 if (const PointerType *ptr = T->getAs<PointerType>()) {
2047 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002048 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002049 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2050 return getPointerType(ResultType);
2051 }
2052 }
Mike Stump1eb44332009-09-09 15:08:12 +00002053
John McCall0953e762009-09-24 19:53:00 +00002054 // If we are composing extended qualifiers together, merge together
2055 // into one ExtQuals node.
2056 QualifierCollector Quals;
2057 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
John McCall0953e762009-09-24 19:53:00 +00002059 // If this type already has an ObjCGC specified, it cannot get
2060 // another one.
2061 assert(!Quals.hasObjCGCAttr() &&
2062 "Type cannot have multiple ObjCGCs!");
2063 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002064
John McCall0953e762009-09-24 19:53:00 +00002065 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002066}
Chris Lattnera7674d82007-07-13 22:13:22 +00002067
John McCalle6a365d2010-12-19 02:44:49 +00002068const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2069 FunctionType::ExtInfo Info) {
2070 if (T->getExtInfo() == Info)
2071 return T;
2072
2073 QualType Result;
2074 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2075 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2076 } else {
2077 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2078 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2079 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002080 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002081 }
2082
2083 return cast<FunctionType>(Result.getTypePtr());
2084}
2085
Richard Smith60e141e2013-05-04 07:00:32 +00002086void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2087 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002088 FD = FD->getMostRecentDecl();
2089 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002090 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2092 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002093 if (FunctionDecl *Next = FD->getPreviousDecl())
2094 FD = Next;
2095 else
2096 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002097 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002098 if (ASTMutationListener *L = getASTMutationListener())
2099 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002100}
2101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102/// getComplexType - Return the uniqued reference to the type for a complex
2103/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002104QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // Unique pointers, to guarantee there is only one pointer of a particular
2106 // structure.
2107 llvm::FoldingSetNodeID ID;
2108 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 void *InsertPos = 0;
2111 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2112 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 // If the pointee type isn't canonical, this won't be a canonical type either,
2115 // so fill in the canonical type field.
2116 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002117 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002118 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 // Get the new insert position for the node we care about.
2121 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002122 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 }
John McCall6b304a02009-09-24 23:30:46 +00002124 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 Types.push_back(New);
2126 ComplexTypes.InsertNode(New, InsertPos);
2127 return QualType(New, 0);
2128}
2129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130/// getPointerType - Return the uniqued reference to the type for a pointer to
2131/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002132QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 // Unique pointers, to guarantee there is only one pointer of a particular
2134 // structure.
2135 llvm::FoldingSetNodeID ID;
2136 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 void *InsertPos = 0;
2139 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2140 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // If the pointee type isn't canonical, this won't be a canonical type either,
2143 // so fill in the canonical type field.
2144 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002145 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002146 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Bob Wilsonc90cc932013-03-15 17:12:43 +00002148 // Get the new insert position for the node we care about.
2149 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2150 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2151 }
John McCall6b304a02009-09-24 23:30:46 +00002152 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 Types.push_back(New);
2154 PointerTypes.InsertNode(New, InsertPos);
2155 return QualType(New, 0);
2156}
2157
Reid Kleckner12df2462013-06-24 17:51:48 +00002158QualType ASTContext::getDecayedType(QualType T) const {
2159 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2160
2161 llvm::FoldingSetNodeID ID;
2162 DecayedType::Profile(ID, T);
2163 void *InsertPos = 0;
2164 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2165 return QualType(DT, 0);
2166
2167 QualType Decayed;
2168
2169 // C99 6.7.5.3p7:
2170 // A declaration of a parameter as "array of type" shall be
2171 // adjusted to "qualified pointer to type", where the type
2172 // qualifiers (if any) are those specified within the [ and ] of
2173 // the array type derivation.
2174 if (T->isArrayType())
2175 Decayed = getArrayDecayedType(T);
2176
2177 // C99 6.7.5.3p8:
2178 // A declaration of a parameter as "function returning type"
2179 // shall be adjusted to "pointer to function returning type", as
2180 // in 6.3.2.1.
2181 if (T->isFunctionType())
2182 Decayed = getPointerType(T);
2183
2184 QualType Canonical = getCanonicalType(Decayed);
2185
2186 // Get the new insert position for the node we care about.
2187 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2188 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2189
2190 DecayedType *New =
2191 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2192 Types.push_back(New);
2193 DecayedTypes.InsertNode(New, InsertPos);
2194 return QualType(New, 0);
2195}
2196
Mike Stump1eb44332009-09-09 15:08:12 +00002197/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002198/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002199QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002200 assert(T->isFunctionType() && "block of function types only");
2201 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002202 // structure.
2203 llvm::FoldingSetNodeID ID;
2204 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Steve Naroff5618bd42008-08-27 16:04:49 +00002206 void *InsertPos = 0;
2207 if (BlockPointerType *PT =
2208 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2209 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002210
2211 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002212 // type either so fill in the canonical type field.
2213 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002214 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002215 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Steve Naroff5618bd42008-08-27 16:04:49 +00002217 // Get the new insert position for the node we care about.
2218 BlockPointerType *NewIP =
2219 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002220 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002221 }
John McCall6b304a02009-09-24 23:30:46 +00002222 BlockPointerType *New
2223 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002224 Types.push_back(New);
2225 BlockPointerTypes.InsertNode(New, InsertPos);
2226 return QualType(New, 0);
2227}
2228
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002229/// getLValueReferenceType - Return the uniqued reference to the type for an
2230/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002231QualType
2232ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002233 assert(getCanonicalType(T) != OverloadTy &&
2234 "Unresolved overloaded function type");
2235
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 // Unique pointers, to guarantee there is only one pointer of a particular
2237 // structure.
2238 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002239 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002240
2241 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002242 if (LValueReferenceType *RT =
2243 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002245
John McCall54e14c42009-10-22 22:37:11 +00002246 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // If the referencee type isn't canonical, this won't be a canonical type
2249 // either, so fill in the canonical type field.
2250 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002251 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2252 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2253 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002254
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002256 LValueReferenceType *NewIP =
2257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002258 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 }
2260
John McCall6b304a02009-09-24 23:30:46 +00002261 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002262 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2263 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002264 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002265 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002266
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002267 return QualType(New, 0);
2268}
2269
2270/// getRValueReferenceType - Return the uniqued reference to the type for an
2271/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002272QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002273 // Unique pointers, to guarantee there is only one pointer of a particular
2274 // structure.
2275 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002276 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002277
2278 void *InsertPos = 0;
2279 if (RValueReferenceType *RT =
2280 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2281 return QualType(RT, 0);
2282
John McCall54e14c42009-10-22 22:37:11 +00002283 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2284
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002285 // If the referencee type isn't canonical, this won't be a canonical type
2286 // either, so fill in the canonical type field.
2287 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002288 if (InnerRef || !T.isCanonical()) {
2289 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2290 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002291
2292 // Get the new insert position for the node we care about.
2293 RValueReferenceType *NewIP =
2294 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002295 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002296 }
2297
John McCall6b304a02009-09-24 23:30:46 +00002298 RValueReferenceType *New
2299 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002300 Types.push_back(New);
2301 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 return QualType(New, 0);
2303}
2304
Sebastian Redlf30208a2009-01-24 21:16:55 +00002305/// getMemberPointerType - Return the uniqued reference to the type for a
2306/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002307QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002308 // Unique pointers, to guarantee there is only one pointer of a particular
2309 // structure.
2310 llvm::FoldingSetNodeID ID;
2311 MemberPointerType::Profile(ID, T, Cls);
2312
2313 void *InsertPos = 0;
2314 if (MemberPointerType *PT =
2315 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2316 return QualType(PT, 0);
2317
2318 // If the pointee or class type isn't canonical, this won't be a canonical
2319 // type either, so fill in the canonical type field.
2320 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002321 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002322 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2323
2324 // Get the new insert position for the node we care about.
2325 MemberPointerType *NewIP =
2326 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002327 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002328 }
John McCall6b304a02009-09-24 23:30:46 +00002329 MemberPointerType *New
2330 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002331 Types.push_back(New);
2332 MemberPointerTypes.InsertNode(New, InsertPos);
2333 return QualType(New, 0);
2334}
2335
Mike Stump1eb44332009-09-09 15:08:12 +00002336/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002337/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002338QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002339 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002340 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002341 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002342 assert((EltTy->isDependentType() ||
2343 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002344 "Constant array of VLAs is illegal!");
2345
Chris Lattner38aeec72009-05-13 04:12:56 +00002346 // Convert the array size into a canonical width matching the pointer size for
2347 // the target.
2348 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002349 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002350 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002353 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002356 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002357 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002359
John McCall3b657512011-01-19 10:06:00 +00002360 // If the element type isn't canonical or has qualifiers, this won't
2361 // be a canonical type either, so fill in the canonical type field.
2362 QualType Canon;
2363 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2364 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002365 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002366 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002367 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002370 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002371 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002372 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
John McCall6b304a02009-09-24 23:30:46 +00002375 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002376 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002377 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 Types.push_back(New);
2379 return QualType(New, 0);
2380}
2381
John McCallce889032011-01-18 08:40:38 +00002382/// getVariableArrayDecayedType - Turns the given type, which may be
2383/// variably-modified, into the corresponding type with all the known
2384/// sizes replaced with [*].
2385QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2386 // Vastly most common case.
2387 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002388
John McCallce889032011-01-18 08:40:38 +00002389 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002390
John McCallce889032011-01-18 08:40:38 +00002391 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002392 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002393 switch (ty->getTypeClass()) {
2394#define TYPE(Class, Base)
2395#define ABSTRACT_TYPE(Class, Base)
2396#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2397#include "clang/AST/TypeNodes.def"
2398 llvm_unreachable("didn't desugar past all non-canonical types?");
2399
2400 // These types should never be variably-modified.
2401 case Type::Builtin:
2402 case Type::Complex:
2403 case Type::Vector:
2404 case Type::ExtVector:
2405 case Type::DependentSizedExtVector:
2406 case Type::ObjCObject:
2407 case Type::ObjCInterface:
2408 case Type::ObjCObjectPointer:
2409 case Type::Record:
2410 case Type::Enum:
2411 case Type::UnresolvedUsing:
2412 case Type::TypeOfExpr:
2413 case Type::TypeOf:
2414 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002415 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002416 case Type::DependentName:
2417 case Type::InjectedClassName:
2418 case Type::TemplateSpecialization:
2419 case Type::DependentTemplateSpecialization:
2420 case Type::TemplateTypeParm:
2421 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002422 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002423 case Type::PackExpansion:
2424 llvm_unreachable("type should never be variably-modified");
2425
2426 // These types can be variably-modified but should never need to
2427 // further decay.
2428 case Type::FunctionNoProto:
2429 case Type::FunctionProto:
2430 case Type::BlockPointer:
2431 case Type::MemberPointer:
2432 return type;
2433
2434 // These types can be variably-modified. All these modifications
2435 // preserve structure except as noted by comments.
2436 // TODO: if we ever care about optimizing VLAs, there are no-op
2437 // optimizations available here.
2438 case Type::Pointer:
2439 result = getPointerType(getVariableArrayDecayedType(
2440 cast<PointerType>(ty)->getPointeeType()));
2441 break;
2442
2443 case Type::LValueReference: {
2444 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2445 result = getLValueReferenceType(
2446 getVariableArrayDecayedType(lv->getPointeeType()),
2447 lv->isSpelledAsLValue());
2448 break;
2449 }
2450
2451 case Type::RValueReference: {
2452 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2453 result = getRValueReferenceType(
2454 getVariableArrayDecayedType(lv->getPointeeType()));
2455 break;
2456 }
2457
Eli Friedmanb001de72011-10-06 23:00:33 +00002458 case Type::Atomic: {
2459 const AtomicType *at = cast<AtomicType>(ty);
2460 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2461 break;
2462 }
2463
John McCallce889032011-01-18 08:40:38 +00002464 case Type::ConstantArray: {
2465 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2466 result = getConstantArrayType(
2467 getVariableArrayDecayedType(cat->getElementType()),
2468 cat->getSize(),
2469 cat->getSizeModifier(),
2470 cat->getIndexTypeCVRQualifiers());
2471 break;
2472 }
2473
2474 case Type::DependentSizedArray: {
2475 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2476 result = getDependentSizedArrayType(
2477 getVariableArrayDecayedType(dat->getElementType()),
2478 dat->getSizeExpr(),
2479 dat->getSizeModifier(),
2480 dat->getIndexTypeCVRQualifiers(),
2481 dat->getBracketsRange());
2482 break;
2483 }
2484
2485 // Turn incomplete types into [*] types.
2486 case Type::IncompleteArray: {
2487 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2488 result = getVariableArrayType(
2489 getVariableArrayDecayedType(iat->getElementType()),
2490 /*size*/ 0,
2491 ArrayType::Normal,
2492 iat->getIndexTypeCVRQualifiers(),
2493 SourceRange());
2494 break;
2495 }
2496
2497 // Turn VLA types into [*] types.
2498 case Type::VariableArray: {
2499 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2500 result = getVariableArrayType(
2501 getVariableArrayDecayedType(vat->getElementType()),
2502 /*size*/ 0,
2503 ArrayType::Star,
2504 vat->getIndexTypeCVRQualifiers(),
2505 vat->getBracketsRange());
2506 break;
2507 }
2508 }
2509
2510 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002511 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002512}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002513
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002514/// getVariableArrayType - Returns a non-unique reference to the type for a
2515/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002516QualType ASTContext::getVariableArrayType(QualType EltTy,
2517 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002518 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002519 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002520 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002521 // Since we don't unique expressions, it isn't possible to unique VLA's
2522 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002523 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002524
John McCall3b657512011-01-19 10:06:00 +00002525 // Be sure to pull qualifiers off the element type.
2526 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2527 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002528 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002529 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002530 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002531 }
2532
John McCall6b304a02009-09-24 23:30:46 +00002533 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002534 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002535
2536 VariableArrayTypes.push_back(New);
2537 Types.push_back(New);
2538 return QualType(New, 0);
2539}
2540
Douglas Gregor898574e2008-12-05 23:32:09 +00002541/// getDependentSizedArrayType - Returns a non-unique reference to
2542/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002543/// type.
John McCall3b657512011-01-19 10:06:00 +00002544QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2545 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002546 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002547 unsigned elementTypeQuals,
2548 SourceRange brackets) const {
2549 assert((!numElements || numElements->isTypeDependent() ||
2550 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002551 "Size must be type- or value-dependent!");
2552
John McCall3b657512011-01-19 10:06:00 +00002553 // Dependently-sized array types that do not have a specified number
2554 // of elements will have their sizes deduced from a dependent
2555 // initializer. We do no canonicalization here at all, which is okay
2556 // because they can't be used in most locations.
2557 if (!numElements) {
2558 DependentSizedArrayType *newType
2559 = new (*this, TypeAlignment)
2560 DependentSizedArrayType(*this, elementType, QualType(),
2561 numElements, ASM, elementTypeQuals,
2562 brackets);
2563 Types.push_back(newType);
2564 return QualType(newType, 0);
2565 }
2566
2567 // Otherwise, we actually build a new type every time, but we
2568 // also build a canonical type.
2569
2570 SplitQualType canonElementType = getCanonicalType(elementType).split();
2571
2572 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002573 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002574 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002575 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002576 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002577
John McCall3b657512011-01-19 10:06:00 +00002578 // Look for an existing type with these properties.
2579 DependentSizedArrayType *canonTy =
2580 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002581
John McCall3b657512011-01-19 10:06:00 +00002582 // If we don't have one, build one.
2583 if (!canonTy) {
2584 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002585 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002586 QualType(), numElements, ASM, elementTypeQuals,
2587 brackets);
2588 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2589 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002590 }
2591
John McCall3b657512011-01-19 10:06:00 +00002592 // Apply qualifiers from the element type to the array.
2593 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002594 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002595
John McCall3b657512011-01-19 10:06:00 +00002596 // If we didn't need extra canonicalization for the element type,
2597 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002598 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002599 return canon;
2600
2601 // Otherwise, we need to build a type which follows the spelling
2602 // of the element type.
2603 DependentSizedArrayType *sugaredType
2604 = new (*this, TypeAlignment)
2605 DependentSizedArrayType(*this, elementType, canon, numElements,
2606 ASM, elementTypeQuals, brackets);
2607 Types.push_back(sugaredType);
2608 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002609}
2610
John McCall3b657512011-01-19 10:06:00 +00002611QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002612 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002613 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002614 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002615 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002616
John McCall3b657512011-01-19 10:06:00 +00002617 void *insertPos = 0;
2618 if (IncompleteArrayType *iat =
2619 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2620 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002621
2622 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002623 // either, so fill in the canonical type field. We also have to pull
2624 // qualifiers off the element type.
2625 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002626
John McCall3b657512011-01-19 10:06:00 +00002627 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2628 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002629 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002630 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002631 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002632
2633 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002634 IncompleteArrayType *existing =
2635 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2636 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002637 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002638
John McCall3b657512011-01-19 10:06:00 +00002639 IncompleteArrayType *newType = new (*this, TypeAlignment)
2640 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002641
John McCall3b657512011-01-19 10:06:00 +00002642 IncompleteArrayTypes.InsertNode(newType, insertPos);
2643 Types.push_back(newType);
2644 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002645}
2646
Steve Naroff73322922007-07-18 18:00:27 +00002647/// getVectorType - Return the unique reference to a vector type of
2648/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002649QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002650 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002651 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 // Check if we've already instantiated a vector of this type.
2654 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002655 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002656
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 void *InsertPos = 0;
2658 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2659 return QualType(VTP, 0);
2660
2661 // If the element type isn't canonical, this won't be a canonical type either,
2662 // so fill in the canonical type field.
2663 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002664 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002665 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 // Get the new insert position for the node we care about.
2668 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002669 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 }
John McCall6b304a02009-09-24 23:30:46 +00002671 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002672 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 VectorTypes.InsertNode(New, InsertPos);
2674 Types.push_back(New);
2675 return QualType(New, 0);
2676}
2677
Nate Begeman213541a2008-04-18 23:10:10 +00002678/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002679/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002680QualType
2681ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002682 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Steve Naroff73322922007-07-18 18:00:27 +00002684 // Check if we've already instantiated a vector of this type.
2685 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002686 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002687 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002688 void *InsertPos = 0;
2689 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2690 return QualType(VTP, 0);
2691
2692 // If the element type isn't canonical, this won't be a canonical type either,
2693 // so fill in the canonical type field.
2694 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002695 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002696 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Steve Naroff73322922007-07-18 18:00:27 +00002698 // Get the new insert position for the node we care about.
2699 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002701 }
John McCall6b304a02009-09-24 23:30:46 +00002702 ExtVectorType *New = new (*this, TypeAlignment)
2703 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002704 VectorTypes.InsertNode(New, InsertPos);
2705 Types.push_back(New);
2706 return QualType(New, 0);
2707}
2708
Jay Foad4ba2a172011-01-12 09:06:06 +00002709QualType
2710ASTContext::getDependentSizedExtVectorType(QualType vecType,
2711 Expr *SizeExpr,
2712 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002713 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002714 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002715 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002717 void *InsertPos = 0;
2718 DependentSizedExtVectorType *Canon
2719 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2720 DependentSizedExtVectorType *New;
2721 if (Canon) {
2722 // We already have a canonical version of this array type; use it as
2723 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002724 New = new (*this, TypeAlignment)
2725 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2726 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002727 } else {
2728 QualType CanonVecTy = getCanonicalType(vecType);
2729 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002730 New = new (*this, TypeAlignment)
2731 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2732 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002733
2734 DependentSizedExtVectorType *CanonCheck
2735 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2736 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2737 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002738 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2739 } else {
2740 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2741 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002742 New = new (*this, TypeAlignment)
2743 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002744 }
2745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002747 Types.push_back(New);
2748 return QualType(New, 0);
2749}
2750
Douglas Gregor72564e72009-02-26 23:50:07 +00002751/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002752///
Jay Foad4ba2a172011-01-12 09:06:06 +00002753QualType
2754ASTContext::getFunctionNoProtoType(QualType ResultTy,
2755 const FunctionType::ExtInfo &Info) const {
Reid Kleckneref072032013-08-27 23:08:25 +00002756 const CallingConv CallConv = Info.getCC();
2757
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 // Unique functions, to guarantee there is only one function of a particular
2759 // structure.
2760 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002761 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002764 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002765 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002766 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002769 if (!ResultTy.isCanonical()) {
2770 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002773 FunctionNoProtoType *NewIP =
2774 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 }
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Roman Divackycfe9af22011-03-01 17:40:53 +00002778 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002779 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002780 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002782 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 return QualType(New, 0);
2784}
2785
Douglas Gregor02dd7982013-01-17 23:36:45 +00002786/// \brief Determine whether \p T is canonical as the result type of a function.
2787static bool isCanonicalResultType(QualType T) {
2788 return T.isCanonical() &&
2789 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2790 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2791}
2792
Reid Spencer5f016e22007-07-11 17:01:13 +00002793/// getFunctionType - Return a normal function type with a typed argument
2794/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002795QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002796ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002797 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002798 size_t NumArgs = ArgArray.size();
2799
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 // Unique functions, to guarantee there is only one function of a particular
2801 // structure.
2802 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002803 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2804 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002805
2806 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002807 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002808 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002810
2811 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002812 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002813 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002814 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002816 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 isCanonical = false;
2818
2819 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002820 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002822 if (!isCanonical) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002823 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 CanonicalArgs.reserve(NumArgs);
2825 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002826 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002827
John McCalle23cf432010-12-14 08:05:40 +00002828 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002829 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002830 CanonicalEPI.ExceptionSpecType = EST_None;
2831 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002832
Douglas Gregor02dd7982013-01-17 23:36:45 +00002833 // Result types do not have ARC lifetime qualifiers.
2834 QualType CanResultTy = getCanonicalType(ResultTy);
2835 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2836 Qualifiers Qs = CanResultTy.getQualifiers();
2837 Qs.removeObjCLifetime();
2838 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2839 }
2840
Jordan Rosebea522f2013-03-08 21:51:21 +00002841 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002842
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002844 FunctionProtoType *NewIP =
2845 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002846 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002848
John McCallf85e1932011-06-15 23:02:42 +00002849 // FunctionProtoType objects are allocated with extra bytes after
2850 // them for three variable size arrays at the end:
2851 // - parameter types
2852 // - exception types
2853 // - consumed-arguments flags
2854 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002855 // expression, or information used to resolve the exception
2856 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002857 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002858 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002859 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002860 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002861 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002862 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002863 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002864 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002865 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2866 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002867 }
John McCallf85e1932011-06-15 23:02:42 +00002868 if (EPI.ConsumedArguments)
2869 Size += NumArgs * sizeof(bool);
2870
John McCalle23cf432010-12-14 08:05:40 +00002871 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002872 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rosebea522f2013-03-08 21:51:21 +00002873 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002875 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 return QualType(FTP, 0);
2877}
2878
John McCall3cb0ebd2010-03-10 03:28:59 +00002879#ifndef NDEBUG
2880static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2881 if (!isa<CXXRecordDecl>(D)) return false;
2882 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2883 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2884 return true;
2885 if (RD->getDescribedClassTemplate() &&
2886 !isa<ClassTemplateSpecializationDecl>(RD))
2887 return true;
2888 return false;
2889}
2890#endif
2891
2892/// getInjectedClassNameType - Return the unique reference to the
2893/// injected class name type for the specified templated declaration.
2894QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002895 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002896 assert(NeedsInjectedClassNameType(Decl));
2897 if (Decl->TypeForDecl) {
2898 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002899 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002900 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2901 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2902 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2903 } else {
John McCallf4c73712011-01-19 06:33:43 +00002904 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002905 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002906 Decl->TypeForDecl = newType;
2907 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002908 }
2909 return QualType(Decl->TypeForDecl, 0);
2910}
2911
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002912/// getTypeDeclType - Return the unique reference to the type for the
2913/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002914QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002915 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002916 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002917
Richard Smith162e1c12011-04-15 14:24:37 +00002918 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002919 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002920
John McCallbecb8d52010-03-10 06:48:02 +00002921 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2922 "Template type parameter types are always available.");
2923
John McCall19c85762010-02-16 03:57:14 +00002924 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002925 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002926 "struct/union has previous declaration");
2927 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002928 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002929 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002930 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002931 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002932 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002933 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002934 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002935 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2936 Decl->TypeForDecl = newType;
2937 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002938 } else
John McCallbecb8d52010-03-10 06:48:02 +00002939 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002940
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002941 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002942}
2943
Reid Spencer5f016e22007-07-11 17:01:13 +00002944/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002945/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002946QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002947ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2948 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002949 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002951 if (Canonical.isNull())
2952 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002953 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002954 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002955 Decl->TypeForDecl = newType;
2956 Types.push_back(newType);
2957 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002958}
2959
Jay Foad4ba2a172011-01-12 09:06:06 +00002960QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002961 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2962
Douglas Gregoref96ee02012-01-14 16:38:05 +00002963 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002964 if (PrevDecl->TypeForDecl)
2965 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2966
John McCallf4c73712011-01-19 06:33:43 +00002967 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2968 Decl->TypeForDecl = newType;
2969 Types.push_back(newType);
2970 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002971}
2972
Jay Foad4ba2a172011-01-12 09:06:06 +00002973QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002974 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2975
Douglas Gregoref96ee02012-01-14 16:38:05 +00002976 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002977 if (PrevDecl->TypeForDecl)
2978 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2979
John McCallf4c73712011-01-19 06:33:43 +00002980 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2981 Decl->TypeForDecl = newType;
2982 Types.push_back(newType);
2983 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002984}
2985
John McCall9d156a72011-01-06 01:58:22 +00002986QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2987 QualType modifiedType,
2988 QualType equivalentType) {
2989 llvm::FoldingSetNodeID id;
2990 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2991
2992 void *insertPos = 0;
2993 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2994 if (type) return QualType(type, 0);
2995
2996 QualType canon = getCanonicalType(equivalentType);
2997 type = new (*this, TypeAlignment)
2998 AttributedType(canon, attrKind, modifiedType, equivalentType);
2999
3000 Types.push_back(type);
3001 AttributedTypes.InsertNode(type, insertPos);
3002
3003 return QualType(type, 0);
3004}
3005
3006
John McCall49a832b2009-10-18 09:09:24 +00003007/// \brief Retrieve a substitution-result type.
3008QualType
3009ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00003010 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00003011 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00003012 && "replacement types must always be canonical");
3013
3014 llvm::FoldingSetNodeID ID;
3015 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3016 void *InsertPos = 0;
3017 SubstTemplateTypeParmType *SubstParm
3018 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3019
3020 if (!SubstParm) {
3021 SubstParm = new (*this, TypeAlignment)
3022 SubstTemplateTypeParmType(Parm, Replacement);
3023 Types.push_back(SubstParm);
3024 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3025 }
3026
3027 return QualType(SubstParm, 0);
3028}
3029
Douglas Gregorc3069d62011-01-14 02:55:32 +00003030/// \brief Retrieve a
3031QualType ASTContext::getSubstTemplateTypeParmPackType(
3032 const TemplateTypeParmType *Parm,
3033 const TemplateArgument &ArgPack) {
3034#ifndef NDEBUG
3035 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3036 PEnd = ArgPack.pack_end();
3037 P != PEnd; ++P) {
3038 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3039 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3040 }
3041#endif
3042
3043 llvm::FoldingSetNodeID ID;
3044 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3045 void *InsertPos = 0;
3046 if (SubstTemplateTypeParmPackType *SubstParm
3047 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3048 return QualType(SubstParm, 0);
3049
3050 QualType Canon;
3051 if (!Parm->isCanonicalUnqualified()) {
3052 Canon = getCanonicalType(QualType(Parm, 0));
3053 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3054 ArgPack);
3055 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3056 }
3057
3058 SubstTemplateTypeParmPackType *SubstParm
3059 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3060 ArgPack);
3061 Types.push_back(SubstParm);
3062 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3063 return QualType(SubstParm, 0);
3064}
3065
Douglas Gregorfab9d672009-02-05 23:33:38 +00003066/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003067/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003068/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003069QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003070 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003071 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003072 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003073 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003074 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003075 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003076 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3077
3078 if (TypeParm)
3079 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003081 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003082 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003083 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003084
3085 TemplateTypeParmType *TypeCheck
3086 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3087 assert(!TypeCheck && "Template type parameter canonical type broken");
3088 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003089 } else
John McCall6b304a02009-09-24 23:30:46 +00003090 TypeParm = new (*this, TypeAlignment)
3091 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003092
3093 Types.push_back(TypeParm);
3094 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3095
3096 return QualType(TypeParm, 0);
3097}
3098
John McCall3cb0ebd2010-03-10 03:28:59 +00003099TypeSourceInfo *
3100ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3101 SourceLocation NameLoc,
3102 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003103 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003104 assert(!Name.getAsDependentTemplateName() &&
3105 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003106 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003107
3108 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003109 TemplateSpecializationTypeLoc TL =
3110 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003111 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003112 TL.setTemplateNameLoc(NameLoc);
3113 TL.setLAngleLoc(Args.getLAngleLoc());
3114 TL.setRAngleLoc(Args.getRAngleLoc());
3115 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3116 TL.setArgLocInfo(i, Args[i].getLocInfo());
3117 return DI;
3118}
3119
Mike Stump1eb44332009-09-09 15:08:12 +00003120QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003121ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003122 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003123 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003124 assert(!Template.getAsDependentTemplateName() &&
3125 "No dependent template names here!");
3126
John McCalld5532b62009-11-23 01:53:49 +00003127 unsigned NumArgs = Args.size();
3128
Chris Lattner5f9e2722011-07-23 10:55:15 +00003129 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003130 ArgVec.reserve(NumArgs);
3131 for (unsigned i = 0; i != NumArgs; ++i)
3132 ArgVec.push_back(Args[i].getArgument());
3133
John McCall31f17ec2010-04-27 00:57:59 +00003134 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003135 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003136}
3137
Douglas Gregorb70126a2012-02-03 17:16:23 +00003138#ifndef NDEBUG
3139static bool hasAnyPackExpansions(const TemplateArgument *Args,
3140 unsigned NumArgs) {
3141 for (unsigned I = 0; I != NumArgs; ++I)
3142 if (Args[I].isPackExpansion())
3143 return true;
3144
3145 return true;
3146}
3147#endif
3148
John McCall833ca992009-10-29 08:12:44 +00003149QualType
3150ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003151 const TemplateArgument *Args,
3152 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003153 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003154 assert(!Template.getAsDependentTemplateName() &&
3155 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003156 // Look through qualified template names.
3157 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3158 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003159
Douglas Gregorb70126a2012-02-03 17:16:23 +00003160 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003161 Template.getAsTemplateDecl() &&
3162 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003163 QualType CanonType;
3164 if (!Underlying.isNull())
3165 CanonType = getCanonicalType(Underlying);
3166 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003167 // We can get here with an alias template when the specialization contains
3168 // a pack expansion that does not match up with a parameter pack.
3169 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3170 "Caller must compute aliased type");
3171 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003172 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3173 NumArgs);
3174 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003175
Douglas Gregor1275ae02009-07-28 23:00:59 +00003176 // Allocate the (non-canonical) template specialization type, but don't
3177 // try to unique it: these types typically have location information that
3178 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003179 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3180 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003181 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003182 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003183 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003184 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3185 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Douglas Gregor55f6b142009-02-09 18:46:07 +00003187 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003188 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003189}
3190
Mike Stump1eb44332009-09-09 15:08:12 +00003191QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003192ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3193 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003194 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003195 assert(!Template.getAsDependentTemplateName() &&
3196 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003197
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003198 // Look through qualified template names.
3199 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3200 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003201
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003202 // Build the canonical template specialization type.
3203 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003204 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003205 CanonArgs.reserve(NumArgs);
3206 for (unsigned I = 0; I != NumArgs; ++I)
3207 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3208
3209 // Determine whether this canonical template specialization type already
3210 // exists.
3211 llvm::FoldingSetNodeID ID;
3212 TemplateSpecializationType::Profile(ID, CanonTemplate,
3213 CanonArgs.data(), NumArgs, *this);
3214
3215 void *InsertPos = 0;
3216 TemplateSpecializationType *Spec
3217 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3218
3219 if (!Spec) {
3220 // Allocate a new canonical template specialization type.
3221 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3222 sizeof(TemplateArgument) * NumArgs),
3223 TypeAlignment);
3224 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3225 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003226 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003227 Types.push_back(Spec);
3228 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3229 }
3230
3231 assert(Spec->isDependentType() &&
3232 "Non-dependent template-id type must have a canonical type");
3233 return QualType(Spec, 0);
3234}
3235
3236QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003237ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3238 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003239 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003240 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003241 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003242
3243 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003244 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003245 if (T)
3246 return QualType(T, 0);
3247
Douglas Gregor789b1f62010-02-04 18:10:26 +00003248 QualType Canon = NamedType;
3249 if (!Canon.isCanonical()) {
3250 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003251 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3252 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003253 (void)CheckT;
3254 }
3255
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003256 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003257 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003258 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003259 return QualType(T, 0);
3260}
3261
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003262QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003263ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003264 llvm::FoldingSetNodeID ID;
3265 ParenType::Profile(ID, InnerType);
3266
3267 void *InsertPos = 0;
3268 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3269 if (T)
3270 return QualType(T, 0);
3271
3272 QualType Canon = InnerType;
3273 if (!Canon.isCanonical()) {
3274 Canon = getCanonicalType(InnerType);
3275 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3276 assert(!CheckT && "Paren canonical type broken");
3277 (void)CheckT;
3278 }
3279
3280 T = new (*this) ParenType(InnerType, Canon);
3281 Types.push_back(T);
3282 ParenTypes.InsertNode(T, InsertPos);
3283 return QualType(T, 0);
3284}
3285
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003286QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3287 NestedNameSpecifier *NNS,
3288 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003289 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003290 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3291
3292 if (Canon.isNull()) {
3293 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003294 ElaboratedTypeKeyword CanonKeyword = Keyword;
3295 if (Keyword == ETK_None)
3296 CanonKeyword = ETK_Typename;
3297
3298 if (CanonNNS != NNS || CanonKeyword != Keyword)
3299 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003300 }
3301
3302 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003303 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003304
3305 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003306 DependentNameType *T
3307 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003308 if (T)
3309 return QualType(T, 0);
3310
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003311 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003312 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003313 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003314 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003315}
3316
Mike Stump1eb44332009-09-09 15:08:12 +00003317QualType
John McCall33500952010-06-11 00:33:02 +00003318ASTContext::getDependentTemplateSpecializationType(
3319 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003320 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003321 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003322 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003323 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003324 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003325 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3326 ArgCopy.push_back(Args[I].getArgument());
3327 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3328 ArgCopy.size(),
3329 ArgCopy.data());
3330}
3331
3332QualType
3333ASTContext::getDependentTemplateSpecializationType(
3334 ElaboratedTypeKeyword Keyword,
3335 NestedNameSpecifier *NNS,
3336 const IdentifierInfo *Name,
3337 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003338 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003339 assert((!NNS || NNS->isDependent()) &&
3340 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003341
Douglas Gregor789b1f62010-02-04 18:10:26 +00003342 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003343 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3344 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003345
3346 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003347 DependentTemplateSpecializationType *T
3348 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003349 if (T)
3350 return QualType(T, 0);
3351
John McCall33500952010-06-11 00:33:02 +00003352 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003353
John McCall33500952010-06-11 00:33:02 +00003354 ElaboratedTypeKeyword CanonKeyword = Keyword;
3355 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3356
3357 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003358 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003359 for (unsigned I = 0; I != NumArgs; ++I) {
3360 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3361 if (!CanonArgs[I].structurallyEquals(Args[I]))
3362 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003363 }
3364
John McCall33500952010-06-11 00:33:02 +00003365 QualType Canon;
3366 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3367 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3368 Name, NumArgs,
3369 CanonArgs.data());
3370
3371 // Find the insert position again.
3372 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 }
3374
3375 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3376 sizeof(TemplateArgument) * NumArgs),
3377 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003378 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003379 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003380 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003381 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003382 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003383}
3384
Douglas Gregorcded4f62011-01-14 17:04:44 +00003385QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003386 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003387 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003388 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003389
3390 assert(Pattern->containsUnexpandedParameterPack() &&
3391 "Pack expansions must expand one or more parameter packs");
3392 void *InsertPos = 0;
3393 PackExpansionType *T
3394 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3395 if (T)
3396 return QualType(T, 0);
3397
3398 QualType Canon;
3399 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003400 Canon = getCanonicalType(Pattern);
3401 // The canonical type might not contain an unexpanded parameter pack, if it
3402 // contains an alias template specialization which ignores one of its
3403 // parameters.
3404 if (Canon->containsUnexpandedParameterPack()) {
3405 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003406
Richard Smithd8672ef2012-07-16 00:20:35 +00003407 // Find the insert position again, in case we inserted an element into
3408 // PackExpansionTypes and invalidated our insert position.
3409 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3410 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003411 }
3412
Douglas Gregorcded4f62011-01-14 17:04:44 +00003413 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003414 Types.push_back(T);
3415 PackExpansionTypes.InsertNode(T, InsertPos);
3416 return QualType(T, 0);
3417}
3418
Chris Lattner88cb27a2008-04-07 04:56:42 +00003419/// CmpProtocolNames - Comparison predicate for sorting protocols
3420/// alphabetically.
3421static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3422 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003423 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003424}
3425
John McCallc12c5bb2010-05-15 11:32:37 +00003426static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003427 unsigned NumProtocols) {
3428 if (NumProtocols == 0) return true;
3429
Douglas Gregor61cc2962012-01-02 02:00:30 +00003430 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3431 return false;
3432
John McCall54e14c42009-10-22 22:37:11 +00003433 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003434 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3435 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003436 return false;
3437 return true;
3438}
3439
3440static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003441 unsigned &NumProtocols) {
3442 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Chris Lattner88cb27a2008-04-07 04:56:42 +00003444 // Sort protocols, keyed by name.
3445 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3446
Douglas Gregor61cc2962012-01-02 02:00:30 +00003447 // Canonicalize.
3448 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3449 Protocols[I] = Protocols[I]->getCanonicalDecl();
3450
Chris Lattner88cb27a2008-04-07 04:56:42 +00003451 // Remove duplicates.
3452 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3453 NumProtocols = ProtocolsEnd-Protocols;
3454}
3455
John McCallc12c5bb2010-05-15 11:32:37 +00003456QualType ASTContext::getObjCObjectType(QualType BaseType,
3457 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003458 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003459 // If the base type is an interface and there aren't any protocols
3460 // to add, then the interface type will do just fine.
3461 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3462 return BaseType;
3463
3464 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003465 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003466 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003467 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003468 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3469 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003470
John McCallc12c5bb2010-05-15 11:32:37 +00003471 // Build the canonical type, which has the canonical base type and
3472 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003473 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003474 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3475 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3476 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003477 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003478 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003479 unsigned UniqueCount = NumProtocols;
3480
John McCall54e14c42009-10-22 22:37:11 +00003481 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003482 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3483 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003484 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003485 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3486 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003487 }
3488
3489 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003490 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3491 }
3492
3493 unsigned Size = sizeof(ObjCObjectTypeImpl);
3494 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3495 void *Mem = Allocate(Size, TypeAlignment);
3496 ObjCObjectTypeImpl *T =
3497 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3498
3499 Types.push_back(T);
3500 ObjCObjectTypes.InsertNode(T, InsertPos);
3501 return QualType(T, 0);
3502}
3503
3504/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3505/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003506QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003507 llvm::FoldingSetNodeID ID;
3508 ObjCObjectPointerType::Profile(ID, ObjectT);
3509
3510 void *InsertPos = 0;
3511 if (ObjCObjectPointerType *QT =
3512 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3513 return QualType(QT, 0);
3514
3515 // Find the canonical object type.
3516 QualType Canonical;
3517 if (!ObjectT.isCanonical()) {
3518 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3519
3520 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003521 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3522 }
3523
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003524 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003525 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3526 ObjCObjectPointerType *QType =
3527 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003529 Types.push_back(QType);
3530 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003531 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003532}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003533
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003534/// getObjCInterfaceType - Return the unique reference to the type for the
3535/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003536QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3537 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003538 if (Decl->TypeForDecl)
3539 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Douglas Gregor0af55012011-12-16 03:12:41 +00003541 if (PrevDecl) {
3542 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3543 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3544 return QualType(PrevDecl->TypeForDecl, 0);
3545 }
3546
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003547 // Prefer the definition, if there is one.
3548 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3549 Decl = Def;
3550
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003551 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3552 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3553 Decl->TypeForDecl = T;
3554 Types.push_back(T);
3555 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003556}
3557
Douglas Gregor72564e72009-02-26 23:50:07 +00003558/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3559/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003560/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003561/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003562/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003563QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003564 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003565 if (tofExpr->isTypeDependent()) {
3566 llvm::FoldingSetNodeID ID;
3567 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Douglas Gregorb1975722009-07-30 23:18:24 +00003569 void *InsertPos = 0;
3570 DependentTypeOfExprType *Canon
3571 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3572 if (Canon) {
3573 // We already have a "canonical" version of an identical, dependent
3574 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003575 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003576 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003577 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003578 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003579 Canon
3580 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003581 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3582 toe = Canon;
3583 }
3584 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003585 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003586 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003587 }
Steve Naroff9752f252007-08-01 18:02:17 +00003588 Types.push_back(toe);
3589 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003590}
3591
Steve Naroff9752f252007-08-01 18:02:17 +00003592/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3593/// TypeOfType AST's. The only motivation to unique these nodes would be
3594/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003596/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003597QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003598 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003599 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003600 Types.push_back(tot);
3601 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003602}
3603
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003604
Anders Carlsson395b4752009-06-24 19:06:50 +00003605/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3606/// DecltypeType AST's. The only motivation to unique these nodes would be
3607/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003608/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003609/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003610QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003611 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003612
3613 // C++0x [temp.type]p2:
3614 // If an expression e involves a template parameter, decltype(e) denotes a
3615 // unique dependent type. Two such decltype-specifiers refer to the same
3616 // type only if their expressions are equivalent (14.5.6.1).
3617 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003618 llvm::FoldingSetNodeID ID;
3619 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003621 void *InsertPos = 0;
3622 DependentDecltypeType *Canon
3623 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3624 if (Canon) {
3625 // We already have a "canonical" version of an equivalent, dependent
3626 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003627 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003628 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003629 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003630 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003631 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003632 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3633 dt = Canon;
3634 }
3635 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003636 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3637 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003638 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003639 Types.push_back(dt);
3640 return QualType(dt, 0);
3641}
3642
Sean Huntca63c202011-05-24 22:41:36 +00003643/// getUnaryTransformationType - We don't unique these, since the memory
3644/// savings are minimal and these are rare.
3645QualType ASTContext::getUnaryTransformType(QualType BaseType,
3646 QualType UnderlyingType,
3647 UnaryTransformType::UTTKind Kind)
3648 const {
3649 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003650 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3651 Kind,
3652 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003653 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003654 Types.push_back(Ty);
3655 return QualType(Ty, 0);
3656}
3657
Richard Smith60e141e2013-05-04 07:00:32 +00003658/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3659/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3660/// canonical deduced-but-dependent 'auto' type.
3661QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003662 bool IsDependent) const {
3663 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith60e141e2013-05-04 07:00:32 +00003664 return getAutoDeductType();
Manuel Klimek152b4e42013-08-22 12:12:24 +00003665
Richard Smith60e141e2013-05-04 07:00:32 +00003666 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003667 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003668 llvm::FoldingSetNodeID ID;
Manuel Klimek152b4e42013-08-22 12:12:24 +00003669 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith60e141e2013-05-04 07:00:32 +00003670 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3671 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003672
Richard Smitha2c36462013-04-26 16:15:35 +00003673 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003674 IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003675 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003676 Types.push_back(AT);
3677 if (InsertPos)
3678 AutoTypes.InsertNode(AT, InsertPos);
3679 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003680}
3681
Eli Friedmanb001de72011-10-06 23:00:33 +00003682/// getAtomicType - Return the uniqued reference to the atomic type for
3683/// the given value type.
3684QualType ASTContext::getAtomicType(QualType T) const {
3685 // Unique pointers, to guarantee there is only one pointer of a particular
3686 // structure.
3687 llvm::FoldingSetNodeID ID;
3688 AtomicType::Profile(ID, T);
3689
3690 void *InsertPos = 0;
3691 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3692 return QualType(AT, 0);
3693
3694 // If the atomic value type isn't canonical, this won't be a canonical type
3695 // either, so fill in the canonical type field.
3696 QualType Canonical;
3697 if (!T.isCanonical()) {
3698 Canonical = getAtomicType(getCanonicalType(T));
3699
3700 // Get the new insert position for the node we care about.
3701 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3703 }
3704 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3705 Types.push_back(New);
3706 AtomicTypes.InsertNode(New, InsertPos);
3707 return QualType(New, 0);
3708}
3709
Richard Smithad762fc2011-04-14 22:09:26 +00003710/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3711QualType ASTContext::getAutoDeductType() const {
3712 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003713 AutoDeductTy = QualType(
3714 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003715 /*dependent*/false),
Richard Smith60e141e2013-05-04 07:00:32 +00003716 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003717 return AutoDeductTy;
3718}
3719
3720/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3721QualType ASTContext::getAutoRRefDeductType() const {
3722 if (AutoRRefDeductTy.isNull())
3723 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3724 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3725 return AutoRRefDeductTy;
3726}
3727
Reid Spencer5f016e22007-07-11 17:01:13 +00003728/// getTagDeclType - Return the unique reference to the type for the
3729/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003730QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003731 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003732 // FIXME: What is the design on getTagDeclType when it requires casting
3733 // away const? mutable?
3734 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003735}
3736
Mike Stump1eb44332009-09-09 15:08:12 +00003737/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3738/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3739/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003740CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003741 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003742}
3743
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003744/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3745CanQualType ASTContext::getIntMaxType() const {
3746 return getFromTargetType(Target->getIntMaxType());
3747}
3748
3749/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3750CanQualType ASTContext::getUIntMaxType() const {
3751 return getFromTargetType(Target->getUIntMaxType());
3752}
3753
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003754/// getSignedWCharType - Return the type of "signed wchar_t".
3755/// Used when in C++, as a GCC extension.
3756QualType ASTContext::getSignedWCharType() const {
3757 // FIXME: derive from "Target" ?
3758 return WCharTy;
3759}
3760
3761/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3762/// Used when in C++, as a GCC extension.
3763QualType ASTContext::getUnsignedWCharType() const {
3764 // FIXME: derive from "Target" ?
3765 return UnsignedIntTy;
3766}
3767
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003768QualType ASTContext::getIntPtrType() const {
3769 return getFromTargetType(Target->getIntPtrType());
3770}
3771
3772QualType ASTContext::getUIntPtrType() const {
3773 return getCorrespondingUnsignedType(getIntPtrType());
3774}
3775
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003776/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003777/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3778QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003779 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003780}
3781
Eli Friedman6902e412012-11-27 02:58:24 +00003782/// \brief Return the unique type for "pid_t" defined in
3783/// <sys/types.h>. We need this to compute the correct type for vfork().
3784QualType ASTContext::getProcessIDType() const {
3785 return getFromTargetType(Target->getProcessIDType());
3786}
3787
Chris Lattnere6327742008-04-02 05:18:44 +00003788//===----------------------------------------------------------------------===//
3789// Type Operators
3790//===----------------------------------------------------------------------===//
3791
Jay Foad4ba2a172011-01-12 09:06:06 +00003792CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003793 // Push qualifiers into arrays, and then discard any remaining
3794 // qualifiers.
3795 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003796 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003797 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003798 QualType Result;
3799 if (isa<ArrayType>(Ty)) {
3800 Result = getArrayDecayedType(QualType(Ty,0));
3801 } else if (isa<FunctionType>(Ty)) {
3802 Result = getPointerType(QualType(Ty, 0));
3803 } else {
3804 Result = QualType(Ty, 0);
3805 }
3806
3807 return CanQualType::CreateUnsafe(Result);
3808}
3809
John McCall62c28c82011-01-18 07:41:22 +00003810QualType ASTContext::getUnqualifiedArrayType(QualType type,
3811 Qualifiers &quals) {
3812 SplitQualType splitType = type.getSplitUnqualifiedType();
3813
3814 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3815 // the unqualified desugared type and then drops it on the floor.
3816 // We then have to strip that sugar back off with
3817 // getUnqualifiedDesugaredType(), which is silly.
3818 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003819 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003820
3821 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003822 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003823 quals = splitType.Quals;
3824 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003825 }
3826
John McCall62c28c82011-01-18 07:41:22 +00003827 // Otherwise, recurse on the array's element type.
3828 QualType elementType = AT->getElementType();
3829 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3830
3831 // If that didn't change the element type, AT has no qualifiers, so we
3832 // can just use the results in splitType.
3833 if (elementType == unqualElementType) {
3834 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003835 quals = splitType.Quals;
3836 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003837 }
3838
3839 // Otherwise, add in the qualifiers from the outermost type, then
3840 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003841 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003842
Douglas Gregor9dadd942010-05-17 18:45:21 +00003843 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003844 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003845 CAT->getSizeModifier(), 0);
3846 }
3847
Douglas Gregor9dadd942010-05-17 18:45:21 +00003848 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003849 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003850 }
3851
Douglas Gregor9dadd942010-05-17 18:45:21 +00003852 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003853 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003854 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003855 VAT->getSizeModifier(),
3856 VAT->getIndexTypeCVRQualifiers(),
3857 VAT->getBracketsRange());
3858 }
3859
3860 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003861 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003862 DSAT->getSizeModifier(), 0,
3863 SourceRange());
3864}
3865
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003866/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3867/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3868/// they point to and return true. If T1 and T2 aren't pointer types
3869/// or pointer-to-member types, or if they are not similar at this
3870/// level, returns false and leaves T1 and T2 unchanged. Top-level
3871/// qualifiers on T1 and T2 are ignored. This function will typically
3872/// be called in a loop that successively "unwraps" pointer and
3873/// pointer-to-member types to compare them at each level.
3874bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3875 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3876 *T2PtrType = T2->getAs<PointerType>();
3877 if (T1PtrType && T2PtrType) {
3878 T1 = T1PtrType->getPointeeType();
3879 T2 = T2PtrType->getPointeeType();
3880 return true;
3881 }
3882
3883 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3884 *T2MPType = T2->getAs<MemberPointerType>();
3885 if (T1MPType && T2MPType &&
3886 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3887 QualType(T2MPType->getClass(), 0))) {
3888 T1 = T1MPType->getPointeeType();
3889 T2 = T2MPType->getPointeeType();
3890 return true;
3891 }
3892
David Blaikie4e4d0842012-03-11 07:00:24 +00003893 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003894 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3895 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3896 if (T1OPType && T2OPType) {
3897 T1 = T1OPType->getPointeeType();
3898 T2 = T2OPType->getPointeeType();
3899 return true;
3900 }
3901 }
3902
3903 // FIXME: Block pointers, too?
3904
3905 return false;
3906}
3907
Jay Foad4ba2a172011-01-12 09:06:06 +00003908DeclarationNameInfo
3909ASTContext::getNameForTemplate(TemplateName Name,
3910 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003911 switch (Name.getKind()) {
3912 case TemplateName::QualifiedTemplate:
3913 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003914 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003915 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3916 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003917
John McCall14606042011-06-30 08:33:18 +00003918 case TemplateName::OverloadedTemplate: {
3919 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3920 // DNInfo work in progress: CHECKME: what about DNLoc?
3921 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3922 }
3923
3924 case TemplateName::DependentTemplate: {
3925 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003926 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003927 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003928 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3929 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003930 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003931 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3932 // DNInfo work in progress: FIXME: source locations?
3933 DeclarationNameLoc DNLoc;
3934 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3935 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3936 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003937 }
3938 }
3939
John McCall14606042011-06-30 08:33:18 +00003940 case TemplateName::SubstTemplateTemplateParm: {
3941 SubstTemplateTemplateParmStorage *subst
3942 = Name.getAsSubstTemplateTemplateParm();
3943 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3944 NameLoc);
3945 }
3946
3947 case TemplateName::SubstTemplateTemplateParmPack: {
3948 SubstTemplateTemplateParmPackStorage *subst
3949 = Name.getAsSubstTemplateTemplateParmPack();
3950 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3951 NameLoc);
3952 }
3953 }
3954
3955 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003956}
3957
Jay Foad4ba2a172011-01-12 09:06:06 +00003958TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003959 switch (Name.getKind()) {
3960 case TemplateName::QualifiedTemplate:
3961 case TemplateName::Template: {
3962 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003963 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003964 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003965 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3966
3967 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003968 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003969 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003970
John McCall14606042011-06-30 08:33:18 +00003971 case TemplateName::OverloadedTemplate:
3972 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003973
John McCall14606042011-06-30 08:33:18 +00003974 case TemplateName::DependentTemplate: {
3975 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3976 assert(DTN && "Non-dependent template names must refer to template decls.");
3977 return DTN->CanonicalTemplateName;
3978 }
3979
3980 case TemplateName::SubstTemplateTemplateParm: {
3981 SubstTemplateTemplateParmStorage *subst
3982 = Name.getAsSubstTemplateTemplateParm();
3983 return getCanonicalTemplateName(subst->getReplacement());
3984 }
3985
3986 case TemplateName::SubstTemplateTemplateParmPack: {
3987 SubstTemplateTemplateParmPackStorage *subst
3988 = Name.getAsSubstTemplateTemplateParmPack();
3989 TemplateTemplateParmDecl *canonParameter
3990 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3991 TemplateArgument canonArgPack
3992 = getCanonicalTemplateArgument(subst->getArgumentPack());
3993 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3994 }
3995 }
3996
3997 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003998}
3999
Douglas Gregordb0d4b72009-11-11 23:06:43 +00004000bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4001 X = getCanonicalTemplateName(X);
4002 Y = getCanonicalTemplateName(Y);
4003 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4004}
4005
Mike Stump1eb44332009-09-09 15:08:12 +00004006TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00004007ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00004008 switch (Arg.getKind()) {
4009 case TemplateArgument::Null:
4010 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Douglas Gregor1275ae02009-07-28 23:00:59 +00004012 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00004013 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Douglas Gregord2008e22012-04-06 22:40:38 +00004015 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004016 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4017 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Eli Friedmand7a6b162012-09-26 02:36:12 +00004020 case TemplateArgument::NullPtr:
4021 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4022 /*isNullPtr*/true);
4023
Douglas Gregor788cd062009-11-11 01:00:40 +00004024 case TemplateArgument::Template:
4025 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004026
4027 case TemplateArgument::TemplateExpansion:
4028 return TemplateArgument(getCanonicalTemplateName(
4029 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004030 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004031
Douglas Gregor1275ae02009-07-28 23:00:59 +00004032 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004033 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Douglas Gregor1275ae02009-07-28 23:00:59 +00004035 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004036 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Douglas Gregor1275ae02009-07-28 23:00:59 +00004038 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004039 if (Arg.pack_size() == 0)
4040 return Arg;
4041
Douglas Gregor910f8002010-11-07 23:05:16 +00004042 TemplateArgument *CanonArgs
4043 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004044 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004045 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004046 AEnd = Arg.pack_end();
4047 A != AEnd; (void)++A, ++Idx)
4048 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Douglas Gregor910f8002010-11-07 23:05:16 +00004050 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004051 }
4052 }
4053
4054 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004055 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004056}
4057
Douglas Gregord57959a2009-03-27 23:10:48 +00004058NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004059ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004060 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004061 return 0;
4062
4063 switch (NNS->getKind()) {
4064 case NestedNameSpecifier::Identifier:
4065 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004066 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004067 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4068 NNS->getAsIdentifier());
4069
4070 case NestedNameSpecifier::Namespace:
4071 // A namespace is canonical; build a nested-name-specifier with
4072 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004073 return NestedNameSpecifier::Create(*this, 0,
4074 NNS->getAsNamespace()->getOriginalNamespace());
4075
4076 case NestedNameSpecifier::NamespaceAlias:
4077 // A namespace is canonical; build a nested-name-specifier with
4078 // this namespace and no prefix.
4079 return NestedNameSpecifier::Create(*this, 0,
4080 NNS->getAsNamespaceAlias()->getNamespace()
4081 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004082
4083 case NestedNameSpecifier::TypeSpec:
4084 case NestedNameSpecifier::TypeSpecWithTemplate: {
4085 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004086
4087 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4088 // break it apart into its prefix and identifier, then reconsititute those
4089 // as the canonical nested-name-specifier. This is required to canonicalize
4090 // a dependent nested-name-specifier involving typedefs of dependent-name
4091 // types, e.g.,
4092 // typedef typename T::type T1;
4093 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004094 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4095 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004096 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004097
Eli Friedman16412ef2012-03-03 04:09:56 +00004098 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4099 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4100 // first place?
John McCall3b657512011-01-19 10:06:00 +00004101 return NestedNameSpecifier::Create(*this, 0, false,
4102 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004103 }
4104
4105 case NestedNameSpecifier::Global:
4106 // The global specifier is canonical and unique.
4107 return NNS;
4108 }
4109
David Blaikie7530c032012-01-17 06:56:22 +00004110 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004111}
4112
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004113
Jay Foad4ba2a172011-01-12 09:06:06 +00004114const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004115 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004116 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004117 // Handle the common positive case fast.
4118 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4119 return AT;
4120 }
Mike Stump1eb44332009-09-09 15:08:12 +00004121
John McCall0953e762009-09-24 19:53:00 +00004122 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004123 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004124 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004125
John McCall0953e762009-09-24 19:53:00 +00004126 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004127 // implements C99 6.7.3p8: "If the specification of an array type includes
4128 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004130 // If we get here, we either have type qualifiers on the type, or we have
4131 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004132 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004133
John McCall3b657512011-01-19 10:06:00 +00004134 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004135 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004137 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004138 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004139 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004140 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004142 // Otherwise, we have an array and we have qualifiers on it. Push the
4143 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004144 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004146 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4147 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4148 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004149 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004150 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4151 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4152 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004153 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004154
Mike Stump1eb44332009-09-09 15:08:12 +00004155 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004156 = dyn_cast<DependentSizedArrayType>(ATy))
4157 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004158 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004159 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004160 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004161 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004162 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004164 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004165 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004166 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004167 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004168 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004169 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004170}
4171
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004172QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004173 if (T->isArrayType() || T->isFunctionType())
4174 return getDecayedType(T);
4175 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004176}
4177
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004178QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004179 T = getVariableArrayDecayedType(T);
4180 T = getAdjustedParameterType(T);
4181 return T.getUnqualifiedType();
4182}
4183
Chris Lattnere6327742008-04-02 05:18:44 +00004184/// getArrayDecayedType - Return the properly qualified result of decaying the
4185/// specified array type to a pointer. This operation is non-trivial when
4186/// handling typedefs etc. The canonical type of "T" must be an array type,
4187/// this returns a pointer to a properly qualified element of the array.
4188///
4189/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004190QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004191 // Get the element type with 'getAsArrayType' so that we don't lose any
4192 // typedefs in the element type of the array. This also handles propagation
4193 // of type qualifiers from the array type into the element type if present
4194 // (C99 6.7.3p8).
4195 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4196 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004198 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004199
4200 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004201 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004202}
4203
John McCall3b657512011-01-19 10:06:00 +00004204QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4205 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004206}
4207
John McCall3b657512011-01-19 10:06:00 +00004208QualType ASTContext::getBaseElementType(QualType type) const {
4209 Qualifiers qs;
4210 while (true) {
4211 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004212 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004213 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004214
John McCall3b657512011-01-19 10:06:00 +00004215 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004216 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
John McCall3b657512011-01-19 10:06:00 +00004219 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004220}
4221
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004222/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004223uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004224ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4225 uint64_t ElementCount = 1;
4226 do {
4227 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004228 CA = dyn_cast_or_null<ConstantArrayType>(
4229 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004230 } while (CA);
4231 return ElementCount;
4232}
4233
Reid Spencer5f016e22007-07-11 17:01:13 +00004234/// getFloatingRank - Return a relative rank for floating point types.
4235/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004236static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004237 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004238 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004239
John McCall183700f2009-09-21 23:43:11 +00004240 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4241 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004242 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004243 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004244 case BuiltinType::Float: return FloatRank;
4245 case BuiltinType::Double: return DoubleRank;
4246 case BuiltinType::LongDouble: return LongDoubleRank;
4247 }
4248}
4249
Mike Stump1eb44332009-09-09 15:08:12 +00004250/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4251/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004252/// 'typeDomain' is a real floating point or complex type.
4253/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004254QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4255 QualType Domain) const {
4256 FloatingRank EltRank = getFloatingRank(Size);
4257 if (Domain->isComplexType()) {
4258 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004259 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004260 case FloatRank: return FloatComplexTy;
4261 case DoubleRank: return DoubleComplexTy;
4262 case LongDoubleRank: return LongDoubleComplexTy;
4263 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004264 }
Chris Lattner1361b112008-04-06 23:58:54 +00004265
4266 assert(Domain->isRealFloatingType() && "Unknown domain!");
4267 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004268 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004269 case FloatRank: return FloatTy;
4270 case DoubleRank: return DoubleTy;
4271 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004272 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004273 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004274}
4275
Chris Lattner7cfeb082008-04-06 23:55:33 +00004276/// getFloatingTypeOrder - Compare the rank of the two specified floating
4277/// point types, ignoring the domain of the type (i.e. 'double' ==
4278/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004279/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004280int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004281 FloatingRank LHSR = getFloatingRank(LHS);
4282 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Chris Lattnera75cea32008-04-06 23:38:49 +00004284 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004285 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004286 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004287 return 1;
4288 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004289}
4290
Chris Lattnerf52ab252008-04-06 22:59:24 +00004291/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4292/// routine will assert if passed a built-in type that isn't an integer or enum,
4293/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004294unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004295 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004296
Chris Lattnerf52ab252008-04-06 22:59:24 +00004297 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004298 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004299 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004300 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004301 case BuiltinType::Char_S:
4302 case BuiltinType::Char_U:
4303 case BuiltinType::SChar:
4304 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004305 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004306 case BuiltinType::Short:
4307 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004308 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004309 case BuiltinType::Int:
4310 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004311 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004312 case BuiltinType::Long:
4313 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004314 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004315 case BuiltinType::LongLong:
4316 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004317 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004318 case BuiltinType::Int128:
4319 case BuiltinType::UInt128:
4320 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004321 }
4322}
4323
Eli Friedman04e83572009-08-20 04:21:42 +00004324/// \brief Whether this is a promotable bitfield reference according
4325/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4326///
4327/// \returns the type this bit-field will promote to, or NULL if no
4328/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004329QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004330 if (E->isTypeDependent() || E->isValueDependent())
4331 return QualType();
4332
John McCall993f43f2013-05-06 21:39:12 +00004333 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004334 if (!Field)
4335 return QualType();
4336
4337 QualType FT = Field->getType();
4338
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004339 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004340 uint64_t IntSize = getTypeSize(IntTy);
4341 // GCC extension compatibility: if the bit-field size is less than or equal
4342 // to the size of int, it gets promoted no matter what its type is.
4343 // For instance, unsigned long bf : 4 gets promoted to signed int.
4344 if (BitWidth < IntSize)
4345 return IntTy;
4346
4347 if (BitWidth == IntSize)
4348 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4349
4350 // Types bigger than int are not subject to promotions, and therefore act
4351 // like the base type.
4352 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4353 // is ridiculous.
4354 return QualType();
4355}
4356
Eli Friedmana95d7572009-08-19 07:44:53 +00004357/// getPromotedIntegerType - Returns the type that Promotable will
4358/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4359/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004360QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004361 assert(!Promotable.isNull());
4362 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004363 if (const EnumType *ET = Promotable->getAs<EnumType>())
4364 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004365
4366 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4367 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4368 // (3.9.1) can be converted to a prvalue of the first of the following
4369 // types that can represent all the values of its underlying type:
4370 // int, unsigned int, long int, unsigned long int, long long int, or
4371 // unsigned long long int [...]
4372 // FIXME: Is there some better way to compute this?
4373 if (BT->getKind() == BuiltinType::WChar_S ||
4374 BT->getKind() == BuiltinType::WChar_U ||
4375 BT->getKind() == BuiltinType::Char16 ||
4376 BT->getKind() == BuiltinType::Char32) {
4377 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4378 uint64_t FromSize = getTypeSize(BT);
4379 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4380 LongLongTy, UnsignedLongLongTy };
4381 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4382 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4383 if (FromSize < ToSize ||
4384 (FromSize == ToSize &&
4385 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4386 return PromoteTypes[Idx];
4387 }
4388 llvm_unreachable("char type should fit into long long");
4389 }
4390 }
4391
4392 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004393 if (Promotable->isSignedIntegerType())
4394 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004395 uint64_t PromotableSize = getIntWidth(Promotable);
4396 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004397 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4398 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4399}
4400
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004401/// \brief Recurses in pointer/array types until it finds an objc retainable
4402/// type and returns its ownership.
4403Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4404 while (!T.isNull()) {
4405 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4406 return T.getObjCLifetime();
4407 if (T->isArrayType())
4408 T = getBaseElementType(T);
4409 else if (const PointerType *PT = T->getAs<PointerType>())
4410 T = PT->getPointeeType();
4411 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004412 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004413 else
4414 break;
4415 }
4416
4417 return Qualifiers::OCL_None;
4418}
4419
Mike Stump1eb44332009-09-09 15:08:12 +00004420/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004421/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004422/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004423int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004424 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4425 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004426 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Chris Lattnerf52ab252008-04-06 22:59:24 +00004428 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4429 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 unsigned LHSRank = getIntegerRank(LHSC);
4432 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Chris Lattner7cfeb082008-04-06 23:55:33 +00004434 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4435 if (LHSRank == RHSRank) return 0;
4436 return LHSRank > RHSRank ? 1 : -1;
4437 }
Mike Stump1eb44332009-09-09 15:08:12 +00004438
Chris Lattner7cfeb082008-04-06 23:55:33 +00004439 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4440 if (LHSUnsigned) {
4441 // If the unsigned [LHS] type is larger, return it.
4442 if (LHSRank >= RHSRank)
4443 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004444
Chris Lattner7cfeb082008-04-06 23:55:33 +00004445 // If the signed type can represent all values of the unsigned type, it
4446 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004447 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004448 return -1;
4449 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004450
Chris Lattner7cfeb082008-04-06 23:55:33 +00004451 // If the unsigned [RHS] type is larger, return it.
4452 if (RHSRank >= LHSRank)
4453 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Chris Lattner7cfeb082008-04-06 23:55:33 +00004455 // If the signed type can represent all values of the unsigned type, it
4456 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004457 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004458 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004459}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004460
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004461static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004462CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4463 DeclContext *DC, IdentifierInfo *Id) {
4464 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004465 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004466 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004467 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004468 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004469}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004470
Mike Stump1eb44332009-09-09 15:08:12 +00004471// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004472QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004473 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004474 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004475 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004476 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004477 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004478
Anders Carlssonf06273f2007-11-19 00:25:30 +00004479 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Anders Carlsson71993dd2007-08-17 05:31:46 +00004481 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004482 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004483 // int flags;
4484 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004485 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004486 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004487 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004488 FieldTypes[3] = LongTy;
4489
Anders Carlsson71993dd2007-08-17 05:31:46 +00004490 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004491 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004492 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004493 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004494 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004495 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004496 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004497 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004498 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004499 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004500 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004501 }
4502
Douglas Gregor838db382010-02-11 01:19:42 +00004503 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004504 }
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Anders Carlsson71993dd2007-08-17 05:31:46 +00004506 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004507}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004508
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004509QualType ASTContext::getObjCSuperType() const {
4510 if (ObjCSuperType.isNull()) {
4511 RecordDecl *ObjCSuperTypeDecl =
4512 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4513 TUDecl->addDecl(ObjCSuperTypeDecl);
4514 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4515 }
4516 return ObjCSuperType;
4517}
4518
Douglas Gregor319ac892009-04-23 22:29:11 +00004519void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004520 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004521 assert(Rec && "Invalid CFConstantStringType");
4522 CFConstantStringTypeDecl = Rec->getDecl();
4523}
4524
Jay Foad4ba2a172011-01-12 09:06:06 +00004525QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004526 if (BlockDescriptorType)
4527 return getTagDeclType(BlockDescriptorType);
4528
4529 RecordDecl *T;
4530 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004531 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004532 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004533 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004534
4535 QualType FieldTypes[] = {
4536 UnsignedLongTy,
4537 UnsignedLongTy,
4538 };
4539
Craig Topper3aa29df2013-07-15 08:24:27 +00004540 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004541 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004542 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004543 };
4544
4545 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004546 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004547 SourceLocation(),
4548 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004549 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004550 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004551 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004552 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004553 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004554 T->addDecl(Field);
4555 }
4556
Douglas Gregor838db382010-02-11 01:19:42 +00004557 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004558
4559 BlockDescriptorType = T;
4560
4561 return getTagDeclType(BlockDescriptorType);
4562}
4563
Jay Foad4ba2a172011-01-12 09:06:06 +00004564QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004565 if (BlockDescriptorExtendedType)
4566 return getTagDeclType(BlockDescriptorExtendedType);
4567
4568 RecordDecl *T;
4569 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004570 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004571 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004572 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004573
4574 QualType FieldTypes[] = {
4575 UnsignedLongTy,
4576 UnsignedLongTy,
4577 getPointerType(VoidPtrTy),
4578 getPointerType(VoidPtrTy)
4579 };
4580
Craig Topper3aa29df2013-07-15 08:24:27 +00004581 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004582 "reserved",
4583 "Size",
4584 "CopyFuncPtr",
4585 "DestroyFuncPtr"
4586 };
4587
4588 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004589 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004590 SourceLocation(),
4591 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004592 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004593 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004594 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004595 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004596 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004597 T->addDecl(Field);
4598 }
4599
Douglas Gregor838db382010-02-11 01:19:42 +00004600 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004601
4602 BlockDescriptorExtendedType = T;
4603
4604 return getTagDeclType(BlockDescriptorExtendedType);
4605}
4606
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004607/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4608/// requires copy/dispose. Note that this must match the logic
4609/// in buildByrefHelpers.
4610bool ASTContext::BlockRequiresCopying(QualType Ty,
4611 const VarDecl *D) {
4612 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4613 const Expr *copyExpr = getBlockVarCopyInits(D);
4614 if (!copyExpr && record->hasTrivialDestructor()) return false;
4615
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004616 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004617 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004618
4619 if (!Ty->isObjCRetainableType()) return false;
4620
4621 Qualifiers qs = Ty.getQualifiers();
4622
4623 // If we have lifetime, that dominates.
4624 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4625 assert(getLangOpts().ObjCAutoRefCount);
4626
4627 switch (lifetime) {
4628 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4629
4630 // These are just bits as far as the runtime is concerned.
4631 case Qualifiers::OCL_ExplicitNone:
4632 case Qualifiers::OCL_Autoreleasing:
4633 return false;
4634
4635 // Tell the runtime that this is ARC __weak, called by the
4636 // byref routines.
4637 case Qualifiers::OCL_Weak:
4638 // ARC __strong __block variables need to be retained.
4639 case Qualifiers::OCL_Strong:
4640 return true;
4641 }
4642 llvm_unreachable("fell out of lifetime switch!");
4643 }
4644 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4645 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004646}
4647
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004648bool ASTContext::getByrefLifetime(QualType Ty,
4649 Qualifiers::ObjCLifetime &LifeTime,
4650 bool &HasByrefExtendedLayout) const {
4651
4652 if (!getLangOpts().ObjC1 ||
4653 getLangOpts().getGC() != LangOptions::NonGC)
4654 return false;
4655
4656 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004657 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004658 HasByrefExtendedLayout = true;
4659 LifeTime = Qualifiers::OCL_None;
4660 }
4661 else if (getLangOpts().ObjCAutoRefCount)
4662 LifeTime = Ty.getObjCLifetime();
4663 // MRR.
4664 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4665 LifeTime = Qualifiers::OCL_ExplicitNone;
4666 else
4667 LifeTime = Qualifiers::OCL_None;
4668 return true;
4669}
4670
Douglas Gregore97179c2011-09-08 01:46:34 +00004671TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4672 if (!ObjCInstanceTypeDecl)
4673 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4674 getTranslationUnitDecl(),
4675 SourceLocation(),
4676 SourceLocation(),
4677 &Idents.get("instancetype"),
4678 getTrivialTypeSourceInfo(getObjCIdType()));
4679 return ObjCInstanceTypeDecl;
4680}
4681
Anders Carlssone8c49532007-10-29 06:33:42 +00004682// This returns true if a type has been typedefed to BOOL:
4683// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004684static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004685 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004686 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4687 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004689 return false;
4690}
4691
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004692/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004693/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004694CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004695 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4696 return CharUnits::Zero();
4697
Ken Dyck199c3d62010-01-11 17:06:35 +00004698 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004700 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004701 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004702 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004703 // Treat arrays as pointers, since that's how they're passed in.
4704 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004705 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004706 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004707}
4708
4709static inline
4710std::string charUnitsToString(const CharUnits &CU) {
4711 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004712}
4713
John McCall6b5a61b2011-02-07 10:33:21 +00004714/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004715/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004716std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4717 std::string S;
4718
David Chisnall5e530af2009-11-17 19:33:30 +00004719 const BlockDecl *Decl = Expr->getBlockDecl();
4720 QualType BlockTy =
4721 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4722 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004723 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004724 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4725 BlockTy->getAs<FunctionType>()->getResultType(),
4726 S, true /*Extended*/);
4727 else
4728 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4729 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004730 // Compute size of all parameters.
4731 // Start with computing size of a pointer in number of bytes.
4732 // FIXME: There might(should) be a better way of doing this computation!
4733 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004734 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4735 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004736 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004737 E = Decl->param_end(); PI != E; ++PI) {
4738 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004739 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004740 if (sz.isZero())
4741 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004742 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004743 ParmOffset += sz;
4744 }
4745 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004746 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004747 // Block pointer and offset.
4748 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004749
4750 // Argument types.
4751 ParmOffset = PtrSize;
4752 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4753 Decl->param_end(); PI != E; ++PI) {
4754 ParmVarDecl *PVDecl = *PI;
4755 QualType PType = PVDecl->getOriginalType();
4756 if (const ArrayType *AT =
4757 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4758 // Use array's original type only if it has known number of
4759 // elements.
4760 if (!isa<ConstantArrayType>(AT))
4761 PType = PVDecl->getType();
4762 } else if (PType->isFunctionType())
4763 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004764 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004765 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4766 S, true /*Extended*/);
4767 else
4768 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004769 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004770 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004771 }
John McCall6b5a61b2011-02-07 10:33:21 +00004772
4773 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004774}
4775
Douglas Gregorf968d832011-05-27 01:19:52 +00004776bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004777 std::string& S) {
4778 // Encode result type.
4779 getObjCEncodingForType(Decl->getResultType(), S);
4780 CharUnits ParmOffset;
4781 // Compute size of all parameters.
4782 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4783 E = Decl->param_end(); PI != E; ++PI) {
4784 QualType PType = (*PI)->getType();
4785 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004786 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004787 continue;
4788
David Chisnall5389f482010-12-30 14:05:53 +00004789 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004790 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004791 ParmOffset += sz;
4792 }
4793 S += charUnitsToString(ParmOffset);
4794 ParmOffset = CharUnits::Zero();
4795
4796 // Argument types.
4797 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4798 E = Decl->param_end(); PI != E; ++PI) {
4799 ParmVarDecl *PVDecl = *PI;
4800 QualType PType = PVDecl->getOriginalType();
4801 if (const ArrayType *AT =
4802 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4803 // Use array's original type only if it has known number of
4804 // elements.
4805 if (!isa<ConstantArrayType>(AT))
4806 PType = PVDecl->getType();
4807 } else if (PType->isFunctionType())
4808 PType = PVDecl->getType();
4809 getObjCEncodingForType(PType, S);
4810 S += charUnitsToString(ParmOffset);
4811 ParmOffset += getObjCEncodingTypeSize(PType);
4812 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004813
4814 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004815}
4816
Bob Wilsondc8dab62011-11-30 01:57:58 +00004817/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4818/// method parameter or return type. If Extended, include class names and
4819/// block object types.
4820void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4821 QualType T, std::string& S,
4822 bool Extended) const {
4823 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4824 getObjCEncodingForTypeQualifier(QT, S);
4825 // Encode parameter type.
4826 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4827 true /*OutermostType*/,
4828 false /*EncodingProperty*/,
4829 false /*StructField*/,
4830 Extended /*EncodeBlockParameters*/,
4831 Extended /*EncodeClassNames*/);
4832}
4833
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004834/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004835/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004836bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004837 std::string& S,
4838 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004839 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004840 // Encode return type.
4841 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4842 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004843 // Compute size of all parameters.
4844 // Start with computing size of a pointer in number of bytes.
4845 // FIXME: There might(should) be a better way of doing this computation!
4846 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004847 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004848 // The first two arguments (self and _cmd) are pointers; account for
4849 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004850 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004851 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004852 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004853 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004854 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004855 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004856 continue;
4857
Ken Dyck199c3d62010-01-11 17:06:35 +00004858 assert (sz.isPositive() &&
4859 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004860 ParmOffset += sz;
4861 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004862 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004863 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004864 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004866 // Argument types.
4867 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004868 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004869 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004870 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004871 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004872 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004873 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4874 // Use array's original type only if it has known number of
4875 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004876 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004877 PType = PVDecl->getType();
4878 } else if (PType->isFunctionType())
4879 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004880 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4881 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004882 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004883 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004884 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004885
4886 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004887}
4888
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004889/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004890/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004891/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4892/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004893/// Property attributes are stored as a comma-delimited C string. The simple
4894/// attributes readonly and bycopy are encoded as single characters. The
4895/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4896/// encoded as single characters, followed by an identifier. Property types
4897/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004898/// these attributes are defined by the following enumeration:
4899/// @code
4900/// enum PropertyAttributes {
4901/// kPropertyReadOnly = 'R', // property is read-only.
4902/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4903/// kPropertyByref = '&', // property is a reference to the value last assigned
4904/// kPropertyDynamic = 'D', // property is dynamic
4905/// kPropertyGetter = 'G', // followed by getter selector name
4906/// kPropertySetter = 'S', // followed by setter selector name
4907/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004908/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004909/// kPropertyWeak = 'W' // 'weak' property
4910/// kPropertyStrong = 'P' // property GC'able
4911/// kPropertyNonAtomic = 'N' // property non-atomic
4912/// };
4913/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004914void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004915 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004916 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004917 // Collect information from the property implementation decl(s).
4918 bool Dynamic = false;
4919 ObjCPropertyImplDecl *SynthesizePID = 0;
4920
4921 // FIXME: Duplicated code due to poor abstraction.
4922 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004923 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004924 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4925 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004926 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004927 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004928 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004929 if (PID->getPropertyDecl() == PD) {
4930 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4931 Dynamic = true;
4932 } else {
4933 SynthesizePID = PID;
4934 }
4935 }
4936 }
4937 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004938 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004939 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004940 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004941 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004942 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004943 if (PID->getPropertyDecl() == PD) {
4944 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4945 Dynamic = true;
4946 } else {
4947 SynthesizePID = PID;
4948 }
4949 }
Mike Stump1eb44332009-09-09 15:08:12 +00004950 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004951 }
4952 }
4953
4954 // FIXME: This is not very efficient.
4955 S = "T";
4956
4957 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004958 // GCC has some special rules regarding encoding of properties which
4959 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004960 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004961 true /* outermost type */,
4962 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004963
4964 if (PD->isReadOnly()) {
4965 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4967 S += ",C";
4968 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4969 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004970 } else {
4971 switch (PD->getSetterKind()) {
4972 case ObjCPropertyDecl::Assign: break;
4973 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004974 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004975 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004976 }
4977 }
4978
4979 // It really isn't clear at all what this means, since properties
4980 // are "dynamic by default".
4981 if (Dynamic)
4982 S += ",D";
4983
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004984 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4985 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004986
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004987 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4988 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004989 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004990 }
4991
4992 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4993 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004994 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004995 }
4996
4997 if (SynthesizePID) {
4998 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4999 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00005000 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005001 }
5002
5003 // FIXME: OBJCGC: weak & strong
5004}
5005
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005006/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005007/// Another legacy compatibility encoding: 32-bit longs are encoded as
5008/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005009/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5010///
5011void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005012 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005013 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005014 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005015 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005016 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005017 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005018 PointeeTy = IntTy;
5019 }
5020 }
5021}
5022
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005023void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005024 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005025 // We follow the behavior of gcc, expanding structures which are
5026 // directly pointed to, and expanding embedded structures. Note that
5027 // these rules are sufficient to prevent recursive encoding of the
5028 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005029 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005030 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005031}
5032
John McCall3624e9e2012-12-20 02:45:14 +00005033static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5034 BuiltinType::Kind kind) {
5035 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005036 case BuiltinType::Void: return 'v';
5037 case BuiltinType::Bool: return 'B';
5038 case BuiltinType::Char_U:
5039 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005040 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005041 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005042 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005043 case BuiltinType::UInt: return 'I';
5044 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005045 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005046 case BuiltinType::UInt128: return 'T';
5047 case BuiltinType::ULongLong: return 'Q';
5048 case BuiltinType::Char_S:
5049 case BuiltinType::SChar: return 'c';
5050 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005051 case BuiltinType::WChar_S:
5052 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005053 case BuiltinType::Int: return 'i';
5054 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005055 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005056 case BuiltinType::LongLong: return 'q';
5057 case BuiltinType::Int128: return 't';
5058 case BuiltinType::Float: return 'f';
5059 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005060 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005061 case BuiltinType::NullPtr: return '*'; // like char*
5062
5063 case BuiltinType::Half:
5064 // FIXME: potentially need @encodes for these!
5065 return ' ';
5066
5067 case BuiltinType::ObjCId:
5068 case BuiltinType::ObjCClass:
5069 case BuiltinType::ObjCSel:
5070 llvm_unreachable("@encoding ObjC primitive type");
5071
5072 // OpenCL and placeholder types don't need @encodings.
5073 case BuiltinType::OCLImage1d:
5074 case BuiltinType::OCLImage1dArray:
5075 case BuiltinType::OCLImage1dBuffer:
5076 case BuiltinType::OCLImage2d:
5077 case BuiltinType::OCLImage2dArray:
5078 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005079 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005080 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005081 case BuiltinType::Dependent:
5082#define BUILTIN_TYPE(KIND, ID)
5083#define PLACEHOLDER_TYPE(KIND, ID) \
5084 case BuiltinType::KIND:
5085#include "clang/AST/BuiltinTypes.def"
5086 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005087 }
David Blaikie719e53f2013-01-09 17:48:41 +00005088 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005089}
5090
Douglas Gregor5471bc82011-09-08 17:18:35 +00005091static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5092 EnumDecl *Enum = ET->getDecl();
5093
5094 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5095 if (!Enum->isFixed())
5096 return 'i';
5097
5098 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005099 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5100 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005101}
5102
Jay Foad4ba2a172011-01-12 09:06:06 +00005103static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005104 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005105 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005106 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005107 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5108 // The GNU runtime requires more information; bitfields are encoded as b,
5109 // then the offset (in bits) of the first element, then the type of the
5110 // bitfield, then the size in bits. For example, in this structure:
5111 //
5112 // struct
5113 // {
5114 // int integer;
5115 // int flags:2;
5116 // };
5117 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5118 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5119 // information is not especially sensible, but we're stuck with it for
5120 // compatibility with GCC, although providing it breaks anything that
5121 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005122 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005123 const RecordDecl *RD = FD->getParent();
5124 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005125 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005126 if (const EnumType *ET = T->getAs<EnumType>())
5127 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005128 else {
5129 const BuiltinType *BT = T->castAs<BuiltinType>();
5130 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5131 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005132 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005133 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005134}
5135
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005136// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005137void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5138 bool ExpandPointedToStructures,
5139 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005140 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005141 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005142 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005143 bool StructField,
5144 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005145 bool EncodeClassNames,
5146 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005147 CanQualType CT = getCanonicalType(T);
5148 switch (CT->getTypeClass()) {
5149 case Type::Builtin:
5150 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005151 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005152 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005153 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5154 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5155 else
5156 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005157 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005158
John McCall3624e9e2012-12-20 02:45:14 +00005159 case Type::Complex: {
5160 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005161 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005162 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005163 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005164 return;
5165 }
John McCall3624e9e2012-12-20 02:45:14 +00005166
5167 case Type::Atomic: {
5168 const AtomicType *AT = T->castAs<AtomicType>();
5169 S += 'A';
5170 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5171 false, false);
5172 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005173 }
John McCall3624e9e2012-12-20 02:45:14 +00005174
5175 // encoding for pointer or reference types.
5176 case Type::Pointer:
5177 case Type::LValueReference:
5178 case Type::RValueReference: {
5179 QualType PointeeTy;
5180 if (isa<PointerType>(CT)) {
5181 const PointerType *PT = T->castAs<PointerType>();
5182 if (PT->isObjCSelType()) {
5183 S += ':';
5184 return;
5185 }
5186 PointeeTy = PT->getPointeeType();
5187 } else {
5188 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5189 }
5190
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005191 bool isReadOnly = false;
5192 // For historical/compatibility reasons, the read-only qualifier of the
5193 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5194 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005195 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005196 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005197 if (OutermostType && T.isConstQualified()) {
5198 isReadOnly = true;
5199 S += 'r';
5200 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005201 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005202 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005203 while (P->getAs<PointerType>())
5204 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005205 if (P.isConstQualified()) {
5206 isReadOnly = true;
5207 S += 'r';
5208 }
5209 }
5210 if (isReadOnly) {
5211 // Another legacy compatibility encoding. Some ObjC qualifier and type
5212 // combinations need to be rearranged.
5213 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005214 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005215 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005216 }
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005218 if (PointeeTy->isCharType()) {
5219 // char pointer types should be encoded as '*' unless it is a
5220 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005221 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005222 S += '*';
5223 return;
5224 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005225 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005226 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5227 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5228 S += '#';
5229 return;
5230 }
5231 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5232 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5233 S += '@';
5234 return;
5235 }
5236 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005237 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005238 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005239 getLegacyIntegralTypeEncoding(PointeeTy);
5240
Mike Stump1eb44332009-09-09 15:08:12 +00005241 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005242 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005243 return;
5244 }
John McCall3624e9e2012-12-20 02:45:14 +00005245
5246 case Type::ConstantArray:
5247 case Type::IncompleteArray:
5248 case Type::VariableArray: {
5249 const ArrayType *AT = cast<ArrayType>(CT);
5250
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005251 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005252 // Incomplete arrays are encoded as a pointer to the array element.
5253 S += '^';
5254
Mike Stump1eb44332009-09-09 15:08:12 +00005255 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005256 false, ExpandStructures, FD);
5257 } else {
5258 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005260 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5261 S += llvm::utostr(CAT->getSize().getZExtValue());
5262 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005263 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005264 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5265 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005266 S += '0';
5267 }
Mike Stump1eb44332009-09-09 15:08:12 +00005268
5269 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005270 false, ExpandStructures, FD);
5271 S += ']';
5272 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005273 return;
5274 }
Mike Stump1eb44332009-09-09 15:08:12 +00005275
John McCall3624e9e2012-12-20 02:45:14 +00005276 case Type::FunctionNoProto:
5277 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005278 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005279 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005280
John McCall3624e9e2012-12-20 02:45:14 +00005281 case Type::Record: {
5282 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005283 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005284 // Anonymous structures print as '?'
5285 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5286 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005287 if (ClassTemplateSpecializationDecl *Spec
5288 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5289 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005290 llvm::raw_string_ostream OS(S);
5291 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005292 TemplateArgs.data(),
5293 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005294 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005295 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005296 } else {
5297 S += '?';
5298 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005299 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005300 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005301 if (!RDecl->isUnion()) {
5302 getObjCEncodingForStructureImpl(RDecl, S, FD);
5303 } else {
5304 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5305 FieldEnd = RDecl->field_end();
5306 Field != FieldEnd; ++Field) {
5307 if (FD) {
5308 S += '"';
5309 S += Field->getNameAsString();
5310 S += '"';
5311 }
Mike Stump1eb44332009-09-09 15:08:12 +00005312
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005313 // Special case bit-fields.
5314 if (Field->isBitField()) {
5315 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005316 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005317 } else {
5318 QualType qt = Field->getType();
5319 getLegacyIntegralTypeEncoding(qt);
5320 getObjCEncodingForTypeImpl(qt, S, false, true,
5321 FD, /*OutermostType*/false,
5322 /*EncodingProperty*/false,
5323 /*StructField*/true);
5324 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005325 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005326 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005327 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005328 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005329 return;
5330 }
Mike Stump1eb44332009-09-09 15:08:12 +00005331
John McCall3624e9e2012-12-20 02:45:14 +00005332 case Type::BlockPointer: {
5333 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005334 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005335 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005336 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005337
5338 S += '<';
5339 // Block return type
5340 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5341 ExpandPointedToStructures, ExpandStructures,
5342 FD,
5343 false /* OutermostType */,
5344 EncodingProperty,
5345 false /* StructField */,
5346 EncodeBlockParameters,
5347 EncodeClassNames);
5348 // Block self
5349 S += "@?";
5350 // Block parameters
5351 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5352 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5353 E = FPT->arg_type_end(); I && (I != E); ++I) {
5354 getObjCEncodingForTypeImpl(*I, S,
5355 ExpandPointedToStructures,
5356 ExpandStructures,
5357 FD,
5358 false /* OutermostType */,
5359 EncodingProperty,
5360 false /* StructField */,
5361 EncodeBlockParameters,
5362 EncodeClassNames);
5363 }
5364 }
5365 S += '>';
5366 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005367 return;
5368 }
Mike Stump1eb44332009-09-09 15:08:12 +00005369
John McCall3624e9e2012-12-20 02:45:14 +00005370 case Type::ObjCObject:
5371 case Type::ObjCInterface: {
5372 // Ignore protocol qualifiers when mangling at this level.
5373 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005374
John McCall3624e9e2012-12-20 02:45:14 +00005375 // The assumption seems to be that this assert will succeed
5376 // because nested levels will have filtered out 'id' and 'Class'.
5377 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005378 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005379 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005380 S += '{';
5381 const IdentifierInfo *II = OI->getIdentifier();
5382 S += II->getName();
5383 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005384 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005385 DeepCollectObjCIvars(OI, true, Ivars);
5386 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005387 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005388 if (Field->isBitField())
5389 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005390 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005391 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5392 false, false, false, false, false,
5393 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005394 }
5395 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005396 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398
John McCall3624e9e2012-12-20 02:45:14 +00005399 case Type::ObjCObjectPointer: {
5400 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005401 if (OPT->isObjCIdType()) {
5402 S += '@';
5403 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005404 }
Mike Stump1eb44332009-09-09 15:08:12 +00005405
Steve Naroff27d20a22009-10-28 22:03:49 +00005406 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5407 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5408 // Since this is a binary compatibility issue, need to consult with runtime
5409 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005410 S += '#';
5411 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005412 }
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005414 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005415 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005416 ExpandPointedToStructures,
5417 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005418 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005419 // Note that we do extended encoding of protocol qualifer list
5420 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005421 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005422 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5423 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005424 S += '<';
5425 S += (*I)->getNameAsString();
5426 S += '>';
5427 }
5428 S += '"';
5429 }
5430 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005431 }
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005433 QualType PointeeTy = OPT->getPointeeType();
5434 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005435 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5436 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005437 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005438 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005439 // {...};
5440 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005441 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005442 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005443 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5444 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5445 DeepCollectObjCIvars(OI, true, Ivars);
5446 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5447 if (cast<FieldDecl>(Ivars[i]) == FD) {
5448 S += '{';
5449 S += OI->getIdentifier()->getName();
5450 S += '}';
5451 return;
5452 }
5453 }
5454 }
Mike Stump1eb44332009-09-09 15:08:12 +00005455 getObjCEncodingForTypeImpl(PointeeTy, S,
5456 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005457 NULL,
5458 false, false, false, false, false,
5459 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005460 return;
5461 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005462
5463 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005464 if (OPT->getInterfaceDecl() &&
5465 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005466 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005467 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005468 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5469 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005470 S += '<';
5471 S += (*I)->getNameAsString();
5472 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005473 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005474 S += '"';
5475 }
5476 return;
5477 }
Mike Stump1eb44332009-09-09 15:08:12 +00005478
John McCall532ec7b2010-05-17 23:56:34 +00005479 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005480 // FIXME: we shoul do better than that. 'M' is available.
5481 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005482 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005483
John McCall3624e9e2012-12-20 02:45:14 +00005484 case Type::Vector:
5485 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005486 // This matches gcc's encoding, even though technically it is
5487 // insufficient.
5488 // FIXME. We should do a better job than gcc.
5489 return;
John McCall3624e9e2012-12-20 02:45:14 +00005490
Richard Smithdc7a4f52013-04-30 13:56:41 +00005491 case Type::Auto:
5492 // We could see an undeduced auto type here during error recovery.
5493 // Just ignore it.
5494 return;
5495
John McCall3624e9e2012-12-20 02:45:14 +00005496#define ABSTRACT_TYPE(KIND, BASE)
5497#define TYPE(KIND, BASE)
5498#define DEPENDENT_TYPE(KIND, BASE) \
5499 case Type::KIND:
5500#define NON_CANONICAL_TYPE(KIND, BASE) \
5501 case Type::KIND:
5502#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5503 case Type::KIND:
5504#include "clang/AST/TypeNodes.def"
5505 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005506 }
John McCall3624e9e2012-12-20 02:45:14 +00005507 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005508}
5509
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005510void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5511 std::string &S,
5512 const FieldDecl *FD,
5513 bool includeVBases) const {
5514 assert(RDecl && "Expected non-null RecordDecl");
5515 assert(!RDecl->isUnion() && "Should not be called for unions");
5516 if (!RDecl->getDefinition())
5517 return;
5518
5519 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5520 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5521 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5522
5523 if (CXXRec) {
5524 for (CXXRecordDecl::base_class_iterator
5525 BI = CXXRec->bases_begin(),
5526 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5527 if (!BI->isVirtual()) {
5528 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005529 if (base->isEmpty())
5530 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005531 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005532 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5533 std::make_pair(offs, base));
5534 }
5535 }
5536 }
5537
5538 unsigned i = 0;
5539 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5540 FieldEnd = RDecl->field_end();
5541 Field != FieldEnd; ++Field, ++i) {
5542 uint64_t offs = layout.getFieldOffset(i);
5543 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005544 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005545 }
5546
5547 if (CXXRec && includeVBases) {
5548 for (CXXRecordDecl::base_class_iterator
5549 BI = CXXRec->vbases_begin(),
5550 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5551 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005552 if (base->isEmpty())
5553 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005554 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1a973442013-09-18 01:59:16 +00005555 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5556 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005557 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5558 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005559 }
5560 }
5561
5562 CharUnits size;
5563 if (CXXRec) {
5564 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5565 } else {
5566 size = layout.getSize();
5567 }
5568
5569 uint64_t CurOffs = 0;
5570 std::multimap<uint64_t, NamedDecl *>::iterator
5571 CurLayObj = FieldOrBaseOffsets.begin();
5572
Douglas Gregor58db7a52012-04-27 22:30:01 +00005573 if (CXXRec && CXXRec->isDynamicClass() &&
5574 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005575 if (FD) {
5576 S += "\"_vptr$";
5577 std::string recname = CXXRec->getNameAsString();
5578 if (recname.empty()) recname = "?";
5579 S += recname;
5580 S += '"';
5581 }
5582 S += "^^?";
5583 CurOffs += getTypeSize(VoidPtrTy);
5584 }
5585
5586 if (!RDecl->hasFlexibleArrayMember()) {
5587 // Mark the end of the structure.
5588 uint64_t offs = toBits(size);
5589 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5590 std::make_pair(offs, (NamedDecl*)0));
5591 }
5592
5593 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5594 assert(CurOffs <= CurLayObj->first);
5595
5596 if (CurOffs < CurLayObj->first) {
5597 uint64_t padding = CurLayObj->first - CurOffs;
5598 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5599 // packing/alignment of members is different that normal, in which case
5600 // the encoding will be out-of-sync with the real layout.
5601 // If the runtime switches to just consider the size of types without
5602 // taking into account alignment, we could make padding explicit in the
5603 // encoding (e.g. using arrays of chars). The encoding strings would be
5604 // longer then though.
5605 CurOffs += padding;
5606 }
5607
5608 NamedDecl *dcl = CurLayObj->second;
5609 if (dcl == 0)
5610 break; // reached end of structure.
5611
5612 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5613 // We expand the bases without their virtual bases since those are going
5614 // in the initial structure. Note that this differs from gcc which
5615 // expands virtual bases each time one is encountered in the hierarchy,
5616 // making the encoding type bigger than it really is.
5617 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005618 assert(!base->isEmpty());
5619 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005620 } else {
5621 FieldDecl *field = cast<FieldDecl>(dcl);
5622 if (FD) {
5623 S += '"';
5624 S += field->getNameAsString();
5625 S += '"';
5626 }
5627
5628 if (field->isBitField()) {
5629 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005630 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005631 } else {
5632 QualType qt = field->getType();
5633 getLegacyIntegralTypeEncoding(qt);
5634 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5635 /*OutermostType*/false,
5636 /*EncodingProperty*/false,
5637 /*StructField*/true);
5638 CurOffs += getTypeSize(field->getType());
5639 }
5640 }
5641 }
5642}
5643
Mike Stump1eb44332009-09-09 15:08:12 +00005644void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005645 std::string& S) const {
5646 if (QT & Decl::OBJC_TQ_In)
5647 S += 'n';
5648 if (QT & Decl::OBJC_TQ_Inout)
5649 S += 'N';
5650 if (QT & Decl::OBJC_TQ_Out)
5651 S += 'o';
5652 if (QT & Decl::OBJC_TQ_Bycopy)
5653 S += 'O';
5654 if (QT & Decl::OBJC_TQ_Byref)
5655 S += 'R';
5656 if (QT & Decl::OBJC_TQ_Oneway)
5657 S += 'V';
5658}
5659
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005660TypedefDecl *ASTContext::getObjCIdDecl() const {
5661 if (!ObjCIdDecl) {
5662 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5663 T = getObjCObjectPointerType(T);
5664 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5665 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5666 getTranslationUnitDecl(),
5667 SourceLocation(), SourceLocation(),
5668 &Idents.get("id"), IdInfo);
5669 }
5670
5671 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005672}
5673
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005674TypedefDecl *ASTContext::getObjCSelDecl() const {
5675 if (!ObjCSelDecl) {
5676 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5677 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5678 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5679 getTranslationUnitDecl(),
5680 SourceLocation(), SourceLocation(),
5681 &Idents.get("SEL"), SelInfo);
5682 }
5683 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005684}
5685
Douglas Gregor79d67262011-08-12 05:59:41 +00005686TypedefDecl *ASTContext::getObjCClassDecl() const {
5687 if (!ObjCClassDecl) {
5688 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5689 T = getObjCObjectPointerType(T);
5690 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5691 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5692 getTranslationUnitDecl(),
5693 SourceLocation(), SourceLocation(),
5694 &Idents.get("Class"), ClassInfo);
5695 }
5696
5697 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005698}
5699
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005700ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5701 if (!ObjCProtocolClassDecl) {
5702 ObjCProtocolClassDecl
5703 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5704 SourceLocation(),
5705 &Idents.get("Protocol"),
5706 /*PrevDecl=*/0,
5707 SourceLocation(), true);
5708 }
5709
5710 return ObjCProtocolClassDecl;
5711}
5712
Meador Ingec5613b22012-06-16 03:34:49 +00005713//===----------------------------------------------------------------------===//
5714// __builtin_va_list Construction Functions
5715//===----------------------------------------------------------------------===//
5716
5717static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5718 // typedef char* __builtin_va_list;
5719 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5720 TypeSourceInfo *TInfo
5721 = Context->getTrivialTypeSourceInfo(CharPtrType);
5722
5723 TypedefDecl *VaListTypeDecl
5724 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5725 Context->getTranslationUnitDecl(),
5726 SourceLocation(), SourceLocation(),
5727 &Context->Idents.get("__builtin_va_list"),
5728 TInfo);
5729 return VaListTypeDecl;
5730}
5731
5732static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5733 // typedef void* __builtin_va_list;
5734 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5735 TypeSourceInfo *TInfo
5736 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5737
5738 TypedefDecl *VaListTypeDecl
5739 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5740 Context->getTranslationUnitDecl(),
5741 SourceLocation(), SourceLocation(),
5742 &Context->Idents.get("__builtin_va_list"),
5743 TInfo);
5744 return VaListTypeDecl;
5745}
5746
Tim Northoverc264e162013-01-31 12:13:10 +00005747static TypedefDecl *
5748CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5749 RecordDecl *VaListTagDecl;
5750 if (Context->getLangOpts().CPlusPlus) {
5751 // namespace std { struct __va_list {
5752 NamespaceDecl *NS;
5753 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5754 Context->getTranslationUnitDecl(),
5755 /*Inline*/false, SourceLocation(),
5756 SourceLocation(), &Context->Idents.get("std"),
5757 /*PrevDecl*/0);
5758
5759 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5760 Context->getTranslationUnitDecl(),
5761 SourceLocation(), SourceLocation(),
5762 &Context->Idents.get("__va_list"));
5763 VaListTagDecl->setDeclContext(NS);
5764 } else {
5765 // struct __va_list
5766 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5767 Context->getTranslationUnitDecl(),
5768 &Context->Idents.get("__va_list"));
5769 }
5770
5771 VaListTagDecl->startDefinition();
5772
5773 const size_t NumFields = 5;
5774 QualType FieldTypes[NumFields];
5775 const char *FieldNames[NumFields];
5776
5777 // void *__stack;
5778 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5779 FieldNames[0] = "__stack";
5780
5781 // void *__gr_top;
5782 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5783 FieldNames[1] = "__gr_top";
5784
5785 // void *__vr_top;
5786 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5787 FieldNames[2] = "__vr_top";
5788
5789 // int __gr_offs;
5790 FieldTypes[3] = Context->IntTy;
5791 FieldNames[3] = "__gr_offs";
5792
5793 // int __vr_offs;
5794 FieldTypes[4] = Context->IntTy;
5795 FieldNames[4] = "__vr_offs";
5796
5797 // Create fields
5798 for (unsigned i = 0; i < NumFields; ++i) {
5799 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5800 VaListTagDecl,
5801 SourceLocation(),
5802 SourceLocation(),
5803 &Context->Idents.get(FieldNames[i]),
5804 FieldTypes[i], /*TInfo=*/0,
5805 /*BitWidth=*/0,
5806 /*Mutable=*/false,
5807 ICIS_NoInit);
5808 Field->setAccess(AS_public);
5809 VaListTagDecl->addDecl(Field);
5810 }
5811 VaListTagDecl->completeDefinition();
5812 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5813 Context->VaListTagTy = VaListTagType;
5814
5815 // } __builtin_va_list;
5816 TypedefDecl *VaListTypedefDecl
5817 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5818 Context->getTranslationUnitDecl(),
5819 SourceLocation(), SourceLocation(),
5820 &Context->Idents.get("__builtin_va_list"),
5821 Context->getTrivialTypeSourceInfo(VaListTagType));
5822
5823 return VaListTypedefDecl;
5824}
5825
Meador Ingec5613b22012-06-16 03:34:49 +00005826static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5827 // typedef struct __va_list_tag {
5828 RecordDecl *VaListTagDecl;
5829
5830 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5831 Context->getTranslationUnitDecl(),
5832 &Context->Idents.get("__va_list_tag"));
5833 VaListTagDecl->startDefinition();
5834
5835 const size_t NumFields = 5;
5836 QualType FieldTypes[NumFields];
5837 const char *FieldNames[NumFields];
5838
5839 // unsigned char gpr;
5840 FieldTypes[0] = Context->UnsignedCharTy;
5841 FieldNames[0] = "gpr";
5842
5843 // unsigned char fpr;
5844 FieldTypes[1] = Context->UnsignedCharTy;
5845 FieldNames[1] = "fpr";
5846
5847 // unsigned short reserved;
5848 FieldTypes[2] = Context->UnsignedShortTy;
5849 FieldNames[2] = "reserved";
5850
5851 // void* overflow_arg_area;
5852 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5853 FieldNames[3] = "overflow_arg_area";
5854
5855 // void* reg_save_area;
5856 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5857 FieldNames[4] = "reg_save_area";
5858
5859 // Create fields
5860 for (unsigned i = 0; i < NumFields; ++i) {
5861 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5862 SourceLocation(),
5863 SourceLocation(),
5864 &Context->Idents.get(FieldNames[i]),
5865 FieldTypes[i], /*TInfo=*/0,
5866 /*BitWidth=*/0,
5867 /*Mutable=*/false,
5868 ICIS_NoInit);
5869 Field->setAccess(AS_public);
5870 VaListTagDecl->addDecl(Field);
5871 }
5872 VaListTagDecl->completeDefinition();
5873 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005874 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005875
5876 // } __va_list_tag;
5877 TypedefDecl *VaListTagTypedefDecl
5878 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5879 Context->getTranslationUnitDecl(),
5880 SourceLocation(), SourceLocation(),
5881 &Context->Idents.get("__va_list_tag"),
5882 Context->getTrivialTypeSourceInfo(VaListTagType));
5883 QualType VaListTagTypedefType =
5884 Context->getTypedefType(VaListTagTypedefDecl);
5885
5886 // typedef __va_list_tag __builtin_va_list[1];
5887 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5888 QualType VaListTagArrayType
5889 = Context->getConstantArrayType(VaListTagTypedefType,
5890 Size, ArrayType::Normal, 0);
5891 TypeSourceInfo *TInfo
5892 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5893 TypedefDecl *VaListTypedefDecl
5894 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5895 Context->getTranslationUnitDecl(),
5896 SourceLocation(), SourceLocation(),
5897 &Context->Idents.get("__builtin_va_list"),
5898 TInfo);
5899
5900 return VaListTypedefDecl;
5901}
5902
5903static TypedefDecl *
5904CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5905 // typedef struct __va_list_tag {
5906 RecordDecl *VaListTagDecl;
5907 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5908 Context->getTranslationUnitDecl(),
5909 &Context->Idents.get("__va_list_tag"));
5910 VaListTagDecl->startDefinition();
5911
5912 const size_t NumFields = 4;
5913 QualType FieldTypes[NumFields];
5914 const char *FieldNames[NumFields];
5915
5916 // unsigned gp_offset;
5917 FieldTypes[0] = Context->UnsignedIntTy;
5918 FieldNames[0] = "gp_offset";
5919
5920 // unsigned fp_offset;
5921 FieldTypes[1] = Context->UnsignedIntTy;
5922 FieldNames[1] = "fp_offset";
5923
5924 // void* overflow_arg_area;
5925 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5926 FieldNames[2] = "overflow_arg_area";
5927
5928 // void* reg_save_area;
5929 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5930 FieldNames[3] = "reg_save_area";
5931
5932 // Create fields
5933 for (unsigned i = 0; i < NumFields; ++i) {
5934 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5935 VaListTagDecl,
5936 SourceLocation(),
5937 SourceLocation(),
5938 &Context->Idents.get(FieldNames[i]),
5939 FieldTypes[i], /*TInfo=*/0,
5940 /*BitWidth=*/0,
5941 /*Mutable=*/false,
5942 ICIS_NoInit);
5943 Field->setAccess(AS_public);
5944 VaListTagDecl->addDecl(Field);
5945 }
5946 VaListTagDecl->completeDefinition();
5947 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005948 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005949
5950 // } __va_list_tag;
5951 TypedefDecl *VaListTagTypedefDecl
5952 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5953 Context->getTranslationUnitDecl(),
5954 SourceLocation(), SourceLocation(),
5955 &Context->Idents.get("__va_list_tag"),
5956 Context->getTrivialTypeSourceInfo(VaListTagType));
5957 QualType VaListTagTypedefType =
5958 Context->getTypedefType(VaListTagTypedefDecl);
5959
5960 // typedef __va_list_tag __builtin_va_list[1];
5961 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5962 QualType VaListTagArrayType
5963 = Context->getConstantArrayType(VaListTagTypedefType,
5964 Size, ArrayType::Normal,0);
5965 TypeSourceInfo *TInfo
5966 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5967 TypedefDecl *VaListTypedefDecl
5968 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5969 Context->getTranslationUnitDecl(),
5970 SourceLocation(), SourceLocation(),
5971 &Context->Idents.get("__builtin_va_list"),
5972 TInfo);
5973
5974 return VaListTypedefDecl;
5975}
5976
5977static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5978 // typedef int __builtin_va_list[4];
5979 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5980 QualType IntArrayType
5981 = Context->getConstantArrayType(Context->IntTy,
5982 Size, ArrayType::Normal, 0);
5983 TypedefDecl *VaListTypedefDecl
5984 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5985 Context->getTranslationUnitDecl(),
5986 SourceLocation(), SourceLocation(),
5987 &Context->Idents.get("__builtin_va_list"),
5988 Context->getTrivialTypeSourceInfo(IntArrayType));
5989
5990 return VaListTypedefDecl;
5991}
5992
Logan Chieneae5a8202012-10-10 06:56:20 +00005993static TypedefDecl *
5994CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5995 RecordDecl *VaListDecl;
5996 if (Context->getLangOpts().CPlusPlus) {
5997 // namespace std { struct __va_list {
5998 NamespaceDecl *NS;
5999 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6000 Context->getTranslationUnitDecl(),
6001 /*Inline*/false, SourceLocation(),
6002 SourceLocation(), &Context->Idents.get("std"),
6003 /*PrevDecl*/0);
6004
6005 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6006 Context->getTranslationUnitDecl(),
6007 SourceLocation(), SourceLocation(),
6008 &Context->Idents.get("__va_list"));
6009
6010 VaListDecl->setDeclContext(NS);
6011
6012 } else {
6013 // struct __va_list {
6014 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6015 Context->getTranslationUnitDecl(),
6016 &Context->Idents.get("__va_list"));
6017 }
6018
6019 VaListDecl->startDefinition();
6020
6021 // void * __ap;
6022 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6023 VaListDecl,
6024 SourceLocation(),
6025 SourceLocation(),
6026 &Context->Idents.get("__ap"),
6027 Context->getPointerType(Context->VoidTy),
6028 /*TInfo=*/0,
6029 /*BitWidth=*/0,
6030 /*Mutable=*/false,
6031 ICIS_NoInit);
6032 Field->setAccess(AS_public);
6033 VaListDecl->addDecl(Field);
6034
6035 // };
6036 VaListDecl->completeDefinition();
6037
6038 // typedef struct __va_list __builtin_va_list;
6039 TypeSourceInfo *TInfo
6040 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6041
6042 TypedefDecl *VaListTypeDecl
6043 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6044 Context->getTranslationUnitDecl(),
6045 SourceLocation(), SourceLocation(),
6046 &Context->Idents.get("__builtin_va_list"),
6047 TInfo);
6048
6049 return VaListTypeDecl;
6050}
6051
Ulrich Weigandb8409212013-05-06 16:26:41 +00006052static TypedefDecl *
6053CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6054 // typedef struct __va_list_tag {
6055 RecordDecl *VaListTagDecl;
6056 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6057 Context->getTranslationUnitDecl(),
6058 &Context->Idents.get("__va_list_tag"));
6059 VaListTagDecl->startDefinition();
6060
6061 const size_t NumFields = 4;
6062 QualType FieldTypes[NumFields];
6063 const char *FieldNames[NumFields];
6064
6065 // long __gpr;
6066 FieldTypes[0] = Context->LongTy;
6067 FieldNames[0] = "__gpr";
6068
6069 // long __fpr;
6070 FieldTypes[1] = Context->LongTy;
6071 FieldNames[1] = "__fpr";
6072
6073 // void *__overflow_arg_area;
6074 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6075 FieldNames[2] = "__overflow_arg_area";
6076
6077 // void *__reg_save_area;
6078 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6079 FieldNames[3] = "__reg_save_area";
6080
6081 // Create fields
6082 for (unsigned i = 0; i < NumFields; ++i) {
6083 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6084 VaListTagDecl,
6085 SourceLocation(),
6086 SourceLocation(),
6087 &Context->Idents.get(FieldNames[i]),
6088 FieldTypes[i], /*TInfo=*/0,
6089 /*BitWidth=*/0,
6090 /*Mutable=*/false,
6091 ICIS_NoInit);
6092 Field->setAccess(AS_public);
6093 VaListTagDecl->addDecl(Field);
6094 }
6095 VaListTagDecl->completeDefinition();
6096 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6097 Context->VaListTagTy = VaListTagType;
6098
6099 // } __va_list_tag;
6100 TypedefDecl *VaListTagTypedefDecl
6101 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6102 Context->getTranslationUnitDecl(),
6103 SourceLocation(), SourceLocation(),
6104 &Context->Idents.get("__va_list_tag"),
6105 Context->getTrivialTypeSourceInfo(VaListTagType));
6106 QualType VaListTagTypedefType =
6107 Context->getTypedefType(VaListTagTypedefDecl);
6108
6109 // typedef __va_list_tag __builtin_va_list[1];
6110 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6111 QualType VaListTagArrayType
6112 = Context->getConstantArrayType(VaListTagTypedefType,
6113 Size, ArrayType::Normal,0);
6114 TypeSourceInfo *TInfo
6115 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6116 TypedefDecl *VaListTypedefDecl
6117 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6118 Context->getTranslationUnitDecl(),
6119 SourceLocation(), SourceLocation(),
6120 &Context->Idents.get("__builtin_va_list"),
6121 TInfo);
6122
6123 return VaListTypedefDecl;
6124}
6125
Meador Ingec5613b22012-06-16 03:34:49 +00006126static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6127 TargetInfo::BuiltinVaListKind Kind) {
6128 switch (Kind) {
6129 case TargetInfo::CharPtrBuiltinVaList:
6130 return CreateCharPtrBuiltinVaListDecl(Context);
6131 case TargetInfo::VoidPtrBuiltinVaList:
6132 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006133 case TargetInfo::AArch64ABIBuiltinVaList:
6134 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006135 case TargetInfo::PowerABIBuiltinVaList:
6136 return CreatePowerABIBuiltinVaListDecl(Context);
6137 case TargetInfo::X86_64ABIBuiltinVaList:
6138 return CreateX86_64ABIBuiltinVaListDecl(Context);
6139 case TargetInfo::PNaClABIBuiltinVaList:
6140 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006141 case TargetInfo::AAPCSABIBuiltinVaList:
6142 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006143 case TargetInfo::SystemZBuiltinVaList:
6144 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006145 }
6146
6147 llvm_unreachable("Unhandled __builtin_va_list type kind");
6148}
6149
6150TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6151 if (!BuiltinVaListDecl)
6152 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6153
6154 return BuiltinVaListDecl;
6155}
6156
Meador Ingefb40e3f2012-07-01 15:57:25 +00006157QualType ASTContext::getVaListTagType() const {
6158 // Force the creation of VaListTagTy by building the __builtin_va_list
6159 // declaration.
6160 if (VaListTagTy.isNull())
6161 (void) getBuiltinVaListDecl();
6162
6163 return VaListTagTy;
6164}
6165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006166void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006167 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006168 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006169
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006170 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006171}
6172
John McCall0bd6feb2009-12-02 08:04:21 +00006173/// \brief Retrieve the template name that corresponds to a non-empty
6174/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006175TemplateName
6176ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6177 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006178 unsigned size = End - Begin;
6179 assert(size > 1 && "set is not overloaded!");
6180
6181 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6182 size * sizeof(FunctionTemplateDecl*));
6183 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6184
6185 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006186 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006187 NamedDecl *D = *I;
6188 assert(isa<FunctionTemplateDecl>(D) ||
6189 (isa<UsingShadowDecl>(D) &&
6190 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6191 *Storage++ = D;
6192 }
6193
6194 return TemplateName(OT);
6195}
6196
Douglas Gregor7532dc62009-03-30 22:58:21 +00006197/// \brief Retrieve the template name that represents a qualified
6198/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006199TemplateName
6200ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6201 bool TemplateKeyword,
6202 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006203 assert(NNS && "Missing nested-name-specifier in qualified template name");
6204
Douglas Gregor789b1f62010-02-04 18:10:26 +00006205 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006206 llvm::FoldingSetNodeID ID;
6207 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6208
6209 void *InsertPos = 0;
6210 QualifiedTemplateName *QTN =
6211 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6212 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006213 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6214 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006215 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6216 }
6217
6218 return TemplateName(QTN);
6219}
6220
6221/// \brief Retrieve the template name that represents a dependent
6222/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006223TemplateName
6224ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6225 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006226 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006227 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006228
6229 llvm::FoldingSetNodeID ID;
6230 DependentTemplateName::Profile(ID, NNS, Name);
6231
6232 void *InsertPos = 0;
6233 DependentTemplateName *QTN =
6234 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6235
6236 if (QTN)
6237 return TemplateName(QTN);
6238
6239 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6240 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006241 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6242 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006243 } else {
6244 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006245 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6246 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006247 DependentTemplateName *CheckQTN =
6248 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6249 assert(!CheckQTN && "Dependent type name canonicalization broken");
6250 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006251 }
6252
6253 DependentTemplateNames.InsertNode(QTN, InsertPos);
6254 return TemplateName(QTN);
6255}
6256
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006257/// \brief Retrieve the template name that represents a dependent
6258/// template name such as \c MetaFun::template operator+.
6259TemplateName
6260ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006261 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006262 assert((!NNS || NNS->isDependent()) &&
6263 "Nested name specifier must be dependent");
6264
6265 llvm::FoldingSetNodeID ID;
6266 DependentTemplateName::Profile(ID, NNS, Operator);
6267
6268 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006269 DependentTemplateName *QTN
6270 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006271
6272 if (QTN)
6273 return TemplateName(QTN);
6274
6275 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6276 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006277 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6278 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006279 } else {
6280 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006281 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6282 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006283
6284 DependentTemplateName *CheckQTN
6285 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6286 assert(!CheckQTN && "Dependent template name canonicalization broken");
6287 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006288 }
6289
6290 DependentTemplateNames.InsertNode(QTN, InsertPos);
6291 return TemplateName(QTN);
6292}
6293
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006294TemplateName
John McCall14606042011-06-30 08:33:18 +00006295ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6296 TemplateName replacement) const {
6297 llvm::FoldingSetNodeID ID;
6298 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6299
6300 void *insertPos = 0;
6301 SubstTemplateTemplateParmStorage *subst
6302 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6303
6304 if (!subst) {
6305 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6306 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6307 }
6308
6309 return TemplateName(subst);
6310}
6311
6312TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006313ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6314 const TemplateArgument &ArgPack) const {
6315 ASTContext &Self = const_cast<ASTContext &>(*this);
6316 llvm::FoldingSetNodeID ID;
6317 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6318
6319 void *InsertPos = 0;
6320 SubstTemplateTemplateParmPackStorage *Subst
6321 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6322
6323 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006324 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006325 ArgPack.pack_size(),
6326 ArgPack.pack_begin());
6327 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6328 }
6329
6330 return TemplateName(Subst);
6331}
6332
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006333/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006334/// TargetInfo, produce the corresponding type. The unsigned @p Type
6335/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006336CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006337 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006338 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00006339 case TargetInfo::SignedChar: return SignedCharTy;
6340 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006341 case TargetInfo::SignedShort: return ShortTy;
6342 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6343 case TargetInfo::SignedInt: return IntTy;
6344 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6345 case TargetInfo::SignedLong: return LongTy;
6346 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6347 case TargetInfo::SignedLongLong: return LongLongTy;
6348 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6349 }
6350
David Blaikieb219cfc2011-09-23 05:06:16 +00006351 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006352}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006353
6354//===----------------------------------------------------------------------===//
6355// Type Predicates.
6356//===----------------------------------------------------------------------===//
6357
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006358/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6359/// garbage collection attribute.
6360///
John McCallae278a32011-01-12 00:34:59 +00006361Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006362 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006363 return Qualifiers::GCNone;
6364
David Blaikie4e4d0842012-03-11 07:00:24 +00006365 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006366 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6367
6368 // Default behaviour under objective-C's gc is for ObjC pointers
6369 // (or pointers to them) be treated as though they were declared
6370 // as __strong.
6371 if (GCAttrs == Qualifiers::GCNone) {
6372 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6373 return Qualifiers::Strong;
6374 else if (Ty->isPointerType())
6375 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6376 } else {
6377 // It's not valid to set GC attributes on anything that isn't a
6378 // pointer.
6379#ifndef NDEBUG
6380 QualType CT = Ty->getCanonicalTypeInternal();
6381 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6382 CT = AT->getElementType();
6383 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6384#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006385 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006386 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006387}
6388
Chris Lattner6ac46a42008-04-07 06:51:04 +00006389//===----------------------------------------------------------------------===//
6390// Type Compatibility Testing
6391//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006392
Mike Stump1eb44332009-09-09 15:08:12 +00006393/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006394/// compatible.
6395static bool areCompatVectorTypes(const VectorType *LHS,
6396 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006397 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006398 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006399 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006400}
6401
Douglas Gregor255210e2010-08-06 10:14:59 +00006402bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6403 QualType SecondVec) {
6404 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6405 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6406
6407 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6408 return true;
6409
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006410 // Treat Neon vector types and most AltiVec vector types as if they are the
6411 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006412 const VectorType *First = FirstVec->getAs<VectorType>();
6413 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006414 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006415 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006416 First->getVectorKind() != VectorType::AltiVecPixel &&
6417 First->getVectorKind() != VectorType::AltiVecBool &&
6418 Second->getVectorKind() != VectorType::AltiVecPixel &&
6419 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006420 return true;
6421
6422 return false;
6423}
6424
Steve Naroff4084c302009-07-23 01:01:38 +00006425//===----------------------------------------------------------------------===//
6426// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6427//===----------------------------------------------------------------------===//
6428
6429/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6430/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006431bool
6432ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6433 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006434 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006435 return true;
6436 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6437 E = rProto->protocol_end(); PI != E; ++PI)
6438 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6439 return true;
6440 return false;
6441}
6442
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006443/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6444/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006445bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6446 QualType rhs) {
6447 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6448 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6449 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6450
6451 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6452 E = lhsQID->qual_end(); I != E; ++I) {
6453 bool match = false;
6454 ObjCProtocolDecl *lhsProto = *I;
6455 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6456 E = rhsOPT->qual_end(); J != E; ++J) {
6457 ObjCProtocolDecl *rhsProto = *J;
6458 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6459 match = true;
6460 break;
6461 }
6462 }
6463 if (!match)
6464 return false;
6465 }
6466 return true;
6467}
6468
Steve Naroff4084c302009-07-23 01:01:38 +00006469/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6470/// ObjCQualifiedIDType.
6471bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6472 bool compare) {
6473 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006474 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006475 lhs->isObjCIdType() || lhs->isObjCClassType())
6476 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006477 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006478 rhs->isObjCIdType() || rhs->isObjCClassType())
6479 return true;
6480
6481 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006482 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006483
Steve Naroff4084c302009-07-23 01:01:38 +00006484 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006485
Steve Naroff4084c302009-07-23 01:01:38 +00006486 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006487 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006488 // make sure we check the class hierarchy.
6489 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6490 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6491 E = lhsQID->qual_end(); I != E; ++I) {
6492 // when comparing an id<P> on lhs with a static type on rhs,
6493 // see if static class implements all of id's protocols, directly or
6494 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006495 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006496 return false;
6497 }
6498 }
6499 // If there are no qualifiers and no interface, we have an 'id'.
6500 return true;
6501 }
Mike Stump1eb44332009-09-09 15:08:12 +00006502 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006503 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6504 E = lhsQID->qual_end(); I != E; ++I) {
6505 ObjCProtocolDecl *lhsProto = *I;
6506 bool match = false;
6507
6508 // when comparing an id<P> on lhs with a static type on rhs,
6509 // see if static class implements all of id's protocols, directly or
6510 // through its super class and categories.
6511 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6512 E = rhsOPT->qual_end(); J != E; ++J) {
6513 ObjCProtocolDecl *rhsProto = *J;
6514 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6515 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6516 match = true;
6517 break;
6518 }
6519 }
Mike Stump1eb44332009-09-09 15:08:12 +00006520 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006521 // make sure we check the class hierarchy.
6522 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6523 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6524 E = lhsQID->qual_end(); I != E; ++I) {
6525 // when comparing an id<P> on lhs with a static type on rhs,
6526 // see if static class implements all of id's protocols, directly or
6527 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006528 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006529 match = true;
6530 break;
6531 }
6532 }
6533 }
6534 if (!match)
6535 return false;
6536 }
Mike Stump1eb44332009-09-09 15:08:12 +00006537
Steve Naroff4084c302009-07-23 01:01:38 +00006538 return true;
6539 }
Mike Stump1eb44332009-09-09 15:08:12 +00006540
Steve Naroff4084c302009-07-23 01:01:38 +00006541 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6542 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6543
Mike Stump1eb44332009-09-09 15:08:12 +00006544 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006545 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006546 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006547 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6548 E = lhsOPT->qual_end(); I != E; ++I) {
6549 ObjCProtocolDecl *lhsProto = *I;
6550 bool match = false;
6551
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006552 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006553 // see if static class implements all of id's protocols, directly or
6554 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006555 // First, lhs protocols in the qualifier list must be found, direct
6556 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006557 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6558 E = rhsQID->qual_end(); J != E; ++J) {
6559 ObjCProtocolDecl *rhsProto = *J;
6560 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6561 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6562 match = true;
6563 break;
6564 }
6565 }
6566 if (!match)
6567 return false;
6568 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006569
6570 // Static class's protocols, or its super class or category protocols
6571 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6572 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6573 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6574 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6575 // This is rather dubious but matches gcc's behavior. If lhs has
6576 // no type qualifier and its class has no static protocol(s)
6577 // assume that it is mismatch.
6578 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6579 return false;
6580 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6581 LHSInheritedProtocols.begin(),
6582 E = LHSInheritedProtocols.end(); I != E; ++I) {
6583 bool match = false;
6584 ObjCProtocolDecl *lhsProto = (*I);
6585 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6586 E = rhsQID->qual_end(); J != E; ++J) {
6587 ObjCProtocolDecl *rhsProto = *J;
6588 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6589 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6590 match = true;
6591 break;
6592 }
6593 }
6594 if (!match)
6595 return false;
6596 }
6597 }
Steve Naroff4084c302009-07-23 01:01:38 +00006598 return true;
6599 }
6600 return false;
6601}
6602
Eli Friedman3d815e72008-08-22 00:56:42 +00006603/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006604/// compatible for assignment from RHS to LHS. This handles validation of any
6605/// protocol qualifiers on the LHS or RHS.
6606///
Steve Naroff14108da2009-07-10 23:34:53 +00006607bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6608 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006609 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6610 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6611
Steve Naroffde2e22d2009-07-15 18:40:39 +00006612 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006613 if (LHS->isObjCUnqualifiedIdOrClass() ||
6614 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006615 return true;
6616
John McCallc12c5bb2010-05-15 11:32:37 +00006617 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006618 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6619 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006620 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006621
6622 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6623 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6624 QualType(RHSOPT,0));
6625
John McCallc12c5bb2010-05-15 11:32:37 +00006626 // If we have 2 user-defined types, fall into that path.
6627 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006628 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006629
Steve Naroff4084c302009-07-23 01:01:38 +00006630 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006631}
6632
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006633/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006634/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006635/// arguments in block literals. When passed as arguments, passing 'A*' where
6636/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6637/// not OK. For the return type, the opposite is not OK.
6638bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6639 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006640 const ObjCObjectPointerType *RHSOPT,
6641 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006642 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006643 return true;
6644
6645 if (LHSOPT->isObjCBuiltinType()) {
6646 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6647 }
6648
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006649 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006650 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6651 QualType(RHSOPT,0),
6652 false);
6653
6654 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6655 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6656 if (LHS && RHS) { // We have 2 user-defined types.
6657 if (LHS != RHS) {
6658 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006659 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006660 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006661 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006662 }
6663 else
6664 return true;
6665 }
6666 return false;
6667}
6668
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006669/// getIntersectionOfProtocols - This routine finds the intersection of set
6670/// of protocols inherited from two distinct objective-c pointer objects.
6671/// It is used to build composite qualifier list of the composite type of
6672/// the conditional expression involving two objective-c pointer objects.
6673static
6674void getIntersectionOfProtocols(ASTContext &Context,
6675 const ObjCObjectPointerType *LHSOPT,
6676 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006677 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006678
John McCallc12c5bb2010-05-15 11:32:37 +00006679 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6680 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6681 assert(LHS->getInterface() && "LHS must have an interface base");
6682 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006683
6684 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6685 unsigned LHSNumProtocols = LHS->getNumProtocols();
6686 if (LHSNumProtocols > 0)
6687 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6688 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006689 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006690 Context.CollectInheritedProtocols(LHS->getInterface(),
6691 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006692 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6693 LHSInheritedProtocols.end());
6694 }
6695
6696 unsigned RHSNumProtocols = RHS->getNumProtocols();
6697 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006698 ObjCProtocolDecl **RHSProtocols =
6699 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006700 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6701 if (InheritedProtocolSet.count(RHSProtocols[i]))
6702 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006703 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006704 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006705 Context.CollectInheritedProtocols(RHS->getInterface(),
6706 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006707 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6708 RHSInheritedProtocols.begin(),
6709 E = RHSInheritedProtocols.end(); I != E; ++I)
6710 if (InheritedProtocolSet.count((*I)))
6711 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006712 }
6713}
6714
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006715/// areCommonBaseCompatible - Returns common base class of the two classes if
6716/// one found. Note that this is O'2 algorithm. But it will be called as the
6717/// last type comparison in a ?-exp of ObjC pointer types before a
6718/// warning is issued. So, its invokation is extremely rare.
6719QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006720 const ObjCObjectPointerType *Lptr,
6721 const ObjCObjectPointerType *Rptr) {
6722 const ObjCObjectType *LHS = Lptr->getObjectType();
6723 const ObjCObjectType *RHS = Rptr->getObjectType();
6724 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6725 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006726 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006727 return QualType();
6728
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006729 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006730 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006731 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006732 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006733 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6734
6735 QualType Result = QualType(LHS, 0);
6736 if (!Protocols.empty())
6737 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6738 Result = getObjCObjectPointerType(Result);
6739 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006740 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006741 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006742
6743 return QualType();
6744}
6745
John McCallc12c5bb2010-05-15 11:32:37 +00006746bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6747 const ObjCObjectType *RHS) {
6748 assert(LHS->getInterface() && "LHS is not an interface type");
6749 assert(RHS->getInterface() && "RHS is not an interface type");
6750
Chris Lattner6ac46a42008-04-07 06:51:04 +00006751 // Verify that the base decls are compatible: the RHS must be a subclass of
6752 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006753 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006754 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006755
Chris Lattner6ac46a42008-04-07 06:51:04 +00006756 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6757 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006758 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006759 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006760
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006761 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6762 // more detailed analysis is required.
6763 if (RHS->getNumProtocols() == 0) {
6764 // OK, if LHS is a superclass of RHS *and*
6765 // this superclass is assignment compatible with LHS.
6766 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006767 bool IsSuperClass =
6768 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6769 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006770 // OK if conversion of LHS to SuperClass results in narrowing of types
6771 // ; i.e., SuperClass may implement at least one of the protocols
6772 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6773 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6774 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006775 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006776 // If super class has no protocols, it is not a match.
6777 if (SuperClassInheritedProtocols.empty())
6778 return false;
6779
6780 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6781 LHSPE = LHS->qual_end();
6782 LHSPI != LHSPE; LHSPI++) {
6783 bool SuperImplementsProtocol = false;
6784 ObjCProtocolDecl *LHSProto = (*LHSPI);
6785
6786 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6787 SuperClassInheritedProtocols.begin(),
6788 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6789 ObjCProtocolDecl *SuperClassProto = (*I);
6790 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6791 SuperImplementsProtocol = true;
6792 break;
6793 }
6794 }
6795 if (!SuperImplementsProtocol)
6796 return false;
6797 }
6798 return true;
6799 }
6800 return false;
6801 }
Mike Stump1eb44332009-09-09 15:08:12 +00006802
John McCallc12c5bb2010-05-15 11:32:37 +00006803 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6804 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006805 LHSPI != LHSPE; LHSPI++) {
6806 bool RHSImplementsProtocol = false;
6807
6808 // If the RHS doesn't implement the protocol on the left, the types
6809 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006810 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6811 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006812 RHSPI != RHSPE; RHSPI++) {
6813 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006814 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006815 break;
6816 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006817 }
6818 // FIXME: For better diagnostics, consider passing back the protocol name.
6819 if (!RHSImplementsProtocol)
6820 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006821 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006822 // The RHS implements all protocols listed on the LHS.
6823 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006824}
6825
Steve Naroff389bf462009-02-12 17:52:19 +00006826bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6827 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006828 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6829 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006830
Steve Naroff14108da2009-07-10 23:34:53 +00006831 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006832 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006833
6834 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6835 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006836}
6837
Douglas Gregor569c3162010-08-07 11:51:51 +00006838bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6839 return canAssignObjCInterfaces(
6840 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6841 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6842}
6843
Mike Stump1eb44332009-09-09 15:08:12 +00006844/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006845/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006846/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006847/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006848bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6849 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006850 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006851 return hasSameType(LHS, RHS);
6852
Douglas Gregor447234d2010-07-29 15:18:02 +00006853 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006854}
6855
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006856bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006857 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006858}
6859
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006860bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6861 return !mergeTypes(LHS, RHS, true).isNull();
6862}
6863
Peter Collingbourne48466752010-10-24 18:30:18 +00006864/// mergeTransparentUnionType - if T is a transparent union type and a member
6865/// of T is compatible with SubType, return the merged type, else return
6866/// QualType()
6867QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6868 bool OfBlockPointer,
6869 bool Unqualified) {
6870 if (const RecordType *UT = T->getAsUnionType()) {
6871 RecordDecl *UD = UT->getDecl();
6872 if (UD->hasAttr<TransparentUnionAttr>()) {
6873 for (RecordDecl::field_iterator it = UD->field_begin(),
6874 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006875 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006876 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6877 if (!MT.isNull())
6878 return MT;
6879 }
6880 }
6881 }
6882
6883 return QualType();
6884}
6885
6886/// mergeFunctionArgumentTypes - merge two types which appear as function
6887/// argument types
6888QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6889 bool OfBlockPointer,
6890 bool Unqualified) {
6891 // GNU extension: two types are compatible if they appear as a function
6892 // argument, one of the types is a transparent union type and the other
6893 // type is compatible with a union member
6894 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6895 Unqualified);
6896 if (!lmerge.isNull())
6897 return lmerge;
6898
6899 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6900 Unqualified);
6901 if (!rmerge.isNull())
6902 return rmerge;
6903
6904 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6905}
6906
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006907QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006908 bool OfBlockPointer,
6909 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006910 const FunctionType *lbase = lhs->getAs<FunctionType>();
6911 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006912 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6913 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006914 bool allLTypes = true;
6915 bool allRTypes = true;
6916
6917 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006918 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006919 if (OfBlockPointer) {
6920 QualType RHS = rbase->getResultType();
6921 QualType LHS = lbase->getResultType();
6922 bool UnqualifiedResult = Unqualified;
6923 if (!UnqualifiedResult)
6924 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006925 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006926 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006927 else
John McCall8cc246c2010-12-15 01:06:38 +00006928 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6929 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006930 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006931
6932 if (Unqualified)
6933 retType = retType.getUnqualifiedType();
6934
6935 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6936 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6937 if (Unqualified) {
6938 LRetType = LRetType.getUnqualifiedType();
6939 RRetType = RRetType.getUnqualifiedType();
6940 }
6941
6942 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006943 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006944 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006945 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006946
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006947 // FIXME: double check this
6948 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6949 // rbase->getRegParmAttr() != 0 &&
6950 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006951 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6952 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006953
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006954 // Compatible functions must have compatible calling conventions
Reid Kleckneref072032013-08-27 23:08:25 +00006955 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006956 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006957
John McCall8cc246c2010-12-15 01:06:38 +00006958 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006959 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6960 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006961 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6962 return QualType();
6963
John McCallf85e1932011-06-15 23:02:42 +00006964 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6965 return QualType();
6966
John McCall8cc246c2010-12-15 01:06:38 +00006967 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6968 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006969
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006970 if (lbaseInfo.getNoReturn() != NoReturn)
6971 allLTypes = false;
6972 if (rbaseInfo.getNoReturn() != NoReturn)
6973 allRTypes = false;
6974
John McCallf85e1932011-06-15 23:02:42 +00006975 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006976
Eli Friedman3d815e72008-08-22 00:56:42 +00006977 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006978 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6979 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006980 unsigned lproto_nargs = lproto->getNumArgs();
6981 unsigned rproto_nargs = rproto->getNumArgs();
6982
6983 // Compatible functions must have the same number of arguments
6984 if (lproto_nargs != rproto_nargs)
6985 return QualType();
6986
6987 // Variadic and non-variadic functions aren't compatible
6988 if (lproto->isVariadic() != rproto->isVariadic())
6989 return QualType();
6990
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006991 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6992 return QualType();
6993
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006994 if (LangOpts.ObjCAutoRefCount &&
6995 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6996 return QualType();
6997
Eli Friedman3d815e72008-08-22 00:56:42 +00006998 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006999 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 for (unsigned i = 0; i < lproto_nargs; i++) {
7001 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7002 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00007003 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7004 OfBlockPointer,
7005 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007006 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007007
7008 if (Unqualified)
7009 argtype = argtype.getUnqualifiedType();
7010
Eli Friedman3d815e72008-08-22 00:56:42 +00007011 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007012 if (Unqualified) {
7013 largtype = largtype.getUnqualifiedType();
7014 rargtype = rargtype.getUnqualifiedType();
7015 }
7016
Chris Lattner61710852008-10-05 17:34:18 +00007017 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7018 allLTypes = false;
7019 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7020 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007021 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007022
Eli Friedman3d815e72008-08-22 00:56:42 +00007023 if (allLTypes) return lhs;
7024 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007025
7026 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7027 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007028 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007029 }
7030
7031 if (lproto) allRTypes = false;
7032 if (rproto) allLTypes = false;
7033
Douglas Gregor72564e72009-02-26 23:50:07 +00007034 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007035 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007036 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007037 if (proto->isVariadic()) return QualType();
7038 // Check that the types are compatible with the types that
7039 // would result from default argument promotions (C99 6.7.5.3p15).
7040 // The only types actually affected are promotable integer
7041 // types and floats, which would be passed as a different
7042 // type depending on whether the prototype is visible.
7043 unsigned proto_nargs = proto->getNumArgs();
7044 for (unsigned i = 0; i < proto_nargs; ++i) {
7045 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007046
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007047 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007048 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007049 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7050 argTy = Enum->getDecl()->getIntegerType();
7051 if (argTy.isNull())
7052 return QualType();
7053 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007054
Eli Friedman3d815e72008-08-22 00:56:42 +00007055 if (argTy->isPromotableIntegerType() ||
7056 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7057 return QualType();
7058 }
7059
7060 if (allLTypes) return lhs;
7061 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007062
7063 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7064 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007065 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007066 }
7067
7068 if (allLTypes) return lhs;
7069 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007070 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007071}
7072
John McCallb9da7132013-03-21 00:10:07 +00007073/// Given that we have an enum type and a non-enum type, try to merge them.
7074static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7075 QualType other, bool isBlockReturnType) {
7076 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7077 // a signed integer type, or an unsigned integer type.
7078 // Compatibility is based on the underlying type, not the promotion
7079 // type.
7080 QualType underlyingType = ET->getDecl()->getIntegerType();
7081 if (underlyingType.isNull()) return QualType();
7082 if (Context.hasSameType(underlyingType, other))
7083 return other;
7084
7085 // In block return types, we're more permissive and accept any
7086 // integral type of the same size.
7087 if (isBlockReturnType && other->isIntegerType() &&
7088 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7089 return other;
7090
7091 return QualType();
7092}
7093
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007094QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007095 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007096 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007097 // C++ [expr]: If an expression initially has the type "reference to T", the
7098 // type is adjusted to "T" prior to any further analysis, the expression
7099 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007100 // expression is an lvalue unless the reference is an rvalue reference and
7101 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007102 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7103 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007104
7105 if (Unqualified) {
7106 LHS = LHS.getUnqualifiedType();
7107 RHS = RHS.getUnqualifiedType();
7108 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007109
Eli Friedman3d815e72008-08-22 00:56:42 +00007110 QualType LHSCan = getCanonicalType(LHS),
7111 RHSCan = getCanonicalType(RHS);
7112
7113 // If two types are identical, they are compatible.
7114 if (LHSCan == RHSCan)
7115 return LHS;
7116
John McCall0953e762009-09-24 19:53:00 +00007117 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007118 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7119 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007120 if (LQuals != RQuals) {
7121 // If any of these qualifiers are different, we have a type
7122 // mismatch.
7123 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007124 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7125 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007126 return QualType();
7127
7128 // Exactly one GC qualifier difference is allowed: __strong is
7129 // okay if the other type has no GC qualifier but is an Objective
7130 // C object pointer (i.e. implicitly strong by default). We fix
7131 // this by pretending that the unqualified type was actually
7132 // qualified __strong.
7133 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7134 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7135 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7136
7137 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7138 return QualType();
7139
7140 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7141 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7142 }
7143 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7144 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7145 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007146 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007147 }
7148
7149 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007150
Eli Friedman852d63b2009-06-01 01:22:52 +00007151 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7152 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007153
Chris Lattner1adb8832008-01-14 05:45:46 +00007154 // We want to consider the two function types to be the same for these
7155 // comparisons, just force one to the other.
7156 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7157 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007158
7159 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007160 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7161 LHSClass = Type::ConstantArray;
7162 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7163 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007164
John McCallc12c5bb2010-05-15 11:32:37 +00007165 // ObjCInterfaces are just specialized ObjCObjects.
7166 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7167 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7168
Nate Begeman213541a2008-04-18 23:10:10 +00007169 // Canonicalize ExtVector -> Vector.
7170 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7171 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007172
Chris Lattnera36a61f2008-04-07 05:43:21 +00007173 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007174 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007175 // Note that we only have special rules for turning block enum
7176 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007177 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007178 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007179 }
John McCall183700f2009-09-21 23:43:11 +00007180 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007181 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007182 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007183 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007184 if (OfBlockPointer && !BlockReturnType) {
7185 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7186 return LHS;
7187 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7188 return RHS;
7189 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007190
Eli Friedman3d815e72008-08-22 00:56:42 +00007191 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007192 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007193
Steve Naroff4a746782008-01-09 22:43:08 +00007194 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007195 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007196#define TYPE(Class, Base)
7197#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007198#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007199#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7200#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7201#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007202 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007203
Richard Smithdc7a4f52013-04-30 13:56:41 +00007204 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007205 case Type::LValueReference:
7206 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007207 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007208 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007209
John McCallc12c5bb2010-05-15 11:32:37 +00007210 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007211 case Type::IncompleteArray:
7212 case Type::VariableArray:
7213 case Type::FunctionProto:
7214 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007215 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007216
Chris Lattner1adb8832008-01-14 05:45:46 +00007217 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007218 {
7219 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007220 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7221 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007222 if (Unqualified) {
7223 LHSPointee = LHSPointee.getUnqualifiedType();
7224 RHSPointee = RHSPointee.getUnqualifiedType();
7225 }
7226 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7227 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007228 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007229 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007230 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007231 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007232 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007233 return getPointerType(ResultType);
7234 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007235 case Type::BlockPointer:
7236 {
7237 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007238 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7239 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007240 if (Unqualified) {
7241 LHSPointee = LHSPointee.getUnqualifiedType();
7242 RHSPointee = RHSPointee.getUnqualifiedType();
7243 }
7244 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7245 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007246 if (ResultType.isNull()) return QualType();
7247 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7248 return LHS;
7249 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7250 return RHS;
7251 return getBlockPointerType(ResultType);
7252 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007253 case Type::Atomic:
7254 {
7255 // Merge two pointer types, while trying to preserve typedef info
7256 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7257 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7258 if (Unqualified) {
7259 LHSValue = LHSValue.getUnqualifiedType();
7260 RHSValue = RHSValue.getUnqualifiedType();
7261 }
7262 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7263 Unqualified);
7264 if (ResultType.isNull()) return QualType();
7265 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7266 return LHS;
7267 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7268 return RHS;
7269 return getAtomicType(ResultType);
7270 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007271 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007272 {
7273 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7274 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7275 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7276 return QualType();
7277
7278 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7279 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007280 if (Unqualified) {
7281 LHSElem = LHSElem.getUnqualifiedType();
7282 RHSElem = RHSElem.getUnqualifiedType();
7283 }
7284
7285 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007286 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007287 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7288 return LHS;
7289 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7290 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007291 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7292 ArrayType::ArraySizeModifier(), 0);
7293 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7294 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007295 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7296 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007297 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7298 return LHS;
7299 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7300 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007301 if (LVAT) {
7302 // FIXME: This isn't correct! But tricky to implement because
7303 // the array's size has to be the size of LHS, but the type
7304 // has to be different.
7305 return LHS;
7306 }
7307 if (RVAT) {
7308 // FIXME: This isn't correct! But tricky to implement because
7309 // the array's size has to be the size of RHS, but the type
7310 // has to be different.
7311 return RHS;
7312 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007313 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7314 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007315 return getIncompleteArrayType(ResultType,
7316 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007317 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007318 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007319 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007320 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007321 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007322 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007323 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007324 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007325 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007326 case Type::Complex:
7327 // Distinct complex types are incompatible.
7328 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007329 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007330 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007331 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7332 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007333 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007334 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007335 case Type::ObjCObject: {
7336 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007337 // FIXME: This should be type compatibility, e.g. whether
7338 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007339 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7340 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7341 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007342 return LHS;
7343
Eli Friedman3d815e72008-08-22 00:56:42 +00007344 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007345 }
Steve Naroff14108da2009-07-10 23:34:53 +00007346 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007347 if (OfBlockPointer) {
7348 if (canAssignObjCInterfacesInBlockPointer(
7349 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007350 RHS->getAs<ObjCObjectPointerType>(),
7351 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007352 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007353 return QualType();
7354 }
John McCall183700f2009-09-21 23:43:11 +00007355 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7356 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007357 return LHS;
7358
Steve Naroffbc76dd02008-12-10 22:14:21 +00007359 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007360 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007361 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007362
David Blaikie7530c032012-01-17 06:56:22 +00007363 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007364}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007365
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007366bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7367 const FunctionProtoType *FromFunctionType,
7368 const FunctionProtoType *ToFunctionType) {
7369 if (FromFunctionType->hasAnyConsumedArgs() !=
7370 ToFunctionType->hasAnyConsumedArgs())
7371 return false;
7372 FunctionProtoType::ExtProtoInfo FromEPI =
7373 FromFunctionType->getExtProtoInfo();
7374 FunctionProtoType::ExtProtoInfo ToEPI =
7375 ToFunctionType->getExtProtoInfo();
7376 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7377 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7378 ArgIdx != NumArgs; ++ArgIdx) {
7379 if (FromEPI.ConsumedArguments[ArgIdx] !=
7380 ToEPI.ConsumedArguments[ArgIdx])
7381 return false;
7382 }
7383 return true;
7384}
7385
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007386/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7387/// 'RHS' attributes and returns the merged version; including for function
7388/// return types.
7389QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7390 QualType LHSCan = getCanonicalType(LHS),
7391 RHSCan = getCanonicalType(RHS);
7392 // If two types are identical, they are compatible.
7393 if (LHSCan == RHSCan)
7394 return LHS;
7395 if (RHSCan->isFunctionType()) {
7396 if (!LHSCan->isFunctionType())
7397 return QualType();
7398 QualType OldReturnType =
7399 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7400 QualType NewReturnType =
7401 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7402 QualType ResReturnType =
7403 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7404 if (ResReturnType.isNull())
7405 return QualType();
7406 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7407 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7408 // In either case, use OldReturnType to build the new function type.
7409 const FunctionType *F = LHS->getAs<FunctionType>();
7410 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007411 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7412 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007413 QualType ResultType =
7414 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007415 return ResultType;
7416 }
7417 }
7418 return QualType();
7419 }
7420
7421 // If the qualifiers are different, the types can still be merged.
7422 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7423 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7424 if (LQuals != RQuals) {
7425 // If any of these qualifiers are different, we have a type mismatch.
7426 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7427 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7428 return QualType();
7429
7430 // Exactly one GC qualifier difference is allowed: __strong is
7431 // okay if the other type has no GC qualifier but is an Objective
7432 // C object pointer (i.e. implicitly strong by default). We fix
7433 // this by pretending that the unqualified type was actually
7434 // qualified __strong.
7435 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7436 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7437 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7438
7439 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7440 return QualType();
7441
7442 if (GC_L == Qualifiers::Strong)
7443 return LHS;
7444 if (GC_R == Qualifiers::Strong)
7445 return RHS;
7446 return QualType();
7447 }
7448
7449 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7450 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7451 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7452 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7453 if (ResQT == LHSBaseQT)
7454 return LHS;
7455 if (ResQT == RHSBaseQT)
7456 return RHS;
7457 }
7458 return QualType();
7459}
7460
Chris Lattner5426bf62008-04-07 07:01:58 +00007461//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007462// Integer Predicates
7463//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007464
Jay Foad4ba2a172011-01-12 09:06:06 +00007465unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007466 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007467 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007468 if (T->isBooleanType())
7469 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007470 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007471 return (unsigned)getTypeSize(T);
7472}
7473
Abramo Bagnara762f1592012-09-09 10:21:24 +00007474QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007475 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007476
7477 // Turn <4 x signed int> -> <4 x unsigned int>
7478 if (const VectorType *VTy = T->getAs<VectorType>())
7479 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007480 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007481
7482 // For enums, we return the unsigned version of the base type.
7483 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007484 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007485
7486 const BuiltinType *BTy = T->getAs<BuiltinType>();
7487 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007488 switch (BTy->getKind()) {
7489 case BuiltinType::Char_S:
7490 case BuiltinType::SChar:
7491 return UnsignedCharTy;
7492 case BuiltinType::Short:
7493 return UnsignedShortTy;
7494 case BuiltinType::Int:
7495 return UnsignedIntTy;
7496 case BuiltinType::Long:
7497 return UnsignedLongTy;
7498 case BuiltinType::LongLong:
7499 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007500 case BuiltinType::Int128:
7501 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007502 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007503 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007504 }
7505}
7506
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007507ASTMutationListener::~ASTMutationListener() { }
7508
Richard Smith9dadfab2013-05-11 05:45:24 +00007509void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7510 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007511
7512//===----------------------------------------------------------------------===//
7513// Builtin Type Computation
7514//===----------------------------------------------------------------------===//
7515
7516/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007517/// pointer over the consumed characters. This returns the resultant type. If
7518/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7519/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7520/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007521///
7522/// RequiresICE is filled in on return to indicate whether the value is required
7523/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007524static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007525 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007526 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007527 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007528 // Modifiers.
7529 int HowLong = 0;
7530 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007531 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007532
Chris Lattner33daae62010-10-01 22:42:38 +00007533 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007534 bool Done = false;
7535 while (!Done) {
7536 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007537 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007538 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007539 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007540 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007541 case 'S':
7542 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7543 assert(!Signed && "Can't use 'S' modifier multiple times!");
7544 Signed = true;
7545 break;
7546 case 'U':
7547 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7548 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7549 Unsigned = true;
7550 break;
7551 case 'L':
7552 assert(HowLong <= 2 && "Can't have LLLL modifier");
7553 ++HowLong;
7554 break;
7555 }
7556 }
7557
7558 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007559
Chris Lattner86df27b2009-06-14 00:45:47 +00007560 // Read the base type.
7561 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007562 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007563 case 'v':
7564 assert(HowLong == 0 && !Signed && !Unsigned &&
7565 "Bad modifiers used with 'v'!");
7566 Type = Context.VoidTy;
7567 break;
Jack Carter146522e2013-08-15 15:16:57 +00007568 case 'h':
7569 assert(HowLong == 0 && !Signed && !Unsigned &&
7570 "Bad modifiers used with 'f'!");
7571 Type = Context.HalfTy;
7572 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007573 case 'f':
7574 assert(HowLong == 0 && !Signed && !Unsigned &&
7575 "Bad modifiers used with 'f'!");
7576 Type = Context.FloatTy;
7577 break;
7578 case 'd':
7579 assert(HowLong < 2 && !Signed && !Unsigned &&
7580 "Bad modifiers used with 'd'!");
7581 if (HowLong)
7582 Type = Context.LongDoubleTy;
7583 else
7584 Type = Context.DoubleTy;
7585 break;
7586 case 's':
7587 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7588 if (Unsigned)
7589 Type = Context.UnsignedShortTy;
7590 else
7591 Type = Context.ShortTy;
7592 break;
7593 case 'i':
7594 if (HowLong == 3)
7595 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7596 else if (HowLong == 2)
7597 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7598 else if (HowLong == 1)
7599 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7600 else
7601 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7602 break;
7603 case 'c':
7604 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7605 if (Signed)
7606 Type = Context.SignedCharTy;
7607 else if (Unsigned)
7608 Type = Context.UnsignedCharTy;
7609 else
7610 Type = Context.CharTy;
7611 break;
7612 case 'b': // boolean
7613 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7614 Type = Context.BoolTy;
7615 break;
7616 case 'z': // size_t.
7617 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7618 Type = Context.getSizeType();
7619 break;
7620 case 'F':
7621 Type = Context.getCFConstantStringType();
7622 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007623 case 'G':
7624 Type = Context.getObjCIdType();
7625 break;
7626 case 'H':
7627 Type = Context.getObjCSelType();
7628 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007629 case 'M':
7630 Type = Context.getObjCSuperType();
7631 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007632 case 'a':
7633 Type = Context.getBuiltinVaListType();
7634 assert(!Type.isNull() && "builtin va list type not initialized!");
7635 break;
7636 case 'A':
7637 // This is a "reference" to a va_list; however, what exactly
7638 // this means depends on how va_list is defined. There are two
7639 // different kinds of va_list: ones passed by value, and ones
7640 // passed by reference. An example of a by-value va_list is
7641 // x86, where va_list is a char*. An example of by-ref va_list
7642 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7643 // we want this argument to be a char*&; for x86-64, we want
7644 // it to be a __va_list_tag*.
7645 Type = Context.getBuiltinVaListType();
7646 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007647 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007648 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007649 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007650 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007651 break;
7652 case 'V': {
7653 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007654 unsigned NumElements = strtoul(Str, &End, 10);
7655 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007656 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007657
Chris Lattner14e0e742010-10-01 22:53:11 +00007658 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7659 RequiresICE, false);
7660 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007661
7662 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007663 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007664 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007665 break;
7666 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007667 case 'E': {
7668 char *End;
7669
7670 unsigned NumElements = strtoul(Str, &End, 10);
7671 assert(End != Str && "Missing vector size");
7672
7673 Str = End;
7674
7675 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7676 false);
7677 Type = Context.getExtVectorType(ElementType, NumElements);
7678 break;
7679 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007680 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007681 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7682 false);
7683 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007684 Type = Context.getComplexType(ElementType);
7685 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007686 }
7687 case 'Y' : {
7688 Type = Context.getPointerDiffType();
7689 break;
7690 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007691 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007692 Type = Context.getFILEType();
7693 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007694 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007695 return QualType();
7696 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007697 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007698 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007699 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007700 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007701 else
7702 Type = Context.getjmp_bufType();
7703
Mike Stumpfd612db2009-07-28 23:47:15 +00007704 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007705 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007706 return QualType();
7707 }
7708 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007709 case 'K':
7710 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7711 Type = Context.getucontext_tType();
7712
7713 if (Type.isNull()) {
7714 Error = ASTContext::GE_Missing_ucontext;
7715 return QualType();
7716 }
7717 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007718 case 'p':
7719 Type = Context.getProcessIDType();
7720 break;
Mike Stump782fa302009-07-28 02:25:19 +00007721 }
Mike Stump1eb44332009-09-09 15:08:12 +00007722
Chris Lattner33daae62010-10-01 22:42:38 +00007723 // If there are modifiers and if we're allowed to parse them, go for it.
7724 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007725 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007726 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007727 default: Done = true; --Str; break;
7728 case '*':
7729 case '&': {
7730 // Both pointers and references can have their pointee types
7731 // qualified with an address space.
7732 char *End;
7733 unsigned AddrSpace = strtoul(Str, &End, 10);
7734 if (End != Str && AddrSpace != 0) {
7735 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7736 Str = End;
7737 }
7738 if (c == '*')
7739 Type = Context.getPointerType(Type);
7740 else
7741 Type = Context.getLValueReferenceType(Type);
7742 break;
7743 }
7744 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7745 case 'C':
7746 Type = Type.withConst();
7747 break;
7748 case 'D':
7749 Type = Context.getVolatileType(Type);
7750 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007751 case 'R':
7752 Type = Type.withRestrict();
7753 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007754 }
7755 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007756
Chris Lattner14e0e742010-10-01 22:53:11 +00007757 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007758 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007759
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 return Type;
7761}
7762
7763/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007764QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007765 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007766 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007767 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007768
Chris Lattner5f9e2722011-07-23 10:55:15 +00007769 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007770
Chris Lattner14e0e742010-10-01 22:53:11 +00007771 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007772 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007773 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7774 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007775 if (Error != GE_None)
7776 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007777
7778 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7779
Chris Lattner86df27b2009-06-14 00:45:47 +00007780 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007781 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007782 if (Error != GE_None)
7783 return QualType();
7784
Chris Lattner14e0e742010-10-01 22:53:11 +00007785 // If this argument is required to be an IntegerConstantExpression and the
7786 // caller cares, fill in the bitmask we return.
7787 if (RequiresICE && IntegerConstantArgs)
7788 *IntegerConstantArgs |= 1 << ArgTypes.size();
7789
Chris Lattner86df27b2009-06-14 00:45:47 +00007790 // Do array -> pointer decay. The builtin should use the decayed type.
7791 if (Ty->isArrayType())
7792 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007793
Chris Lattner86df27b2009-06-14 00:45:47 +00007794 ArgTypes.push_back(Ty);
7795 }
7796
7797 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7798 "'.' should only occur at end of builtin type list!");
7799
Reid Kleckneref072032013-08-27 23:08:25 +00007800 FunctionType::ExtInfo EI(CC_C);
John McCall00ccbef2010-12-21 00:44:39 +00007801 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7802
7803 bool Variadic = (TypeStr[0] == '.');
7804
7805 // We really shouldn't be making a no-proto type here, especially in C++.
7806 if (ArgTypes.empty() && Variadic)
7807 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007808
John McCalle23cf432010-12-14 08:05:40 +00007809 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007810 EPI.ExtInfo = EI;
7811 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007812
Jordan Rosebea522f2013-03-08 21:51:21 +00007813 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007814}
Eli Friedmana95d7572009-08-19 07:44:53 +00007815
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007816GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007817 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007818 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007819
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007820 GVALinkage External = GVA_StrongExternal;
7821 switch (FD->getTemplateSpecializationKind()) {
7822 case TSK_Undeclared:
7823 case TSK_ExplicitSpecialization:
7824 External = GVA_StrongExternal;
7825 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007826
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007827 case TSK_ExplicitInstantiationDefinition:
7828 return GVA_ExplicitTemplateInstantiation;
7829
7830 case TSK_ExplicitInstantiationDeclaration:
7831 case TSK_ImplicitInstantiation:
7832 External = GVA_TemplateInstantiation;
7833 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007834 }
7835
7836 if (!FD->isInlined())
7837 return External;
David Majnemer13163702013-08-01 17:26:42 +00007838
7839 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7840 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007841 // GNU or C99 inline semantics. Determine whether this symbol should be
7842 // externally visible.
7843 if (FD->isInlineDefinitionExternallyVisible())
7844 return External;
7845
7846 // C99 inline semantics, where the symbol is not externally visible.
7847 return GVA_C99Inline;
7848 }
7849
7850 // C++0x [temp.explicit]p9:
7851 // [ Note: The intent is that an inline function that is the subject of
7852 // an explicit instantiation declaration will still be implicitly
7853 // instantiated when used so that the body can be considered for
7854 // inlining, but that no out-of-line copy of the inline function would be
7855 // generated in the translation unit. -- end note ]
7856 if (FD->getTemplateSpecializationKind()
7857 == TSK_ExplicitInstantiationDeclaration)
7858 return GVA_C99Inline;
7859
7860 return GVA_CXXInline;
7861}
7862
7863GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007864 if (!VD->isExternallyVisible())
7865 return GVA_Internal;
7866
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007867 // If this is a static data member, compute the kind of template
7868 // specialization. Otherwise, this variable is not part of a
7869 // template.
7870 TemplateSpecializationKind TSK = TSK_Undeclared;
7871 if (VD->isStaticDataMember())
7872 TSK = VD->getTemplateSpecializationKind();
7873
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007874 switch (TSK) {
7875 case TSK_Undeclared:
7876 case TSK_ExplicitSpecialization:
7877 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007878
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007879 case TSK_ExplicitInstantiationDeclaration:
7880 llvm_unreachable("Variable should not be instantiated");
7881 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007882
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007883 case TSK_ExplicitInstantiationDefinition:
7884 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007885
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007886 case TSK_ImplicitInstantiation:
7887 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007888 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007889
7890 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007891}
7892
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007893bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007894 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7895 if (!VD->isFileVarDecl())
7896 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007897 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7898 // We never need to emit an uninstantiated function template.
7899 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7900 return false;
7901 } else
7902 return false;
7903
7904 // If this is a member of a class template, we do not need to emit it.
7905 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007906 return false;
7907
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007908 // Weak references don't produce any output by themselves.
7909 if (D->hasAttr<WeakRefAttr>())
7910 return false;
7911
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007912 // Aliases and used decls are required.
7913 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7914 return true;
7915
7916 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7917 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007918 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007919 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007920
7921 // Constructors and destructors are required.
7922 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7923 return true;
7924
John McCalld5617ee2013-01-25 22:31:03 +00007925 // The key function for a class is required. This rule only comes
7926 // into play when inline functions can be key functions, though.
7927 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7928 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7929 const CXXRecordDecl *RD = MD->getParent();
7930 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7931 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7932 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7933 return true;
7934 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007935 }
7936 }
7937
7938 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7939
7940 // static, static inline, always_inline, and extern inline functions can
7941 // always be deferred. Normal inline functions can be deferred in C99/C++.
7942 // Implicit template instantiations can also be deferred in C++.
7943 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007944 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007945 return false;
7946 return true;
7947 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007948
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007949 const VarDecl *VD = cast<VarDecl>(D);
7950 assert(VD->isFileVarDecl() && "Expected file scoped var");
7951
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007952 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7953 return false;
7954
Richard Smith5f9a7e32012-11-12 21:38:00 +00007955 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007956 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007957 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7958 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007959
Richard Smith5f9a7e32012-11-12 21:38:00 +00007960 // Variables that have destruction with side-effects are required.
7961 if (VD->getType().isDestructedType())
7962 return true;
7963
7964 // Variables that have initialization with side-effects are required.
7965 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7966 return true;
7967
7968 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007969}
Charles Davis071cc7d2010-08-16 03:33:14 +00007970
Reid Kleckneref072032013-08-27 23:08:25 +00007971CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7972 bool IsCXXMethod) const {
Charles Davisee743f92010-11-09 18:04:24 +00007973 // Pass through to the C++ ABI object
Reid Kleckneref072032013-08-27 23:08:25 +00007974 if (IsCXXMethod)
7975 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007976
Reid Kleckneref072032013-08-27 23:08:25 +00007977 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davisee743f92010-11-09 18:04:24 +00007978}
7979
Jay Foad4ba2a172011-01-12 09:06:06 +00007980bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007981 // Pass through to the C++ ABI object
7982 return ABI->isNearlyEmpty(RD);
7983}
7984
Peter Collingbourne14110472011-01-13 18:57:25 +00007985MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007986 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007987 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007988 case TargetCXXABI::GenericItanium:
7989 case TargetCXXABI::GenericARM:
7990 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007991 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007992 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007993 return createMicrosoftMangleContext(*this, getDiagnostics());
7994 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007995 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007996}
7997
Charles Davis071cc7d2010-08-16 03:33:14 +00007998CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007999
8000size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00008001 return ASTRecordLayouts.getMemorySize() +
8002 llvm::capacity_in_bytes(ObjCLayouts) +
8003 llvm::capacity_in_bytes(KeyFunctions) +
8004 llvm::capacity_in_bytes(ObjCImpls) +
8005 llvm::capacity_in_bytes(BlockVarCopyInits) +
8006 llvm::capacity_in_bytes(DeclAttrs) +
8007 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8008 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8009 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8010 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8011 llvm::capacity_in_bytes(OverriddenMethods) +
8012 llvm::capacity_in_bytes(Types) +
8013 llvm::capacity_in_bytes(VariableArrayTypes) +
8014 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008015}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008016
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00008017/// getIntTypeForBitwidth -
8018/// sets integer QualTy according to specified details:
8019/// bitwidth, signed/unsigned.
8020/// Returns empty type if there is no appropriate target types.
8021QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8022 unsigned Signed) const {
8023 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8024 CanQualType QualTy = getFromTargetType(Ty);
8025 if (!QualTy && DestWidth == 128)
8026 return Signed ? Int128Ty : UnsignedInt128Ty;
8027 return QualTy;
8028}
8029
8030/// getRealTypeForBitwidth -
8031/// sets floating point QualTy according to specified bitwidth.
8032/// Returns empty type if there is no appropriate target types.
8033QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8034 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8035 switch (Ty) {
8036 case TargetInfo::Float:
8037 return FloatTy;
8038 case TargetInfo::Double:
8039 return DoubleTy;
8040 case TargetInfo::LongDouble:
8041 return LongDoubleTy;
8042 case TargetInfo::NoFloat:
8043 return QualType();
8044 }
8045
8046 llvm_unreachable("Unhandled TargetInfo::RealType value");
8047}
8048
Eli Friedman5e867c82013-07-10 00:30:46 +00008049void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8050 if (Number > 1)
8051 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00008052}
8053
Eli Friedman5e867c82013-07-10 00:30:46 +00008054unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8055 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8056 MangleNumbers.find(ND);
8057 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008058}
8059
Eli Friedman5e867c82013-07-10 00:30:46 +00008060MangleNumberingContext &
8061ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00008062 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8063 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8064 if (!MCtx)
8065 MCtx = createMangleNumberingContext();
8066 return *MCtx;
8067}
8068
8069MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8070 return ABI->createMangleNumberingContext();
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008071}
8072
Ted Kremenekd211cb72011-10-06 05:00:56 +00008073void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8074 ParamIndices[D] = index;
8075}
8076
8077unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8078 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8079 assert(I != ParamIndices.end() &&
8080 "ParmIndices lacks entry set by ParmVarDecl");
8081 return I->second;
8082}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008083
Richard Smith211c8dd2013-06-05 00:46:14 +00008084APValue *
8085ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8086 bool MayCreate) {
8087 assert(E && E->getStorageDuration() == SD_Static &&
8088 "don't need to cache the computed value for this temporary");
8089 if (MayCreate)
8090 return &MaterializedTemporaryValues[E];
8091
8092 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8093 MaterializedTemporaryValues.find(E);
8094 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8095}
8096
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008097bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8098 const llvm::Triple &T = getTargetInfo().getTriple();
8099 if (!T.isOSDarwin())
8100 return false;
8101
8102 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8103 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8104 uint64_t Size = sizeChars.getQuantity();
8105 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8106 unsigned Align = alignChars.getQuantity();
8107 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8108 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8109}
Reid Klecknercff15122013-06-17 12:56:08 +00008110
8111namespace {
8112
8113 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8114 /// parents as defined by the \c RecursiveASTVisitor.
8115 ///
8116 /// Note that the relationship described here is purely in terms of AST
8117 /// traversal - there are other relationships (for example declaration context)
8118 /// in the AST that are better modeled by special matchers.
8119 ///
8120 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8121 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8122
8123 public:
8124 /// \brief Builds and returns the translation unit's parent map.
8125 ///
8126 /// The caller takes ownership of the returned \c ParentMap.
8127 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8128 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8129 Visitor.TraverseDecl(&TU);
8130 return Visitor.Parents;
8131 }
8132
8133 private:
8134 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8135
8136 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8137 }
8138
8139 bool shouldVisitTemplateInstantiations() const {
8140 return true;
8141 }
8142 bool shouldVisitImplicitCode() const {
8143 return true;
8144 }
8145 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8146 // are not triggered during data recursion.
8147 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8148 return false;
8149 }
8150
8151 template <typename T>
8152 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8153 if (Node == NULL)
8154 return true;
8155 if (ParentStack.size() > 0)
8156 // FIXME: Currently we add the same parent multiple times, for example
8157 // when we visit all subexpressions of template instantiations; this is
8158 // suboptimal, bug benign: the only way to visit those is with
8159 // hasAncestor / hasParent, and those do not create new matches.
8160 // The plan is to enable DynTypedNode to be storable in a map or hash
8161 // map. The main problem there is to implement hash functions /
8162 // comparison operators for all types that DynTypedNode supports that
8163 // do not have pointer identity.
8164 (*Parents)[Node].push_back(ParentStack.back());
8165 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8166 bool Result = (this ->* traverse) (Node);
8167 ParentStack.pop_back();
8168 return Result;
8169 }
8170
8171 bool TraverseDecl(Decl *DeclNode) {
8172 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8173 }
8174
8175 bool TraverseStmt(Stmt *StmtNode) {
8176 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8177 }
8178
8179 ASTContext::ParentMap *Parents;
8180 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8181
8182 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8183 };
8184
8185} // end namespace
8186
8187ASTContext::ParentVector
8188ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8189 assert(Node.getMemoizationData() &&
8190 "Invariant broken: only nodes that support memoization may be "
8191 "used in the parent map.");
8192 if (!AllParents) {
8193 // We always need to run over the whole translation unit, as
8194 // hasAncestor can escape any subtree.
8195 AllParents.reset(
8196 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8197 }
8198 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8199 if (I == AllParents->end()) {
8200 return ParentVector();
8201 }
8202 return I->second;
8203}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008204
8205bool
8206ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8207 const ObjCMethodDecl *MethodImpl) {
8208 // No point trying to match an unavailable/deprecated mothod.
8209 if (MethodDecl->hasAttr<UnavailableAttr>()
8210 || MethodDecl->hasAttr<DeprecatedAttr>())
8211 return false;
8212 if (MethodDecl->getObjCDeclQualifier() !=
8213 MethodImpl->getObjCDeclQualifier())
8214 return false;
8215 if (!hasSameType(MethodDecl->getResultType(),
8216 MethodImpl->getResultType()))
8217 return false;
8218
8219 if (MethodDecl->param_size() != MethodImpl->param_size())
8220 return false;
8221
8222 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8223 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8224 EF = MethodDecl->param_end();
8225 IM != EM && IF != EF; ++IM, ++IF) {
8226 const ParmVarDecl *DeclVar = (*IF);
8227 const ParmVarDecl *ImplVar = (*IM);
8228 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8229 return false;
8230 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8231 return false;
8232 }
8233 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8234
8235}