blob: 05d83547939f6459d9e83f69e9e371c64850a187 [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.");
709 return false;
David Tweed1eef8522013-09-13 12:04:22 +0000710}
711
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000712ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000714 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000715 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000724 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000726 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000728 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000734 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000739 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000740 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000742 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000743{
Mike Stump1eb44332009-09-09 15:08:12 +0000744 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000745 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000746
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
750 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000751}
752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000757
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor63200642010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000784
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
788 I != E; ++I)
789 delete I->second;
Douglas Gregor63200642010-08-30 16:49:28 +0000790}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000791
Douglas Gregor00545312010-05-23 18:26:36 +0000792void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000793 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000794}
795
Mike Stump1eb44332009-09-09 15:08:12 +0000796void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000797ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000798 ExternalSource.reset(Source.take());
799}
800
Reid Spencer5f016e22007-07-11 17:01:13 +0000801void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000804
Douglas Gregordbe833d2009-05-26 14:40:08 +0000805 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000806#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000807#define ABSTRACT_TYPE(Name, Parent)
808#include "clang/AST/TypeNodes.def"
809 0 // Extra
810 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000814 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 }
816
Douglas Gregordbe833d2009-05-26 14:40:08 +0000817 unsigned Idx = 0;
818 unsigned TotalBytes = 0;
819#define TYPE(Name, Parent) \
820 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000821 llvm::errs() << " " << counts[Idx] << " " << #Name \
822 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
824 ++Idx;
825#define ABSTRACT_TYPE(Name, Parent)
826#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Chandler Carruthcd92a652011-07-04 05:32:14 +0000828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829
Douglas Gregor4923aa22010-07-02 20:37:36 +0000830 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000837 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000844 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
851
Douglas Gregor2cf26342009-04-09 22:27:44 +0000852 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000853 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000854 ExternalSource->PrintStats();
855 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000856
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000857 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000858}
859
Douglas Gregor772eeae2011-08-12 06:49:56 +0000860TypedefDecl *ASTContext::getInt128Decl() const {
861 if (!Int128Decl) {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
863 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__int128_t"),
868 TInfo);
869 }
870
871 return Int128Decl;
872}
873
874TypedefDecl *ASTContext::getUInt128Decl() const {
875 if (!UInt128Decl) {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
877 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
878 getTranslationUnitDecl(),
879 SourceLocation(),
880 SourceLocation(),
881 &Idents.get("__uint128_t"),
882 TInfo);
883 }
884
885 return UInt128Decl;
886}
Reid Spencer5f016e22007-07-11 17:01:13 +0000887
Nico Webercac18ad2013-06-20 21:44:55 +0000888TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000889 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000890 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000891 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
892 TTK_Struct,
893 getTranslationUnitDecl(),
894 SourceLocation(),
895 SourceLocation(),
896 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000897 }
898
899 return Float128StubDecl;
900}
901
John McCalle27ec8a2009-10-23 23:03:21 +0000902void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000903 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000904 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000905 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000906}
907
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000908void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
909 assert((!this->Target || this->Target == &Target) &&
910 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 this->Target = &Target;
914
915 ABI.reset(createCXXABI(Target));
916 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed1eef8522013-09-13 12:04:22 +0000917 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000918
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 // C99 6.2.5p19.
920 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 // C99 6.2.5p2.
923 InitBuiltinType(BoolTy, BuiltinType::Bool);
924 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000925 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 InitBuiltinType(CharTy, BuiltinType::Char_S);
927 else
928 InitBuiltinType(CharTy, BuiltinType::Char_U);
929 // C99 6.2.5p4.
930 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
931 InitBuiltinType(ShortTy, BuiltinType::Short);
932 InitBuiltinType(IntTy, BuiltinType::Int);
933 InitBuiltinType(LongTy, BuiltinType::Long);
934 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 // C99 6.2.5p6.
937 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
938 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
939 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
940 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
941 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 // C99 6.2.5p10.
944 InitBuiltinType(FloatTy, BuiltinType::Float);
945 InitBuiltinType(DoubleTy, BuiltinType::Double);
946 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000947
Chris Lattner2df9ced2009-04-30 02:43:43 +0000948 // GNU extension, 128-bit integers.
949 InitBuiltinType(Int128Ty, BuiltinType::Int128);
950 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
951
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000952 // C++ 3.9.1p5
953 if (TargetInfo::isTypeSigned(Target.getWCharType()))
954 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
955 else // -fshort-wchar makes wchar_t be unsigned.
956 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
957 if (LangOpts.CPlusPlus && LangOpts.WChar)
958 WideCharTy = WCharTy;
959 else {
960 // C99 (or C++ using -fno-wchar).
961 WideCharTy = getFromTargetType(Target.getWCharType());
962 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000963
James Molloy392da482012-05-04 10:55:22 +0000964 WIntTy = getFromTargetType(Target.getWIntType());
965
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char16Ty, BuiltinType::Char16);
968 else // C99
969 Char16Ty = getFromTargetType(Target.getChar16Type());
970
971 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
972 InitBuiltinType(Char32Ty, BuiltinType::Char32);
973 else // C99
974 Char32Ty = getFromTargetType(Target.getChar32Type());
975
Douglas Gregor898574e2008-12-05 23:32:09 +0000976 // Placeholder type for type-dependent expressions whose type is
977 // completely unknown. No code should ever check a type against
978 // DependentTy and users should never see it; however, it is here to
979 // help diagnose failures to properly check for type-dependent
980 // expressions.
981 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000982
John McCall2a984ca2010-10-12 00:20:44 +0000983 // Placeholder type for functions.
984 InitBuiltinType(OverloadTy, BuiltinType::Overload);
985
John McCall864c0412011-04-26 20:42:42 +0000986 // Placeholder type for bound members.
987 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
988
John McCall3c3b7f92011-10-25 17:37:35 +0000989 // Placeholder type for pseudo-objects.
990 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
991
John McCall1de4d4e2011-04-07 08:22:57 +0000992 // "any" type; useful for debugger-like clients.
993 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
994
John McCall0ddaeb92011-10-17 18:09:15 +0000995 // Placeholder type for unbridged ARC casts.
996 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
997
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000998 // Placeholder type for builtin functions.
999 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 // C99 6.2.5p11.
1002 FloatComplexTy = getComplexType(FloatTy);
1003 DoubleComplexTy = getComplexType(DoubleTy);
1004 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001006 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001007 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1008 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001009 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +00001010
1011 if (LangOpts.OpenCL) {
1012 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1013 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1014 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1015 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1016 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1017 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001018
Guy Benyei21f18c42013-02-07 10:55:47 +00001019 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001020 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +00001021 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001022
1023 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001024 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1025 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001026
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001027 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001028
1029 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001031 // void * type
1032 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001033
1034 // nullptr type (C++0x 2.14.7)
1035 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001036
1037 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1038 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001039
1040 // Builtin type used to help define __builtin_va_list.
1041 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001042}
1043
David Blaikied6471f72011-09-25 23:23:43 +00001044DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001045 return SourceMgr.getDiagnostics();
1046}
1047
Douglas Gregor63200642010-08-30 16:49:28 +00001048AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1049 AttrVec *&Result = DeclAttrs[D];
1050 if (!Result) {
1051 void *Mem = Allocate(sizeof(AttrVec));
1052 Result = new (Mem) AttrVec;
1053 }
1054
1055 return *Result;
1056}
1057
1058/// \brief Erase the attributes corresponding to the given declaration.
1059void ASTContext::eraseDeclAttrs(const Decl *D) {
1060 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1061 if (Pos != DeclAttrs.end()) {
1062 Pos->second->~AttrVec();
1063 DeclAttrs.erase(Pos);
1064 }
1065}
1066
Larisse Voufoef4579c2013-08-06 01:03:05 +00001067// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001068MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001069ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001070 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001071 return getTemplateOrSpecializationInfo(Var)
1072 .dyn_cast<MemberSpecializationInfo *>();
1073}
1074
1075ASTContext::TemplateOrSpecializationInfo
1076ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1077 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1078 TemplateOrInstantiation.find(Var);
1079 if (Pos == TemplateOrInstantiation.end())
1080 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Douglas Gregor7caa6822009-07-24 20:34:43 +00001082 return Pos->second;
1083}
1084
Mike Stump1eb44332009-09-09 15:08:12 +00001085void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001086ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001087 TemplateSpecializationKind TSK,
1088 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001089 assert(Inst->isStaticDataMember() && "Not a static data member");
1090 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001091 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1092 Tmpl, TSK, PointOfInstantiation));
1093}
1094
1095void
1096ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1097 TemplateOrSpecializationInfo TSI) {
1098 assert(!TemplateOrInstantiation[Inst] &&
1099 "Already noted what the variable was instantiated from");
1100 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001101}
1102
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001103FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1104 const FunctionDecl *FD){
1105 assert(FD && "Specialization is 0");
1106 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001107 = ClassScopeSpecializationPattern.find(FD);
1108 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001109 return 0;
1110
1111 return Pos->second;
1112}
1113
1114void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1115 FunctionDecl *Pattern) {
1116 assert(FD && "Specialization is 0");
1117 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001118 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001119}
1120
John McCall7ba107a2009-11-18 02:36:19 +00001121NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001122ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001123 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001124 = InstantiatedFromUsingDecl.find(UUD);
1125 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001126 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Anders Carlsson0d8df782009-08-29 19:37:28 +00001128 return Pos->second;
1129}
1130
1131void
John McCalled976492009-12-04 22:46:56 +00001132ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1133 assert((isa<UsingDecl>(Pattern) ||
1134 isa<UnresolvedUsingValueDecl>(Pattern) ||
1135 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1136 "pattern decl is not a using decl");
1137 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1138 InstantiatedFromUsingDecl[Inst] = Pattern;
1139}
1140
1141UsingShadowDecl *
1142ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1143 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1144 = InstantiatedFromUsingShadowDecl.find(Inst);
1145 if (Pos == InstantiatedFromUsingShadowDecl.end())
1146 return 0;
1147
1148 return Pos->second;
1149}
1150
1151void
1152ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1153 UsingShadowDecl *Pattern) {
1154 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1155 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001156}
1157
Anders Carlssond8b285f2009-09-01 04:26:58 +00001158FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1159 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1160 = InstantiatedFromUnnamedFieldDecl.find(Field);
1161 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1162 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Anders Carlssond8b285f2009-09-01 04:26:58 +00001164 return Pos->second;
1165}
1166
1167void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1168 FieldDecl *Tmpl) {
1169 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1170 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1171 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1172 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Anders Carlssond8b285f2009-09-01 04:26:58 +00001174 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1175}
1176
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.begin();
1185}
1186
1187ASTContext::overridden_cxx_method_iterator
1188ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.end();
1195}
1196
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001197unsigned
1198ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001201 if (Pos == OverriddenMethods.end())
1202 return 0;
1203
1204 return Pos->second.size();
1205}
1206
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001207void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1208 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001209 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001210 OverriddenMethods[Method].push_back(Overridden);
1211}
1212
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001213void ASTContext::getOverriddenMethods(
1214 const NamedDecl *D,
1215 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001216 assert(D);
1217
1218 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001219 Overridden.append(overridden_methods_begin(CXXMethod),
1220 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001221 return;
1222 }
1223
1224 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1225 if (!Method)
1226 return;
1227
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001228 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1229 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001230 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001231}
1232
Douglas Gregore6649772011-12-03 00:30:27 +00001233void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1234 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1235 assert(!Import->isFromASTFile() && "Non-local import declaration");
1236 if (!FirstLocalImport) {
1237 FirstLocalImport = Import;
1238 LastLocalImport = Import;
1239 return;
1240 }
1241
1242 LastLocalImport->NextLocalImport = Import;
1243 LastLocalImport = Import;
1244}
1245
Chris Lattner464175b2007-07-18 17:52:12 +00001246//===----------------------------------------------------------------------===//
1247// Type Sizing and Analysis
1248//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001249
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001250/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1251/// scalar floating point type.
1252const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001253 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001254 assert(BT && "Not a floating point type!");
1255 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001256 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001257 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001258 case BuiltinType::Float: return Target->getFloatFormat();
1259 case BuiltinType::Double: return Target->getDoubleFormat();
1260 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001261 }
1262}
1263
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001264CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001265 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001266
John McCall4081a5c2010-10-08 18:24:19 +00001267 bool UseAlignAttrOnly = false;
1268 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1269 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001270
John McCall4081a5c2010-10-08 18:24:19 +00001271 // __attribute__((aligned)) can increase or decrease alignment
1272 // *except* on a struct or struct member, where it only increases
1273 // alignment unless 'packed' is also specified.
1274 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001275 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001276 // ignore that possibility; Sema should diagnose it.
1277 if (isa<FieldDecl>(D)) {
1278 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1279 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1280 } else {
1281 UseAlignAttrOnly = true;
1282 }
1283 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001284 else if (isa<FieldDecl>(D))
1285 UseAlignAttrOnly =
1286 D->hasAttr<PackedAttr>() ||
1287 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001288
John McCallba4f5d52011-01-20 07:57:12 +00001289 // If we're using the align attribute only, just ignore everything
1290 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001291 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001292 // do nothing
1293
John McCall4081a5c2010-10-08 18:24:19 +00001294 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001295 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001296 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001297 if (ForAlignof)
Sebastian Redl5d484e82009-11-23 17:18:46 +00001298 T = RT->getPointeeType();
1299 else
1300 T = getPointerType(RT->getPointeeType());
1301 }
1302 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001303 // Adjust alignments of declarations with array type by the
1304 // large-array alignment on the target.
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001305 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001306 unsigned MinWidth = Target->getLargeArrayMinWidth();
1307 if (!ForAlignof && MinWidth) {
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001308 if (isa<VariableArrayType>(arrayType))
1309 Align = std::max(Align, Target->getLargeArrayAlign());
1310 else if (isa<ConstantArrayType>(arrayType) &&
1311 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1313 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001314
John McCall3b657512011-01-19 10:06:00 +00001315 // Walk through any array types while we're at it.
1316 T = getBaseElementType(arrayType);
1317 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001318 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001319 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1320 if (VD->hasGlobalStorage())
1321 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1322 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001323 }
John McCallba4f5d52011-01-20 07:57:12 +00001324
1325 // Fields can be subject to extra alignment constraints, like if
1326 // the field is packed, the struct is packed, or the struct has a
1327 // a max-field-alignment constraint (#pragma pack). So calculate
1328 // the actual alignment of the field within the struct, and then
1329 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001330 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1331 const RecordDecl *Parent = Field->getParent();
1332 // We can only produce a sensible answer if the record is valid.
1333 if (!Parent->isInvalidDecl()) {
1334 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001335
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001336 // Start with the record's overall alignment.
1337 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001338
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001339 // Use the GCD of that and the offset within the record.
1340 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1341 if (Offset > 0) {
1342 // Alignment is always a power of 2, so the GCD will be a power of 2,
1343 // which means we get to do this crazy thing instead of Euclid's.
1344 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1345 if (LowBitOfOffset < FieldAlign)
1346 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1347 }
1348
1349 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001350 }
Charles Davis05f62472010-02-23 04:52:00 +00001351 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001352 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001353
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001354 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001355}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001356
John McCall929bbfb2012-08-21 04:10:00 +00001357// getTypeInfoDataSizeInChars - Return the size of a type, in
1358// chars. If the type is a record, its data size is returned. This is
1359// the size of the memcpy that's performed when assigning this type
1360// using a trivial copy/move assignment operator.
1361std::pair<CharUnits, CharUnits>
1362ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1363 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1364
1365 // In C++, objects can sometimes be allocated into the tail padding
1366 // of a base-class subobject. We decide whether that's possible
1367 // during class layout, so here we can just trust the layout results.
1368 if (getLangOpts().CPlusPlus) {
1369 if (const RecordType *RT = T->getAs<RecordType>()) {
1370 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1371 sizeAndAlign.first = layout.getDataSize();
1372 }
1373 }
1374
1375 return sizeAndAlign;
1376}
1377
Richard Trieu910f17e2013-05-14 21:59:17 +00001378/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1379/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1380std::pair<CharUnits, CharUnits>
1381static getConstantArrayInfoInChars(const ASTContext &Context,
1382 const ConstantArrayType *CAT) {
1383 std::pair<CharUnits, CharUnits> EltInfo =
1384 Context.getTypeInfoInChars(CAT->getElementType());
1385 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001386 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1387 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001388 "Overflow in array type char size evaluation");
1389 uint64_t Width = EltInfo.first.getQuantity() * Size;
1390 unsigned Align = EltInfo.second.getQuantity();
1391 Width = llvm::RoundUpToAlignment(Width, Align);
1392 return std::make_pair(CharUnits::fromQuantity(Width),
1393 CharUnits::fromQuantity(Align));
1394}
1395
John McCallea1471e2010-05-20 01:18:31 +00001396std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001397ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001398 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1399 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001400 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001401 return std::make_pair(toCharUnitsFromBits(Info.first),
1402 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001403}
1404
1405std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001406ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001407 return getTypeInfoInChars(T.getTypePtr());
1408}
1409
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001410std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1411 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1412 if (it != MemoizedTypeInfo.end())
1413 return it->second;
1414
1415 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1416 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1417 return Info;
1418}
1419
1420/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1421/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001422///
1423/// FIXME: Pointers into different addr spaces could have different sizes and
1424/// alignment requirements: getPointerInfo should take an AddrSpace, this
1425/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001426std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001427ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001428 uint64_t Width=0;
1429 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001430 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001431#define TYPE(Class, Base)
1432#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001433#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001434#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001435#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1436 case Type::Class: \
1437 assert(!T->isDependentType() && "should not see dependent types here"); \
1438 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001439#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001440 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001441
Chris Lattner692233e2007-07-13 22:27:08 +00001442 case Type::FunctionNoProto:
1443 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001444 // GCC extension: alignof(function) = 32 bits
1445 Width = 0;
1446 Align = 32;
1447 break;
1448
Douglas Gregor72564e72009-02-26 23:50:07 +00001449 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001450 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001451 Width = 0;
1452 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1453 break;
1454
Steve Narofffb22d962007-08-30 01:06:46 +00001455 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001456 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Chris Lattner98be4942008-03-05 18:54:05 +00001458 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001459 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001460 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1461 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001462 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001463 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001464 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001465 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001466 }
Nate Begeman213541a2008-04-18 23:10:10 +00001467 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001468 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001469 const VectorType *VT = cast<VectorType>(T);
1470 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1471 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001472 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001473 // If the alignment is not a power of 2, round up to the next power of 2.
1474 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001475 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001476 Align = llvm::NextPowerOf2(Align);
1477 Width = llvm::RoundUpToAlignment(Width, Align);
1478 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001479 // Adjust the alignment based on the target max.
1480 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1481 if (TargetVectorAlign && TargetVectorAlign < Align)
1482 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001483 break;
1484 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001485
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001486 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001487 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001488 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001489 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001490 // GCC extension: alignof(void) = 8 bits.
1491 Width = 0;
1492 Align = 8;
1493 break;
1494
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001495 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001496 Width = Target->getBoolWidth();
1497 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001498 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001499 case BuiltinType::Char_S:
1500 case BuiltinType::Char_U:
1501 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001502 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getCharWidth();
1504 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001506 case BuiltinType::WChar_S:
1507 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001508 Width = Target->getWCharWidth();
1509 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001510 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001511 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001512 Width = Target->getChar16Width();
1513 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001514 break;
1515 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001516 Width = Target->getChar32Width();
1517 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001518 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001519 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001521 Width = Target->getShortWidth();
1522 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001523 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001524 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001525 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001526 Width = Target->getIntWidth();
1527 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001528 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001529 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001530 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001531 Width = Target->getLongWidth();
1532 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001533 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001534 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001535 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001536 Width = Target->getLongLongWidth();
1537 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001538 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001539 case BuiltinType::Int128:
1540 case BuiltinType::UInt128:
1541 Width = 128;
1542 Align = 128; // int128_t is 128-bit aligned on all targets.
1543 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001544 case BuiltinType::Half:
1545 Width = Target->getHalfWidth();
1546 Align = Target->getHalfAlign();
1547 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001548 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001549 Width = Target->getFloatWidth();
1550 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001551 break;
1552 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001553 Width = Target->getDoubleWidth();
1554 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001555 break;
1556 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001557 Width = Target->getLongDoubleWidth();
1558 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001559 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001560 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001561 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1562 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001563 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001564 case BuiltinType::ObjCId:
1565 case BuiltinType::ObjCClass:
1566 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001567 Width = Target->getPointerWidth(0);
1568 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001569 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001570 case BuiltinType::OCLSampler:
1571 // Samplers are modeled as integers.
1572 Width = Target->getIntWidth();
1573 Align = Target->getIntAlign();
1574 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001575 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001576 case BuiltinType::OCLImage1d:
1577 case BuiltinType::OCLImage1dArray:
1578 case BuiltinType::OCLImage1dBuffer:
1579 case BuiltinType::OCLImage2d:
1580 case BuiltinType::OCLImage2dArray:
1581 case BuiltinType::OCLImage3d:
1582 // Currently these types are pointers to opaque types.
1583 Width = Target->getPointerWidth(0);
1584 Align = Target->getPointerAlign(0);
1585 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001586 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001587 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001588 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001589 Width = Target->getPointerWidth(0);
1590 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001591 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001592 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001593 unsigned AS = getTargetAddressSpace(
1594 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001595 Width = Target->getPointerWidth(AS);
1596 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001597 break;
1598 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001599 case Type::LValueReference:
1600 case Type::RValueReference: {
1601 // alignof and sizeof should never enter this code path here, so we go
1602 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001603 unsigned AS = getTargetAddressSpace(
1604 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001605 Width = Target->getPointerWidth(AS);
1606 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001607 break;
1608 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001609 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001610 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001611 Width = Target->getPointerWidth(AS);
1612 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001613 break;
1614 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001615 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001616 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001617 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001618 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001619 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001620 case Type::Complex: {
1621 // Complex types have the same alignment as their elements, but twice the
1622 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001623 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001624 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001625 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001626 Align = EltInfo.second;
1627 break;
1628 }
John McCallc12c5bb2010-05-15 11:32:37 +00001629 case Type::ObjCObject:
1630 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001631 case Type::Decayed:
1632 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001633 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001634 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001635 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001636 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001637 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001638 break;
1639 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001640 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001641 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001642 const TagType *TT = cast<TagType>(T);
1643
1644 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001645 Width = 8;
1646 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001647 break;
1648 }
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Daniel Dunbar1d751182008-11-08 05:48:37 +00001650 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001651 return getTypeInfo(ET->getDecl()->getIntegerType());
1652
Daniel Dunbar1d751182008-11-08 05:48:37 +00001653 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001654 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001655 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001656 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001657 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001658 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001659
Chris Lattner9fcfe922009-10-22 05:17:15 +00001660 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001661 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1662 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001663
Richard Smith34b41d92011-02-20 03:19:35 +00001664 case Type::Auto: {
1665 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001666 assert(!A->getDeducedType().isNull() &&
1667 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001668 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001669 }
1670
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001671 case Type::Paren:
1672 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1673
Douglas Gregor18857642009-04-30 17:32:17 +00001674 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001675 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001676 std::pair<uint64_t, unsigned> Info
1677 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001678 // If the typedef has an aligned attribute on it, it overrides any computed
1679 // alignment we have. This violates the GCC documentation (which says that
1680 // attribute(aligned) can only round up) but matches its implementation.
1681 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1682 Align = AttrAlign;
1683 else
1684 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001685 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001686 break;
Chris Lattner71763312008-04-06 22:05:18 +00001687 }
Douglas Gregor18857642009-04-30 17:32:17 +00001688
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001689 case Type::Elaborated:
1690 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001691
John McCall9d156a72011-01-06 01:58:22 +00001692 case Type::Attributed:
1693 return getTypeInfo(
1694 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1695
Eli Friedmanb001de72011-10-06 23:00:33 +00001696 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001697 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001698 std::pair<uint64_t, unsigned> Info
1699 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1700 Width = Info.first;
1701 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001702
1703 // If the size of the type doesn't exceed the platform's max
1704 // atomic promotion width, make the size and alignment more
1705 // favorable to atomic operations:
1706 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1707 // Round the size up to a power of 2.
1708 if (!llvm::isPowerOf2_64(Width))
1709 Width = llvm::NextPowerOf2(Width);
1710
1711 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001712 Align = static_cast<unsigned>(Width);
1713 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001714 }
1715
Douglas Gregor18857642009-04-30 17:32:17 +00001716 }
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Eli Friedman2be46072011-10-14 20:59:01 +00001718 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001719 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001720}
1721
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001722/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1723CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1724 return CharUnits::fromQuantity(BitSize / getCharWidth());
1725}
1726
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001727/// toBits - Convert a size in characters to a size in characters.
1728int64_t ASTContext::toBits(CharUnits CharSize) const {
1729 return CharSize.getQuantity() * getCharWidth();
1730}
1731
Ken Dyckbdc601b2009-12-22 14:23:30 +00001732/// getTypeSizeInChars - Return the size of the specified type, in characters.
1733/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001734CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001735 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001736}
Jay Foad4ba2a172011-01-12 09:06:06 +00001737CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001738 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001739}
1740
Ken Dyck16e20cc2010-01-26 17:25:18 +00001741/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001742/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001743CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001744 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001745}
Jay Foad4ba2a172011-01-12 09:06:06 +00001746CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001747 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001748}
1749
Chris Lattner34ebde42009-01-27 18:08:34 +00001750/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1751/// type for the current target in bits. This can be different than the ABI
1752/// alignment in cases where it is beneficial for performance to overalign
1753/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001754unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001755 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001756
1757 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001758 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001759 T = CT->getElementType().getTypePtr();
1760 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001761 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1762 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001763 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1764
Chris Lattner34ebde42009-01-27 18:08:34 +00001765 return ABIAlign;
1766}
1767
Ulrich Weigand6b203512013-05-06 16:23:57 +00001768/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1769/// to a global variable of the specified type.
1770unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1771 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1772}
1773
1774/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1775/// should be given to a global variable of the specified type.
1776CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1777 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1778}
1779
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001780/// DeepCollectObjCIvars -
1781/// This routine first collects all declared, but not synthesized, ivars in
1782/// super class and then collects all ivars, including those synthesized for
1783/// current class. This routine is used for implementation of current class
1784/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001785///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001786void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1787 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001788 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001789 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1790 DeepCollectObjCIvars(SuperClass, false, Ivars);
1791 if (!leafClass) {
1792 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1793 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001794 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001795 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001796 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001797 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001798 Iv= Iv->getNextIvar())
1799 Ivars.push_back(Iv);
1800 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001801}
1802
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001803/// CollectInheritedProtocols - Collect all protocols in current class and
1804/// those inherited by it.
1805void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001806 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001807 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001808 // We can use protocol_iterator here instead of
1809 // all_referenced_protocol_iterator since we are walking all categories.
1810 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1811 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001812 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001813 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001815 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001816 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001817 CollectInheritedProtocols(*P, Protocols);
1818 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001819 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001820
1821 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001822 for (ObjCInterfaceDecl::visible_categories_iterator
1823 Cat = OI->visible_categories_begin(),
1824 CatEnd = OI->visible_categories_end();
1825 Cat != CatEnd; ++Cat) {
1826 CollectInheritedProtocols(*Cat, Protocols);
1827 }
1828
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001829 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1830 while (SD) {
1831 CollectInheritedProtocols(SD, Protocols);
1832 SD = SD->getSuperClass();
1833 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001834 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001835 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001836 PE = OC->protocol_end(); P != PE; ++P) {
1837 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001838 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001839 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1840 PE = Proto->protocol_end(); P != PE; ++P)
1841 CollectInheritedProtocols(*P, Protocols);
1842 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001843 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001844 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1845 PE = OP->protocol_end(); P != PE; ++P) {
1846 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001847 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001848 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1849 PE = Proto->protocol_end(); P != PE; ++P)
1850 CollectInheritedProtocols(*P, Protocols);
1851 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001852 }
1853}
1854
Jay Foad4ba2a172011-01-12 09:06:06 +00001855unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001856 unsigned count = 0;
1857 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001858 for (ObjCInterfaceDecl::known_extensions_iterator
1859 Ext = OI->known_extensions_begin(),
1860 ExtEnd = OI->known_extensions_end();
1861 Ext != ExtEnd; ++Ext) {
1862 count += Ext->ivar_size();
1863 }
1864
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001865 // Count ivar defined in this class's implementation. This
1866 // includes synthesized ivars.
1867 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001868 count += ImplDecl->ivar_size();
1869
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001870 return count;
1871}
1872
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001873bool ASTContext::isSentinelNullExpr(const Expr *E) {
1874 if (!E)
1875 return false;
1876
1877 // nullptr_t is always treated as null.
1878 if (E->getType()->isNullPtrType()) return true;
1879
1880 if (E->getType()->isAnyPointerType() &&
1881 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1882 Expr::NPC_ValueDependentIsNull))
1883 return true;
1884
1885 // Unfortunately, __null has type 'int'.
1886 if (isa<GNUNullExpr>(E)) return true;
1887
1888 return false;
1889}
1890
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001891/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1892ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1893 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1894 I = ObjCImpls.find(D);
1895 if (I != ObjCImpls.end())
1896 return cast<ObjCImplementationDecl>(I->second);
1897 return 0;
1898}
1899/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1900ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1901 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1902 I = ObjCImpls.find(D);
1903 if (I != ObjCImpls.end())
1904 return cast<ObjCCategoryImplDecl>(I->second);
1905 return 0;
1906}
1907
1908/// \brief Set the implementation of ObjCInterfaceDecl.
1909void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1910 ObjCImplementationDecl *ImplD) {
1911 assert(IFaceD && ImplD && "Passed null params");
1912 ObjCImpls[IFaceD] = ImplD;
1913}
1914/// \brief Set the implementation of ObjCCategoryDecl.
1915void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1916 ObjCCategoryImplDecl *ImplD) {
1917 assert(CatD && ImplD && "Passed null params");
1918 ObjCImpls[CatD] = ImplD;
1919}
1920
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001921const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1922 const NamedDecl *ND) const {
1923 if (const ObjCInterfaceDecl *ID =
1924 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001925 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001926 if (const ObjCCategoryDecl *CD =
1927 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001928 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001929 if (const ObjCImplDecl *IMD =
1930 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001931 return IMD->getClassInterface();
1932
1933 return 0;
1934}
1935
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001936/// \brief Get the copy initialization expression of VarDecl,or NULL if
1937/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001938Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001939 assert(VD && "Passed null params");
1940 assert(VD->hasAttr<BlocksAttr>() &&
1941 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001942 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001943 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001944 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1945}
1946
1947/// \brief Set the copy inialization expression of a block var decl.
1948void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1949 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001950 assert(VD->hasAttr<BlocksAttr>() &&
1951 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001952 BlockVarCopyInits[VD] = Init;
1953}
1954
John McCalla93c9342009-12-07 02:54:59 +00001955TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001956 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001957 if (!DataSize)
1958 DataSize = TypeLoc::getFullDataSizeForType(T);
1959 else
1960 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001961 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001962
John McCalla93c9342009-12-07 02:54:59 +00001963 TypeSourceInfo *TInfo =
1964 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1965 new (TInfo) TypeSourceInfo(T);
1966 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001967}
1968
John McCalla93c9342009-12-07 02:54:59 +00001969TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001970 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001971 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001972 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001973 return DI;
1974}
1975
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001976const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001977ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001978 return getObjCLayout(D, 0);
1979}
1980
1981const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001982ASTContext::getASTObjCImplementationLayout(
1983 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001984 return getObjCLayout(D->getClassInterface(), D);
1985}
1986
Chris Lattnera7674d82007-07-13 22:13:22 +00001987//===----------------------------------------------------------------------===//
1988// Type creation/memoization methods
1989//===----------------------------------------------------------------------===//
1990
Jay Foad4ba2a172011-01-12 09:06:06 +00001991QualType
John McCall3b657512011-01-19 10:06:00 +00001992ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1993 unsigned fastQuals = quals.getFastQualifiers();
1994 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001995
1996 // Check if we've already instantiated this type.
1997 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001998 ExtQuals::Profile(ID, baseType, quals);
1999 void *insertPos = 0;
2000 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2001 assert(eq->getQualifiers() == quals);
2002 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002003 }
2004
John McCall3b657512011-01-19 10:06:00 +00002005 // If the base type is not canonical, make the appropriate canonical type.
2006 QualType canon;
2007 if (!baseType->isCanonicalUnqualified()) {
2008 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002009 canonSplit.Quals.addConsistentQualifiers(quals);
2010 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002011
2012 // Re-find the insert position.
2013 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2014 }
2015
2016 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2017 ExtQualNodes.InsertNode(eq, insertPos);
2018 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002019}
2020
Jay Foad4ba2a172011-01-12 09:06:06 +00002021QualType
2022ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002023 QualType CanT = getCanonicalType(T);
2024 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002025 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002026
John McCall0953e762009-09-24 19:53:00 +00002027 // If we are composing extended qualifiers together, merge together
2028 // into one ExtQuals node.
2029 QualifierCollector Quals;
2030 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002031
John McCall0953e762009-09-24 19:53:00 +00002032 // If this type already has an address space specified, it cannot get
2033 // another one.
2034 assert(!Quals.hasAddressSpace() &&
2035 "Type cannot be in multiple addr spaces!");
2036 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
John McCall0953e762009-09-24 19:53:00 +00002038 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002039}
2040
Chris Lattnerb7d25532009-02-18 22:53:11 +00002041QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002042 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002043 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002044 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002045 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002046
John McCall7f040a92010-12-24 02:08:15 +00002047 if (const PointerType *ptr = T->getAs<PointerType>()) {
2048 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002049 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002050 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2051 return getPointerType(ResultType);
2052 }
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
John McCall0953e762009-09-24 19:53:00 +00002055 // If we are composing extended qualifiers together, merge together
2056 // into one ExtQuals node.
2057 QualifierCollector Quals;
2058 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall0953e762009-09-24 19:53:00 +00002060 // If this type already has an ObjCGC specified, it cannot get
2061 // another one.
2062 assert(!Quals.hasObjCGCAttr() &&
2063 "Type cannot have multiple ObjCGCs!");
2064 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002065
John McCall0953e762009-09-24 19:53:00 +00002066 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002067}
Chris Lattnera7674d82007-07-13 22:13:22 +00002068
John McCalle6a365d2010-12-19 02:44:49 +00002069const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2070 FunctionType::ExtInfo Info) {
2071 if (T->getExtInfo() == Info)
2072 return T;
2073
2074 QualType Result;
2075 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2076 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2077 } else {
2078 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2079 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2080 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002081 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002082 }
2083
2084 return cast<FunctionType>(Result.getTypePtr());
2085}
2086
Richard Smith60e141e2013-05-04 07:00:32 +00002087void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2088 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002089 FD = FD->getMostRecentDecl();
2090 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002091 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2093 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002094 if (FunctionDecl *Next = FD->getPreviousDecl())
2095 FD = Next;
2096 else
2097 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002098 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002099 if (ASTMutationListener *L = getASTMutationListener())
2100 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002101}
2102
Reid Spencer5f016e22007-07-11 17:01:13 +00002103/// getComplexType - Return the uniqued reference to the type for a complex
2104/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002105QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // Unique pointers, to guarantee there is only one pointer of a particular
2107 // structure.
2108 llvm::FoldingSetNodeID ID;
2109 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 void *InsertPos = 0;
2112 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2113 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 // If the pointee type isn't canonical, this won't be a canonical type either,
2116 // so fill in the canonical type field.
2117 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002118 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002119 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // Get the new insert position for the node we care about.
2122 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002123 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 }
John McCall6b304a02009-09-24 23:30:46 +00002125 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 Types.push_back(New);
2127 ComplexTypes.InsertNode(New, InsertPos);
2128 return QualType(New, 0);
2129}
2130
Reid Spencer5f016e22007-07-11 17:01:13 +00002131/// getPointerType - Return the uniqued reference to the type for a pointer to
2132/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002133QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 // Unique pointers, to guarantee there is only one pointer of a particular
2135 // structure.
2136 llvm::FoldingSetNodeID ID;
2137 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 void *InsertPos = 0;
2140 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2141 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 // If the pointee type isn't canonical, this won't be a canonical type either,
2144 // so fill in the canonical type field.
2145 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002146 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002147 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Bob Wilsonc90cc932013-03-15 17:12:43 +00002149 // Get the new insert position for the node we care about.
2150 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2151 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2152 }
John McCall6b304a02009-09-24 23:30:46 +00002153 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 Types.push_back(New);
2155 PointerTypes.InsertNode(New, InsertPos);
2156 return QualType(New, 0);
2157}
2158
Reid Kleckner12df2462013-06-24 17:51:48 +00002159QualType ASTContext::getDecayedType(QualType T) const {
2160 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2161
2162 llvm::FoldingSetNodeID ID;
2163 DecayedType::Profile(ID, T);
2164 void *InsertPos = 0;
2165 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2166 return QualType(DT, 0);
2167
2168 QualType Decayed;
2169
2170 // C99 6.7.5.3p7:
2171 // A declaration of a parameter as "array of type" shall be
2172 // adjusted to "qualified pointer to type", where the type
2173 // qualifiers (if any) are those specified within the [ and ] of
2174 // the array type derivation.
2175 if (T->isArrayType())
2176 Decayed = getArrayDecayedType(T);
2177
2178 // C99 6.7.5.3p8:
2179 // A declaration of a parameter as "function returning type"
2180 // shall be adjusted to "pointer to function returning type", as
2181 // in 6.3.2.1.
2182 if (T->isFunctionType())
2183 Decayed = getPointerType(T);
2184
2185 QualType Canonical = getCanonicalType(Decayed);
2186
2187 // Get the new insert position for the node we care about.
2188 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2189 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2190
2191 DecayedType *New =
2192 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2193 Types.push_back(New);
2194 DecayedTypes.InsertNode(New, InsertPos);
2195 return QualType(New, 0);
2196}
2197
Mike Stump1eb44332009-09-09 15:08:12 +00002198/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002199/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002200QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002201 assert(T->isFunctionType() && "block of function types only");
2202 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002203 // structure.
2204 llvm::FoldingSetNodeID ID;
2205 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Steve Naroff5618bd42008-08-27 16:04:49 +00002207 void *InsertPos = 0;
2208 if (BlockPointerType *PT =
2209 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2210 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
2212 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002213 // type either so fill in the canonical type field.
2214 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002215 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002216 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Steve Naroff5618bd42008-08-27 16:04:49 +00002218 // Get the new insert position for the node we care about.
2219 BlockPointerType *NewIP =
2220 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002221 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002222 }
John McCall6b304a02009-09-24 23:30:46 +00002223 BlockPointerType *New
2224 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002225 Types.push_back(New);
2226 BlockPointerTypes.InsertNode(New, InsertPos);
2227 return QualType(New, 0);
2228}
2229
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002230/// getLValueReferenceType - Return the uniqued reference to the type for an
2231/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002232QualType
2233ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002234 assert(getCanonicalType(T) != OverloadTy &&
2235 "Unresolved overloaded function type");
2236
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 // Unique pointers, to guarantee there is only one pointer of a particular
2238 // structure.
2239 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002240 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002241
2242 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002243 if (LValueReferenceType *RT =
2244 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002246
John McCall54e14c42009-10-22 22:37:11 +00002247 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2248
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // If the referencee type isn't canonical, this won't be a canonical type
2250 // either, so fill in the canonical type field.
2251 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002252 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2253 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2254 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002255
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002257 LValueReferenceType *NewIP =
2258 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002259 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 }
2261
John McCall6b304a02009-09-24 23:30:46 +00002262 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002263 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2264 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002266 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002267
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002268 return QualType(New, 0);
2269}
2270
2271/// getRValueReferenceType - Return the uniqued reference to the type for an
2272/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002273QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002274 // Unique pointers, to guarantee there is only one pointer of a particular
2275 // structure.
2276 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002277 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002278
2279 void *InsertPos = 0;
2280 if (RValueReferenceType *RT =
2281 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2282 return QualType(RT, 0);
2283
John McCall54e14c42009-10-22 22:37:11 +00002284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2285
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002286 // If the referencee type isn't canonical, this won't be a canonical type
2287 // either, so fill in the canonical type field.
2288 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002289 if (InnerRef || !T.isCanonical()) {
2290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2291 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002292
2293 // Get the new insert position for the node we care about.
2294 RValueReferenceType *NewIP =
2295 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002296 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002297 }
2298
John McCall6b304a02009-09-24 23:30:46 +00002299 RValueReferenceType *New
2300 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002301 Types.push_back(New);
2302 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 return QualType(New, 0);
2304}
2305
Sebastian Redlf30208a2009-01-24 21:16:55 +00002306/// getMemberPointerType - Return the uniqued reference to the type for a
2307/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002308QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002309 // Unique pointers, to guarantee there is only one pointer of a particular
2310 // structure.
2311 llvm::FoldingSetNodeID ID;
2312 MemberPointerType::Profile(ID, T, Cls);
2313
2314 void *InsertPos = 0;
2315 if (MemberPointerType *PT =
2316 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2317 return QualType(PT, 0);
2318
2319 // If the pointee or class type isn't canonical, this won't be a canonical
2320 // type either, so fill in the canonical type field.
2321 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002322 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002323 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2324
2325 // Get the new insert position for the node we care about.
2326 MemberPointerType *NewIP =
2327 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002328 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002329 }
John McCall6b304a02009-09-24 23:30:46 +00002330 MemberPointerType *New
2331 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002332 Types.push_back(New);
2333 MemberPointerTypes.InsertNode(New, InsertPos);
2334 return QualType(New, 0);
2335}
2336
Mike Stump1eb44332009-09-09 15:08:12 +00002337/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002338/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002339QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002340 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002341 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002342 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002343 assert((EltTy->isDependentType() ||
2344 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002345 "Constant array of VLAs is illegal!");
2346
Chris Lattner38aeec72009-05-13 04:12:56 +00002347 // Convert the array size into a canonical width matching the pointer size for
2348 // the target.
2349 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002350 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002351 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002354 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002357 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002358 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002360
John McCall3b657512011-01-19 10:06:00 +00002361 // If the element type isn't canonical or has qualifiers, this won't
2362 // be a canonical type either, so fill in the canonical type field.
2363 QualType Canon;
2364 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2365 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002366 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002367 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002368 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002369
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002371 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002372 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002373 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 }
Mike Stump1eb44332009-09-09 15:08:12 +00002375
John McCall6b304a02009-09-24 23:30:46 +00002376 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002377 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002378 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 Types.push_back(New);
2380 return QualType(New, 0);
2381}
2382
John McCallce889032011-01-18 08:40:38 +00002383/// getVariableArrayDecayedType - Turns the given type, which may be
2384/// variably-modified, into the corresponding type with all the known
2385/// sizes replaced with [*].
2386QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2387 // Vastly most common case.
2388 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002389
John McCallce889032011-01-18 08:40:38 +00002390 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002391
John McCallce889032011-01-18 08:40:38 +00002392 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002393 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002394 switch (ty->getTypeClass()) {
2395#define TYPE(Class, Base)
2396#define ABSTRACT_TYPE(Class, Base)
2397#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2398#include "clang/AST/TypeNodes.def"
2399 llvm_unreachable("didn't desugar past all non-canonical types?");
2400
2401 // These types should never be variably-modified.
2402 case Type::Builtin:
2403 case Type::Complex:
2404 case Type::Vector:
2405 case Type::ExtVector:
2406 case Type::DependentSizedExtVector:
2407 case Type::ObjCObject:
2408 case Type::ObjCInterface:
2409 case Type::ObjCObjectPointer:
2410 case Type::Record:
2411 case Type::Enum:
2412 case Type::UnresolvedUsing:
2413 case Type::TypeOfExpr:
2414 case Type::TypeOf:
2415 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002416 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002417 case Type::DependentName:
2418 case Type::InjectedClassName:
2419 case Type::TemplateSpecialization:
2420 case Type::DependentTemplateSpecialization:
2421 case Type::TemplateTypeParm:
2422 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002423 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002424 case Type::PackExpansion:
2425 llvm_unreachable("type should never be variably-modified");
2426
2427 // These types can be variably-modified but should never need to
2428 // further decay.
2429 case Type::FunctionNoProto:
2430 case Type::FunctionProto:
2431 case Type::BlockPointer:
2432 case Type::MemberPointer:
2433 return type;
2434
2435 // These types can be variably-modified. All these modifications
2436 // preserve structure except as noted by comments.
2437 // TODO: if we ever care about optimizing VLAs, there are no-op
2438 // optimizations available here.
2439 case Type::Pointer:
2440 result = getPointerType(getVariableArrayDecayedType(
2441 cast<PointerType>(ty)->getPointeeType()));
2442 break;
2443
2444 case Type::LValueReference: {
2445 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2446 result = getLValueReferenceType(
2447 getVariableArrayDecayedType(lv->getPointeeType()),
2448 lv->isSpelledAsLValue());
2449 break;
2450 }
2451
2452 case Type::RValueReference: {
2453 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2454 result = getRValueReferenceType(
2455 getVariableArrayDecayedType(lv->getPointeeType()));
2456 break;
2457 }
2458
Eli Friedmanb001de72011-10-06 23:00:33 +00002459 case Type::Atomic: {
2460 const AtomicType *at = cast<AtomicType>(ty);
2461 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2462 break;
2463 }
2464
John McCallce889032011-01-18 08:40:38 +00002465 case Type::ConstantArray: {
2466 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2467 result = getConstantArrayType(
2468 getVariableArrayDecayedType(cat->getElementType()),
2469 cat->getSize(),
2470 cat->getSizeModifier(),
2471 cat->getIndexTypeCVRQualifiers());
2472 break;
2473 }
2474
2475 case Type::DependentSizedArray: {
2476 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2477 result = getDependentSizedArrayType(
2478 getVariableArrayDecayedType(dat->getElementType()),
2479 dat->getSizeExpr(),
2480 dat->getSizeModifier(),
2481 dat->getIndexTypeCVRQualifiers(),
2482 dat->getBracketsRange());
2483 break;
2484 }
2485
2486 // Turn incomplete types into [*] types.
2487 case Type::IncompleteArray: {
2488 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2489 result = getVariableArrayType(
2490 getVariableArrayDecayedType(iat->getElementType()),
2491 /*size*/ 0,
2492 ArrayType::Normal,
2493 iat->getIndexTypeCVRQualifiers(),
2494 SourceRange());
2495 break;
2496 }
2497
2498 // Turn VLA types into [*] types.
2499 case Type::VariableArray: {
2500 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2501 result = getVariableArrayType(
2502 getVariableArrayDecayedType(vat->getElementType()),
2503 /*size*/ 0,
2504 ArrayType::Star,
2505 vat->getIndexTypeCVRQualifiers(),
2506 vat->getBracketsRange());
2507 break;
2508 }
2509 }
2510
2511 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002512 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002513}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002514
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002515/// getVariableArrayType - Returns a non-unique reference to the type for a
2516/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002517QualType ASTContext::getVariableArrayType(QualType EltTy,
2518 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002519 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002520 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002521 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002522 // Since we don't unique expressions, it isn't possible to unique VLA's
2523 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002524 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002525
John McCall3b657512011-01-19 10:06:00 +00002526 // Be sure to pull qualifiers off the element type.
2527 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2528 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002529 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002530 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002531 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002532 }
2533
John McCall6b304a02009-09-24 23:30:46 +00002534 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002535 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002536
2537 VariableArrayTypes.push_back(New);
2538 Types.push_back(New);
2539 return QualType(New, 0);
2540}
2541
Douglas Gregor898574e2008-12-05 23:32:09 +00002542/// getDependentSizedArrayType - Returns a non-unique reference to
2543/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002544/// type.
John McCall3b657512011-01-19 10:06:00 +00002545QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2546 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002547 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002548 unsigned elementTypeQuals,
2549 SourceRange brackets) const {
2550 assert((!numElements || numElements->isTypeDependent() ||
2551 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002552 "Size must be type- or value-dependent!");
2553
John McCall3b657512011-01-19 10:06:00 +00002554 // Dependently-sized array types that do not have a specified number
2555 // of elements will have their sizes deduced from a dependent
2556 // initializer. We do no canonicalization here at all, which is okay
2557 // because they can't be used in most locations.
2558 if (!numElements) {
2559 DependentSizedArrayType *newType
2560 = new (*this, TypeAlignment)
2561 DependentSizedArrayType(*this, elementType, QualType(),
2562 numElements, ASM, elementTypeQuals,
2563 brackets);
2564 Types.push_back(newType);
2565 return QualType(newType, 0);
2566 }
2567
2568 // Otherwise, we actually build a new type every time, but we
2569 // also build a canonical type.
2570
2571 SplitQualType canonElementType = getCanonicalType(elementType).split();
2572
2573 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002574 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002575 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002576 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002577 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002578
John McCall3b657512011-01-19 10:06:00 +00002579 // Look for an existing type with these properties.
2580 DependentSizedArrayType *canonTy =
2581 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002582
John McCall3b657512011-01-19 10:06:00 +00002583 // If we don't have one, build one.
2584 if (!canonTy) {
2585 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002586 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002587 QualType(), numElements, ASM, elementTypeQuals,
2588 brackets);
2589 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2590 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002591 }
2592
John McCall3b657512011-01-19 10:06:00 +00002593 // Apply qualifiers from the element type to the array.
2594 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002595 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002596
John McCall3b657512011-01-19 10:06:00 +00002597 // If we didn't need extra canonicalization for the element type,
2598 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002599 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002600 return canon;
2601
2602 // Otherwise, we need to build a type which follows the spelling
2603 // of the element type.
2604 DependentSizedArrayType *sugaredType
2605 = new (*this, TypeAlignment)
2606 DependentSizedArrayType(*this, elementType, canon, numElements,
2607 ASM, elementTypeQuals, brackets);
2608 Types.push_back(sugaredType);
2609 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002610}
2611
John McCall3b657512011-01-19 10:06:00 +00002612QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002613 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002614 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002615 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002616 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002617
John McCall3b657512011-01-19 10:06:00 +00002618 void *insertPos = 0;
2619 if (IncompleteArrayType *iat =
2620 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2621 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002622
2623 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002624 // either, so fill in the canonical type field. We also have to pull
2625 // qualifiers off the element type.
2626 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002627
John McCall3b657512011-01-19 10:06:00 +00002628 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2629 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002630 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002631 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002632 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002633
2634 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002635 IncompleteArrayType *existing =
2636 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2637 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002638 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002639
John McCall3b657512011-01-19 10:06:00 +00002640 IncompleteArrayType *newType = new (*this, TypeAlignment)
2641 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002642
John McCall3b657512011-01-19 10:06:00 +00002643 IncompleteArrayTypes.InsertNode(newType, insertPos);
2644 Types.push_back(newType);
2645 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002646}
2647
Steve Naroff73322922007-07-18 18:00:27 +00002648/// getVectorType - Return the unique reference to a vector type of
2649/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002650QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002651 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002652 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 // Check if we've already instantiated a vector of this type.
2655 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002656 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002657
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 void *InsertPos = 0;
2659 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2660 return QualType(VTP, 0);
2661
2662 // If the element type isn't canonical, this won't be a canonical type either,
2663 // so fill in the canonical type field.
2664 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002665 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002666 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 // Get the new insert position for the node we care about.
2669 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002670 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
John McCall6b304a02009-09-24 23:30:46 +00002672 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002673 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 VectorTypes.InsertNode(New, InsertPos);
2675 Types.push_back(New);
2676 return QualType(New, 0);
2677}
2678
Nate Begeman213541a2008-04-18 23:10:10 +00002679/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002680/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002681QualType
2682ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002683 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Steve Naroff73322922007-07-18 18:00:27 +00002685 // Check if we've already instantiated a vector of this type.
2686 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002687 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002688 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002689 void *InsertPos = 0;
2690 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2691 return QualType(VTP, 0);
2692
2693 // If the element type isn't canonical, this won't be a canonical type either,
2694 // so fill in the canonical type field.
2695 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002696 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002697 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Steve Naroff73322922007-07-18 18:00:27 +00002699 // Get the new insert position for the node we care about.
2700 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002701 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002702 }
John McCall6b304a02009-09-24 23:30:46 +00002703 ExtVectorType *New = new (*this, TypeAlignment)
2704 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002705 VectorTypes.InsertNode(New, InsertPos);
2706 Types.push_back(New);
2707 return QualType(New, 0);
2708}
2709
Jay Foad4ba2a172011-01-12 09:06:06 +00002710QualType
2711ASTContext::getDependentSizedExtVectorType(QualType vecType,
2712 Expr *SizeExpr,
2713 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002714 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002715 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002716 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002718 void *InsertPos = 0;
2719 DependentSizedExtVectorType *Canon
2720 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2721 DependentSizedExtVectorType *New;
2722 if (Canon) {
2723 // We already have a canonical version of this array type; use it as
2724 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002725 New = new (*this, TypeAlignment)
2726 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2727 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002728 } else {
2729 QualType CanonVecTy = getCanonicalType(vecType);
2730 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002731 New = new (*this, TypeAlignment)
2732 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2733 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002734
2735 DependentSizedExtVectorType *CanonCheck
2736 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2737 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2738 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002739 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2740 } else {
2741 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2742 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002743 New = new (*this, TypeAlignment)
2744 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002745 }
2746 }
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002748 Types.push_back(New);
2749 return QualType(New, 0);
2750}
2751
Douglas Gregor72564e72009-02-26 23:50:07 +00002752/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002753///
Jay Foad4ba2a172011-01-12 09:06:06 +00002754QualType
2755ASTContext::getFunctionNoProtoType(QualType ResultTy,
2756 const FunctionType::ExtInfo &Info) const {
Reid Kleckneref072032013-08-27 23:08:25 +00002757 const CallingConv CallConv = Info.getCC();
2758
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 // Unique functions, to guarantee there is only one function of a particular
2760 // structure.
2761 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002762 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002765 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002766 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002770 if (!ResultTy.isCanonical()) {
2771 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002774 FunctionNoProtoType *NewIP =
2775 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002776 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 }
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Roman Divackycfe9af22011-03-01 17:40:53 +00002779 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002780 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002781 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002783 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 return QualType(New, 0);
2785}
2786
Douglas Gregor02dd7982013-01-17 23:36:45 +00002787/// \brief Determine whether \p T is canonical as the result type of a function.
2788static bool isCanonicalResultType(QualType T) {
2789 return T.isCanonical() &&
2790 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2791 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2792}
2793
Reid Spencer5f016e22007-07-11 17:01:13 +00002794/// getFunctionType - Return a normal function type with a typed argument
2795/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002796QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002797ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002798 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002799 size_t NumArgs = ArgArray.size();
2800
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 // Unique functions, to guarantee there is only one function of a particular
2802 // structure.
2803 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002804 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2805 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002806
2807 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002808 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002809 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002811
2812 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002813 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002814 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002815 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002817 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 isCanonical = false;
2819
2820 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002821 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002823 if (!isCanonical) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002824 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 CanonicalArgs.reserve(NumArgs);
2826 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002827 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002828
John McCalle23cf432010-12-14 08:05:40 +00002829 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002830 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002831 CanonicalEPI.ExceptionSpecType = EST_None;
2832 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002833
Douglas Gregor02dd7982013-01-17 23:36:45 +00002834 // Result types do not have ARC lifetime qualifiers.
2835 QualType CanResultTy = getCanonicalType(ResultTy);
2836 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2837 Qualifiers Qs = CanResultTy.getQualifiers();
2838 Qs.removeObjCLifetime();
2839 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2840 }
2841
Jordan Rosebea522f2013-03-08 21:51:21 +00002842 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002843
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002845 FunctionProtoType *NewIP =
2846 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002847 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002849
John McCallf85e1932011-06-15 23:02:42 +00002850 // FunctionProtoType objects are allocated with extra bytes after
2851 // them for three variable size arrays at the end:
2852 // - parameter types
2853 // - exception types
2854 // - consumed-arguments flags
2855 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002856 // expression, or information used to resolve the exception
2857 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002858 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002859 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002860 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002861 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002862 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002863 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002864 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002865 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002866 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2867 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002868 }
John McCallf85e1932011-06-15 23:02:42 +00002869 if (EPI.ConsumedArguments)
2870 Size += NumArgs * sizeof(bool);
2871
John McCalle23cf432010-12-14 08:05:40 +00002872 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002873 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rosebea522f2013-03-08 21:51:21 +00002874 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002875 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002876 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002877 return QualType(FTP, 0);
2878}
2879
John McCall3cb0ebd2010-03-10 03:28:59 +00002880#ifndef NDEBUG
2881static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2882 if (!isa<CXXRecordDecl>(D)) return false;
2883 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2884 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2885 return true;
2886 if (RD->getDescribedClassTemplate() &&
2887 !isa<ClassTemplateSpecializationDecl>(RD))
2888 return true;
2889 return false;
2890}
2891#endif
2892
2893/// getInjectedClassNameType - Return the unique reference to the
2894/// injected class name type for the specified templated declaration.
2895QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002896 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002897 assert(NeedsInjectedClassNameType(Decl));
2898 if (Decl->TypeForDecl) {
2899 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002900 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002901 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2902 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2903 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2904 } else {
John McCallf4c73712011-01-19 06:33:43 +00002905 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002906 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002907 Decl->TypeForDecl = newType;
2908 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002909 }
2910 return QualType(Decl->TypeForDecl, 0);
2911}
2912
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002913/// getTypeDeclType - Return the unique reference to the type for the
2914/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002915QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002916 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002917 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Richard Smith162e1c12011-04-15 14:24:37 +00002919 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002920 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002921
John McCallbecb8d52010-03-10 06:48:02 +00002922 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2923 "Template type parameter types are always available.");
2924
John McCall19c85762010-02-16 03:57:14 +00002925 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002926 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002927 "struct/union has previous declaration");
2928 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002929 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002930 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002931 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002932 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002933 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002934 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002935 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002936 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2937 Decl->TypeForDecl = newType;
2938 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002939 } else
John McCallbecb8d52010-03-10 06:48:02 +00002940 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002941
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002942 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002943}
2944
Reid Spencer5f016e22007-07-11 17:01:13 +00002945/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002946/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002947QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002948ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2949 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002952 if (Canonical.isNull())
2953 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002954 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002955 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002956 Decl->TypeForDecl = newType;
2957 Types.push_back(newType);
2958 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002959}
2960
Jay Foad4ba2a172011-01-12 09:06:06 +00002961QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002962 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2963
Douglas Gregoref96ee02012-01-14 16:38:05 +00002964 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002965 if (PrevDecl->TypeForDecl)
2966 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2967
John McCallf4c73712011-01-19 06:33:43 +00002968 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2969 Decl->TypeForDecl = newType;
2970 Types.push_back(newType);
2971 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002972}
2973
Jay Foad4ba2a172011-01-12 09:06:06 +00002974QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002975 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2976
Douglas Gregoref96ee02012-01-14 16:38:05 +00002977 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002978 if (PrevDecl->TypeForDecl)
2979 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2980
John McCallf4c73712011-01-19 06:33:43 +00002981 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2982 Decl->TypeForDecl = newType;
2983 Types.push_back(newType);
2984 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002985}
2986
John McCall9d156a72011-01-06 01:58:22 +00002987QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2988 QualType modifiedType,
2989 QualType equivalentType) {
2990 llvm::FoldingSetNodeID id;
2991 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2992
2993 void *insertPos = 0;
2994 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2995 if (type) return QualType(type, 0);
2996
2997 QualType canon = getCanonicalType(equivalentType);
2998 type = new (*this, TypeAlignment)
2999 AttributedType(canon, attrKind, modifiedType, equivalentType);
3000
3001 Types.push_back(type);
3002 AttributedTypes.InsertNode(type, insertPos);
3003
3004 return QualType(type, 0);
3005}
3006
3007
John McCall49a832b2009-10-18 09:09:24 +00003008/// \brief Retrieve a substitution-result type.
3009QualType
3010ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00003011 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00003012 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00003013 && "replacement types must always be canonical");
3014
3015 llvm::FoldingSetNodeID ID;
3016 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3017 void *InsertPos = 0;
3018 SubstTemplateTypeParmType *SubstParm
3019 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3020
3021 if (!SubstParm) {
3022 SubstParm = new (*this, TypeAlignment)
3023 SubstTemplateTypeParmType(Parm, Replacement);
3024 Types.push_back(SubstParm);
3025 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3026 }
3027
3028 return QualType(SubstParm, 0);
3029}
3030
Douglas Gregorc3069d62011-01-14 02:55:32 +00003031/// \brief Retrieve a
3032QualType ASTContext::getSubstTemplateTypeParmPackType(
3033 const TemplateTypeParmType *Parm,
3034 const TemplateArgument &ArgPack) {
3035#ifndef NDEBUG
3036 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3037 PEnd = ArgPack.pack_end();
3038 P != PEnd; ++P) {
3039 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3040 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3041 }
3042#endif
3043
3044 llvm::FoldingSetNodeID ID;
3045 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3046 void *InsertPos = 0;
3047 if (SubstTemplateTypeParmPackType *SubstParm
3048 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3049 return QualType(SubstParm, 0);
3050
3051 QualType Canon;
3052 if (!Parm->isCanonicalUnqualified()) {
3053 Canon = getCanonicalType(QualType(Parm, 0));
3054 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3055 ArgPack);
3056 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3057 }
3058
3059 SubstTemplateTypeParmPackType *SubstParm
3060 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3061 ArgPack);
3062 Types.push_back(SubstParm);
3063 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3064 return QualType(SubstParm, 0);
3065}
3066
Douglas Gregorfab9d672009-02-05 23:33:38 +00003067/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003068/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003069/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003070QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003071 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003072 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003073 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003074 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003075 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003076 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003077 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3078
3079 if (TypeParm)
3080 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003082 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003083 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003084 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003085
3086 TemplateTypeParmType *TypeCheck
3087 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3088 assert(!TypeCheck && "Template type parameter canonical type broken");
3089 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003090 } else
John McCall6b304a02009-09-24 23:30:46 +00003091 TypeParm = new (*this, TypeAlignment)
3092 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003093
3094 Types.push_back(TypeParm);
3095 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3096
3097 return QualType(TypeParm, 0);
3098}
3099
John McCall3cb0ebd2010-03-10 03:28:59 +00003100TypeSourceInfo *
3101ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3102 SourceLocation NameLoc,
3103 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003104 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003105 assert(!Name.getAsDependentTemplateName() &&
3106 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003107 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003108
3109 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003110 TemplateSpecializationTypeLoc TL =
3111 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003112 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003113 TL.setTemplateNameLoc(NameLoc);
3114 TL.setLAngleLoc(Args.getLAngleLoc());
3115 TL.setRAngleLoc(Args.getRAngleLoc());
3116 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3117 TL.setArgLocInfo(i, Args[i].getLocInfo());
3118 return DI;
3119}
3120
Mike Stump1eb44332009-09-09 15:08:12 +00003121QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003122ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003123 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003124 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003125 assert(!Template.getAsDependentTemplateName() &&
3126 "No dependent template names here!");
3127
John McCalld5532b62009-11-23 01:53:49 +00003128 unsigned NumArgs = Args.size();
3129
Chris Lattner5f9e2722011-07-23 10:55:15 +00003130 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003131 ArgVec.reserve(NumArgs);
3132 for (unsigned i = 0; i != NumArgs; ++i)
3133 ArgVec.push_back(Args[i].getArgument());
3134
John McCall31f17ec2010-04-27 00:57:59 +00003135 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003136 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003137}
3138
Douglas Gregorb70126a2012-02-03 17:16:23 +00003139#ifndef NDEBUG
3140static bool hasAnyPackExpansions(const TemplateArgument *Args,
3141 unsigned NumArgs) {
3142 for (unsigned I = 0; I != NumArgs; ++I)
3143 if (Args[I].isPackExpansion())
3144 return true;
3145
3146 return true;
3147}
3148#endif
3149
John McCall833ca992009-10-29 08:12:44 +00003150QualType
3151ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003152 const TemplateArgument *Args,
3153 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003154 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003155 assert(!Template.getAsDependentTemplateName() &&
3156 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003157 // Look through qualified template names.
3158 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3159 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003160
Douglas Gregorb70126a2012-02-03 17:16:23 +00003161 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003162 Template.getAsTemplateDecl() &&
3163 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003164 QualType CanonType;
3165 if (!Underlying.isNull())
3166 CanonType = getCanonicalType(Underlying);
3167 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003168 // We can get here with an alias template when the specialization contains
3169 // a pack expansion that does not match up with a parameter pack.
3170 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3171 "Caller must compute aliased type");
3172 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003173 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3174 NumArgs);
3175 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003176
Douglas Gregor1275ae02009-07-28 23:00:59 +00003177 // Allocate the (non-canonical) template specialization type, but don't
3178 // try to unique it: these types typically have location information that
3179 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003180 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3181 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003182 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003183 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003184 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003185 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3186 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003187
Douglas Gregor55f6b142009-02-09 18:46:07 +00003188 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003189 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003190}
3191
Mike Stump1eb44332009-09-09 15:08:12 +00003192QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003193ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3194 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003195 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003196 assert(!Template.getAsDependentTemplateName() &&
3197 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003198
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003199 // Look through qualified template names.
3200 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3201 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003202
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003203 // Build the canonical template specialization type.
3204 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003205 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003206 CanonArgs.reserve(NumArgs);
3207 for (unsigned I = 0; I != NumArgs; ++I)
3208 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3209
3210 // Determine whether this canonical template specialization type already
3211 // exists.
3212 llvm::FoldingSetNodeID ID;
3213 TemplateSpecializationType::Profile(ID, CanonTemplate,
3214 CanonArgs.data(), NumArgs, *this);
3215
3216 void *InsertPos = 0;
3217 TemplateSpecializationType *Spec
3218 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3219
3220 if (!Spec) {
3221 // Allocate a new canonical template specialization type.
3222 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3223 sizeof(TemplateArgument) * NumArgs),
3224 TypeAlignment);
3225 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3226 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003227 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003228 Types.push_back(Spec);
3229 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3230 }
3231
3232 assert(Spec->isDependentType() &&
3233 "Non-dependent template-id type must have a canonical type");
3234 return QualType(Spec, 0);
3235}
3236
3237QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003238ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3239 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003240 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003241 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003242 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003243
3244 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003245 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003246 if (T)
3247 return QualType(T, 0);
3248
Douglas Gregor789b1f62010-02-04 18:10:26 +00003249 QualType Canon = NamedType;
3250 if (!Canon.isCanonical()) {
3251 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003252 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3253 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003254 (void)CheckT;
3255 }
3256
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003257 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003258 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003259 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003260 return QualType(T, 0);
3261}
3262
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003263QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003264ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003265 llvm::FoldingSetNodeID ID;
3266 ParenType::Profile(ID, InnerType);
3267
3268 void *InsertPos = 0;
3269 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3270 if (T)
3271 return QualType(T, 0);
3272
3273 QualType Canon = InnerType;
3274 if (!Canon.isCanonical()) {
3275 Canon = getCanonicalType(InnerType);
3276 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3277 assert(!CheckT && "Paren canonical type broken");
3278 (void)CheckT;
3279 }
3280
3281 T = new (*this) ParenType(InnerType, Canon);
3282 Types.push_back(T);
3283 ParenTypes.InsertNode(T, InsertPos);
3284 return QualType(T, 0);
3285}
3286
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003287QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3288 NestedNameSpecifier *NNS,
3289 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003290 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003291 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3292
3293 if (Canon.isNull()) {
3294 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003295 ElaboratedTypeKeyword CanonKeyword = Keyword;
3296 if (Keyword == ETK_None)
3297 CanonKeyword = ETK_Typename;
3298
3299 if (CanonNNS != NNS || CanonKeyword != Keyword)
3300 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003301 }
3302
3303 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003304 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003305
3306 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003307 DependentNameType *T
3308 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003309 if (T)
3310 return QualType(T, 0);
3311
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003312 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003313 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003314 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003315 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003316}
3317
Mike Stump1eb44332009-09-09 15:08:12 +00003318QualType
John McCall33500952010-06-11 00:33:02 +00003319ASTContext::getDependentTemplateSpecializationType(
3320 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003321 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003322 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003323 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003324 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003325 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003326 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3327 ArgCopy.push_back(Args[I].getArgument());
3328 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3329 ArgCopy.size(),
3330 ArgCopy.data());
3331}
3332
3333QualType
3334ASTContext::getDependentTemplateSpecializationType(
3335 ElaboratedTypeKeyword Keyword,
3336 NestedNameSpecifier *NNS,
3337 const IdentifierInfo *Name,
3338 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003339 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003340 assert((!NNS || NNS->isDependent()) &&
3341 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003342
Douglas Gregor789b1f62010-02-04 18:10:26 +00003343 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003344 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3345 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003346
3347 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003348 DependentTemplateSpecializationType *T
3349 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003350 if (T)
3351 return QualType(T, 0);
3352
John McCall33500952010-06-11 00:33:02 +00003353 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003354
John McCall33500952010-06-11 00:33:02 +00003355 ElaboratedTypeKeyword CanonKeyword = Keyword;
3356 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3357
3358 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003359 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003360 for (unsigned I = 0; I != NumArgs; ++I) {
3361 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3362 if (!CanonArgs[I].structurallyEquals(Args[I]))
3363 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003364 }
3365
John McCall33500952010-06-11 00:33:02 +00003366 QualType Canon;
3367 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3368 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3369 Name, NumArgs,
3370 CanonArgs.data());
3371
3372 // Find the insert position again.
3373 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 }
3375
3376 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3377 sizeof(TemplateArgument) * NumArgs),
3378 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003379 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003380 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003381 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003382 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003383 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003384}
3385
Douglas Gregorcded4f62011-01-14 17:04:44 +00003386QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003387 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003388 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003389 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003390
3391 assert(Pattern->containsUnexpandedParameterPack() &&
3392 "Pack expansions must expand one or more parameter packs");
3393 void *InsertPos = 0;
3394 PackExpansionType *T
3395 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3396 if (T)
3397 return QualType(T, 0);
3398
3399 QualType Canon;
3400 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003401 Canon = getCanonicalType(Pattern);
3402 // The canonical type might not contain an unexpanded parameter pack, if it
3403 // contains an alias template specialization which ignores one of its
3404 // parameters.
3405 if (Canon->containsUnexpandedParameterPack()) {
3406 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003407
Richard Smithd8672ef2012-07-16 00:20:35 +00003408 // Find the insert position again, in case we inserted an element into
3409 // PackExpansionTypes and invalidated our insert position.
3410 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3411 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003412 }
3413
Douglas Gregorcded4f62011-01-14 17:04:44 +00003414 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003415 Types.push_back(T);
3416 PackExpansionTypes.InsertNode(T, InsertPos);
3417 return QualType(T, 0);
3418}
3419
Chris Lattner88cb27a2008-04-07 04:56:42 +00003420/// CmpProtocolNames - Comparison predicate for sorting protocols
3421/// alphabetically.
3422static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3423 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003424 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003425}
3426
John McCallc12c5bb2010-05-15 11:32:37 +00003427static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003428 unsigned NumProtocols) {
3429 if (NumProtocols == 0) return true;
3430
Douglas Gregor61cc2962012-01-02 02:00:30 +00003431 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3432 return false;
3433
John McCall54e14c42009-10-22 22:37:11 +00003434 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003435 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3436 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003437 return false;
3438 return true;
3439}
3440
3441static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003442 unsigned &NumProtocols) {
3443 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Chris Lattner88cb27a2008-04-07 04:56:42 +00003445 // Sort protocols, keyed by name.
3446 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3447
Douglas Gregor61cc2962012-01-02 02:00:30 +00003448 // Canonicalize.
3449 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3450 Protocols[I] = Protocols[I]->getCanonicalDecl();
3451
Chris Lattner88cb27a2008-04-07 04:56:42 +00003452 // Remove duplicates.
3453 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3454 NumProtocols = ProtocolsEnd-Protocols;
3455}
3456
John McCallc12c5bb2010-05-15 11:32:37 +00003457QualType ASTContext::getObjCObjectType(QualType BaseType,
3458 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003459 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003460 // If the base type is an interface and there aren't any protocols
3461 // to add, then the interface type will do just fine.
3462 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3463 return BaseType;
3464
3465 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003466 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003467 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003468 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003469 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3470 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003471
John McCallc12c5bb2010-05-15 11:32:37 +00003472 // Build the canonical type, which has the canonical base type and
3473 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003474 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003475 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3476 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3477 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003478 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003479 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003480 unsigned UniqueCount = NumProtocols;
3481
John McCall54e14c42009-10-22 22:37:11 +00003482 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003483 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3484 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003485 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003486 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3487 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003488 }
3489
3490 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003491 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3492 }
3493
3494 unsigned Size = sizeof(ObjCObjectTypeImpl);
3495 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3496 void *Mem = Allocate(Size, TypeAlignment);
3497 ObjCObjectTypeImpl *T =
3498 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3499
3500 Types.push_back(T);
3501 ObjCObjectTypes.InsertNode(T, InsertPos);
3502 return QualType(T, 0);
3503}
3504
3505/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3506/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003507QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003508 llvm::FoldingSetNodeID ID;
3509 ObjCObjectPointerType::Profile(ID, ObjectT);
3510
3511 void *InsertPos = 0;
3512 if (ObjCObjectPointerType *QT =
3513 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3514 return QualType(QT, 0);
3515
3516 // Find the canonical object type.
3517 QualType Canonical;
3518 if (!ObjectT.isCanonical()) {
3519 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3520
3521 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003522 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3523 }
3524
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003525 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003526 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3527 ObjCObjectPointerType *QType =
3528 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003530 Types.push_back(QType);
3531 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003532 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003533}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003534
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003535/// getObjCInterfaceType - Return the unique reference to the type for the
3536/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003537QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3538 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003539 if (Decl->TypeForDecl)
3540 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Douglas Gregor0af55012011-12-16 03:12:41 +00003542 if (PrevDecl) {
3543 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3544 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3545 return QualType(PrevDecl->TypeForDecl, 0);
3546 }
3547
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003548 // Prefer the definition, if there is one.
3549 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3550 Decl = Def;
3551
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003552 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3553 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3554 Decl->TypeForDecl = T;
3555 Types.push_back(T);
3556 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003557}
3558
Douglas Gregor72564e72009-02-26 23:50:07 +00003559/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3560/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003561/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003562/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003563/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003564QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003565 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003566 if (tofExpr->isTypeDependent()) {
3567 llvm::FoldingSetNodeID ID;
3568 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Douglas Gregorb1975722009-07-30 23:18:24 +00003570 void *InsertPos = 0;
3571 DependentTypeOfExprType *Canon
3572 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3573 if (Canon) {
3574 // We already have a "canonical" version of an identical, dependent
3575 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003576 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003577 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003578 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003579 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003580 Canon
3581 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003582 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3583 toe = Canon;
3584 }
3585 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003586 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003587 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003588 }
Steve Naroff9752f252007-08-01 18:02:17 +00003589 Types.push_back(toe);
3590 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003591}
3592
Steve Naroff9752f252007-08-01 18:02:17 +00003593/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3594/// TypeOfType AST's. The only motivation to unique these nodes would be
3595/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003596/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003597/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003598QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003599 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003600 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003601 Types.push_back(tot);
3602 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003603}
3604
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003605
Anders Carlsson395b4752009-06-24 19:06:50 +00003606/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3607/// DecltypeType AST's. The only motivation to unique these nodes would be
3608/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003609/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003610/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003611QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003612 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003613
3614 // C++0x [temp.type]p2:
3615 // If an expression e involves a template parameter, decltype(e) denotes a
3616 // unique dependent type. Two such decltype-specifiers refer to the same
3617 // type only if their expressions are equivalent (14.5.6.1).
3618 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003619 llvm::FoldingSetNodeID ID;
3620 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003622 void *InsertPos = 0;
3623 DependentDecltypeType *Canon
3624 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3625 if (Canon) {
3626 // We already have a "canonical" version of an equivalent, dependent
3627 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003628 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003629 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003630 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003631 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003632 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003633 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3634 dt = Canon;
3635 }
3636 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003637 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3638 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003639 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003640 Types.push_back(dt);
3641 return QualType(dt, 0);
3642}
3643
Sean Huntca63c202011-05-24 22:41:36 +00003644/// getUnaryTransformationType - We don't unique these, since the memory
3645/// savings are minimal and these are rare.
3646QualType ASTContext::getUnaryTransformType(QualType BaseType,
3647 QualType UnderlyingType,
3648 UnaryTransformType::UTTKind Kind)
3649 const {
3650 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003651 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3652 Kind,
3653 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003654 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003655 Types.push_back(Ty);
3656 return QualType(Ty, 0);
3657}
3658
Richard Smith60e141e2013-05-04 07:00:32 +00003659/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3660/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3661/// canonical deduced-but-dependent 'auto' type.
3662QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003663 bool IsDependent) const {
3664 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith60e141e2013-05-04 07:00:32 +00003665 return getAutoDeductType();
Manuel Klimek152b4e42013-08-22 12:12:24 +00003666
Richard Smith60e141e2013-05-04 07:00:32 +00003667 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003668 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003669 llvm::FoldingSetNodeID ID;
Manuel Klimek152b4e42013-08-22 12:12:24 +00003670 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith60e141e2013-05-04 07:00:32 +00003671 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3672 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003673
Richard Smitha2c36462013-04-26 16:15:35 +00003674 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003675 IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003676 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003677 Types.push_back(AT);
3678 if (InsertPos)
3679 AutoTypes.InsertNode(AT, InsertPos);
3680 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003681}
3682
Eli Friedmanb001de72011-10-06 23:00:33 +00003683/// getAtomicType - Return the uniqued reference to the atomic type for
3684/// the given value type.
3685QualType ASTContext::getAtomicType(QualType T) const {
3686 // Unique pointers, to guarantee there is only one pointer of a particular
3687 // structure.
3688 llvm::FoldingSetNodeID ID;
3689 AtomicType::Profile(ID, T);
3690
3691 void *InsertPos = 0;
3692 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3693 return QualType(AT, 0);
3694
3695 // If the atomic value type isn't canonical, this won't be a canonical type
3696 // either, so fill in the canonical type field.
3697 QualType Canonical;
3698 if (!T.isCanonical()) {
3699 Canonical = getAtomicType(getCanonicalType(T));
3700
3701 // Get the new insert position for the node we care about.
3702 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3703 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3704 }
3705 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3706 Types.push_back(New);
3707 AtomicTypes.InsertNode(New, InsertPos);
3708 return QualType(New, 0);
3709}
3710
Richard Smithad762fc2011-04-14 22:09:26 +00003711/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3712QualType ASTContext::getAutoDeductType() const {
3713 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003714 AutoDeductTy = QualType(
3715 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003716 /*dependent*/false),
Richard Smith60e141e2013-05-04 07:00:32 +00003717 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003718 return AutoDeductTy;
3719}
3720
3721/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3722QualType ASTContext::getAutoRRefDeductType() const {
3723 if (AutoRRefDeductTy.isNull())
3724 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3725 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3726 return AutoRRefDeductTy;
3727}
3728
Reid Spencer5f016e22007-07-11 17:01:13 +00003729/// getTagDeclType - Return the unique reference to the type for the
3730/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003731QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003732 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003733 // FIXME: What is the design on getTagDeclType when it requires casting
3734 // away const? mutable?
3735 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003736}
3737
Mike Stump1eb44332009-09-09 15:08:12 +00003738/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3739/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3740/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003741CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003742 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003743}
3744
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003745/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3746CanQualType ASTContext::getIntMaxType() const {
3747 return getFromTargetType(Target->getIntMaxType());
3748}
3749
3750/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3751CanQualType ASTContext::getUIntMaxType() const {
3752 return getFromTargetType(Target->getUIntMaxType());
3753}
3754
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003755/// getSignedWCharType - Return the type of "signed wchar_t".
3756/// Used when in C++, as a GCC extension.
3757QualType ASTContext::getSignedWCharType() const {
3758 // FIXME: derive from "Target" ?
3759 return WCharTy;
3760}
3761
3762/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3763/// Used when in C++, as a GCC extension.
3764QualType ASTContext::getUnsignedWCharType() const {
3765 // FIXME: derive from "Target" ?
3766 return UnsignedIntTy;
3767}
3768
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003769QualType ASTContext::getIntPtrType() const {
3770 return getFromTargetType(Target->getIntPtrType());
3771}
3772
3773QualType ASTContext::getUIntPtrType() const {
3774 return getCorrespondingUnsignedType(getIntPtrType());
3775}
3776
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003777/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003778/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3779QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003780 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003781}
3782
Eli Friedman6902e412012-11-27 02:58:24 +00003783/// \brief Return the unique type for "pid_t" defined in
3784/// <sys/types.h>. We need this to compute the correct type for vfork().
3785QualType ASTContext::getProcessIDType() const {
3786 return getFromTargetType(Target->getProcessIDType());
3787}
3788
Chris Lattnere6327742008-04-02 05:18:44 +00003789//===----------------------------------------------------------------------===//
3790// Type Operators
3791//===----------------------------------------------------------------------===//
3792
Jay Foad4ba2a172011-01-12 09:06:06 +00003793CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003794 // Push qualifiers into arrays, and then discard any remaining
3795 // qualifiers.
3796 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003797 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003798 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003799 QualType Result;
3800 if (isa<ArrayType>(Ty)) {
3801 Result = getArrayDecayedType(QualType(Ty,0));
3802 } else if (isa<FunctionType>(Ty)) {
3803 Result = getPointerType(QualType(Ty, 0));
3804 } else {
3805 Result = QualType(Ty, 0);
3806 }
3807
3808 return CanQualType::CreateUnsafe(Result);
3809}
3810
John McCall62c28c82011-01-18 07:41:22 +00003811QualType ASTContext::getUnqualifiedArrayType(QualType type,
3812 Qualifiers &quals) {
3813 SplitQualType splitType = type.getSplitUnqualifiedType();
3814
3815 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3816 // the unqualified desugared type and then drops it on the floor.
3817 // We then have to strip that sugar back off with
3818 // getUnqualifiedDesugaredType(), which is silly.
3819 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003820 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003821
3822 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003823 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003824 quals = splitType.Quals;
3825 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003826 }
3827
John McCall62c28c82011-01-18 07:41:22 +00003828 // Otherwise, recurse on the array's element type.
3829 QualType elementType = AT->getElementType();
3830 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3831
3832 // If that didn't change the element type, AT has no qualifiers, so we
3833 // can just use the results in splitType.
3834 if (elementType == unqualElementType) {
3835 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003836 quals = splitType.Quals;
3837 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003838 }
3839
3840 // Otherwise, add in the qualifiers from the outermost type, then
3841 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003842 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003843
Douglas Gregor9dadd942010-05-17 18:45:21 +00003844 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003845 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003846 CAT->getSizeModifier(), 0);
3847 }
3848
Douglas Gregor9dadd942010-05-17 18:45:21 +00003849 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003850 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003851 }
3852
Douglas Gregor9dadd942010-05-17 18:45:21 +00003853 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003854 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003855 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003856 VAT->getSizeModifier(),
3857 VAT->getIndexTypeCVRQualifiers(),
3858 VAT->getBracketsRange());
3859 }
3860
3861 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003862 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003863 DSAT->getSizeModifier(), 0,
3864 SourceRange());
3865}
3866
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003867/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3868/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3869/// they point to and return true. If T1 and T2 aren't pointer types
3870/// or pointer-to-member types, or if they are not similar at this
3871/// level, returns false and leaves T1 and T2 unchanged. Top-level
3872/// qualifiers on T1 and T2 are ignored. This function will typically
3873/// be called in a loop that successively "unwraps" pointer and
3874/// pointer-to-member types to compare them at each level.
3875bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3876 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3877 *T2PtrType = T2->getAs<PointerType>();
3878 if (T1PtrType && T2PtrType) {
3879 T1 = T1PtrType->getPointeeType();
3880 T2 = T2PtrType->getPointeeType();
3881 return true;
3882 }
3883
3884 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3885 *T2MPType = T2->getAs<MemberPointerType>();
3886 if (T1MPType && T2MPType &&
3887 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3888 QualType(T2MPType->getClass(), 0))) {
3889 T1 = T1MPType->getPointeeType();
3890 T2 = T2MPType->getPointeeType();
3891 return true;
3892 }
3893
David Blaikie4e4d0842012-03-11 07:00:24 +00003894 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003895 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3896 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3897 if (T1OPType && T2OPType) {
3898 T1 = T1OPType->getPointeeType();
3899 T2 = T2OPType->getPointeeType();
3900 return true;
3901 }
3902 }
3903
3904 // FIXME: Block pointers, too?
3905
3906 return false;
3907}
3908
Jay Foad4ba2a172011-01-12 09:06:06 +00003909DeclarationNameInfo
3910ASTContext::getNameForTemplate(TemplateName Name,
3911 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003912 switch (Name.getKind()) {
3913 case TemplateName::QualifiedTemplate:
3914 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003915 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003916 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3917 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003918
John McCall14606042011-06-30 08:33:18 +00003919 case TemplateName::OverloadedTemplate: {
3920 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3921 // DNInfo work in progress: CHECKME: what about DNLoc?
3922 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3923 }
3924
3925 case TemplateName::DependentTemplate: {
3926 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003927 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003928 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003929 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3930 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003931 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003932 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3933 // DNInfo work in progress: FIXME: source locations?
3934 DeclarationNameLoc DNLoc;
3935 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3936 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3937 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003938 }
3939 }
3940
John McCall14606042011-06-30 08:33:18 +00003941 case TemplateName::SubstTemplateTemplateParm: {
3942 SubstTemplateTemplateParmStorage *subst
3943 = Name.getAsSubstTemplateTemplateParm();
3944 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3945 NameLoc);
3946 }
3947
3948 case TemplateName::SubstTemplateTemplateParmPack: {
3949 SubstTemplateTemplateParmPackStorage *subst
3950 = Name.getAsSubstTemplateTemplateParmPack();
3951 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3952 NameLoc);
3953 }
3954 }
3955
3956 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003957}
3958
Jay Foad4ba2a172011-01-12 09:06:06 +00003959TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003960 switch (Name.getKind()) {
3961 case TemplateName::QualifiedTemplate:
3962 case TemplateName::Template: {
3963 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003964 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003965 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003966 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3967
3968 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003969 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003970 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003971
John McCall14606042011-06-30 08:33:18 +00003972 case TemplateName::OverloadedTemplate:
3973 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003974
John McCall14606042011-06-30 08:33:18 +00003975 case TemplateName::DependentTemplate: {
3976 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3977 assert(DTN && "Non-dependent template names must refer to template decls.");
3978 return DTN->CanonicalTemplateName;
3979 }
3980
3981 case TemplateName::SubstTemplateTemplateParm: {
3982 SubstTemplateTemplateParmStorage *subst
3983 = Name.getAsSubstTemplateTemplateParm();
3984 return getCanonicalTemplateName(subst->getReplacement());
3985 }
3986
3987 case TemplateName::SubstTemplateTemplateParmPack: {
3988 SubstTemplateTemplateParmPackStorage *subst
3989 = Name.getAsSubstTemplateTemplateParmPack();
3990 TemplateTemplateParmDecl *canonParameter
3991 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3992 TemplateArgument canonArgPack
3993 = getCanonicalTemplateArgument(subst->getArgumentPack());
3994 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3995 }
3996 }
3997
3998 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003999}
4000
Douglas Gregordb0d4b72009-11-11 23:06:43 +00004001bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4002 X = getCanonicalTemplateName(X);
4003 Y = getCanonicalTemplateName(Y);
4004 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4005}
4006
Mike Stump1eb44332009-09-09 15:08:12 +00004007TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00004008ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00004009 switch (Arg.getKind()) {
4010 case TemplateArgument::Null:
4011 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Douglas Gregor1275ae02009-07-28 23:00:59 +00004013 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00004014 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Douglas Gregord2008e22012-04-06 22:40:38 +00004016 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004017 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4018 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004019 }
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Eli Friedmand7a6b162012-09-26 02:36:12 +00004021 case TemplateArgument::NullPtr:
4022 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4023 /*isNullPtr*/true);
4024
Douglas Gregor788cd062009-11-11 01:00:40 +00004025 case TemplateArgument::Template:
4026 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004027
4028 case TemplateArgument::TemplateExpansion:
4029 return TemplateArgument(getCanonicalTemplateName(
4030 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004031 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004032
Douglas Gregor1275ae02009-07-28 23:00:59 +00004033 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004034 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Douglas Gregor1275ae02009-07-28 23:00:59 +00004036 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004037 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Douglas Gregor1275ae02009-07-28 23:00:59 +00004039 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004040 if (Arg.pack_size() == 0)
4041 return Arg;
4042
Douglas Gregor910f8002010-11-07 23:05:16 +00004043 TemplateArgument *CanonArgs
4044 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004045 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004046 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004047 AEnd = Arg.pack_end();
4048 A != AEnd; (void)++A, ++Idx)
4049 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Douglas Gregor910f8002010-11-07 23:05:16 +00004051 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004052 }
4053 }
4054
4055 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004056 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004057}
4058
Douglas Gregord57959a2009-03-27 23:10:48 +00004059NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004060ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004061 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004062 return 0;
4063
4064 switch (NNS->getKind()) {
4065 case NestedNameSpecifier::Identifier:
4066 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004067 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004068 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4069 NNS->getAsIdentifier());
4070
4071 case NestedNameSpecifier::Namespace:
4072 // A namespace is canonical; build a nested-name-specifier with
4073 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004074 return NestedNameSpecifier::Create(*this, 0,
4075 NNS->getAsNamespace()->getOriginalNamespace());
4076
4077 case NestedNameSpecifier::NamespaceAlias:
4078 // A namespace is canonical; build a nested-name-specifier with
4079 // this namespace and no prefix.
4080 return NestedNameSpecifier::Create(*this, 0,
4081 NNS->getAsNamespaceAlias()->getNamespace()
4082 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004083
4084 case NestedNameSpecifier::TypeSpec:
4085 case NestedNameSpecifier::TypeSpecWithTemplate: {
4086 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004087
4088 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4089 // break it apart into its prefix and identifier, then reconsititute those
4090 // as the canonical nested-name-specifier. This is required to canonicalize
4091 // a dependent nested-name-specifier involving typedefs of dependent-name
4092 // types, e.g.,
4093 // typedef typename T::type T1;
4094 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004095 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4096 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004097 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004098
Eli Friedman16412ef2012-03-03 04:09:56 +00004099 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4100 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4101 // first place?
John McCall3b657512011-01-19 10:06:00 +00004102 return NestedNameSpecifier::Create(*this, 0, false,
4103 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004104 }
4105
4106 case NestedNameSpecifier::Global:
4107 // The global specifier is canonical and unique.
4108 return NNS;
4109 }
4110
David Blaikie7530c032012-01-17 06:56:22 +00004111 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004112}
4113
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004114
Jay Foad4ba2a172011-01-12 09:06:06 +00004115const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004117 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004118 // Handle the common positive case fast.
4119 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4120 return AT;
4121 }
Mike Stump1eb44332009-09-09 15:08:12 +00004122
John McCall0953e762009-09-24 19:53:00 +00004123 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004124 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004125 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004126
John McCall0953e762009-09-24 19:53:00 +00004127 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004128 // implements C99 6.7.3p8: "If the specification of an array type includes
4129 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004131 // If we get here, we either have type qualifiers on the type, or we have
4132 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004133 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004134
John McCall3b657512011-01-19 10:06:00 +00004135 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004136 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004138 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004139 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004140 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004141 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004143 // Otherwise, we have an array and we have qualifiers on it. Push the
4144 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004145 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004147 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4148 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4149 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004150 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004151 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4152 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4153 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004154 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004155
Mike Stump1eb44332009-09-09 15:08:12 +00004156 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004157 = dyn_cast<DependentSizedArrayType>(ATy))
4158 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004159 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004160 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004161 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004162 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004163 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004165 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004166 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004167 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004168 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004169 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004170 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004171}
4172
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004173QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004174 if (T->isArrayType() || T->isFunctionType())
4175 return getDecayedType(T);
4176 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004177}
4178
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004179QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004180 T = getVariableArrayDecayedType(T);
4181 T = getAdjustedParameterType(T);
4182 return T.getUnqualifiedType();
4183}
4184
Chris Lattnere6327742008-04-02 05:18:44 +00004185/// getArrayDecayedType - Return the properly qualified result of decaying the
4186/// specified array type to a pointer. This operation is non-trivial when
4187/// handling typedefs etc. The canonical type of "T" must be an array type,
4188/// this returns a pointer to a properly qualified element of the array.
4189///
4190/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004191QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004192 // Get the element type with 'getAsArrayType' so that we don't lose any
4193 // typedefs in the element type of the array. This also handles propagation
4194 // of type qualifiers from the array type into the element type if present
4195 // (C99 6.7.3p8).
4196 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4197 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004198
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004199 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004200
4201 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004202 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004203}
4204
John McCall3b657512011-01-19 10:06:00 +00004205QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4206 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004207}
4208
John McCall3b657512011-01-19 10:06:00 +00004209QualType ASTContext::getBaseElementType(QualType type) const {
4210 Qualifiers qs;
4211 while (true) {
4212 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004213 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004214 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004215
John McCall3b657512011-01-19 10:06:00 +00004216 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004217 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004218 }
Mike Stump1eb44332009-09-09 15:08:12 +00004219
John McCall3b657512011-01-19 10:06:00 +00004220 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004221}
4222
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004223/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004224uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004225ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4226 uint64_t ElementCount = 1;
4227 do {
4228 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004229 CA = dyn_cast_or_null<ConstantArrayType>(
4230 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004231 } while (CA);
4232 return ElementCount;
4233}
4234
Reid Spencer5f016e22007-07-11 17:01:13 +00004235/// getFloatingRank - Return a relative rank for floating point types.
4236/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004237static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004238 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004239 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004240
John McCall183700f2009-09-21 23:43:11 +00004241 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4242 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004243 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004244 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004245 case BuiltinType::Float: return FloatRank;
4246 case BuiltinType::Double: return DoubleRank;
4247 case BuiltinType::LongDouble: return LongDoubleRank;
4248 }
4249}
4250
Mike Stump1eb44332009-09-09 15:08:12 +00004251/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4252/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004253/// 'typeDomain' is a real floating point or complex type.
4254/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004255QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4256 QualType Domain) const {
4257 FloatingRank EltRank = getFloatingRank(Size);
4258 if (Domain->isComplexType()) {
4259 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004260 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004261 case FloatRank: return FloatComplexTy;
4262 case DoubleRank: return DoubleComplexTy;
4263 case LongDoubleRank: return LongDoubleComplexTy;
4264 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004265 }
Chris Lattner1361b112008-04-06 23:58:54 +00004266
4267 assert(Domain->isRealFloatingType() && "Unknown domain!");
4268 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004269 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004270 case FloatRank: return FloatTy;
4271 case DoubleRank: return DoubleTy;
4272 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004273 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004274 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004275}
4276
Chris Lattner7cfeb082008-04-06 23:55:33 +00004277/// getFloatingTypeOrder - Compare the rank of the two specified floating
4278/// point types, ignoring the domain of the type (i.e. 'double' ==
4279/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004280/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004281int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004282 FloatingRank LHSR = getFloatingRank(LHS);
4283 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Chris Lattnera75cea32008-04-06 23:38:49 +00004285 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004286 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004287 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004288 return 1;
4289 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004290}
4291
Chris Lattnerf52ab252008-04-06 22:59:24 +00004292/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4293/// routine will assert if passed a built-in type that isn't an integer or enum,
4294/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004295unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004296 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004297
Chris Lattnerf52ab252008-04-06 22:59:24 +00004298 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004299 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004300 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004301 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004302 case BuiltinType::Char_S:
4303 case BuiltinType::Char_U:
4304 case BuiltinType::SChar:
4305 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004306 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004307 case BuiltinType::Short:
4308 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004309 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004310 case BuiltinType::Int:
4311 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004312 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004313 case BuiltinType::Long:
4314 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004315 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004316 case BuiltinType::LongLong:
4317 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004318 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004319 case BuiltinType::Int128:
4320 case BuiltinType::UInt128:
4321 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004322 }
4323}
4324
Eli Friedman04e83572009-08-20 04:21:42 +00004325/// \brief Whether this is a promotable bitfield reference according
4326/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4327///
4328/// \returns the type this bit-field will promote to, or NULL if no
4329/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004330QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004331 if (E->isTypeDependent() || E->isValueDependent())
4332 return QualType();
4333
John McCall993f43f2013-05-06 21:39:12 +00004334 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004335 if (!Field)
4336 return QualType();
4337
4338 QualType FT = Field->getType();
4339
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004340 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004341 uint64_t IntSize = getTypeSize(IntTy);
4342 // GCC extension compatibility: if the bit-field size is less than or equal
4343 // to the size of int, it gets promoted no matter what its type is.
4344 // For instance, unsigned long bf : 4 gets promoted to signed int.
4345 if (BitWidth < IntSize)
4346 return IntTy;
4347
4348 if (BitWidth == IntSize)
4349 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4350
4351 // Types bigger than int are not subject to promotions, and therefore act
4352 // like the base type.
4353 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4354 // is ridiculous.
4355 return QualType();
4356}
4357
Eli Friedmana95d7572009-08-19 07:44:53 +00004358/// getPromotedIntegerType - Returns the type that Promotable will
4359/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4360/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004361QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004362 assert(!Promotable.isNull());
4363 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004364 if (const EnumType *ET = Promotable->getAs<EnumType>())
4365 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004366
4367 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4368 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4369 // (3.9.1) can be converted to a prvalue of the first of the following
4370 // types that can represent all the values of its underlying type:
4371 // int, unsigned int, long int, unsigned long int, long long int, or
4372 // unsigned long long int [...]
4373 // FIXME: Is there some better way to compute this?
4374 if (BT->getKind() == BuiltinType::WChar_S ||
4375 BT->getKind() == BuiltinType::WChar_U ||
4376 BT->getKind() == BuiltinType::Char16 ||
4377 BT->getKind() == BuiltinType::Char32) {
4378 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4379 uint64_t FromSize = getTypeSize(BT);
4380 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4381 LongLongTy, UnsignedLongLongTy };
4382 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4383 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4384 if (FromSize < ToSize ||
4385 (FromSize == ToSize &&
4386 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4387 return PromoteTypes[Idx];
4388 }
4389 llvm_unreachable("char type should fit into long long");
4390 }
4391 }
4392
4393 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004394 if (Promotable->isSignedIntegerType())
4395 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004396 uint64_t PromotableSize = getIntWidth(Promotable);
4397 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004398 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4399 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4400}
4401
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004402/// \brief Recurses in pointer/array types until it finds an objc retainable
4403/// type and returns its ownership.
4404Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4405 while (!T.isNull()) {
4406 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4407 return T.getObjCLifetime();
4408 if (T->isArrayType())
4409 T = getBaseElementType(T);
4410 else if (const PointerType *PT = T->getAs<PointerType>())
4411 T = PT->getPointeeType();
4412 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004413 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004414 else
4415 break;
4416 }
4417
4418 return Qualifiers::OCL_None;
4419}
4420
Mike Stump1eb44332009-09-09 15:08:12 +00004421/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004422/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004423/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004424int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004425 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4426 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004427 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Chris Lattnerf52ab252008-04-06 22:59:24 +00004429 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4430 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004431
Chris Lattner7cfeb082008-04-06 23:55:33 +00004432 unsigned LHSRank = getIntegerRank(LHSC);
4433 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Chris Lattner7cfeb082008-04-06 23:55:33 +00004435 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4436 if (LHSRank == RHSRank) return 0;
4437 return LHSRank > RHSRank ? 1 : -1;
4438 }
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Chris Lattner7cfeb082008-04-06 23:55:33 +00004440 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4441 if (LHSUnsigned) {
4442 // If the unsigned [LHS] type is larger, return it.
4443 if (LHSRank >= RHSRank)
4444 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Chris Lattner7cfeb082008-04-06 23:55:33 +00004446 // If the signed type can represent all values of the unsigned type, it
4447 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004448 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004449 return -1;
4450 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004451
Chris Lattner7cfeb082008-04-06 23:55:33 +00004452 // If the unsigned [RHS] type is larger, return it.
4453 if (RHSRank >= LHSRank)
4454 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Chris Lattner7cfeb082008-04-06 23:55:33 +00004456 // If the signed type can represent all values of the unsigned type, it
4457 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004458 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004459 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004460}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004461
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004462static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004463CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4464 DeclContext *DC, IdentifierInfo *Id) {
4465 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004466 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004467 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004468 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004469 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004470}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004471
Mike Stump1eb44332009-09-09 15:08:12 +00004472// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004473QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004474 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004475 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004476 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004477 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004478 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004479
Anders Carlssonf06273f2007-11-19 00:25:30 +00004480 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004481
Anders Carlsson71993dd2007-08-17 05:31:46 +00004482 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004483 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004484 // int flags;
4485 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004486 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004487 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004488 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004489 FieldTypes[3] = LongTy;
4490
Anders Carlsson71993dd2007-08-17 05:31:46 +00004491 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004492 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004493 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004494 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004495 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004496 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004497 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004498 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004499 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004500 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004501 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004502 }
4503
Douglas Gregor838db382010-02-11 01:19:42 +00004504 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004505 }
Mike Stump1eb44332009-09-09 15:08:12 +00004506
Anders Carlsson71993dd2007-08-17 05:31:46 +00004507 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004508}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004509
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004510QualType ASTContext::getObjCSuperType() const {
4511 if (ObjCSuperType.isNull()) {
4512 RecordDecl *ObjCSuperTypeDecl =
4513 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4514 TUDecl->addDecl(ObjCSuperTypeDecl);
4515 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4516 }
4517 return ObjCSuperType;
4518}
4519
Douglas Gregor319ac892009-04-23 22:29:11 +00004520void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004521 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004522 assert(Rec && "Invalid CFConstantStringType");
4523 CFConstantStringTypeDecl = Rec->getDecl();
4524}
4525
Jay Foad4ba2a172011-01-12 09:06:06 +00004526QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004527 if (BlockDescriptorType)
4528 return getTagDeclType(BlockDescriptorType);
4529
4530 RecordDecl *T;
4531 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004532 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004533 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004534 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004535
4536 QualType FieldTypes[] = {
4537 UnsignedLongTy,
4538 UnsignedLongTy,
4539 };
4540
Craig Topper3aa29df2013-07-15 08:24:27 +00004541 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004542 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004543 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004544 };
4545
4546 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004547 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004548 SourceLocation(),
4549 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004550 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004551 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004552 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004553 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004554 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004555 T->addDecl(Field);
4556 }
4557
Douglas Gregor838db382010-02-11 01:19:42 +00004558 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004559
4560 BlockDescriptorType = T;
4561
4562 return getTagDeclType(BlockDescriptorType);
4563}
4564
Jay Foad4ba2a172011-01-12 09:06:06 +00004565QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004566 if (BlockDescriptorExtendedType)
4567 return getTagDeclType(BlockDescriptorExtendedType);
4568
4569 RecordDecl *T;
4570 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004571 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004572 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004573 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004574
4575 QualType FieldTypes[] = {
4576 UnsignedLongTy,
4577 UnsignedLongTy,
4578 getPointerType(VoidPtrTy),
4579 getPointerType(VoidPtrTy)
4580 };
4581
Craig Topper3aa29df2013-07-15 08:24:27 +00004582 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004583 "reserved",
4584 "Size",
4585 "CopyFuncPtr",
4586 "DestroyFuncPtr"
4587 };
4588
4589 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004590 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004591 SourceLocation(),
4592 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004593 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004594 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004595 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004596 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004597 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004598 T->addDecl(Field);
4599 }
4600
Douglas Gregor838db382010-02-11 01:19:42 +00004601 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004602
4603 BlockDescriptorExtendedType = T;
4604
4605 return getTagDeclType(BlockDescriptorExtendedType);
4606}
4607
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004608/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4609/// requires copy/dispose. Note that this must match the logic
4610/// in buildByrefHelpers.
4611bool ASTContext::BlockRequiresCopying(QualType Ty,
4612 const VarDecl *D) {
4613 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4614 const Expr *copyExpr = getBlockVarCopyInits(D);
4615 if (!copyExpr && record->hasTrivialDestructor()) return false;
4616
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004617 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004618 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004619
4620 if (!Ty->isObjCRetainableType()) return false;
4621
4622 Qualifiers qs = Ty.getQualifiers();
4623
4624 // If we have lifetime, that dominates.
4625 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4626 assert(getLangOpts().ObjCAutoRefCount);
4627
4628 switch (lifetime) {
4629 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4630
4631 // These are just bits as far as the runtime is concerned.
4632 case Qualifiers::OCL_ExplicitNone:
4633 case Qualifiers::OCL_Autoreleasing:
4634 return false;
4635
4636 // Tell the runtime that this is ARC __weak, called by the
4637 // byref routines.
4638 case Qualifiers::OCL_Weak:
4639 // ARC __strong __block variables need to be retained.
4640 case Qualifiers::OCL_Strong:
4641 return true;
4642 }
4643 llvm_unreachable("fell out of lifetime switch!");
4644 }
4645 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4646 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004647}
4648
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004649bool ASTContext::getByrefLifetime(QualType Ty,
4650 Qualifiers::ObjCLifetime &LifeTime,
4651 bool &HasByrefExtendedLayout) const {
4652
4653 if (!getLangOpts().ObjC1 ||
4654 getLangOpts().getGC() != LangOptions::NonGC)
4655 return false;
4656
4657 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004658 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004659 HasByrefExtendedLayout = true;
4660 LifeTime = Qualifiers::OCL_None;
4661 }
4662 else if (getLangOpts().ObjCAutoRefCount)
4663 LifeTime = Ty.getObjCLifetime();
4664 // MRR.
4665 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4666 LifeTime = Qualifiers::OCL_ExplicitNone;
4667 else
4668 LifeTime = Qualifiers::OCL_None;
4669 return true;
4670}
4671
Douglas Gregore97179c2011-09-08 01:46:34 +00004672TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4673 if (!ObjCInstanceTypeDecl)
4674 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4675 getTranslationUnitDecl(),
4676 SourceLocation(),
4677 SourceLocation(),
4678 &Idents.get("instancetype"),
4679 getTrivialTypeSourceInfo(getObjCIdType()));
4680 return ObjCInstanceTypeDecl;
4681}
4682
Anders Carlssone8c49532007-10-29 06:33:42 +00004683// This returns true if a type has been typedefed to BOOL:
4684// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004685static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004686 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004687 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4688 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004689
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004690 return false;
4691}
4692
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004693/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004694/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004695CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004696 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4697 return CharUnits::Zero();
4698
Ken Dyck199c3d62010-01-11 17:06:35 +00004699 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004701 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004702 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004703 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004704 // Treat arrays as pointers, since that's how they're passed in.
4705 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004706 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004707 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004708}
4709
4710static inline
4711std::string charUnitsToString(const CharUnits &CU) {
4712 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004713}
4714
John McCall6b5a61b2011-02-07 10:33:21 +00004715/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004716/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004717std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4718 std::string S;
4719
David Chisnall5e530af2009-11-17 19:33:30 +00004720 const BlockDecl *Decl = Expr->getBlockDecl();
4721 QualType BlockTy =
4722 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4723 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004724 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004725 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4726 BlockTy->getAs<FunctionType>()->getResultType(),
4727 S, true /*Extended*/);
4728 else
4729 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4730 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004731 // Compute size of all parameters.
4732 // Start with computing size of a pointer in number of bytes.
4733 // FIXME: There might(should) be a better way of doing this computation!
4734 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004735 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4736 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004737 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004738 E = Decl->param_end(); PI != E; ++PI) {
4739 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004740 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004741 if (sz.isZero())
4742 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004743 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004744 ParmOffset += sz;
4745 }
4746 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004747 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004748 // Block pointer and offset.
4749 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004750
4751 // Argument types.
4752 ParmOffset = PtrSize;
4753 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4754 Decl->param_end(); PI != E; ++PI) {
4755 ParmVarDecl *PVDecl = *PI;
4756 QualType PType = PVDecl->getOriginalType();
4757 if (const ArrayType *AT =
4758 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4759 // Use array's original type only if it has known number of
4760 // elements.
4761 if (!isa<ConstantArrayType>(AT))
4762 PType = PVDecl->getType();
4763 } else if (PType->isFunctionType())
4764 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004765 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004766 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4767 S, true /*Extended*/);
4768 else
4769 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004770 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004771 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004772 }
John McCall6b5a61b2011-02-07 10:33:21 +00004773
4774 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004775}
4776
Douglas Gregorf968d832011-05-27 01:19:52 +00004777bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004778 std::string& S) {
4779 // Encode result type.
4780 getObjCEncodingForType(Decl->getResultType(), S);
4781 CharUnits ParmOffset;
4782 // Compute size of all parameters.
4783 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4784 E = Decl->param_end(); PI != E; ++PI) {
4785 QualType PType = (*PI)->getType();
4786 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004787 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004788 continue;
4789
David Chisnall5389f482010-12-30 14:05:53 +00004790 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004791 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004792 ParmOffset += sz;
4793 }
4794 S += charUnitsToString(ParmOffset);
4795 ParmOffset = CharUnits::Zero();
4796
4797 // Argument types.
4798 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4799 E = Decl->param_end(); PI != E; ++PI) {
4800 ParmVarDecl *PVDecl = *PI;
4801 QualType PType = PVDecl->getOriginalType();
4802 if (const ArrayType *AT =
4803 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4804 // Use array's original type only if it has known number of
4805 // elements.
4806 if (!isa<ConstantArrayType>(AT))
4807 PType = PVDecl->getType();
4808 } else if (PType->isFunctionType())
4809 PType = PVDecl->getType();
4810 getObjCEncodingForType(PType, S);
4811 S += charUnitsToString(ParmOffset);
4812 ParmOffset += getObjCEncodingTypeSize(PType);
4813 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004814
4815 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004816}
4817
Bob Wilsondc8dab62011-11-30 01:57:58 +00004818/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4819/// method parameter or return type. If Extended, include class names and
4820/// block object types.
4821void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4822 QualType T, std::string& S,
4823 bool Extended) const {
4824 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4825 getObjCEncodingForTypeQualifier(QT, S);
4826 // Encode parameter type.
4827 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4828 true /*OutermostType*/,
4829 false /*EncodingProperty*/,
4830 false /*StructField*/,
4831 Extended /*EncodeBlockParameters*/,
4832 Extended /*EncodeClassNames*/);
4833}
4834
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004835/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004836/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004837bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004838 std::string& S,
4839 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004840 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004841 // Encode return type.
4842 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4843 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004844 // Compute size of all parameters.
4845 // Start with computing size of a pointer in number of bytes.
4846 // FIXME: There might(should) be a better way of doing this computation!
4847 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004848 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004849 // The first two arguments (self and _cmd) are pointers; account for
4850 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004851 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004852 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004853 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004854 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004855 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004856 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004857 continue;
4858
Ken Dyck199c3d62010-01-11 17:06:35 +00004859 assert (sz.isPositive() &&
4860 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004861 ParmOffset += sz;
4862 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004863 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004864 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004865 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004866
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004867 // Argument types.
4868 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004869 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004870 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004871 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004872 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004873 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004874 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4875 // Use array's original type only if it has known number of
4876 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004877 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004878 PType = PVDecl->getType();
4879 } else if (PType->isFunctionType())
4880 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004881 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4882 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004883 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004884 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004885 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004886
4887 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004888}
4889
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004890/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004891/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004892/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4893/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004894/// Property attributes are stored as a comma-delimited C string. The simple
4895/// attributes readonly and bycopy are encoded as single characters. The
4896/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4897/// encoded as single characters, followed by an identifier. Property types
4898/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004899/// these attributes are defined by the following enumeration:
4900/// @code
4901/// enum PropertyAttributes {
4902/// kPropertyReadOnly = 'R', // property is read-only.
4903/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4904/// kPropertyByref = '&', // property is a reference to the value last assigned
4905/// kPropertyDynamic = 'D', // property is dynamic
4906/// kPropertyGetter = 'G', // followed by getter selector name
4907/// kPropertySetter = 'S', // followed by setter selector name
4908/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004909/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004910/// kPropertyWeak = 'W' // 'weak' property
4911/// kPropertyStrong = 'P' // property GC'able
4912/// kPropertyNonAtomic = 'N' // property non-atomic
4913/// };
4914/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004915void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004916 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004917 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004918 // Collect information from the property implementation decl(s).
4919 bool Dynamic = false;
4920 ObjCPropertyImplDecl *SynthesizePID = 0;
4921
4922 // FIXME: Duplicated code due to poor abstraction.
4923 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004924 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004925 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4926 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004927 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004928 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004929 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004930 if (PID->getPropertyDecl() == PD) {
4931 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4932 Dynamic = true;
4933 } else {
4934 SynthesizePID = PID;
4935 }
4936 }
4937 }
4938 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004939 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004940 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004941 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004942 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004943 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004944 if (PID->getPropertyDecl() == PD) {
4945 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4946 Dynamic = true;
4947 } else {
4948 SynthesizePID = PID;
4949 }
4950 }
Mike Stump1eb44332009-09-09 15:08:12 +00004951 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004952 }
4953 }
4954
4955 // FIXME: This is not very efficient.
4956 S = "T";
4957
4958 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004959 // GCC has some special rules regarding encoding of properties which
4960 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004961 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004962 true /* outermost type */,
4963 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004964
4965 if (PD->isReadOnly()) {
4966 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004967 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4968 S += ",C";
4969 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4970 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004971 } else {
4972 switch (PD->getSetterKind()) {
4973 case ObjCPropertyDecl::Assign: break;
4974 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004975 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004976 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004977 }
4978 }
4979
4980 // It really isn't clear at all what this means, since properties
4981 // are "dynamic by default".
4982 if (Dynamic)
4983 S += ",D";
4984
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004985 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4986 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004987
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004988 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4989 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004990 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004991 }
4992
4993 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4994 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004995 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004996 }
4997
4998 if (SynthesizePID) {
4999 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5000 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00005001 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005002 }
5003
5004 // FIXME: OBJCGC: weak & strong
5005}
5006
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005007/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005008/// Another legacy compatibility encoding: 32-bit longs are encoded as
5009/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005010/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5011///
5012void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005013 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005014 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005015 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005016 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005017 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005018 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005019 PointeeTy = IntTy;
5020 }
5021 }
5022}
5023
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005024void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005025 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005026 // We follow the behavior of gcc, expanding structures which are
5027 // directly pointed to, and expanding embedded structures. Note that
5028 // these rules are sufficient to prevent recursive encoding of the
5029 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005030 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005031 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005032}
5033
John McCall3624e9e2012-12-20 02:45:14 +00005034static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5035 BuiltinType::Kind kind) {
5036 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005037 case BuiltinType::Void: return 'v';
5038 case BuiltinType::Bool: return 'B';
5039 case BuiltinType::Char_U:
5040 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005041 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005042 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005043 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005044 case BuiltinType::UInt: return 'I';
5045 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005046 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005047 case BuiltinType::UInt128: return 'T';
5048 case BuiltinType::ULongLong: return 'Q';
5049 case BuiltinType::Char_S:
5050 case BuiltinType::SChar: return 'c';
5051 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005052 case BuiltinType::WChar_S:
5053 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005054 case BuiltinType::Int: return 'i';
5055 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005056 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005057 case BuiltinType::LongLong: return 'q';
5058 case BuiltinType::Int128: return 't';
5059 case BuiltinType::Float: return 'f';
5060 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005061 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005062 case BuiltinType::NullPtr: return '*'; // like char*
5063
5064 case BuiltinType::Half:
5065 // FIXME: potentially need @encodes for these!
5066 return ' ';
5067
5068 case BuiltinType::ObjCId:
5069 case BuiltinType::ObjCClass:
5070 case BuiltinType::ObjCSel:
5071 llvm_unreachable("@encoding ObjC primitive type");
5072
5073 // OpenCL and placeholder types don't need @encodings.
5074 case BuiltinType::OCLImage1d:
5075 case BuiltinType::OCLImage1dArray:
5076 case BuiltinType::OCLImage1dBuffer:
5077 case BuiltinType::OCLImage2d:
5078 case BuiltinType::OCLImage2dArray:
5079 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005080 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005081 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005082 case BuiltinType::Dependent:
5083#define BUILTIN_TYPE(KIND, ID)
5084#define PLACEHOLDER_TYPE(KIND, ID) \
5085 case BuiltinType::KIND:
5086#include "clang/AST/BuiltinTypes.def"
5087 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005088 }
David Blaikie719e53f2013-01-09 17:48:41 +00005089 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005090}
5091
Douglas Gregor5471bc82011-09-08 17:18:35 +00005092static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5093 EnumDecl *Enum = ET->getDecl();
5094
5095 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5096 if (!Enum->isFixed())
5097 return 'i';
5098
5099 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005100 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5101 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005102}
5103
Jay Foad4ba2a172011-01-12 09:06:06 +00005104static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005105 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005106 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005107 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005108 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5109 // The GNU runtime requires more information; bitfields are encoded as b,
5110 // then the offset (in bits) of the first element, then the type of the
5111 // bitfield, then the size in bits. For example, in this structure:
5112 //
5113 // struct
5114 // {
5115 // int integer;
5116 // int flags:2;
5117 // };
5118 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5119 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5120 // information is not especially sensible, but we're stuck with it for
5121 // compatibility with GCC, although providing it breaks anything that
5122 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005123 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005124 const RecordDecl *RD = FD->getParent();
5125 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005126 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005127 if (const EnumType *ET = T->getAs<EnumType>())
5128 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005129 else {
5130 const BuiltinType *BT = T->castAs<BuiltinType>();
5131 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5132 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005133 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005134 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005135}
5136
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005137// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005138void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5139 bool ExpandPointedToStructures,
5140 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005141 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005142 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005143 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005144 bool StructField,
5145 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005146 bool EncodeClassNames,
5147 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005148 CanQualType CT = getCanonicalType(T);
5149 switch (CT->getTypeClass()) {
5150 case Type::Builtin:
5151 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005152 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005153 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005154 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5155 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5156 else
5157 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005158 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005159
John McCall3624e9e2012-12-20 02:45:14 +00005160 case Type::Complex: {
5161 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005162 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005163 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005164 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005165 return;
5166 }
John McCall3624e9e2012-12-20 02:45:14 +00005167
5168 case Type::Atomic: {
5169 const AtomicType *AT = T->castAs<AtomicType>();
5170 S += 'A';
5171 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5172 false, false);
5173 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005174 }
John McCall3624e9e2012-12-20 02:45:14 +00005175
5176 // encoding for pointer or reference types.
5177 case Type::Pointer:
5178 case Type::LValueReference:
5179 case Type::RValueReference: {
5180 QualType PointeeTy;
5181 if (isa<PointerType>(CT)) {
5182 const PointerType *PT = T->castAs<PointerType>();
5183 if (PT->isObjCSelType()) {
5184 S += ':';
5185 return;
5186 }
5187 PointeeTy = PT->getPointeeType();
5188 } else {
5189 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5190 }
5191
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005192 bool isReadOnly = false;
5193 // For historical/compatibility reasons, the read-only qualifier of the
5194 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5195 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005196 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005197 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005198 if (OutermostType && T.isConstQualified()) {
5199 isReadOnly = true;
5200 S += 'r';
5201 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005202 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005203 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005204 while (P->getAs<PointerType>())
5205 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005206 if (P.isConstQualified()) {
5207 isReadOnly = true;
5208 S += 'r';
5209 }
5210 }
5211 if (isReadOnly) {
5212 // Another legacy compatibility encoding. Some ObjC qualifier and type
5213 // combinations need to be rearranged.
5214 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005215 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005216 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005217 }
Mike Stump1eb44332009-09-09 15:08:12 +00005218
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005219 if (PointeeTy->isCharType()) {
5220 // char pointer types should be encoded as '*' unless it is a
5221 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005222 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005223 S += '*';
5224 return;
5225 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005226 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005227 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5228 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5229 S += '#';
5230 return;
5231 }
5232 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5233 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5234 S += '@';
5235 return;
5236 }
5237 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005238 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005239 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005240 getLegacyIntegralTypeEncoding(PointeeTy);
5241
Mike Stump1eb44332009-09-09 15:08:12 +00005242 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005243 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005244 return;
5245 }
John McCall3624e9e2012-12-20 02:45:14 +00005246
5247 case Type::ConstantArray:
5248 case Type::IncompleteArray:
5249 case Type::VariableArray: {
5250 const ArrayType *AT = cast<ArrayType>(CT);
5251
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005252 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005253 // Incomplete arrays are encoded as a pointer to the array element.
5254 S += '^';
5255
Mike Stump1eb44332009-09-09 15:08:12 +00005256 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005257 false, ExpandStructures, FD);
5258 } else {
5259 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005260
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005261 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5262 S += llvm::utostr(CAT->getSize().getZExtValue());
5263 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005264 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005265 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5266 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005267 S += '0';
5268 }
Mike Stump1eb44332009-09-09 15:08:12 +00005269
5270 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005271 false, ExpandStructures, FD);
5272 S += ']';
5273 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005274 return;
5275 }
Mike Stump1eb44332009-09-09 15:08:12 +00005276
John McCall3624e9e2012-12-20 02:45:14 +00005277 case Type::FunctionNoProto:
5278 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005279 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005280 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005281
John McCall3624e9e2012-12-20 02:45:14 +00005282 case Type::Record: {
5283 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005284 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005285 // Anonymous structures print as '?'
5286 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5287 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005288 if (ClassTemplateSpecializationDecl *Spec
5289 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5290 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005291 llvm::raw_string_ostream OS(S);
5292 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005293 TemplateArgs.data(),
5294 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005295 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005296 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005297 } else {
5298 S += '?';
5299 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005300 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005301 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005302 if (!RDecl->isUnion()) {
5303 getObjCEncodingForStructureImpl(RDecl, S, FD);
5304 } else {
5305 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5306 FieldEnd = RDecl->field_end();
5307 Field != FieldEnd; ++Field) {
5308 if (FD) {
5309 S += '"';
5310 S += Field->getNameAsString();
5311 S += '"';
5312 }
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005314 // Special case bit-fields.
5315 if (Field->isBitField()) {
5316 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005317 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005318 } else {
5319 QualType qt = Field->getType();
5320 getLegacyIntegralTypeEncoding(qt);
5321 getObjCEncodingForTypeImpl(qt, S, false, true,
5322 FD, /*OutermostType*/false,
5323 /*EncodingProperty*/false,
5324 /*StructField*/true);
5325 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005326 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005327 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005328 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005329 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005330 return;
5331 }
Mike Stump1eb44332009-09-09 15:08:12 +00005332
John McCall3624e9e2012-12-20 02:45:14 +00005333 case Type::BlockPointer: {
5334 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005335 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005336 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005337 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005338
5339 S += '<';
5340 // Block return type
5341 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5342 ExpandPointedToStructures, ExpandStructures,
5343 FD,
5344 false /* OutermostType */,
5345 EncodingProperty,
5346 false /* StructField */,
5347 EncodeBlockParameters,
5348 EncodeClassNames);
5349 // Block self
5350 S += "@?";
5351 // Block parameters
5352 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5353 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5354 E = FPT->arg_type_end(); I && (I != E); ++I) {
5355 getObjCEncodingForTypeImpl(*I, S,
5356 ExpandPointedToStructures,
5357 ExpandStructures,
5358 FD,
5359 false /* OutermostType */,
5360 EncodingProperty,
5361 false /* StructField */,
5362 EncodeBlockParameters,
5363 EncodeClassNames);
5364 }
5365 }
5366 S += '>';
5367 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005368 return;
5369 }
Mike Stump1eb44332009-09-09 15:08:12 +00005370
John McCall3624e9e2012-12-20 02:45:14 +00005371 case Type::ObjCObject:
5372 case Type::ObjCInterface: {
5373 // Ignore protocol qualifiers when mangling at this level.
5374 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005375
John McCall3624e9e2012-12-20 02:45:14 +00005376 // The assumption seems to be that this assert will succeed
5377 // because nested levels will have filtered out 'id' and 'Class'.
5378 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005379 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005380 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005381 S += '{';
5382 const IdentifierInfo *II = OI->getIdentifier();
5383 S += II->getName();
5384 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005385 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005386 DeepCollectObjCIvars(OI, true, Ivars);
5387 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005388 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005389 if (Field->isBitField())
5390 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005391 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005392 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5393 false, false, false, false, false,
5394 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005395 }
5396 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005397 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005398 }
Mike Stump1eb44332009-09-09 15:08:12 +00005399
John McCall3624e9e2012-12-20 02:45:14 +00005400 case Type::ObjCObjectPointer: {
5401 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005402 if (OPT->isObjCIdType()) {
5403 S += '@';
5404 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005405 }
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Steve Naroff27d20a22009-10-28 22:03:49 +00005407 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5408 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5409 // Since this is a binary compatibility issue, need to consult with runtime
5410 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005411 S += '#';
5412 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005413 }
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005415 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005416 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005417 ExpandPointedToStructures,
5418 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005419 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005420 // Note that we do extended encoding of protocol qualifer list
5421 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005422 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005423 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5424 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005425 S += '<';
5426 S += (*I)->getNameAsString();
5427 S += '>';
5428 }
5429 S += '"';
5430 }
5431 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005432 }
Mike Stump1eb44332009-09-09 15:08:12 +00005433
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005434 QualType PointeeTy = OPT->getPointeeType();
5435 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005436 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5437 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005438 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005439 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005440 // {...};
5441 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005442 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005443 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005444 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5445 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5446 DeepCollectObjCIvars(OI, true, Ivars);
5447 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5448 if (cast<FieldDecl>(Ivars[i]) == FD) {
5449 S += '{';
5450 S += OI->getIdentifier()->getName();
5451 S += '}';
5452 return;
5453 }
5454 }
5455 }
Mike Stump1eb44332009-09-09 15:08:12 +00005456 getObjCEncodingForTypeImpl(PointeeTy, S,
5457 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005458 NULL,
5459 false, false, false, false, false,
5460 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005461 return;
5462 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005463
5464 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005465 if (OPT->getInterfaceDecl() &&
5466 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005467 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005468 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005469 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5470 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005471 S += '<';
5472 S += (*I)->getNameAsString();
5473 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005474 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005475 S += '"';
5476 }
5477 return;
5478 }
Mike Stump1eb44332009-09-09 15:08:12 +00005479
John McCall532ec7b2010-05-17 23:56:34 +00005480 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005481 // FIXME: we shoul do better than that. 'M' is available.
5482 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005483 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005484
John McCall3624e9e2012-12-20 02:45:14 +00005485 case Type::Vector:
5486 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005487 // This matches gcc's encoding, even though technically it is
5488 // insufficient.
5489 // FIXME. We should do a better job than gcc.
5490 return;
John McCall3624e9e2012-12-20 02:45:14 +00005491
Richard Smithdc7a4f52013-04-30 13:56:41 +00005492 case Type::Auto:
5493 // We could see an undeduced auto type here during error recovery.
5494 // Just ignore it.
5495 return;
5496
John McCall3624e9e2012-12-20 02:45:14 +00005497#define ABSTRACT_TYPE(KIND, BASE)
5498#define TYPE(KIND, BASE)
5499#define DEPENDENT_TYPE(KIND, BASE) \
5500 case Type::KIND:
5501#define NON_CANONICAL_TYPE(KIND, BASE) \
5502 case Type::KIND:
5503#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5504 case Type::KIND:
5505#include "clang/AST/TypeNodes.def"
5506 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005507 }
John McCall3624e9e2012-12-20 02:45:14 +00005508 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005509}
5510
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005511void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5512 std::string &S,
5513 const FieldDecl *FD,
5514 bool includeVBases) const {
5515 assert(RDecl && "Expected non-null RecordDecl");
5516 assert(!RDecl->isUnion() && "Should not be called for unions");
5517 if (!RDecl->getDefinition())
5518 return;
5519
5520 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5521 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5522 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5523
5524 if (CXXRec) {
5525 for (CXXRecordDecl::base_class_iterator
5526 BI = CXXRec->bases_begin(),
5527 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5528 if (!BI->isVirtual()) {
5529 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005530 if (base->isEmpty())
5531 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005532 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005533 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5534 std::make_pair(offs, base));
5535 }
5536 }
5537 }
5538
5539 unsigned i = 0;
5540 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5541 FieldEnd = RDecl->field_end();
5542 Field != FieldEnd; ++Field, ++i) {
5543 uint64_t offs = layout.getFieldOffset(i);
5544 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005545 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005546 }
5547
5548 if (CXXRec && includeVBases) {
5549 for (CXXRecordDecl::base_class_iterator
5550 BI = CXXRec->vbases_begin(),
5551 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5552 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005553 if (base->isEmpty())
5554 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005555 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005556 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5557 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}