blob: 1b465312cc8d70aee5bdcb3e120145b47ab8b1fa [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"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000029#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000034#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000035#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000037#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000038#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000072 // User can not attach documentation to implicit instantiations.
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
75 return NULL;
76 }
77
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
79 if (VD->isStaticDataMember() &&
80 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
81 return NULL;
82 }
83
84 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
85 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 return NULL;
87 }
88
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000089 if (const ClassTemplateSpecializationDecl *CTSD =
90 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
91 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
92 if (TSK == TSK_ImplicitInstantiation ||
93 TSK == TSK_Undeclared)
94 return NULL;
95 }
96
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000097 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
98 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 return NULL;
100 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000101 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
102 // When tag declaration (but not definition!) is part of the
103 // decl-specifier-seq of some other declaration, it doesn't get comment
104 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
105 return NULL;
106 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000107 // TODO: handle comments for function parameters properly.
108 if (isa<ParmVarDecl>(D))
109 return NULL;
110
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000111 // TODO: we could look up template parameter documentation in the template
112 // documentation.
113 if (isa<TemplateTypeParmDecl>(D) ||
114 isa<NonTypeTemplateParmDecl>(D) ||
115 isa<TemplateTemplateParmDecl>(D))
116 return NULL;
117
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000118 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000119
120 // If there are no comments anywhere, we won't find anything.
121 if (RawComments.empty())
122 return NULL;
123
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000124 // Find declaration location.
125 // For Objective-C declarations we generally don't expect to have multiple
126 // declarators, thus use declaration starting location as the "declaration
127 // location".
128 // For all other declarations multiple declarators are used quite frequently,
129 // so we use the location of the identifier as the "declaration location".
130 SourceLocation DeclLoc;
131 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000132 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000133 isa<RedeclarableTemplateDecl>(D) ||
134 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000135 DeclLoc = D->getLocStart();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000136 else {
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000137 DeclLoc = D->getLocation();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000138 // If location of the typedef name is in a macro, it is because being
139 // declared via a macro. Try using declaration's starting location
140 // as the "declaration location".
141 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
142 DeclLoc = D->getLocStart();
143 }
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000144
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000145 // If the declaration doesn't map directly to a location in a file, we
146 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000147 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
148 return NULL;
149
150 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000151 ArrayRef<RawComment *>::iterator Comment;
152 {
153 // When searching for comments during parsing, the comment we are looking
154 // for is usually among the last two comments we parsed -- check them
155 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000156 RawComment CommentAtDeclLoc(
157 SourceMgr, SourceRange(DeclLoc), false,
158 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000159 BeforeThanCompare<RawComment> Compare(SourceMgr);
160 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
161 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
162 if (!Found && RawComments.size() >= 2) {
163 MaybeBeforeDecl--;
164 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 }
166
167 if (Found) {
168 Comment = MaybeBeforeDecl + 1;
169 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
170 &CommentAtDeclLoc, Compare));
171 } else {
172 // Slow path.
173 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
174 &CommentAtDeclLoc, Compare);
175 }
176 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000177
178 // Decompose the location for the declaration and find the beginning of the
179 // file buffer.
180 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
181
182 // First check whether we have a trailing comment.
183 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000184 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000185 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000186 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000187 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000188 // Check that Doxygen trailing comment comes after the declaration, starts
189 // on the same line and in the same file as the declaration.
190 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
191 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
192 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
193 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000194 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000195 }
196 }
197
198 // The comment just after the declaration was not a trailing comment.
199 // Let's look at the previous comment.
200 if (Comment == RawComments.begin())
201 return NULL;
202 --Comment;
203
204 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000205 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000206 return NULL;
207
208 // Decompose the end of the comment.
209 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000211
212 // If the comment and the declaration aren't in the same file, then they
213 // aren't related.
214 if (DeclLocDecomp.first != CommentEndDecomp.first)
215 return NULL;
216
217 // Get the corresponding buffer.
218 bool Invalid = false;
219 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
220 &Invalid).data();
221 if (Invalid)
222 return NULL;
223
224 // Extract text between the comment and declaration.
225 StringRef Text(Buffer + CommentEndDecomp.second,
226 DeclLocDecomp.second - CommentEndDecomp.second);
227
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000228 // There should be no other declarations or preprocessor directives between
229 // comment and declaration.
Argyrios Kyrtzidisdc663262013-07-26 18:38:12 +0000230 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000231 return NULL;
232
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000233 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000234}
235
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000236namespace {
237/// If we have a 'templated' declaration for a template, adjust 'D' to
238/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000239/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000240const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000241 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000242 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000243 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000244 return FTD;
245
246 // Nothing to do if function is not an implicit instantiation.
247 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
248 return D;
249
250 // Function is an implicit instantiation of a function template?
251 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
252 return FTD;
253
254 // Function is instantiated from a member definition of a class template?
255 if (const FunctionDecl *MemberDecl =
256 FD->getInstantiatedFromMemberFunction())
257 return MemberDecl;
258
259 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000260 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000261 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
262 // Static data member is instantiated from a member definition of a class
263 // template?
264 if (VD->isStaticDataMember())
265 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
266 return MemberDecl;
267
268 return D;
269 }
270 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
271 // Is this class declaration part of a class template?
272 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
273 return CTD;
274
275 // Class is an implicit instantiation of a class template or partial
276 // specialization?
277 if (const ClassTemplateSpecializationDecl *CTSD =
278 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
279 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
280 return D;
281 llvm::PointerUnion<ClassTemplateDecl *,
282 ClassTemplatePartialSpecializationDecl *>
283 PU = CTSD->getSpecializedTemplateOrPartial();
284 return PU.is<ClassTemplateDecl*>() ?
285 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
286 static_cast<const Decl*>(
287 PU.get<ClassTemplatePartialSpecializationDecl *>());
288 }
289
290 // Class is instantiated from a member definition of a class template?
291 if (const MemberSpecializationInfo *Info =
292 CRD->getMemberSpecializationInfo())
293 return Info->getInstantiatedFrom();
294
295 return D;
296 }
297 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
298 // Enum is instantiated from a member definition of a class template?
299 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
300 return MemberDecl;
301
302 return D;
303 }
304 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000305 return D;
306}
307} // unnamed namespace
308
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000309const RawComment *ASTContext::getRawCommentForAnyRedecl(
310 const Decl *D,
311 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000312 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000313
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000314 // Check whether we have cached a comment for this declaration already.
315 {
316 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
317 RedeclComments.find(D);
318 if (Pos != RedeclComments.end()) {
319 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000320 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
321 if (OriginalDecl)
322 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000323 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000324 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000326 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000327
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000328 // Search for comments attached to declarations in the redeclaration chain.
329 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000330 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000331 for (Decl::redecl_iterator I = D->redecls_begin(),
332 E = D->redecls_end();
333 I != E; ++I) {
334 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
335 RedeclComments.find(*I);
336 if (Pos != RedeclComments.end()) {
337 const RawCommentAndCacheFlags &Raw = Pos->second;
338 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
339 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000340 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000341 break;
342 }
343 } else {
344 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000345 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000346 RawCommentAndCacheFlags Raw;
347 if (RC) {
348 Raw.setRaw(RC);
349 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
350 } else
351 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000352 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000353 RedeclComments[*I] = Raw;
354 if (RC)
355 break;
356 }
357 }
358
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000359 // If we found a comment, it should be a documentation comment.
360 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000361
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000362 if (OriginalDecl)
363 *OriginalDecl = OriginalDeclForRC;
364
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000365 // Update cache for every declaration in the redeclaration chain.
366 RawCommentAndCacheFlags Raw;
367 Raw.setRaw(RC);
368 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000369 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000370
371 for (Decl::redecl_iterator I = D->redecls_begin(),
372 E = D->redecls_end();
373 I != E; ++I) {
374 RawCommentAndCacheFlags &R = RedeclComments[*I];
375 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
376 R = Raw;
377 }
378
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000379 return RC;
380}
381
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000382static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
383 SmallVectorImpl<const NamedDecl *> &Redeclared) {
384 const DeclContext *DC = ObjCMethod->getDeclContext();
385 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
386 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
387 if (!ID)
388 return;
389 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000390 for (ObjCInterfaceDecl::known_extensions_iterator
391 Ext = ID->known_extensions_begin(),
392 ExtEnd = ID->known_extensions_end();
393 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000394 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000395 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000396 ObjCMethod->isInstanceMethod()))
397 Redeclared.push_back(RedeclaredMethod);
398 }
399 }
400}
401
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000402comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
403 const Decl *D) const {
404 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
405 ThisDeclInfo->CommentDecl = D;
406 ThisDeclInfo->IsFilled = false;
407 ThisDeclInfo->fill();
408 ThisDeclInfo->CommentDecl = FC->getDecl();
409 comments::FullComment *CFC =
410 new (*this) comments::FullComment(FC->getBlocks(),
411 ThisDeclInfo);
412 return CFC;
413
414}
415
Richard Smith0a74a4c2013-05-21 05:24:00 +0000416comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
417 const RawComment *RC = getRawCommentForDeclNoCache(D);
418 return RC ? RC->parse(*this, 0, D) : 0;
419}
420
Dmitri Gribenko19523542012-09-29 11:40:46 +0000421comments::FullComment *ASTContext::getCommentForDecl(
422 const Decl *D,
423 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000424 if (D->isInvalidDecl())
425 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000426 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000427
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000428 const Decl *Canonical = D->getCanonicalDecl();
429 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
430 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000431
432 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000433 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000434 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000435 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436 return CFC;
437 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000438 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000439 }
440
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000441 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000442
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000443 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000444 if (!RC) {
445 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000446 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000447 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000448 if (OMD && OMD->isPropertyAccessor())
449 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
450 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000452 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000453 addRedeclaredMethods(OMD, Overridden);
454 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000455 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
456 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
457 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000458 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000459 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000460 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000461 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000462 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000463 if (const TagType *TT = QT->getAs<TagType>())
464 if (const Decl *TD = TT->getDecl())
465 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000466 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000467 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000468 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
469 while (IC->getSuperClass()) {
470 IC = IC->getSuperClass();
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 }
475 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
476 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
477 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
478 return cloneFullComment(FC, D);
479 }
480 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
481 if (!(RD = RD->getDefinition()))
482 return NULL;
483 // Check non-virtual bases.
484 for (CXXRecordDecl::base_class_const_iterator I =
485 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000486 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000487 continue;
488 QualType Ty = I->getType();
489 if (Ty.isNull())
490 continue;
491 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
492 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
493 continue;
494
495 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
496 return cloneFullComment(FC, D);
497 }
498 }
499 // Check virtual bases.
500 for (CXXRecordDecl::base_class_const_iterator I =
501 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000502 if (I->getAccessSpecifier() != AS_public)
503 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000504 QualType Ty = I->getType();
505 if (Ty.isNull())
506 continue;
507 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
508 if (!(VirtualBase= VirtualBase->getDefinition()))
509 continue;
510 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
511 return cloneFullComment(FC, D);
512 }
513 }
514 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000515 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000516 }
517
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000518 // If the RawComment was attached to other redeclaration of this Decl, we
519 // should parse the comment in context of that other Decl. This is important
520 // because comments can contain references to parameter names which can be
521 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000522 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000523 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000524
Dmitri Gribenko19523542012-09-29 11:40:46 +0000525 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000526 ParsedComments[Canonical] = FC;
527 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000528}
529
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000530void
531ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
532 TemplateTemplateParmDecl *Parm) {
533 ID.AddInteger(Parm->getDepth());
534 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000535 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000536
537 TemplateParameterList *Params = Parm->getTemplateParameters();
538 ID.AddInteger(Params->size());
539 for (TemplateParameterList::const_iterator P = Params->begin(),
540 PEnd = Params->end();
541 P != PEnd; ++P) {
542 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
543 ID.AddInteger(0);
544 ID.AddBoolean(TTP->isParameterPack());
545 continue;
546 }
547
548 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
549 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000550 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000551 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000552 if (NTTP->isExpandedParameterPack()) {
553 ID.AddBoolean(true);
554 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000555 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
556 QualType T = NTTP->getExpansionType(I);
557 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
558 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000559 } else
560 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000561 continue;
562 }
563
564 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
565 ID.AddInteger(2);
566 Profile(ID, TTP);
567 }
568}
569
570TemplateTemplateParmDecl *
571ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000572 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000573 // Check if we already have a canonical template template parameter.
574 llvm::FoldingSetNodeID ID;
575 CanonicalTemplateTemplateParm::Profile(ID, TTP);
576 void *InsertPos = 0;
577 CanonicalTemplateTemplateParm *Canonical
578 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
579 if (Canonical)
580 return Canonical->getParam();
581
582 // Build a canonical template parameter list.
583 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000585 CanonParams.reserve(Params->size());
586 for (TemplateParameterList::const_iterator P = Params->begin(),
587 PEnd = Params->end();
588 P != PEnd; ++P) {
589 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
590 CanonParams.push_back(
591 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000592 SourceLocation(),
593 SourceLocation(),
594 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000595 TTP->getIndex(), 0, false,
596 TTP->isParameterPack()));
597 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000598 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
599 QualType T = getCanonicalType(NTTP->getType());
600 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
601 NonTypeTemplateParmDecl *Param;
602 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000603 SmallVector<QualType, 2> ExpandedTypes;
604 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000605 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
606 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
607 ExpandedTInfos.push_back(
608 getTrivialTypeSourceInfo(ExpandedTypes.back()));
609 }
610
611 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000612 SourceLocation(),
613 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000614 NTTP->getDepth(),
615 NTTP->getPosition(), 0,
616 T,
617 TInfo,
618 ExpandedTypes.data(),
619 ExpandedTypes.size(),
620 ExpandedTInfos.data());
621 } else {
622 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000623 SourceLocation(),
624 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000625 NTTP->getDepth(),
626 NTTP->getPosition(), 0,
627 T,
628 NTTP->isParameterPack(),
629 TInfo);
630 }
631 CanonParams.push_back(Param);
632
633 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000634 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
635 cast<TemplateTemplateParmDecl>(*P)));
636 }
637
638 TemplateTemplateParmDecl *CanonTTP
639 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
640 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000641 TTP->getPosition(),
642 TTP->isParameterPack(),
643 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000644 TemplateParameterList::Create(*this, SourceLocation(),
645 SourceLocation(),
646 CanonParams.data(),
647 CanonParams.size(),
648 SourceLocation()));
649
650 // Get the new insert position for the node we care about.
651 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
652 assert(Canonical == 0 && "Shouldn't be in the map!");
653 (void)Canonical;
654
655 // Create the canonical template template parameter entry.
656 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
657 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
658 return CanonTTP;
659}
660
Charles Davis071cc7d2010-08-16 03:33:14 +0000661CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000662 if (!LangOpts.CPlusPlus) return 0;
663
John McCallb8b2c9d2013-01-25 22:30:49 +0000664 switch (T.getCXXABI().getKind()) {
665 case TargetCXXABI::GenericARM:
666 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000667 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000668 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000669 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000670 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000671 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000672 return CreateMicrosoftCXXABI(*this);
673 }
David Blaikie7530c032012-01-17 06:56:22 +0000674 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000675}
676
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000677static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000678 const LangOptions &LOpts) {
679 if (LOpts.FakeAddressSpaceMap) {
680 // The fake address space map must have a distinct entry for each
681 // language-specific address space.
682 static const unsigned FakeAddrSpaceMap[] = {
683 1, // opencl_global
684 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000685 3, // opencl_constant
686 4, // cuda_device
687 5, // cuda_constant
688 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000689 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000690 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000691 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000692 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000693 }
694}
695
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000696ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000697 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000698 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000699 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000700 unsigned size_reserve,
701 bool DelayInitialization)
702 : FunctionProtoTypes(this_()),
703 TemplateSpecializationTypes(this_()),
704 DependentTemplateSpecializationTypes(this_()),
705 SubstTemplateTemplateParmPacks(this_()),
706 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000707 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000708 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000709 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000710 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000711 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000713 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
714 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
715 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000716 NullTypeSourceInfo(QualType()),
717 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000718 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000719 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000720 Idents(idents), Selectors(sels),
721 BuiltinInfo(builtins),
722 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000723 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000724 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000725 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000726 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000727{
Mike Stump1eb44332009-09-09 15:08:12 +0000728 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000730
731 if (!DelayInitialization) {
732 assert(t && "No target supplied for ASTContext initialization");
733 InitBuiltinTypes(*t);
734 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000735}
736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000738 // Release the DenseMaps associated with DeclContext objects.
739 // FIXME: Is this the ideal solution?
740 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000741
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000742 // Call all of the deallocation functions on all of their targets.
743 for (DeallocationMap::const_iterator I = Deallocations.begin(),
744 E = Deallocations.end(); I != E; ++I)
745 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
746 (I->first)((I->second)[J]);
747
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000748 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000749 // because they can contain DenseMaps.
750 for (llvm::DenseMap<const ObjCContainerDecl*,
751 const ASTRecordLayout*>::iterator
752 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
753 // Increment in loop to prevent using deallocated memory.
754 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
755 R->Destroy(*this);
756
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000757 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
758 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
759 // Increment in loop to prevent using deallocated memory.
760 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
761 R->Destroy(*this);
762 }
Douglas Gregor63200642010-08-30 16:49:28 +0000763
764 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
765 AEnd = DeclAttrs.end();
766 A != AEnd; ++A)
767 A->second->~AttrVec();
768}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000769
Douglas Gregor00545312010-05-23 18:26:36 +0000770void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000771 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000772}
773
Mike Stump1eb44332009-09-09 15:08:12 +0000774void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000775ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000776 ExternalSource.reset(Source.take());
777}
778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000780 llvm::errs() << "\n*** AST Context Stats:\n";
781 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000782
Douglas Gregordbe833d2009-05-26 14:40:08 +0000783 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000784#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000785#define ABSTRACT_TYPE(Name, Parent)
786#include "clang/AST/TypeNodes.def"
787 0 // Extra
788 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000789
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
791 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000792 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 }
794
Douglas Gregordbe833d2009-05-26 14:40:08 +0000795 unsigned Idx = 0;
796 unsigned TotalBytes = 0;
797#define TYPE(Name, Parent) \
798 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000799 llvm::errs() << " " << counts[Idx] << " " << #Name \
800 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000801 TotalBytes += counts[Idx] * sizeof(Name##Type); \
802 ++Idx;
803#define ABSTRACT_TYPE(Name, Parent)
804#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chandler Carruthcd92a652011-07-04 05:32:14 +0000806 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
807
Douglas Gregor4923aa22010-07-02 20:37:36 +0000808 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000809 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
810 << NumImplicitDefaultConstructors
811 << " implicit default constructors created\n";
812 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
813 << NumImplicitCopyConstructors
814 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000815 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000816 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
817 << NumImplicitMoveConstructors
818 << " implicit move constructors created\n";
819 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
820 << NumImplicitCopyAssignmentOperators
821 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000822 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000823 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
824 << NumImplicitMoveAssignmentOperators
825 << " implicit move assignment operators created\n";
826 llvm::errs() << NumImplicitDestructorsDeclared << "/"
827 << NumImplicitDestructors
828 << " implicit destructors created\n";
829
Douglas Gregor2cf26342009-04-09 22:27:44 +0000830 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000831 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000832 ExternalSource->PrintStats();
833 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000834
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000835 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000836}
837
Douglas Gregor772eeae2011-08-12 06:49:56 +0000838TypedefDecl *ASTContext::getInt128Decl() const {
839 if (!Int128Decl) {
840 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
841 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
842 getTranslationUnitDecl(),
843 SourceLocation(),
844 SourceLocation(),
845 &Idents.get("__int128_t"),
846 TInfo);
847 }
848
849 return Int128Decl;
850}
851
852TypedefDecl *ASTContext::getUInt128Decl() const {
853 if (!UInt128Decl) {
854 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
855 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
856 getTranslationUnitDecl(),
857 SourceLocation(),
858 SourceLocation(),
859 &Idents.get("__uint128_t"),
860 TInfo);
861 }
862
863 return UInt128Decl;
864}
Reid Spencer5f016e22007-07-11 17:01:13 +0000865
Nico Webercac18ad2013-06-20 21:44:55 +0000866TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000867 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000868 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000869 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
870 TTK_Struct,
871 getTranslationUnitDecl(),
872 SourceLocation(),
873 SourceLocation(),
874 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000875 }
876
877 return Float128StubDecl;
878}
879
John McCalle27ec8a2009-10-23 23:03:21 +0000880void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000881 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000882 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000883 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884}
885
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000886void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
887 assert((!this->Target || this->Target == &Target) &&
888 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000891 this->Target = &Target;
892
893 ABI.reset(createCXXABI(Target));
894 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
895
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 // C99 6.2.5p19.
897 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 // C99 6.2.5p2.
900 InitBuiltinType(BoolTy, BuiltinType::Bool);
901 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000902 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 InitBuiltinType(CharTy, BuiltinType::Char_S);
904 else
905 InitBuiltinType(CharTy, BuiltinType::Char_U);
906 // C99 6.2.5p4.
907 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
908 InitBuiltinType(ShortTy, BuiltinType::Short);
909 InitBuiltinType(IntTy, BuiltinType::Int);
910 InitBuiltinType(LongTy, BuiltinType::Long);
911 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 // C99 6.2.5p6.
914 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
915 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
916 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
917 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
918 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 // C99 6.2.5p10.
921 InitBuiltinType(FloatTy, BuiltinType::Float);
922 InitBuiltinType(DoubleTy, BuiltinType::Double);
923 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000924
Chris Lattner2df9ced2009-04-30 02:43:43 +0000925 // GNU extension, 128-bit integers.
926 InitBuiltinType(Int128Ty, BuiltinType::Int128);
927 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
928
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000929 // C++ 3.9.1p5
930 if (TargetInfo::isTypeSigned(Target.getWCharType()))
931 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
932 else // -fshort-wchar makes wchar_t be unsigned.
933 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
934 if (LangOpts.CPlusPlus && LangOpts.WChar)
935 WideCharTy = WCharTy;
936 else {
937 // C99 (or C++ using -fno-wchar).
938 WideCharTy = getFromTargetType(Target.getWCharType());
939 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000940
James Molloy392da482012-05-04 10:55:22 +0000941 WIntTy = getFromTargetType(Target.getWIntType());
942
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000943 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
944 InitBuiltinType(Char16Ty, BuiltinType::Char16);
945 else // C99
946 Char16Ty = getFromTargetType(Target.getChar16Type());
947
948 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
949 InitBuiltinType(Char32Ty, BuiltinType::Char32);
950 else // C99
951 Char32Ty = getFromTargetType(Target.getChar32Type());
952
Douglas Gregor898574e2008-12-05 23:32:09 +0000953 // Placeholder type for type-dependent expressions whose type is
954 // completely unknown. No code should ever check a type against
955 // DependentTy and users should never see it; however, it is here to
956 // help diagnose failures to properly check for type-dependent
957 // expressions.
958 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000959
John McCall2a984ca2010-10-12 00:20:44 +0000960 // Placeholder type for functions.
961 InitBuiltinType(OverloadTy, BuiltinType::Overload);
962
John McCall864c0412011-04-26 20:42:42 +0000963 // Placeholder type for bound members.
964 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
965
John McCall3c3b7f92011-10-25 17:37:35 +0000966 // Placeholder type for pseudo-objects.
967 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
968
John McCall1de4d4e2011-04-07 08:22:57 +0000969 // "any" type; useful for debugger-like clients.
970 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
971
John McCall0ddaeb92011-10-17 18:09:15 +0000972 // Placeholder type for unbridged ARC casts.
973 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
974
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000975 // Placeholder type for builtin functions.
976 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 // C99 6.2.5p11.
979 FloatComplexTy = getComplexType(FloatTy);
980 DoubleComplexTy = getComplexType(DoubleTy);
981 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000982
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000983 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000984 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
985 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000986 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000987
988 if (LangOpts.OpenCL) {
989 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
990 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
991 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
992 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
993 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
994 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000995
Guy Benyei21f18c42013-02-07 10:55:47 +0000996 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000997 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000998 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000999
1000 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001001 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1002 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001003
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001004 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001005
1006 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001008 // void * type
1009 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001010
1011 // nullptr type (C++0x 2.14.7)
1012 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001013
1014 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1015 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001016
1017 // Builtin type used to help define __builtin_va_list.
1018 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001019}
1020
David Blaikied6471f72011-09-25 23:23:43 +00001021DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001022 return SourceMgr.getDiagnostics();
1023}
1024
Douglas Gregor63200642010-08-30 16:49:28 +00001025AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1026 AttrVec *&Result = DeclAttrs[D];
1027 if (!Result) {
1028 void *Mem = Allocate(sizeof(AttrVec));
1029 Result = new (Mem) AttrVec;
1030 }
1031
1032 return *Result;
1033}
1034
1035/// \brief Erase the attributes corresponding to the given declaration.
1036void ASTContext::eraseDeclAttrs(const Decl *D) {
1037 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1038 if (Pos != DeclAttrs.end()) {
1039 Pos->second->~AttrVec();
1040 DeclAttrs.erase(Pos);
1041 }
1042}
1043
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001044MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001045ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001046 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001047 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001048 = InstantiatedFromStaticDataMember.find(Var);
1049 if (Pos == InstantiatedFromStaticDataMember.end())
1050 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Douglas Gregor7caa6822009-07-24 20:34:43 +00001052 return Pos->second;
1053}
1054
Mike Stump1eb44332009-09-09 15:08:12 +00001055void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001056ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001057 TemplateSpecializationKind TSK,
1058 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001059 assert(Inst->isStaticDataMember() && "Not a static data member");
1060 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1061 assert(!InstantiatedFromStaticDataMember[Inst] &&
1062 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001063 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001064 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001065}
1066
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001067FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1068 const FunctionDecl *FD){
1069 assert(FD && "Specialization is 0");
1070 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001071 = ClassScopeSpecializationPattern.find(FD);
1072 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001073 return 0;
1074
1075 return Pos->second;
1076}
1077
1078void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1079 FunctionDecl *Pattern) {
1080 assert(FD && "Specialization is 0");
1081 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001082 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001083}
1084
John McCall7ba107a2009-11-18 02:36:19 +00001085NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001086ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001087 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001088 = InstantiatedFromUsingDecl.find(UUD);
1089 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001090 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlsson0d8df782009-08-29 19:37:28 +00001092 return Pos->second;
1093}
1094
1095void
John McCalled976492009-12-04 22:46:56 +00001096ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1097 assert((isa<UsingDecl>(Pattern) ||
1098 isa<UnresolvedUsingValueDecl>(Pattern) ||
1099 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1100 "pattern decl is not a using decl");
1101 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1102 InstantiatedFromUsingDecl[Inst] = Pattern;
1103}
1104
1105UsingShadowDecl *
1106ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1107 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1108 = InstantiatedFromUsingShadowDecl.find(Inst);
1109 if (Pos == InstantiatedFromUsingShadowDecl.end())
1110 return 0;
1111
1112 return Pos->second;
1113}
1114
1115void
1116ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1117 UsingShadowDecl *Pattern) {
1118 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1119 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001120}
1121
Anders Carlssond8b285f2009-09-01 04:26:58 +00001122FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1123 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1124 = InstantiatedFromUnnamedFieldDecl.find(Field);
1125 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1126 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Anders Carlssond8b285f2009-09-01 04:26:58 +00001128 return Pos->second;
1129}
1130
1131void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1132 FieldDecl *Tmpl) {
1133 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1134 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1135 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1136 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Anders Carlssond8b285f2009-09-01 04:26:58 +00001138 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1139}
1140
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001141ASTContext::overridden_cxx_method_iterator
1142ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1143 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001144 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001145 if (Pos == OverriddenMethods.end())
1146 return 0;
1147
1148 return Pos->second.begin();
1149}
1150
1151ASTContext::overridden_cxx_method_iterator
1152ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1153 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001154 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001155 if (Pos == OverriddenMethods.end())
1156 return 0;
1157
1158 return Pos->second.end();
1159}
1160
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001161unsigned
1162ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1163 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001164 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001165 if (Pos == OverriddenMethods.end())
1166 return 0;
1167
1168 return Pos->second.size();
1169}
1170
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001171void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1172 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001173 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001174 OverriddenMethods[Method].push_back(Overridden);
1175}
1176
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001177void ASTContext::getOverriddenMethods(
1178 const NamedDecl *D,
1179 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001180 assert(D);
1181
1182 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001183 Overridden.append(overridden_methods_begin(CXXMethod),
1184 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001185 return;
1186 }
1187
1188 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1189 if (!Method)
1190 return;
1191
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001192 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1193 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001194 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001195}
1196
Douglas Gregore6649772011-12-03 00:30:27 +00001197void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1198 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1199 assert(!Import->isFromASTFile() && "Non-local import declaration");
1200 if (!FirstLocalImport) {
1201 FirstLocalImport = Import;
1202 LastLocalImport = Import;
1203 return;
1204 }
1205
1206 LastLocalImport->NextLocalImport = Import;
1207 LastLocalImport = Import;
1208}
1209
Chris Lattner464175b2007-07-18 17:52:12 +00001210//===----------------------------------------------------------------------===//
1211// Type Sizing and Analysis
1212//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001213
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001214/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1215/// scalar floating point type.
1216const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001217 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001218 assert(BT && "Not a floating point type!");
1219 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001220 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001221 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001222 case BuiltinType::Float: return Target->getFloatFormat();
1223 case BuiltinType::Double: return Target->getDoubleFormat();
1224 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001225 }
1226}
1227
Ken Dyck8b752f12010-01-27 17:10:57 +00001228/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001229/// specified decl. Note that bitfields do not have a valid alignment, so
1230/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001231/// If @p RefAsPointee, references are treated like their underlying type
1232/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001233CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001234 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001235
John McCall4081a5c2010-10-08 18:24:19 +00001236 bool UseAlignAttrOnly = false;
1237 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1238 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001239
John McCall4081a5c2010-10-08 18:24:19 +00001240 // __attribute__((aligned)) can increase or decrease alignment
1241 // *except* on a struct or struct member, where it only increases
1242 // alignment unless 'packed' is also specified.
1243 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001244 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001245 // ignore that possibility; Sema should diagnose it.
1246 if (isa<FieldDecl>(D)) {
1247 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1248 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1249 } else {
1250 UseAlignAttrOnly = true;
1251 }
1252 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001253 else if (isa<FieldDecl>(D))
1254 UseAlignAttrOnly =
1255 D->hasAttr<PackedAttr>() ||
1256 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001257
John McCallba4f5d52011-01-20 07:57:12 +00001258 // If we're using the align attribute only, just ignore everything
1259 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001260 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001261 // do nothing
1262
John McCall4081a5c2010-10-08 18:24:19 +00001263 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001264 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001265 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001266 if (RefAsPointee)
1267 T = RT->getPointeeType();
1268 else
1269 T = getPointerType(RT->getPointeeType());
1270 }
1271 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001272 // Adjust alignments of declarations with array type by the
1273 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001274 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001275 const ArrayType *arrayType;
1276 if (MinWidth && (arrayType = getAsArrayType(T))) {
1277 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001278 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001279 else if (isa<ConstantArrayType>(arrayType) &&
1280 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001281 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001282
John McCall3b657512011-01-19 10:06:00 +00001283 // Walk through any array types while we're at it.
1284 T = getBaseElementType(arrayType);
1285 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001286 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001287 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1288 if (VD->hasGlobalStorage())
1289 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1290 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001291 }
John McCallba4f5d52011-01-20 07:57:12 +00001292
1293 // Fields can be subject to extra alignment constraints, like if
1294 // the field is packed, the struct is packed, or the struct has a
1295 // a max-field-alignment constraint (#pragma pack). So calculate
1296 // the actual alignment of the field within the struct, and then
1297 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001298 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1299 const RecordDecl *Parent = Field->getParent();
1300 // We can only produce a sensible answer if the record is valid.
1301 if (!Parent->isInvalidDecl()) {
1302 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001303
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001304 // Start with the record's overall alignment.
1305 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001306
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001307 // Use the GCD of that and the offset within the record.
1308 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1309 if (Offset > 0) {
1310 // Alignment is always a power of 2, so the GCD will be a power of 2,
1311 // which means we get to do this crazy thing instead of Euclid's.
1312 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1313 if (LowBitOfOffset < FieldAlign)
1314 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1315 }
1316
1317 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001318 }
Charles Davis05f62472010-02-23 04:52:00 +00001319 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001320 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001321
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001322 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001323}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001324
John McCall929bbfb2012-08-21 04:10:00 +00001325// getTypeInfoDataSizeInChars - Return the size of a type, in
1326// chars. If the type is a record, its data size is returned. This is
1327// the size of the memcpy that's performed when assigning this type
1328// using a trivial copy/move assignment operator.
1329std::pair<CharUnits, CharUnits>
1330ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1331 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1332
1333 // In C++, objects can sometimes be allocated into the tail padding
1334 // of a base-class subobject. We decide whether that's possible
1335 // during class layout, so here we can just trust the layout results.
1336 if (getLangOpts().CPlusPlus) {
1337 if (const RecordType *RT = T->getAs<RecordType>()) {
1338 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1339 sizeAndAlign.first = layout.getDataSize();
1340 }
1341 }
1342
1343 return sizeAndAlign;
1344}
1345
Richard Trieu910f17e2013-05-14 21:59:17 +00001346/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1347/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1348std::pair<CharUnits, CharUnits>
1349static getConstantArrayInfoInChars(const ASTContext &Context,
1350 const ConstantArrayType *CAT) {
1351 std::pair<CharUnits, CharUnits> EltInfo =
1352 Context.getTypeInfoInChars(CAT->getElementType());
1353 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001354 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1355 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001356 "Overflow in array type char size evaluation");
1357 uint64_t Width = EltInfo.first.getQuantity() * Size;
1358 unsigned Align = EltInfo.second.getQuantity();
1359 Width = llvm::RoundUpToAlignment(Width, Align);
1360 return std::make_pair(CharUnits::fromQuantity(Width),
1361 CharUnits::fromQuantity(Align));
1362}
1363
John McCallea1471e2010-05-20 01:18:31 +00001364std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001365ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001366 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1367 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001368 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001369 return std::make_pair(toCharUnitsFromBits(Info.first),
1370 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001371}
1372
1373std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001374ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001375 return getTypeInfoInChars(T.getTypePtr());
1376}
1377
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001378std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1379 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1380 if (it != MemoizedTypeInfo.end())
1381 return it->second;
1382
1383 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1384 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1385 return Info;
1386}
1387
1388/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1389/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001390///
1391/// FIXME: Pointers into different addr spaces could have different sizes and
1392/// alignment requirements: getPointerInfo should take an AddrSpace, this
1393/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001394std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001395ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001396 uint64_t Width=0;
1397 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001398 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001399#define TYPE(Class, Base)
1400#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001401#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001402#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001403#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1404 case Type::Class: \
1405 assert(!T->isDependentType() && "should not see dependent types here"); \
1406 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001407#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001408 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001409
Chris Lattner692233e2007-07-13 22:27:08 +00001410 case Type::FunctionNoProto:
1411 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001412 // GCC extension: alignof(function) = 32 bits
1413 Width = 0;
1414 Align = 32;
1415 break;
1416
Douglas Gregor72564e72009-02-26 23:50:07 +00001417 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001418 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001419 Width = 0;
1420 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1421 break;
1422
Steve Narofffb22d962007-08-30 01:06:46 +00001423 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001424 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Chris Lattner98be4942008-03-05 18:54:05 +00001426 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001427 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001428 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1429 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001430 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001431 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001432 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001433 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001434 }
Nate Begeman213541a2008-04-18 23:10:10 +00001435 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001436 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001437 const VectorType *VT = cast<VectorType>(T);
1438 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1439 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001440 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001441 // If the alignment is not a power of 2, round up to the next power of 2.
1442 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001443 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001444 Align = llvm::NextPowerOf2(Align);
1445 Width = llvm::RoundUpToAlignment(Width, Align);
1446 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001447 // Adjust the alignment based on the target max.
1448 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1449 if (TargetVectorAlign && TargetVectorAlign < Align)
1450 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001451 break;
1452 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001453
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001454 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001455 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001456 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001457 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001458 // GCC extension: alignof(void) = 8 bits.
1459 Width = 0;
1460 Align = 8;
1461 break;
1462
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001463 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001464 Width = Target->getBoolWidth();
1465 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001466 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001467 case BuiltinType::Char_S:
1468 case BuiltinType::Char_U:
1469 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001470 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001471 Width = Target->getCharWidth();
1472 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001473 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001474 case BuiltinType::WChar_S:
1475 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001476 Width = Target->getWCharWidth();
1477 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001478 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001479 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001480 Width = Target->getChar16Width();
1481 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001482 break;
1483 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001484 Width = Target->getChar32Width();
1485 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001486 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001487 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001488 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001489 Width = Target->getShortWidth();
1490 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001491 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001492 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001493 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001494 Width = Target->getIntWidth();
1495 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001496 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001497 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001498 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getLongWidth();
1500 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001502 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001503 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001504 Width = Target->getLongLongWidth();
1505 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001507 case BuiltinType::Int128:
1508 case BuiltinType::UInt128:
1509 Width = 128;
1510 Align = 128; // int128_t is 128-bit aligned on all targets.
1511 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001512 case BuiltinType::Half:
1513 Width = Target->getHalfWidth();
1514 Align = Target->getHalfAlign();
1515 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001516 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001517 Width = Target->getFloatWidth();
1518 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001519 break;
1520 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001521 Width = Target->getDoubleWidth();
1522 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001523 break;
1524 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001525 Width = Target->getLongDoubleWidth();
1526 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001527 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001528 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001529 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1530 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001531 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001532 case BuiltinType::ObjCId:
1533 case BuiltinType::ObjCClass:
1534 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getPointerWidth(0);
1536 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001537 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001538 case BuiltinType::OCLSampler:
1539 // Samplers are modeled as integers.
1540 Width = Target->getIntWidth();
1541 Align = Target->getIntAlign();
1542 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001543 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001544 case BuiltinType::OCLImage1d:
1545 case BuiltinType::OCLImage1dArray:
1546 case BuiltinType::OCLImage1dBuffer:
1547 case BuiltinType::OCLImage2d:
1548 case BuiltinType::OCLImage2dArray:
1549 case BuiltinType::OCLImage3d:
1550 // Currently these types are pointers to opaque types.
1551 Width = Target->getPointerWidth(0);
1552 Align = Target->getPointerAlign(0);
1553 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001554 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001555 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001556 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001557 Width = Target->getPointerWidth(0);
1558 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001559 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001560 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001561 unsigned AS = getTargetAddressSpace(
1562 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001563 Width = Target->getPointerWidth(AS);
1564 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001565 break;
1566 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001567 case Type::LValueReference:
1568 case Type::RValueReference: {
1569 // alignof and sizeof should never enter this code path here, so we go
1570 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001571 unsigned AS = getTargetAddressSpace(
1572 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001573 Width = Target->getPointerWidth(AS);
1574 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001575 break;
1576 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001577 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001578 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001579 Width = Target->getPointerWidth(AS);
1580 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001581 break;
1582 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001583 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001584 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001585 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001586 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001587 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001588 case Type::Complex: {
1589 // Complex types have the same alignment as their elements, but twice the
1590 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001591 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001592 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001593 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001594 Align = EltInfo.second;
1595 break;
1596 }
John McCallc12c5bb2010-05-15 11:32:37 +00001597 case Type::ObjCObject:
1598 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001599 case Type::Decayed:
1600 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001601 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001602 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001603 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001604 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001605 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001606 break;
1607 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001608 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001609 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001610 const TagType *TT = cast<TagType>(T);
1611
1612 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001613 Width = 8;
1614 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001615 break;
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Daniel Dunbar1d751182008-11-08 05:48:37 +00001618 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001619 return getTypeInfo(ET->getDecl()->getIntegerType());
1620
Daniel Dunbar1d751182008-11-08 05:48:37 +00001621 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001622 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001623 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001624 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001625 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001626 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001627
Chris Lattner9fcfe922009-10-22 05:17:15 +00001628 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001629 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1630 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001631
Richard Smith34b41d92011-02-20 03:19:35 +00001632 case Type::Auto: {
1633 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001634 assert(!A->getDeducedType().isNull() &&
1635 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001636 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001637 }
1638
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001639 case Type::Paren:
1640 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1641
Douglas Gregor18857642009-04-30 17:32:17 +00001642 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001643 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001644 std::pair<uint64_t, unsigned> Info
1645 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001646 // If the typedef has an aligned attribute on it, it overrides any computed
1647 // alignment we have. This violates the GCC documentation (which says that
1648 // attribute(aligned) can only round up) but matches its implementation.
1649 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1650 Align = AttrAlign;
1651 else
1652 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001653 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001654 break;
Chris Lattner71763312008-04-06 22:05:18 +00001655 }
Douglas Gregor18857642009-04-30 17:32:17 +00001656
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001657 case Type::Elaborated:
1658 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001659
John McCall9d156a72011-01-06 01:58:22 +00001660 case Type::Attributed:
1661 return getTypeInfo(
1662 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1663
Eli Friedmanb001de72011-10-06 23:00:33 +00001664 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001665 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001666 std::pair<uint64_t, unsigned> Info
1667 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1668 Width = Info.first;
1669 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001670
1671 // If the size of the type doesn't exceed the platform's max
1672 // atomic promotion width, make the size and alignment more
1673 // favorable to atomic operations:
1674 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1675 // Round the size up to a power of 2.
1676 if (!llvm::isPowerOf2_64(Width))
1677 Width = llvm::NextPowerOf2(Width);
1678
1679 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001680 Align = static_cast<unsigned>(Width);
1681 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001682 }
1683
Douglas Gregor18857642009-04-30 17:32:17 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Eli Friedman2be46072011-10-14 20:59:01 +00001686 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001687 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001688}
1689
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001690/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1691CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1692 return CharUnits::fromQuantity(BitSize / getCharWidth());
1693}
1694
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001695/// toBits - Convert a size in characters to a size in characters.
1696int64_t ASTContext::toBits(CharUnits CharSize) const {
1697 return CharSize.getQuantity() * getCharWidth();
1698}
1699
Ken Dyckbdc601b2009-12-22 14:23:30 +00001700/// getTypeSizeInChars - Return the size of the specified type, in characters.
1701/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001702CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001703 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001704}
Jay Foad4ba2a172011-01-12 09:06:06 +00001705CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001706 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001707}
1708
Ken Dyck16e20cc2010-01-26 17:25:18 +00001709/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001710/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001711CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001712 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001713}
Jay Foad4ba2a172011-01-12 09:06:06 +00001714CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001715 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001716}
1717
Chris Lattner34ebde42009-01-27 18:08:34 +00001718/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1719/// type for the current target in bits. This can be different than the ABI
1720/// alignment in cases where it is beneficial for performance to overalign
1721/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001722unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001723 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001724
1725 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001726 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001727 T = CT->getElementType().getTypePtr();
1728 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001729 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1730 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001731 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1732
Chris Lattner34ebde42009-01-27 18:08:34 +00001733 return ABIAlign;
1734}
1735
Ulrich Weigand6b203512013-05-06 16:23:57 +00001736/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1737/// to a global variable of the specified type.
1738unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1739 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1740}
1741
1742/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1743/// should be given to a global variable of the specified type.
1744CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1745 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1746}
1747
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001748/// DeepCollectObjCIvars -
1749/// This routine first collects all declared, but not synthesized, ivars in
1750/// super class and then collects all ivars, including those synthesized for
1751/// current class. This routine is used for implementation of current class
1752/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001753///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001754void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1755 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001756 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001757 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1758 DeepCollectObjCIvars(SuperClass, false, Ivars);
1759 if (!leafClass) {
1760 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1761 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001762 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001763 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001764 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001765 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001766 Iv= Iv->getNextIvar())
1767 Ivars.push_back(Iv);
1768 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001769}
1770
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001771/// CollectInheritedProtocols - Collect all protocols in current class and
1772/// those inherited by it.
1773void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001774 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001775 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001776 // We can use protocol_iterator here instead of
1777 // all_referenced_protocol_iterator since we are walking all categories.
1778 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1779 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001780 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001781 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001782 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001783 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001784 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001785 CollectInheritedProtocols(*P, Protocols);
1786 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001787 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001788
1789 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001790 for (ObjCInterfaceDecl::visible_categories_iterator
1791 Cat = OI->visible_categories_begin(),
1792 CatEnd = OI->visible_categories_end();
1793 Cat != CatEnd; ++Cat) {
1794 CollectInheritedProtocols(*Cat, Protocols);
1795 }
1796
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001797 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1798 while (SD) {
1799 CollectInheritedProtocols(SD, Protocols);
1800 SD = SD->getSuperClass();
1801 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001802 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001803 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001804 PE = OC->protocol_end(); P != PE; ++P) {
1805 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001806 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001807 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1808 PE = Proto->protocol_end(); P != PE; ++P)
1809 CollectInheritedProtocols(*P, Protocols);
1810 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001811 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001812 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1813 PE = OP->protocol_end(); P != PE; ++P) {
1814 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001815 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001816 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1817 PE = Proto->protocol_end(); P != PE; ++P)
1818 CollectInheritedProtocols(*P, Protocols);
1819 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001820 }
1821}
1822
Jay Foad4ba2a172011-01-12 09:06:06 +00001823unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001824 unsigned count = 0;
1825 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001826 for (ObjCInterfaceDecl::known_extensions_iterator
1827 Ext = OI->known_extensions_begin(),
1828 ExtEnd = OI->known_extensions_end();
1829 Ext != ExtEnd; ++Ext) {
1830 count += Ext->ivar_size();
1831 }
1832
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001833 // Count ivar defined in this class's implementation. This
1834 // includes synthesized ivars.
1835 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001836 count += ImplDecl->ivar_size();
1837
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001838 return count;
1839}
1840
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001841bool ASTContext::isSentinelNullExpr(const Expr *E) {
1842 if (!E)
1843 return false;
1844
1845 // nullptr_t is always treated as null.
1846 if (E->getType()->isNullPtrType()) return true;
1847
1848 if (E->getType()->isAnyPointerType() &&
1849 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1850 Expr::NPC_ValueDependentIsNull))
1851 return true;
1852
1853 // Unfortunately, __null has type 'int'.
1854 if (isa<GNUNullExpr>(E)) return true;
1855
1856 return false;
1857}
1858
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001859/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1860ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1861 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1862 I = ObjCImpls.find(D);
1863 if (I != ObjCImpls.end())
1864 return cast<ObjCImplementationDecl>(I->second);
1865 return 0;
1866}
1867/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1868ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1869 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1870 I = ObjCImpls.find(D);
1871 if (I != ObjCImpls.end())
1872 return cast<ObjCCategoryImplDecl>(I->second);
1873 return 0;
1874}
1875
1876/// \brief Set the implementation of ObjCInterfaceDecl.
1877void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1878 ObjCImplementationDecl *ImplD) {
1879 assert(IFaceD && ImplD && "Passed null params");
1880 ObjCImpls[IFaceD] = ImplD;
1881}
1882/// \brief Set the implementation of ObjCCategoryDecl.
1883void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1884 ObjCCategoryImplDecl *ImplD) {
1885 assert(CatD && ImplD && "Passed null params");
1886 ObjCImpls[CatD] = ImplD;
1887}
1888
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001889const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1890 const NamedDecl *ND) const {
1891 if (const ObjCInterfaceDecl *ID =
1892 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001893 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001894 if (const ObjCCategoryDecl *CD =
1895 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001896 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001897 if (const ObjCImplDecl *IMD =
1898 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001899 return IMD->getClassInterface();
1900
1901 return 0;
1902}
1903
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001904/// \brief Get the copy initialization expression of VarDecl,or NULL if
1905/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001906Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001907 assert(VD && "Passed null params");
1908 assert(VD->hasAttr<BlocksAttr>() &&
1909 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001910 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001911 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001912 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1913}
1914
1915/// \brief Set the copy inialization expression of a block var decl.
1916void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1917 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001918 assert(VD->hasAttr<BlocksAttr>() &&
1919 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001920 BlockVarCopyInits[VD] = Init;
1921}
1922
John McCalla93c9342009-12-07 02:54:59 +00001923TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001924 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001925 if (!DataSize)
1926 DataSize = TypeLoc::getFullDataSizeForType(T);
1927 else
1928 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001929 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001930
John McCalla93c9342009-12-07 02:54:59 +00001931 TypeSourceInfo *TInfo =
1932 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1933 new (TInfo) TypeSourceInfo(T);
1934 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001935}
1936
John McCalla93c9342009-12-07 02:54:59 +00001937TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001938 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001939 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001940 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001941 return DI;
1942}
1943
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001944const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001945ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001946 return getObjCLayout(D, 0);
1947}
1948
1949const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001950ASTContext::getASTObjCImplementationLayout(
1951 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001952 return getObjCLayout(D->getClassInterface(), D);
1953}
1954
Chris Lattnera7674d82007-07-13 22:13:22 +00001955//===----------------------------------------------------------------------===//
1956// Type creation/memoization methods
1957//===----------------------------------------------------------------------===//
1958
Jay Foad4ba2a172011-01-12 09:06:06 +00001959QualType
John McCall3b657512011-01-19 10:06:00 +00001960ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1961 unsigned fastQuals = quals.getFastQualifiers();
1962 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001963
1964 // Check if we've already instantiated this type.
1965 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001966 ExtQuals::Profile(ID, baseType, quals);
1967 void *insertPos = 0;
1968 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1969 assert(eq->getQualifiers() == quals);
1970 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001971 }
1972
John McCall3b657512011-01-19 10:06:00 +00001973 // If the base type is not canonical, make the appropriate canonical type.
1974 QualType canon;
1975 if (!baseType->isCanonicalUnqualified()) {
1976 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001977 canonSplit.Quals.addConsistentQualifiers(quals);
1978 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001979
1980 // Re-find the insert position.
1981 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1982 }
1983
1984 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1985 ExtQualNodes.InsertNode(eq, insertPos);
1986 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001987}
1988
Jay Foad4ba2a172011-01-12 09:06:06 +00001989QualType
1990ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001991 QualType CanT = getCanonicalType(T);
1992 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001993 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001994
John McCall0953e762009-09-24 19:53:00 +00001995 // If we are composing extended qualifiers together, merge together
1996 // into one ExtQuals node.
1997 QualifierCollector Quals;
1998 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001999
John McCall0953e762009-09-24 19:53:00 +00002000 // If this type already has an address space specified, it cannot get
2001 // another one.
2002 assert(!Quals.hasAddressSpace() &&
2003 "Type cannot be in multiple addr spaces!");
2004 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
John McCall0953e762009-09-24 19:53:00 +00002006 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002007}
2008
Chris Lattnerb7d25532009-02-18 22:53:11 +00002009QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002010 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002011 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002012 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002013 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCall7f040a92010-12-24 02:08:15 +00002015 if (const PointerType *ptr = T->getAs<PointerType>()) {
2016 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002017 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002018 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2019 return getPointerType(ResultType);
2020 }
2021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCall0953e762009-09-24 19:53:00 +00002023 // If we are composing extended qualifiers together, merge together
2024 // into one ExtQuals node.
2025 QualifierCollector Quals;
2026 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall0953e762009-09-24 19:53:00 +00002028 // If this type already has an ObjCGC specified, it cannot get
2029 // another one.
2030 assert(!Quals.hasObjCGCAttr() &&
2031 "Type cannot have multiple ObjCGCs!");
2032 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002033
John McCall0953e762009-09-24 19:53:00 +00002034 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002035}
Chris Lattnera7674d82007-07-13 22:13:22 +00002036
John McCalle6a365d2010-12-19 02:44:49 +00002037const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2038 FunctionType::ExtInfo Info) {
2039 if (T->getExtInfo() == Info)
2040 return T;
2041
2042 QualType Result;
2043 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2044 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2045 } else {
2046 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2047 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2048 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002049 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002050 }
2051
2052 return cast<FunctionType>(Result.getTypePtr());
2053}
2054
Richard Smith60e141e2013-05-04 07:00:32 +00002055void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2056 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002057 FD = FD->getMostRecentDecl();
2058 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002059 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2060 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2061 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002062 if (FunctionDecl *Next = FD->getPreviousDecl())
2063 FD = Next;
2064 else
2065 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002066 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002067 if (ASTMutationListener *L = getASTMutationListener())
2068 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002069}
2070
Reid Spencer5f016e22007-07-11 17:01:13 +00002071/// getComplexType - Return the uniqued reference to the type for a complex
2072/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002073QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 // Unique pointers, to guarantee there is only one pointer of a particular
2075 // structure.
2076 llvm::FoldingSetNodeID ID;
2077 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 void *InsertPos = 0;
2080 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2081 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 // If the pointee type isn't canonical, this won't be a canonical type either,
2084 // so fill in the canonical type field.
2085 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002086 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002087 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 // Get the new insert position for the node we care about.
2090 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002091 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 }
John McCall6b304a02009-09-24 23:30:46 +00002093 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 Types.push_back(New);
2095 ComplexTypes.InsertNode(New, InsertPos);
2096 return QualType(New, 0);
2097}
2098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099/// getPointerType - Return the uniqued reference to the type for a pointer to
2100/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002101QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // Unique pointers, to guarantee there is only one pointer of a particular
2103 // structure.
2104 llvm::FoldingSetNodeID ID;
2105 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 void *InsertPos = 0;
2108 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2109 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // If the pointee type isn't canonical, this won't be a canonical type either,
2112 // so fill in the canonical type field.
2113 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002114 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002115 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Bob Wilsonc90cc932013-03-15 17:12:43 +00002117 // Get the new insert position for the node we care about.
2118 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2119 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2120 }
John McCall6b304a02009-09-24 23:30:46 +00002121 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 Types.push_back(New);
2123 PointerTypes.InsertNode(New, InsertPos);
2124 return QualType(New, 0);
2125}
2126
Reid Kleckner12df2462013-06-24 17:51:48 +00002127QualType ASTContext::getDecayedType(QualType T) const {
2128 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2129
2130 llvm::FoldingSetNodeID ID;
2131 DecayedType::Profile(ID, T);
2132 void *InsertPos = 0;
2133 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2134 return QualType(DT, 0);
2135
2136 QualType Decayed;
2137
2138 // C99 6.7.5.3p7:
2139 // A declaration of a parameter as "array of type" shall be
2140 // adjusted to "qualified pointer to type", where the type
2141 // qualifiers (if any) are those specified within the [ and ] of
2142 // the array type derivation.
2143 if (T->isArrayType())
2144 Decayed = getArrayDecayedType(T);
2145
2146 // C99 6.7.5.3p8:
2147 // A declaration of a parameter as "function returning type"
2148 // shall be adjusted to "pointer to function returning type", as
2149 // in 6.3.2.1.
2150 if (T->isFunctionType())
2151 Decayed = getPointerType(T);
2152
2153 QualType Canonical = getCanonicalType(Decayed);
2154
2155 // Get the new insert position for the node we care about.
2156 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2157 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2158
2159 DecayedType *New =
2160 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2161 Types.push_back(New);
2162 DecayedTypes.InsertNode(New, InsertPos);
2163 return QualType(New, 0);
2164}
2165
Mike Stump1eb44332009-09-09 15:08:12 +00002166/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002167/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002168QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002169 assert(T->isFunctionType() && "block of function types only");
2170 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002171 // structure.
2172 llvm::FoldingSetNodeID ID;
2173 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroff5618bd42008-08-27 16:04:49 +00002175 void *InsertPos = 0;
2176 if (BlockPointerType *PT =
2177 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2178 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
2180 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002181 // type either so fill in the canonical type field.
2182 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002183 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002184 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Steve Naroff5618bd42008-08-27 16:04:49 +00002186 // Get the new insert position for the node we care about.
2187 BlockPointerType *NewIP =
2188 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002189 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002190 }
John McCall6b304a02009-09-24 23:30:46 +00002191 BlockPointerType *New
2192 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002193 Types.push_back(New);
2194 BlockPointerTypes.InsertNode(New, InsertPos);
2195 return QualType(New, 0);
2196}
2197
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002198/// getLValueReferenceType - Return the uniqued reference to the type for an
2199/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002200QualType
2201ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002202 assert(getCanonicalType(T) != OverloadTy &&
2203 "Unresolved overloaded function type");
2204
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 // Unique pointers, to guarantee there is only one pointer of a particular
2206 // structure.
2207 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002208 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002209
2210 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002211 if (LValueReferenceType *RT =
2212 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002214
John McCall54e14c42009-10-22 22:37:11 +00002215 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2216
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 // If the referencee type isn't canonical, this won't be a canonical type
2218 // either, so fill in the canonical type field.
2219 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002220 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2221 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2222 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002223
Reid Spencer5f016e22007-07-11 17:01:13 +00002224 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002225 LValueReferenceType *NewIP =
2226 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002227 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 }
2229
John McCall6b304a02009-09-24 23:30:46 +00002230 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002231 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2232 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002234 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002235
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002236 return QualType(New, 0);
2237}
2238
2239/// getRValueReferenceType - Return the uniqued reference to the type for an
2240/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002241QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002242 // Unique pointers, to guarantee there is only one pointer of a particular
2243 // structure.
2244 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002245 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002246
2247 void *InsertPos = 0;
2248 if (RValueReferenceType *RT =
2249 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2250 return QualType(RT, 0);
2251
John McCall54e14c42009-10-22 22:37:11 +00002252 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2253
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002254 // If the referencee type isn't canonical, this won't be a canonical type
2255 // either, so fill in the canonical type field.
2256 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002257 if (InnerRef || !T.isCanonical()) {
2258 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2259 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002260
2261 // Get the new insert position for the node we care about.
2262 RValueReferenceType *NewIP =
2263 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002264 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002265 }
2266
John McCall6b304a02009-09-24 23:30:46 +00002267 RValueReferenceType *New
2268 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002269 Types.push_back(New);
2270 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 return QualType(New, 0);
2272}
2273
Sebastian Redlf30208a2009-01-24 21:16:55 +00002274/// getMemberPointerType - Return the uniqued reference to the type for a
2275/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002276QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002277 // Unique pointers, to guarantee there is only one pointer of a particular
2278 // structure.
2279 llvm::FoldingSetNodeID ID;
2280 MemberPointerType::Profile(ID, T, Cls);
2281
2282 void *InsertPos = 0;
2283 if (MemberPointerType *PT =
2284 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2285 return QualType(PT, 0);
2286
2287 // If the pointee or class type isn't canonical, this won't be a canonical
2288 // type either, so fill in the canonical type field.
2289 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002290 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002291 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2292
2293 // Get the new insert position for the node we care about.
2294 MemberPointerType *NewIP =
2295 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002296 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002297 }
John McCall6b304a02009-09-24 23:30:46 +00002298 MemberPointerType *New
2299 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002300 Types.push_back(New);
2301 MemberPointerTypes.InsertNode(New, InsertPos);
2302 return QualType(New, 0);
2303}
2304
Mike Stump1eb44332009-09-09 15:08:12 +00002305/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002306/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002307QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002308 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002309 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002310 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002311 assert((EltTy->isDependentType() ||
2312 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002313 "Constant array of VLAs is illegal!");
2314
Chris Lattner38aeec72009-05-13 04:12:56 +00002315 // Convert the array size into a canonical width matching the pointer size for
2316 // the target.
2317 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002318 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002319 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002322 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002325 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002326 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002328
John McCall3b657512011-01-19 10:06:00 +00002329 // If the element type isn't canonical or has qualifiers, this won't
2330 // be a canonical type either, so fill in the canonical type field.
2331 QualType Canon;
2332 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2333 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002334 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002335 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002336 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002337
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002339 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002340 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002341 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 }
Mike Stump1eb44332009-09-09 15:08:12 +00002343
John McCall6b304a02009-09-24 23:30:46 +00002344 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002345 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002346 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 Types.push_back(New);
2348 return QualType(New, 0);
2349}
2350
John McCallce889032011-01-18 08:40:38 +00002351/// getVariableArrayDecayedType - Turns the given type, which may be
2352/// variably-modified, into the corresponding type with all the known
2353/// sizes replaced with [*].
2354QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2355 // Vastly most common case.
2356 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002357
John McCallce889032011-01-18 08:40:38 +00002358 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002359
John McCallce889032011-01-18 08:40:38 +00002360 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002361 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002362 switch (ty->getTypeClass()) {
2363#define TYPE(Class, Base)
2364#define ABSTRACT_TYPE(Class, Base)
2365#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2366#include "clang/AST/TypeNodes.def"
2367 llvm_unreachable("didn't desugar past all non-canonical types?");
2368
2369 // These types should never be variably-modified.
2370 case Type::Builtin:
2371 case Type::Complex:
2372 case Type::Vector:
2373 case Type::ExtVector:
2374 case Type::DependentSizedExtVector:
2375 case Type::ObjCObject:
2376 case Type::ObjCInterface:
2377 case Type::ObjCObjectPointer:
2378 case Type::Record:
2379 case Type::Enum:
2380 case Type::UnresolvedUsing:
2381 case Type::TypeOfExpr:
2382 case Type::TypeOf:
2383 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002384 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002385 case Type::DependentName:
2386 case Type::InjectedClassName:
2387 case Type::TemplateSpecialization:
2388 case Type::DependentTemplateSpecialization:
2389 case Type::TemplateTypeParm:
2390 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002391 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002392 case Type::PackExpansion:
2393 llvm_unreachable("type should never be variably-modified");
2394
2395 // These types can be variably-modified but should never need to
2396 // further decay.
2397 case Type::FunctionNoProto:
2398 case Type::FunctionProto:
2399 case Type::BlockPointer:
2400 case Type::MemberPointer:
2401 return type;
2402
2403 // These types can be variably-modified. All these modifications
2404 // preserve structure except as noted by comments.
2405 // TODO: if we ever care about optimizing VLAs, there are no-op
2406 // optimizations available here.
2407 case Type::Pointer:
2408 result = getPointerType(getVariableArrayDecayedType(
2409 cast<PointerType>(ty)->getPointeeType()));
2410 break;
2411
2412 case Type::LValueReference: {
2413 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2414 result = getLValueReferenceType(
2415 getVariableArrayDecayedType(lv->getPointeeType()),
2416 lv->isSpelledAsLValue());
2417 break;
2418 }
2419
2420 case Type::RValueReference: {
2421 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2422 result = getRValueReferenceType(
2423 getVariableArrayDecayedType(lv->getPointeeType()));
2424 break;
2425 }
2426
Eli Friedmanb001de72011-10-06 23:00:33 +00002427 case Type::Atomic: {
2428 const AtomicType *at = cast<AtomicType>(ty);
2429 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2430 break;
2431 }
2432
John McCallce889032011-01-18 08:40:38 +00002433 case Type::ConstantArray: {
2434 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2435 result = getConstantArrayType(
2436 getVariableArrayDecayedType(cat->getElementType()),
2437 cat->getSize(),
2438 cat->getSizeModifier(),
2439 cat->getIndexTypeCVRQualifiers());
2440 break;
2441 }
2442
2443 case Type::DependentSizedArray: {
2444 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2445 result = getDependentSizedArrayType(
2446 getVariableArrayDecayedType(dat->getElementType()),
2447 dat->getSizeExpr(),
2448 dat->getSizeModifier(),
2449 dat->getIndexTypeCVRQualifiers(),
2450 dat->getBracketsRange());
2451 break;
2452 }
2453
2454 // Turn incomplete types into [*] types.
2455 case Type::IncompleteArray: {
2456 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2457 result = getVariableArrayType(
2458 getVariableArrayDecayedType(iat->getElementType()),
2459 /*size*/ 0,
2460 ArrayType::Normal,
2461 iat->getIndexTypeCVRQualifiers(),
2462 SourceRange());
2463 break;
2464 }
2465
2466 // Turn VLA types into [*] types.
2467 case Type::VariableArray: {
2468 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2469 result = getVariableArrayType(
2470 getVariableArrayDecayedType(vat->getElementType()),
2471 /*size*/ 0,
2472 ArrayType::Star,
2473 vat->getIndexTypeCVRQualifiers(),
2474 vat->getBracketsRange());
2475 break;
2476 }
2477 }
2478
2479 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002480 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002481}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002482
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002483/// getVariableArrayType - Returns a non-unique reference to the type for a
2484/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002485QualType ASTContext::getVariableArrayType(QualType EltTy,
2486 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002487 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002488 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002489 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002490 // Since we don't unique expressions, it isn't possible to unique VLA's
2491 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002492 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002493
John McCall3b657512011-01-19 10:06:00 +00002494 // Be sure to pull qualifiers off the element type.
2495 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2496 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002497 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002498 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002499 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002500 }
2501
John McCall6b304a02009-09-24 23:30:46 +00002502 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002503 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002504
2505 VariableArrayTypes.push_back(New);
2506 Types.push_back(New);
2507 return QualType(New, 0);
2508}
2509
Douglas Gregor898574e2008-12-05 23:32:09 +00002510/// getDependentSizedArrayType - Returns a non-unique reference to
2511/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002512/// type.
John McCall3b657512011-01-19 10:06:00 +00002513QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2514 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002515 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002516 unsigned elementTypeQuals,
2517 SourceRange brackets) const {
2518 assert((!numElements || numElements->isTypeDependent() ||
2519 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002520 "Size must be type- or value-dependent!");
2521
John McCall3b657512011-01-19 10:06:00 +00002522 // Dependently-sized array types that do not have a specified number
2523 // of elements will have their sizes deduced from a dependent
2524 // initializer. We do no canonicalization here at all, which is okay
2525 // because they can't be used in most locations.
2526 if (!numElements) {
2527 DependentSizedArrayType *newType
2528 = new (*this, TypeAlignment)
2529 DependentSizedArrayType(*this, elementType, QualType(),
2530 numElements, ASM, elementTypeQuals,
2531 brackets);
2532 Types.push_back(newType);
2533 return QualType(newType, 0);
2534 }
2535
2536 // Otherwise, we actually build a new type every time, but we
2537 // also build a canonical type.
2538
2539 SplitQualType canonElementType = getCanonicalType(elementType).split();
2540
2541 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002542 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002543 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002544 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002545 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002546
John McCall3b657512011-01-19 10:06:00 +00002547 // Look for an existing type with these properties.
2548 DependentSizedArrayType *canonTy =
2549 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002550
John McCall3b657512011-01-19 10:06:00 +00002551 // If we don't have one, build one.
2552 if (!canonTy) {
2553 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002554 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002555 QualType(), numElements, ASM, elementTypeQuals,
2556 brackets);
2557 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2558 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002559 }
2560
John McCall3b657512011-01-19 10:06:00 +00002561 // Apply qualifiers from the element type to the array.
2562 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002563 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002564
John McCall3b657512011-01-19 10:06:00 +00002565 // If we didn't need extra canonicalization for the element type,
2566 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002567 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002568 return canon;
2569
2570 // Otherwise, we need to build a type which follows the spelling
2571 // of the element type.
2572 DependentSizedArrayType *sugaredType
2573 = new (*this, TypeAlignment)
2574 DependentSizedArrayType(*this, elementType, canon, numElements,
2575 ASM, elementTypeQuals, brackets);
2576 Types.push_back(sugaredType);
2577 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002578}
2579
John McCall3b657512011-01-19 10:06:00 +00002580QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002581 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002582 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002583 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002584 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002585
John McCall3b657512011-01-19 10:06:00 +00002586 void *insertPos = 0;
2587 if (IncompleteArrayType *iat =
2588 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2589 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002590
2591 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002592 // either, so fill in the canonical type field. We also have to pull
2593 // qualifiers off the element type.
2594 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002595
John McCall3b657512011-01-19 10:06:00 +00002596 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2597 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002598 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002599 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002600 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002601
2602 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002603 IncompleteArrayType *existing =
2604 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2605 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002606 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002607
John McCall3b657512011-01-19 10:06:00 +00002608 IncompleteArrayType *newType = new (*this, TypeAlignment)
2609 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002610
John McCall3b657512011-01-19 10:06:00 +00002611 IncompleteArrayTypes.InsertNode(newType, insertPos);
2612 Types.push_back(newType);
2613 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002614}
2615
Steve Naroff73322922007-07-18 18:00:27 +00002616/// getVectorType - Return the unique reference to a vector type of
2617/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002618QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002619 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002620 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 // Check if we've already instantiated a vector of this type.
2623 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002624 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 void *InsertPos = 0;
2627 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2628 return QualType(VTP, 0);
2629
2630 // If the element type isn't canonical, this won't be a canonical type either,
2631 // so fill in the canonical type field.
2632 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002633 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002634 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 // Get the new insert position for the node we care about.
2637 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
John McCall6b304a02009-09-24 23:30:46 +00002640 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002641 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 VectorTypes.InsertNode(New, InsertPos);
2643 Types.push_back(New);
2644 return QualType(New, 0);
2645}
2646
Nate Begeman213541a2008-04-18 23:10:10 +00002647/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002648/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002649QualType
2650ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002651 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Steve Naroff73322922007-07-18 18:00:27 +00002653 // Check if we've already instantiated a vector of this type.
2654 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002655 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002656 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002657 void *InsertPos = 0;
2658 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2659 return QualType(VTP, 0);
2660
2661 // If the element type isn't canonical, this won't be a canonical type either,
2662 // so fill in the canonical type field.
2663 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002664 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002665 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Steve Naroff73322922007-07-18 18:00:27 +00002667 // Get the new insert position for the node we care about.
2668 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002669 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002670 }
John McCall6b304a02009-09-24 23:30:46 +00002671 ExtVectorType *New = new (*this, TypeAlignment)
2672 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002673 VectorTypes.InsertNode(New, InsertPos);
2674 Types.push_back(New);
2675 return QualType(New, 0);
2676}
2677
Jay Foad4ba2a172011-01-12 09:06:06 +00002678QualType
2679ASTContext::getDependentSizedExtVectorType(QualType vecType,
2680 Expr *SizeExpr,
2681 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002682 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002683 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002684 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002686 void *InsertPos = 0;
2687 DependentSizedExtVectorType *Canon
2688 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2689 DependentSizedExtVectorType *New;
2690 if (Canon) {
2691 // We already have a canonical version of this array type; use it as
2692 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002693 New = new (*this, TypeAlignment)
2694 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2695 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002696 } else {
2697 QualType CanonVecTy = getCanonicalType(vecType);
2698 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002699 New = new (*this, TypeAlignment)
2700 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2701 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002702
2703 DependentSizedExtVectorType *CanonCheck
2704 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2705 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2706 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002707 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2708 } else {
2709 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2710 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002711 New = new (*this, TypeAlignment)
2712 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002713 }
2714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002716 Types.push_back(New);
2717 return QualType(New, 0);
2718}
2719
Douglas Gregor72564e72009-02-26 23:50:07 +00002720/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002721///
Jay Foad4ba2a172011-01-12 09:06:06 +00002722QualType
2723ASTContext::getFunctionNoProtoType(QualType ResultTy,
2724 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002725 const CallingConv DefaultCC = Info.getCC();
2726 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2727 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 // Unique functions, to guarantee there is only one function of a particular
2729 // structure.
2730 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002731 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002734 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002735 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002739 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002740 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002741 Canonical =
2742 getFunctionNoProtoType(getCanonicalType(ResultTy),
2743 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002746 FunctionNoProtoType *NewIP =
2747 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002748 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Roman Divackycfe9af22011-03-01 17:40:53 +00002751 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002752 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002753 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002755 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 return QualType(New, 0);
2757}
2758
Douglas Gregor02dd7982013-01-17 23:36:45 +00002759/// \brief Determine whether \p T is canonical as the result type of a function.
2760static bool isCanonicalResultType(QualType T) {
2761 return T.isCanonical() &&
2762 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2763 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2764}
2765
Reid Spencer5f016e22007-07-11 17:01:13 +00002766/// getFunctionType - Return a normal function type with a typed argument
2767/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002768QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002769ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002770 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002771 size_t NumArgs = ArgArray.size();
2772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // Unique functions, to guarantee there is only one function of a particular
2774 // structure.
2775 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002776 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2777 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002778
2779 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002780 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002781 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002783
2784 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002785 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002786 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002787 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002789 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 isCanonical = false;
2791
Roman Divackycfe9af22011-03-01 17:40:53 +00002792 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2793 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2794 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002795
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002797 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002799 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 CanonicalArgs.reserve(NumArgs);
2802 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002803 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002804
John McCalle23cf432010-12-14 08:05:40 +00002805 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002806 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002807 CanonicalEPI.ExceptionSpecType = EST_None;
2808 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002809 CanonicalEPI.ExtInfo
2810 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2811
Douglas Gregor02dd7982013-01-17 23:36:45 +00002812 // Result types do not have ARC lifetime qualifiers.
2813 QualType CanResultTy = getCanonicalType(ResultTy);
2814 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2815 Qualifiers Qs = CanResultTy.getQualifiers();
2816 Qs.removeObjCLifetime();
2817 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2818 }
2819
Jordan Rosebea522f2013-03-08 21:51:21 +00002820 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002821
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002823 FunctionProtoType *NewIP =
2824 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002825 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002827
John McCallf85e1932011-06-15 23:02:42 +00002828 // FunctionProtoType objects are allocated with extra bytes after
2829 // them for three variable size arrays at the end:
2830 // - parameter types
2831 // - exception types
2832 // - consumed-arguments flags
2833 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002834 // expression, or information used to resolve the exception
2835 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002836 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002837 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002838 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002839 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002840 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002841 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002842 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002843 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002844 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2845 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002846 }
John McCallf85e1932011-06-15 23:02:42 +00002847 if (EPI.ConsumedArguments)
2848 Size += NumArgs * sizeof(bool);
2849
John McCalle23cf432010-12-14 08:05:40 +00002850 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002851 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2852 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002853 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002855 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 return QualType(FTP, 0);
2857}
2858
John McCall3cb0ebd2010-03-10 03:28:59 +00002859#ifndef NDEBUG
2860static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2861 if (!isa<CXXRecordDecl>(D)) return false;
2862 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2863 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2864 return true;
2865 if (RD->getDescribedClassTemplate() &&
2866 !isa<ClassTemplateSpecializationDecl>(RD))
2867 return true;
2868 return false;
2869}
2870#endif
2871
2872/// getInjectedClassNameType - Return the unique reference to the
2873/// injected class name type for the specified templated declaration.
2874QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002875 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002876 assert(NeedsInjectedClassNameType(Decl));
2877 if (Decl->TypeForDecl) {
2878 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002879 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002880 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2881 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2882 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2883 } else {
John McCallf4c73712011-01-19 06:33:43 +00002884 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002885 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002886 Decl->TypeForDecl = newType;
2887 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002888 }
2889 return QualType(Decl->TypeForDecl, 0);
2890}
2891
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002892/// getTypeDeclType - Return the unique reference to the type for the
2893/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002894QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002895 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002896 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Richard Smith162e1c12011-04-15 14:24:37 +00002898 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002899 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002900
John McCallbecb8d52010-03-10 06:48:02 +00002901 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2902 "Template type parameter types are always available.");
2903
John McCall19c85762010-02-16 03:57:14 +00002904 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002905 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002906 "struct/union has previous declaration");
2907 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002908 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002909 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002910 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002911 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002912 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002913 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002914 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002915 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2916 Decl->TypeForDecl = newType;
2917 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002918 } else
John McCallbecb8d52010-03-10 06:48:02 +00002919 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002920
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002921 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002922}
2923
Reid Spencer5f016e22007-07-11 17:01:13 +00002924/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002925/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002926QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002927ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2928 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002931 if (Canonical.isNull())
2932 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002933 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002934 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002935 Decl->TypeForDecl = newType;
2936 Types.push_back(newType);
2937 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002938}
2939
Jay Foad4ba2a172011-01-12 09:06:06 +00002940QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002941 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2942
Douglas Gregoref96ee02012-01-14 16:38:05 +00002943 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002944 if (PrevDecl->TypeForDecl)
2945 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2946
John McCallf4c73712011-01-19 06:33:43 +00002947 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2948 Decl->TypeForDecl = newType;
2949 Types.push_back(newType);
2950 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002951}
2952
Jay Foad4ba2a172011-01-12 09:06:06 +00002953QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002954 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2955
Douglas Gregoref96ee02012-01-14 16:38:05 +00002956 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002957 if (PrevDecl->TypeForDecl)
2958 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2959
John McCallf4c73712011-01-19 06:33:43 +00002960 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
2963 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002964}
2965
John McCall9d156a72011-01-06 01:58:22 +00002966QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2967 QualType modifiedType,
2968 QualType equivalentType) {
2969 llvm::FoldingSetNodeID id;
2970 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2971
2972 void *insertPos = 0;
2973 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2974 if (type) return QualType(type, 0);
2975
2976 QualType canon = getCanonicalType(equivalentType);
2977 type = new (*this, TypeAlignment)
2978 AttributedType(canon, attrKind, modifiedType, equivalentType);
2979
2980 Types.push_back(type);
2981 AttributedTypes.InsertNode(type, insertPos);
2982
2983 return QualType(type, 0);
2984}
2985
2986
John McCall49a832b2009-10-18 09:09:24 +00002987/// \brief Retrieve a substitution-result type.
2988QualType
2989ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002990 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002991 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002992 && "replacement types must always be canonical");
2993
2994 llvm::FoldingSetNodeID ID;
2995 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2996 void *InsertPos = 0;
2997 SubstTemplateTypeParmType *SubstParm
2998 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2999
3000 if (!SubstParm) {
3001 SubstParm = new (*this, TypeAlignment)
3002 SubstTemplateTypeParmType(Parm, Replacement);
3003 Types.push_back(SubstParm);
3004 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3005 }
3006
3007 return QualType(SubstParm, 0);
3008}
3009
Douglas Gregorc3069d62011-01-14 02:55:32 +00003010/// \brief Retrieve a
3011QualType ASTContext::getSubstTemplateTypeParmPackType(
3012 const TemplateTypeParmType *Parm,
3013 const TemplateArgument &ArgPack) {
3014#ifndef NDEBUG
3015 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3016 PEnd = ArgPack.pack_end();
3017 P != PEnd; ++P) {
3018 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3019 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3020 }
3021#endif
3022
3023 llvm::FoldingSetNodeID ID;
3024 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3025 void *InsertPos = 0;
3026 if (SubstTemplateTypeParmPackType *SubstParm
3027 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3028 return QualType(SubstParm, 0);
3029
3030 QualType Canon;
3031 if (!Parm->isCanonicalUnqualified()) {
3032 Canon = getCanonicalType(QualType(Parm, 0));
3033 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3034 ArgPack);
3035 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3036 }
3037
3038 SubstTemplateTypeParmPackType *SubstParm
3039 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3040 ArgPack);
3041 Types.push_back(SubstParm);
3042 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3043 return QualType(SubstParm, 0);
3044}
3045
Douglas Gregorfab9d672009-02-05 23:33:38 +00003046/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003047/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003048/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003049QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003050 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003051 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003052 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003053 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003054 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003055 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003056 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3057
3058 if (TypeParm)
3059 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003061 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003062 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003063 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003064
3065 TemplateTypeParmType *TypeCheck
3066 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 assert(!TypeCheck && "Template type parameter canonical type broken");
3068 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003069 } else
John McCall6b304a02009-09-24 23:30:46 +00003070 TypeParm = new (*this, TypeAlignment)
3071 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003072
3073 Types.push_back(TypeParm);
3074 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3075
3076 return QualType(TypeParm, 0);
3077}
3078
John McCall3cb0ebd2010-03-10 03:28:59 +00003079TypeSourceInfo *
3080ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3081 SourceLocation NameLoc,
3082 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003083 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003084 assert(!Name.getAsDependentTemplateName() &&
3085 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003086 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003087
3088 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003089 TemplateSpecializationTypeLoc TL =
3090 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003091 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003092 TL.setTemplateNameLoc(NameLoc);
3093 TL.setLAngleLoc(Args.getLAngleLoc());
3094 TL.setRAngleLoc(Args.getRAngleLoc());
3095 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3096 TL.setArgLocInfo(i, Args[i].getLocInfo());
3097 return DI;
3098}
3099
Mike Stump1eb44332009-09-09 15:08:12 +00003100QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003101ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003102 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003103 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003104 assert(!Template.getAsDependentTemplateName() &&
3105 "No dependent template names here!");
3106
John McCalld5532b62009-11-23 01:53:49 +00003107 unsigned NumArgs = Args.size();
3108
Chris Lattner5f9e2722011-07-23 10:55:15 +00003109 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003110 ArgVec.reserve(NumArgs);
3111 for (unsigned i = 0; i != NumArgs; ++i)
3112 ArgVec.push_back(Args[i].getArgument());
3113
John McCall31f17ec2010-04-27 00:57:59 +00003114 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003115 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003116}
3117
Douglas Gregorb70126a2012-02-03 17:16:23 +00003118#ifndef NDEBUG
3119static bool hasAnyPackExpansions(const TemplateArgument *Args,
3120 unsigned NumArgs) {
3121 for (unsigned I = 0; I != NumArgs; ++I)
3122 if (Args[I].isPackExpansion())
3123 return true;
3124
3125 return true;
3126}
3127#endif
3128
John McCall833ca992009-10-29 08:12:44 +00003129QualType
3130ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003131 const TemplateArgument *Args,
3132 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003133 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003134 assert(!Template.getAsDependentTemplateName() &&
3135 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003136 // Look through qualified template names.
3137 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3138 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003139
Douglas Gregorb70126a2012-02-03 17:16:23 +00003140 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003141 Template.getAsTemplateDecl() &&
3142 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003143 QualType CanonType;
3144 if (!Underlying.isNull())
3145 CanonType = getCanonicalType(Underlying);
3146 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003147 // We can get here with an alias template when the specialization contains
3148 // a pack expansion that does not match up with a parameter pack.
3149 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3150 "Caller must compute aliased type");
3151 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003152 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3153 NumArgs);
3154 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003155
Douglas Gregor1275ae02009-07-28 23:00:59 +00003156 // Allocate the (non-canonical) template specialization type, but don't
3157 // try to unique it: these types typically have location information that
3158 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003159 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3160 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003161 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003162 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003163 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003164 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3165 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Douglas Gregor55f6b142009-02-09 18:46:07 +00003167 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003168 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003169}
3170
Mike Stump1eb44332009-09-09 15:08:12 +00003171QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003172ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3173 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003174 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003175 assert(!Template.getAsDependentTemplateName() &&
3176 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003177
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003178 // Look through qualified template names.
3179 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3180 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003181
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003182 // Build the canonical template specialization type.
3183 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003184 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003185 CanonArgs.reserve(NumArgs);
3186 for (unsigned I = 0; I != NumArgs; ++I)
3187 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3188
3189 // Determine whether this canonical template specialization type already
3190 // exists.
3191 llvm::FoldingSetNodeID ID;
3192 TemplateSpecializationType::Profile(ID, CanonTemplate,
3193 CanonArgs.data(), NumArgs, *this);
3194
3195 void *InsertPos = 0;
3196 TemplateSpecializationType *Spec
3197 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3198
3199 if (!Spec) {
3200 // Allocate a new canonical template specialization type.
3201 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3202 sizeof(TemplateArgument) * NumArgs),
3203 TypeAlignment);
3204 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3205 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003206 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003207 Types.push_back(Spec);
3208 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3209 }
3210
3211 assert(Spec->isDependentType() &&
3212 "Non-dependent template-id type must have a canonical type");
3213 return QualType(Spec, 0);
3214}
3215
3216QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003217ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3218 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003219 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003220 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003221 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003222
3223 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003224 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003225 if (T)
3226 return QualType(T, 0);
3227
Douglas Gregor789b1f62010-02-04 18:10:26 +00003228 QualType Canon = NamedType;
3229 if (!Canon.isCanonical()) {
3230 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003231 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3232 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003233 (void)CheckT;
3234 }
3235
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003236 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003237 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003238 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003239 return QualType(T, 0);
3240}
3241
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003242QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003243ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003244 llvm::FoldingSetNodeID ID;
3245 ParenType::Profile(ID, InnerType);
3246
3247 void *InsertPos = 0;
3248 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3249 if (T)
3250 return QualType(T, 0);
3251
3252 QualType Canon = InnerType;
3253 if (!Canon.isCanonical()) {
3254 Canon = getCanonicalType(InnerType);
3255 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3256 assert(!CheckT && "Paren canonical type broken");
3257 (void)CheckT;
3258 }
3259
3260 T = new (*this) ParenType(InnerType, Canon);
3261 Types.push_back(T);
3262 ParenTypes.InsertNode(T, InsertPos);
3263 return QualType(T, 0);
3264}
3265
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003266QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3267 NestedNameSpecifier *NNS,
3268 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003269 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003270 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3271
3272 if (Canon.isNull()) {
3273 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003274 ElaboratedTypeKeyword CanonKeyword = Keyword;
3275 if (Keyword == ETK_None)
3276 CanonKeyword = ETK_Typename;
3277
3278 if (CanonNNS != NNS || CanonKeyword != Keyword)
3279 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003280 }
3281
3282 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003283 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003284
3285 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003286 DependentNameType *T
3287 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003288 if (T)
3289 return QualType(T, 0);
3290
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003291 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003292 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003293 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003294 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003295}
3296
Mike Stump1eb44332009-09-09 15:08:12 +00003297QualType
John McCall33500952010-06-11 00:33:02 +00003298ASTContext::getDependentTemplateSpecializationType(
3299 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003300 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003301 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003302 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003303 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003304 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003305 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3306 ArgCopy.push_back(Args[I].getArgument());
3307 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3308 ArgCopy.size(),
3309 ArgCopy.data());
3310}
3311
3312QualType
3313ASTContext::getDependentTemplateSpecializationType(
3314 ElaboratedTypeKeyword Keyword,
3315 NestedNameSpecifier *NNS,
3316 const IdentifierInfo *Name,
3317 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003318 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003319 assert((!NNS || NNS->isDependent()) &&
3320 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003321
Douglas Gregor789b1f62010-02-04 18:10:26 +00003322 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003323 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3324 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003325
3326 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003327 DependentTemplateSpecializationType *T
3328 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003329 if (T)
3330 return QualType(T, 0);
3331
John McCall33500952010-06-11 00:33:02 +00003332 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003333
John McCall33500952010-06-11 00:33:02 +00003334 ElaboratedTypeKeyword CanonKeyword = Keyword;
3335 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3336
3337 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003338 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003339 for (unsigned I = 0; I != NumArgs; ++I) {
3340 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3341 if (!CanonArgs[I].structurallyEquals(Args[I]))
3342 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003343 }
3344
John McCall33500952010-06-11 00:33:02 +00003345 QualType Canon;
3346 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3347 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3348 Name, NumArgs,
3349 CanonArgs.data());
3350
3351 // Find the insert position again.
3352 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3353 }
3354
3355 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3356 sizeof(TemplateArgument) * NumArgs),
3357 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003358 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003359 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003360 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003361 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003362 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003363}
3364
Douglas Gregorcded4f62011-01-14 17:04:44 +00003365QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003366 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003367 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003368 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003369
3370 assert(Pattern->containsUnexpandedParameterPack() &&
3371 "Pack expansions must expand one or more parameter packs");
3372 void *InsertPos = 0;
3373 PackExpansionType *T
3374 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3375 if (T)
3376 return QualType(T, 0);
3377
3378 QualType Canon;
3379 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003380 Canon = getCanonicalType(Pattern);
3381 // The canonical type might not contain an unexpanded parameter pack, if it
3382 // contains an alias template specialization which ignores one of its
3383 // parameters.
3384 if (Canon->containsUnexpandedParameterPack()) {
3385 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003386
Richard Smithd8672ef2012-07-16 00:20:35 +00003387 // Find the insert position again, in case we inserted an element into
3388 // PackExpansionTypes and invalidated our insert position.
3389 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3390 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003391 }
3392
Douglas Gregorcded4f62011-01-14 17:04:44 +00003393 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003394 Types.push_back(T);
3395 PackExpansionTypes.InsertNode(T, InsertPos);
3396 return QualType(T, 0);
3397}
3398
Chris Lattner88cb27a2008-04-07 04:56:42 +00003399/// CmpProtocolNames - Comparison predicate for sorting protocols
3400/// alphabetically.
3401static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3402 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003403 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003404}
3405
John McCallc12c5bb2010-05-15 11:32:37 +00003406static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003407 unsigned NumProtocols) {
3408 if (NumProtocols == 0) return true;
3409
Douglas Gregor61cc2962012-01-02 02:00:30 +00003410 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3411 return false;
3412
John McCall54e14c42009-10-22 22:37:11 +00003413 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003414 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3415 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003416 return false;
3417 return true;
3418}
3419
3420static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003421 unsigned &NumProtocols) {
3422 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Chris Lattner88cb27a2008-04-07 04:56:42 +00003424 // Sort protocols, keyed by name.
3425 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3426
Douglas Gregor61cc2962012-01-02 02:00:30 +00003427 // Canonicalize.
3428 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3429 Protocols[I] = Protocols[I]->getCanonicalDecl();
3430
Chris Lattner88cb27a2008-04-07 04:56:42 +00003431 // Remove duplicates.
3432 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3433 NumProtocols = ProtocolsEnd-Protocols;
3434}
3435
John McCallc12c5bb2010-05-15 11:32:37 +00003436QualType ASTContext::getObjCObjectType(QualType BaseType,
3437 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003438 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003439 // If the base type is an interface and there aren't any protocols
3440 // to add, then the interface type will do just fine.
3441 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3442 return BaseType;
3443
3444 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003445 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003446 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003447 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003448 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3449 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003450
John McCallc12c5bb2010-05-15 11:32:37 +00003451 // Build the canonical type, which has the canonical base type and
3452 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003453 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003454 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3455 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3456 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003457 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003458 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003459 unsigned UniqueCount = NumProtocols;
3460
John McCall54e14c42009-10-22 22:37:11 +00003461 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003462 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3463 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003464 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003465 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3466 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003467 }
3468
3469 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003470 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3471 }
3472
3473 unsigned Size = sizeof(ObjCObjectTypeImpl);
3474 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3475 void *Mem = Allocate(Size, TypeAlignment);
3476 ObjCObjectTypeImpl *T =
3477 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3478
3479 Types.push_back(T);
3480 ObjCObjectTypes.InsertNode(T, InsertPos);
3481 return QualType(T, 0);
3482}
3483
3484/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3485/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003486QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003487 llvm::FoldingSetNodeID ID;
3488 ObjCObjectPointerType::Profile(ID, ObjectT);
3489
3490 void *InsertPos = 0;
3491 if (ObjCObjectPointerType *QT =
3492 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3493 return QualType(QT, 0);
3494
3495 // Find the canonical object type.
3496 QualType Canonical;
3497 if (!ObjectT.isCanonical()) {
3498 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3499
3500 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003501 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3502 }
3503
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003504 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003505 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3506 ObjCObjectPointerType *QType =
3507 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003509 Types.push_back(QType);
3510 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003511 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003512}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003513
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003514/// getObjCInterfaceType - Return the unique reference to the type for the
3515/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003516QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3517 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003518 if (Decl->TypeForDecl)
3519 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Douglas Gregor0af55012011-12-16 03:12:41 +00003521 if (PrevDecl) {
3522 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3523 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3524 return QualType(PrevDecl->TypeForDecl, 0);
3525 }
3526
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003527 // Prefer the definition, if there is one.
3528 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3529 Decl = Def;
3530
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003531 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3532 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3533 Decl->TypeForDecl = T;
3534 Types.push_back(T);
3535 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003536}
3537
Douglas Gregor72564e72009-02-26 23:50:07 +00003538/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3539/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003540/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003541/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003542/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003543QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003544 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003545 if (tofExpr->isTypeDependent()) {
3546 llvm::FoldingSetNodeID ID;
3547 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Douglas Gregorb1975722009-07-30 23:18:24 +00003549 void *InsertPos = 0;
3550 DependentTypeOfExprType *Canon
3551 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3552 if (Canon) {
3553 // We already have a "canonical" version of an identical, dependent
3554 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003555 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003556 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003557 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003558 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003559 Canon
3560 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003561 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3562 toe = Canon;
3563 }
3564 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003565 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003566 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003567 }
Steve Naroff9752f252007-08-01 18:02:17 +00003568 Types.push_back(toe);
3569 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003570}
3571
Steve Naroff9752f252007-08-01 18:02:17 +00003572/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3573/// TypeOfType AST's. The only motivation to unique these nodes would be
3574/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003575/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003576/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003577QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003578 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003579 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003580 Types.push_back(tot);
3581 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003582}
3583
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003584
Anders Carlsson395b4752009-06-24 19:06:50 +00003585/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3586/// DecltypeType AST's. The only motivation to unique these nodes would be
3587/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003588/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003589/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003590QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003591 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003592
3593 // C++0x [temp.type]p2:
3594 // If an expression e involves a template parameter, decltype(e) denotes a
3595 // unique dependent type. Two such decltype-specifiers refer to the same
3596 // type only if their expressions are equivalent (14.5.6.1).
3597 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003598 llvm::FoldingSetNodeID ID;
3599 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003601 void *InsertPos = 0;
3602 DependentDecltypeType *Canon
3603 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3604 if (Canon) {
3605 // We already have a "canonical" version of an equivalent, dependent
3606 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003607 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003608 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003609 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003610 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003611 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003612 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3613 dt = Canon;
3614 }
3615 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003616 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3617 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003618 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003619 Types.push_back(dt);
3620 return QualType(dt, 0);
3621}
3622
Sean Huntca63c202011-05-24 22:41:36 +00003623/// getUnaryTransformationType - We don't unique these, since the memory
3624/// savings are minimal and these are rare.
3625QualType ASTContext::getUnaryTransformType(QualType BaseType,
3626 QualType UnderlyingType,
3627 UnaryTransformType::UTTKind Kind)
3628 const {
3629 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003630 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3631 Kind,
3632 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003633 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003634 Types.push_back(Ty);
3635 return QualType(Ty, 0);
3636}
3637
Richard Smith60e141e2013-05-04 07:00:32 +00003638/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3639/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3640/// canonical deduced-but-dependent 'auto' type.
3641QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003642 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003643 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3644 return getAutoDeductType();
3645
3646 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003647 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003648 llvm::FoldingSetNodeID ID;
3649 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3650 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3651 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003652
Richard Smitha2c36462013-04-26 16:15:35 +00003653 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003654 IsDecltypeAuto,
3655 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003656 Types.push_back(AT);
3657 if (InsertPos)
3658 AutoTypes.InsertNode(AT, InsertPos);
3659 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003660}
3661
Eli Friedmanb001de72011-10-06 23:00:33 +00003662/// getAtomicType - Return the uniqued reference to the atomic type for
3663/// the given value type.
3664QualType ASTContext::getAtomicType(QualType T) const {
3665 // Unique pointers, to guarantee there is only one pointer of a particular
3666 // structure.
3667 llvm::FoldingSetNodeID ID;
3668 AtomicType::Profile(ID, T);
3669
3670 void *InsertPos = 0;
3671 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3672 return QualType(AT, 0);
3673
3674 // If the atomic value type isn't canonical, this won't be a canonical type
3675 // either, so fill in the canonical type field.
3676 QualType Canonical;
3677 if (!T.isCanonical()) {
3678 Canonical = getAtomicType(getCanonicalType(T));
3679
3680 // Get the new insert position for the node we care about.
3681 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3682 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3683 }
3684 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3685 Types.push_back(New);
3686 AtomicTypes.InsertNode(New, InsertPos);
3687 return QualType(New, 0);
3688}
3689
Richard Smithad762fc2011-04-14 22:09:26 +00003690/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3691QualType ASTContext::getAutoDeductType() const {
3692 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003693 AutoDeductTy = QualType(
3694 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3695 /*dependent*/false),
3696 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003697 return AutoDeductTy;
3698}
3699
3700/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3701QualType ASTContext::getAutoRRefDeductType() const {
3702 if (AutoRRefDeductTy.isNull())
3703 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3704 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3705 return AutoRRefDeductTy;
3706}
3707
Reid Spencer5f016e22007-07-11 17:01:13 +00003708/// getTagDeclType - Return the unique reference to the type for the
3709/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003710QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003711 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003712 // FIXME: What is the design on getTagDeclType when it requires casting
3713 // away const? mutable?
3714 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003715}
3716
Mike Stump1eb44332009-09-09 15:08:12 +00003717/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3718/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3719/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003720CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003721 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003722}
3723
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003724/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3725CanQualType ASTContext::getIntMaxType() const {
3726 return getFromTargetType(Target->getIntMaxType());
3727}
3728
3729/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3730CanQualType ASTContext::getUIntMaxType() const {
3731 return getFromTargetType(Target->getUIntMaxType());
3732}
3733
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003734/// getSignedWCharType - Return the type of "signed wchar_t".
3735/// Used when in C++, as a GCC extension.
3736QualType ASTContext::getSignedWCharType() const {
3737 // FIXME: derive from "Target" ?
3738 return WCharTy;
3739}
3740
3741/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3742/// Used when in C++, as a GCC extension.
3743QualType ASTContext::getUnsignedWCharType() const {
3744 // FIXME: derive from "Target" ?
3745 return UnsignedIntTy;
3746}
3747
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003748QualType ASTContext::getIntPtrType() const {
3749 return getFromTargetType(Target->getIntPtrType());
3750}
3751
3752QualType ASTContext::getUIntPtrType() const {
3753 return getCorrespondingUnsignedType(getIntPtrType());
3754}
3755
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003756/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003757/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3758QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003759 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003760}
3761
Eli Friedman6902e412012-11-27 02:58:24 +00003762/// \brief Return the unique type for "pid_t" defined in
3763/// <sys/types.h>. We need this to compute the correct type for vfork().
3764QualType ASTContext::getProcessIDType() const {
3765 return getFromTargetType(Target->getProcessIDType());
3766}
3767
Chris Lattnere6327742008-04-02 05:18:44 +00003768//===----------------------------------------------------------------------===//
3769// Type Operators
3770//===----------------------------------------------------------------------===//
3771
Jay Foad4ba2a172011-01-12 09:06:06 +00003772CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003773 // Push qualifiers into arrays, and then discard any remaining
3774 // qualifiers.
3775 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003776 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003777 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003778 QualType Result;
3779 if (isa<ArrayType>(Ty)) {
3780 Result = getArrayDecayedType(QualType(Ty,0));
3781 } else if (isa<FunctionType>(Ty)) {
3782 Result = getPointerType(QualType(Ty, 0));
3783 } else {
3784 Result = QualType(Ty, 0);
3785 }
3786
3787 return CanQualType::CreateUnsafe(Result);
3788}
3789
John McCall62c28c82011-01-18 07:41:22 +00003790QualType ASTContext::getUnqualifiedArrayType(QualType type,
3791 Qualifiers &quals) {
3792 SplitQualType splitType = type.getSplitUnqualifiedType();
3793
3794 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3795 // the unqualified desugared type and then drops it on the floor.
3796 // We then have to strip that sugar back off with
3797 // getUnqualifiedDesugaredType(), which is silly.
3798 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003799 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003800
3801 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003802 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003803 quals = splitType.Quals;
3804 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003805 }
3806
John McCall62c28c82011-01-18 07:41:22 +00003807 // Otherwise, recurse on the array's element type.
3808 QualType elementType = AT->getElementType();
3809 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3810
3811 // If that didn't change the element type, AT has no qualifiers, so we
3812 // can just use the results in splitType.
3813 if (elementType == unqualElementType) {
3814 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003815 quals = splitType.Quals;
3816 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003817 }
3818
3819 // Otherwise, add in the qualifiers from the outermost type, then
3820 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003821 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003822
Douglas Gregor9dadd942010-05-17 18:45:21 +00003823 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003824 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003825 CAT->getSizeModifier(), 0);
3826 }
3827
Douglas Gregor9dadd942010-05-17 18:45:21 +00003828 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003829 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003830 }
3831
Douglas Gregor9dadd942010-05-17 18:45:21 +00003832 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003833 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003834 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003835 VAT->getSizeModifier(),
3836 VAT->getIndexTypeCVRQualifiers(),
3837 VAT->getBracketsRange());
3838 }
3839
3840 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003841 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003842 DSAT->getSizeModifier(), 0,
3843 SourceRange());
3844}
3845
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003846/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3847/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3848/// they point to and return true. If T1 and T2 aren't pointer types
3849/// or pointer-to-member types, or if they are not similar at this
3850/// level, returns false and leaves T1 and T2 unchanged. Top-level
3851/// qualifiers on T1 and T2 are ignored. This function will typically
3852/// be called in a loop that successively "unwraps" pointer and
3853/// pointer-to-member types to compare them at each level.
3854bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3855 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3856 *T2PtrType = T2->getAs<PointerType>();
3857 if (T1PtrType && T2PtrType) {
3858 T1 = T1PtrType->getPointeeType();
3859 T2 = T2PtrType->getPointeeType();
3860 return true;
3861 }
3862
3863 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3864 *T2MPType = T2->getAs<MemberPointerType>();
3865 if (T1MPType && T2MPType &&
3866 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3867 QualType(T2MPType->getClass(), 0))) {
3868 T1 = T1MPType->getPointeeType();
3869 T2 = T2MPType->getPointeeType();
3870 return true;
3871 }
3872
David Blaikie4e4d0842012-03-11 07:00:24 +00003873 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003874 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3875 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3876 if (T1OPType && T2OPType) {
3877 T1 = T1OPType->getPointeeType();
3878 T2 = T2OPType->getPointeeType();
3879 return true;
3880 }
3881 }
3882
3883 // FIXME: Block pointers, too?
3884
3885 return false;
3886}
3887
Jay Foad4ba2a172011-01-12 09:06:06 +00003888DeclarationNameInfo
3889ASTContext::getNameForTemplate(TemplateName Name,
3890 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003891 switch (Name.getKind()) {
3892 case TemplateName::QualifiedTemplate:
3893 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003894 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003895 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3896 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003897
John McCall14606042011-06-30 08:33:18 +00003898 case TemplateName::OverloadedTemplate: {
3899 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3900 // DNInfo work in progress: CHECKME: what about DNLoc?
3901 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3902 }
3903
3904 case TemplateName::DependentTemplate: {
3905 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003906 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003907 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003908 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3909 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003910 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003911 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3912 // DNInfo work in progress: FIXME: source locations?
3913 DeclarationNameLoc DNLoc;
3914 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3915 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3916 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003917 }
3918 }
3919
John McCall14606042011-06-30 08:33:18 +00003920 case TemplateName::SubstTemplateTemplateParm: {
3921 SubstTemplateTemplateParmStorage *subst
3922 = Name.getAsSubstTemplateTemplateParm();
3923 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3924 NameLoc);
3925 }
3926
3927 case TemplateName::SubstTemplateTemplateParmPack: {
3928 SubstTemplateTemplateParmPackStorage *subst
3929 = Name.getAsSubstTemplateTemplateParmPack();
3930 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3931 NameLoc);
3932 }
3933 }
3934
3935 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003936}
3937
Jay Foad4ba2a172011-01-12 09:06:06 +00003938TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003939 switch (Name.getKind()) {
3940 case TemplateName::QualifiedTemplate:
3941 case TemplateName::Template: {
3942 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003943 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003944 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003945 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3946
3947 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003948 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003949 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003950
John McCall14606042011-06-30 08:33:18 +00003951 case TemplateName::OverloadedTemplate:
3952 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003953
John McCall14606042011-06-30 08:33:18 +00003954 case TemplateName::DependentTemplate: {
3955 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3956 assert(DTN && "Non-dependent template names must refer to template decls.");
3957 return DTN->CanonicalTemplateName;
3958 }
3959
3960 case TemplateName::SubstTemplateTemplateParm: {
3961 SubstTemplateTemplateParmStorage *subst
3962 = Name.getAsSubstTemplateTemplateParm();
3963 return getCanonicalTemplateName(subst->getReplacement());
3964 }
3965
3966 case TemplateName::SubstTemplateTemplateParmPack: {
3967 SubstTemplateTemplateParmPackStorage *subst
3968 = Name.getAsSubstTemplateTemplateParmPack();
3969 TemplateTemplateParmDecl *canonParameter
3970 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3971 TemplateArgument canonArgPack
3972 = getCanonicalTemplateArgument(subst->getArgumentPack());
3973 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3974 }
3975 }
3976
3977 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003978}
3979
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003980bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3981 X = getCanonicalTemplateName(X);
3982 Y = getCanonicalTemplateName(Y);
3983 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3984}
3985
Mike Stump1eb44332009-09-09 15:08:12 +00003986TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003987ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003988 switch (Arg.getKind()) {
3989 case TemplateArgument::Null:
3990 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003991
Douglas Gregor1275ae02009-07-28 23:00:59 +00003992 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003993 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Douglas Gregord2008e22012-04-06 22:40:38 +00003995 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003996 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3997 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Eli Friedmand7a6b162012-09-26 02:36:12 +00004000 case TemplateArgument::NullPtr:
4001 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4002 /*isNullPtr*/true);
4003
Douglas Gregor788cd062009-11-11 01:00:40 +00004004 case TemplateArgument::Template:
4005 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004006
4007 case TemplateArgument::TemplateExpansion:
4008 return TemplateArgument(getCanonicalTemplateName(
4009 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004010 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004011
Douglas Gregor1275ae02009-07-28 23:00:59 +00004012 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004013 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Douglas Gregor1275ae02009-07-28 23:00:59 +00004015 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004016 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregor1275ae02009-07-28 23:00:59 +00004018 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004019 if (Arg.pack_size() == 0)
4020 return Arg;
4021
Douglas Gregor910f8002010-11-07 23:05:16 +00004022 TemplateArgument *CanonArgs
4023 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004024 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004025 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004026 AEnd = Arg.pack_end();
4027 A != AEnd; (void)++A, ++Idx)
4028 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Douglas Gregor910f8002010-11-07 23:05:16 +00004030 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004031 }
4032 }
4033
4034 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004035 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004036}
4037
Douglas Gregord57959a2009-03-27 23:10:48 +00004038NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004039ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004040 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004041 return 0;
4042
4043 switch (NNS->getKind()) {
4044 case NestedNameSpecifier::Identifier:
4045 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004046 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004047 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4048 NNS->getAsIdentifier());
4049
4050 case NestedNameSpecifier::Namespace:
4051 // A namespace is canonical; build a nested-name-specifier with
4052 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004053 return NestedNameSpecifier::Create(*this, 0,
4054 NNS->getAsNamespace()->getOriginalNamespace());
4055
4056 case NestedNameSpecifier::NamespaceAlias:
4057 // A namespace is canonical; build a nested-name-specifier with
4058 // this namespace and no prefix.
4059 return NestedNameSpecifier::Create(*this, 0,
4060 NNS->getAsNamespaceAlias()->getNamespace()
4061 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004062
4063 case NestedNameSpecifier::TypeSpec:
4064 case NestedNameSpecifier::TypeSpecWithTemplate: {
4065 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004066
4067 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4068 // break it apart into its prefix and identifier, then reconsititute those
4069 // as the canonical nested-name-specifier. This is required to canonicalize
4070 // a dependent nested-name-specifier involving typedefs of dependent-name
4071 // types, e.g.,
4072 // typedef typename T::type T1;
4073 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004074 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4075 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004076 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004077
Eli Friedman16412ef2012-03-03 04:09:56 +00004078 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4079 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4080 // first place?
John McCall3b657512011-01-19 10:06:00 +00004081 return NestedNameSpecifier::Create(*this, 0, false,
4082 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004083 }
4084
4085 case NestedNameSpecifier::Global:
4086 // The global specifier is canonical and unique.
4087 return NNS;
4088 }
4089
David Blaikie7530c032012-01-17 06:56:22 +00004090 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004091}
4092
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004093
Jay Foad4ba2a172011-01-12 09:06:06 +00004094const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004095 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004096 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004097 // Handle the common positive case fast.
4098 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4099 return AT;
4100 }
Mike Stump1eb44332009-09-09 15:08:12 +00004101
John McCall0953e762009-09-24 19:53:00 +00004102 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004103 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004104 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004105
John McCall0953e762009-09-24 19:53:00 +00004106 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004107 // implements C99 6.7.3p8: "If the specification of an array type includes
4108 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 // If we get here, we either have type qualifiers on the type, or we have
4111 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004112 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004113
John McCall3b657512011-01-19 10:06:00 +00004114 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004115 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004117 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004118 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004119 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004121
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004122 // Otherwise, we have an array and we have qualifiers on it. Push the
4123 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004124 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004126 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4127 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4128 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004129 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004130 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4131 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4132 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004133 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004134
Mike Stump1eb44332009-09-09 15:08:12 +00004135 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004136 = dyn_cast<DependentSizedArrayType>(ATy))
4137 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004138 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004139 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004140 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004141 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004142 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004144 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004145 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004146 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004147 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004148 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004149 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004150}
4151
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004152QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004153 if (T->isArrayType() || T->isFunctionType())
4154 return getDecayedType(T);
4155 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004156}
4157
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004158QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004159 T = getVariableArrayDecayedType(T);
4160 T = getAdjustedParameterType(T);
4161 return T.getUnqualifiedType();
4162}
4163
Chris Lattnere6327742008-04-02 05:18:44 +00004164/// getArrayDecayedType - Return the properly qualified result of decaying the
4165/// specified array type to a pointer. This operation is non-trivial when
4166/// handling typedefs etc. The canonical type of "T" must be an array type,
4167/// this returns a pointer to a properly qualified element of the array.
4168///
4169/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004170QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004171 // Get the element type with 'getAsArrayType' so that we don't lose any
4172 // typedefs in the element type of the array. This also handles propagation
4173 // of type qualifiers from the array type into the element type if present
4174 // (C99 6.7.3p8).
4175 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4176 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004178 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004179
4180 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004181 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004182}
4183
John McCall3b657512011-01-19 10:06:00 +00004184QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4185 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004186}
4187
John McCall3b657512011-01-19 10:06:00 +00004188QualType ASTContext::getBaseElementType(QualType type) const {
4189 Qualifiers qs;
4190 while (true) {
4191 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004192 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004193 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004194
John McCall3b657512011-01-19 10:06:00 +00004195 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004196 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004197 }
Mike Stump1eb44332009-09-09 15:08:12 +00004198
John McCall3b657512011-01-19 10:06:00 +00004199 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004200}
4201
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004202/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004203uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004204ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4205 uint64_t ElementCount = 1;
4206 do {
4207 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004208 CA = dyn_cast_or_null<ConstantArrayType>(
4209 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004210 } while (CA);
4211 return ElementCount;
4212}
4213
Reid Spencer5f016e22007-07-11 17:01:13 +00004214/// getFloatingRank - Return a relative rank for floating point types.
4215/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004216static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004217 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004218 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004219
John McCall183700f2009-09-21 23:43:11 +00004220 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4221 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004222 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004223 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004224 case BuiltinType::Float: return FloatRank;
4225 case BuiltinType::Double: return DoubleRank;
4226 case BuiltinType::LongDouble: return LongDoubleRank;
4227 }
4228}
4229
Mike Stump1eb44332009-09-09 15:08:12 +00004230/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4231/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004232/// 'typeDomain' is a real floating point or complex type.
4233/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004234QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4235 QualType Domain) const {
4236 FloatingRank EltRank = getFloatingRank(Size);
4237 if (Domain->isComplexType()) {
4238 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004239 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004240 case FloatRank: return FloatComplexTy;
4241 case DoubleRank: return DoubleComplexTy;
4242 case LongDoubleRank: return LongDoubleComplexTy;
4243 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004244 }
Chris Lattner1361b112008-04-06 23:58:54 +00004245
4246 assert(Domain->isRealFloatingType() && "Unknown domain!");
4247 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004248 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004249 case FloatRank: return FloatTy;
4250 case DoubleRank: return DoubleTy;
4251 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004252 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004253 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004254}
4255
Chris Lattner7cfeb082008-04-06 23:55:33 +00004256/// getFloatingTypeOrder - Compare the rank of the two specified floating
4257/// point types, ignoring the domain of the type (i.e. 'double' ==
4258/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004259/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004260int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004261 FloatingRank LHSR = getFloatingRank(LHS);
4262 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004263
Chris Lattnera75cea32008-04-06 23:38:49 +00004264 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004265 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004266 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004267 return 1;
4268 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004269}
4270
Chris Lattnerf52ab252008-04-06 22:59:24 +00004271/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4272/// routine will assert if passed a built-in type that isn't an integer or enum,
4273/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004274unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004275 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004276
Chris Lattnerf52ab252008-04-06 22:59:24 +00004277 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004278 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004279 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004280 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004281 case BuiltinType::Char_S:
4282 case BuiltinType::Char_U:
4283 case BuiltinType::SChar:
4284 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004285 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004286 case BuiltinType::Short:
4287 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004288 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004289 case BuiltinType::Int:
4290 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004291 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004292 case BuiltinType::Long:
4293 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004294 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::LongLong:
4296 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004297 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004298 case BuiltinType::Int128:
4299 case BuiltinType::UInt128:
4300 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004301 }
4302}
4303
Eli Friedman04e83572009-08-20 04:21:42 +00004304/// \brief Whether this is a promotable bitfield reference according
4305/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4306///
4307/// \returns the type this bit-field will promote to, or NULL if no
4308/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004309QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004310 if (E->isTypeDependent() || E->isValueDependent())
4311 return QualType();
4312
John McCall993f43f2013-05-06 21:39:12 +00004313 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004314 if (!Field)
4315 return QualType();
4316
4317 QualType FT = Field->getType();
4318
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004319 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004320 uint64_t IntSize = getTypeSize(IntTy);
4321 // GCC extension compatibility: if the bit-field size is less than or equal
4322 // to the size of int, it gets promoted no matter what its type is.
4323 // For instance, unsigned long bf : 4 gets promoted to signed int.
4324 if (BitWidth < IntSize)
4325 return IntTy;
4326
4327 if (BitWidth == IntSize)
4328 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4329
4330 // Types bigger than int are not subject to promotions, and therefore act
4331 // like the base type.
4332 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4333 // is ridiculous.
4334 return QualType();
4335}
4336
Eli Friedmana95d7572009-08-19 07:44:53 +00004337/// getPromotedIntegerType - Returns the type that Promotable will
4338/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4339/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004340QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004341 assert(!Promotable.isNull());
4342 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004343 if (const EnumType *ET = Promotable->getAs<EnumType>())
4344 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004345
4346 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4347 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4348 // (3.9.1) can be converted to a prvalue of the first of the following
4349 // types that can represent all the values of its underlying type:
4350 // int, unsigned int, long int, unsigned long int, long long int, or
4351 // unsigned long long int [...]
4352 // FIXME: Is there some better way to compute this?
4353 if (BT->getKind() == BuiltinType::WChar_S ||
4354 BT->getKind() == BuiltinType::WChar_U ||
4355 BT->getKind() == BuiltinType::Char16 ||
4356 BT->getKind() == BuiltinType::Char32) {
4357 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4358 uint64_t FromSize = getTypeSize(BT);
4359 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4360 LongLongTy, UnsignedLongLongTy };
4361 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4362 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4363 if (FromSize < ToSize ||
4364 (FromSize == ToSize &&
4365 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4366 return PromoteTypes[Idx];
4367 }
4368 llvm_unreachable("char type should fit into long long");
4369 }
4370 }
4371
4372 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004373 if (Promotable->isSignedIntegerType())
4374 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004375 uint64_t PromotableSize = getIntWidth(Promotable);
4376 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004377 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4378 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4379}
4380
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004381/// \brief Recurses in pointer/array types until it finds an objc retainable
4382/// type and returns its ownership.
4383Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4384 while (!T.isNull()) {
4385 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4386 return T.getObjCLifetime();
4387 if (T->isArrayType())
4388 T = getBaseElementType(T);
4389 else if (const PointerType *PT = T->getAs<PointerType>())
4390 T = PT->getPointeeType();
4391 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004392 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004393 else
4394 break;
4395 }
4396
4397 return Qualifiers::OCL_None;
4398}
4399
Mike Stump1eb44332009-09-09 15:08:12 +00004400/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004401/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004402/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004403int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004404 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4405 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004406 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Chris Lattnerf52ab252008-04-06 22:59:24 +00004408 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4409 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Chris Lattner7cfeb082008-04-06 23:55:33 +00004411 unsigned LHSRank = getIntegerRank(LHSC);
4412 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattner7cfeb082008-04-06 23:55:33 +00004414 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4415 if (LHSRank == RHSRank) return 0;
4416 return LHSRank > RHSRank ? 1 : -1;
4417 }
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Chris Lattner7cfeb082008-04-06 23:55:33 +00004419 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4420 if (LHSUnsigned) {
4421 // If the unsigned [LHS] type is larger, return it.
4422 if (LHSRank >= RHSRank)
4423 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Chris Lattner7cfeb082008-04-06 23:55:33 +00004425 // If the signed type can represent all values of the unsigned type, it
4426 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004427 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004428 return -1;
4429 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004430
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 // If the unsigned [RHS] type is larger, return it.
4432 if (RHSRank >= LHSRank)
4433 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Chris Lattner7cfeb082008-04-06 23:55:33 +00004435 // If the signed type can represent all values of the unsigned type, it
4436 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004437 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004438 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004439}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004440
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004441static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004442CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4443 DeclContext *DC, IdentifierInfo *Id) {
4444 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004445 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004446 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004447 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004448 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004449}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004450
Mike Stump1eb44332009-09-09 15:08:12 +00004451// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004452QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004453 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004454 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004455 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004456 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004457 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004458
Anders Carlssonf06273f2007-11-19 00:25:30 +00004459 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Anders Carlsson71993dd2007-08-17 05:31:46 +00004461 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004462 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004463 // int flags;
4464 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004465 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004466 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004467 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004468 FieldTypes[3] = LongTy;
4469
Anders Carlsson71993dd2007-08-17 05:31:46 +00004470 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004471 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004472 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004473 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004474 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004475 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004476 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004477 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004478 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004479 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004480 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004481 }
4482
Douglas Gregor838db382010-02-11 01:19:42 +00004483 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004484 }
Mike Stump1eb44332009-09-09 15:08:12 +00004485
Anders Carlsson71993dd2007-08-17 05:31:46 +00004486 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004487}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004488
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004489QualType ASTContext::getObjCSuperType() const {
4490 if (ObjCSuperType.isNull()) {
4491 RecordDecl *ObjCSuperTypeDecl =
4492 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4493 TUDecl->addDecl(ObjCSuperTypeDecl);
4494 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4495 }
4496 return ObjCSuperType;
4497}
4498
Douglas Gregor319ac892009-04-23 22:29:11 +00004499void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004500 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004501 assert(Rec && "Invalid CFConstantStringType");
4502 CFConstantStringTypeDecl = Rec->getDecl();
4503}
4504
Jay Foad4ba2a172011-01-12 09:06:06 +00004505QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004506 if (BlockDescriptorType)
4507 return getTagDeclType(BlockDescriptorType);
4508
4509 RecordDecl *T;
4510 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004511 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004512 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004513 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004514
4515 QualType FieldTypes[] = {
4516 UnsignedLongTy,
4517 UnsignedLongTy,
4518 };
4519
Craig Topper3aa29df2013-07-15 08:24:27 +00004520 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004521 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004522 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004523 };
4524
4525 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004526 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004527 SourceLocation(),
4528 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004529 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004530 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004531 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004532 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004533 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004534 T->addDecl(Field);
4535 }
4536
Douglas Gregor838db382010-02-11 01:19:42 +00004537 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004538
4539 BlockDescriptorType = T;
4540
4541 return getTagDeclType(BlockDescriptorType);
4542}
4543
Jay Foad4ba2a172011-01-12 09:06:06 +00004544QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004545 if (BlockDescriptorExtendedType)
4546 return getTagDeclType(BlockDescriptorExtendedType);
4547
4548 RecordDecl *T;
4549 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004550 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004551 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004552 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004553
4554 QualType FieldTypes[] = {
4555 UnsignedLongTy,
4556 UnsignedLongTy,
4557 getPointerType(VoidPtrTy),
4558 getPointerType(VoidPtrTy)
4559 };
4560
Craig Topper3aa29df2013-07-15 08:24:27 +00004561 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004562 "reserved",
4563 "Size",
4564 "CopyFuncPtr",
4565 "DestroyFuncPtr"
4566 };
4567
4568 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004569 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004570 SourceLocation(),
4571 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004572 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004573 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004574 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004575 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004576 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004577 T->addDecl(Field);
4578 }
4579
Douglas Gregor838db382010-02-11 01:19:42 +00004580 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004581
4582 BlockDescriptorExtendedType = T;
4583
4584 return getTagDeclType(BlockDescriptorExtendedType);
4585}
4586
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004587/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4588/// requires copy/dispose. Note that this must match the logic
4589/// in buildByrefHelpers.
4590bool ASTContext::BlockRequiresCopying(QualType Ty,
4591 const VarDecl *D) {
4592 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4593 const Expr *copyExpr = getBlockVarCopyInits(D);
4594 if (!copyExpr && record->hasTrivialDestructor()) return false;
4595
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004596 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004597 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004598
4599 if (!Ty->isObjCRetainableType()) return false;
4600
4601 Qualifiers qs = Ty.getQualifiers();
4602
4603 // If we have lifetime, that dominates.
4604 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4605 assert(getLangOpts().ObjCAutoRefCount);
4606
4607 switch (lifetime) {
4608 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4609
4610 // These are just bits as far as the runtime is concerned.
4611 case Qualifiers::OCL_ExplicitNone:
4612 case Qualifiers::OCL_Autoreleasing:
4613 return false;
4614
4615 // Tell the runtime that this is ARC __weak, called by the
4616 // byref routines.
4617 case Qualifiers::OCL_Weak:
4618 // ARC __strong __block variables need to be retained.
4619 case Qualifiers::OCL_Strong:
4620 return true;
4621 }
4622 llvm_unreachable("fell out of lifetime switch!");
4623 }
4624 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4625 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004626}
4627
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004628bool ASTContext::getByrefLifetime(QualType Ty,
4629 Qualifiers::ObjCLifetime &LifeTime,
4630 bool &HasByrefExtendedLayout) const {
4631
4632 if (!getLangOpts().ObjC1 ||
4633 getLangOpts().getGC() != LangOptions::NonGC)
4634 return false;
4635
4636 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004637 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004638 HasByrefExtendedLayout = true;
4639 LifeTime = Qualifiers::OCL_None;
4640 }
4641 else if (getLangOpts().ObjCAutoRefCount)
4642 LifeTime = Ty.getObjCLifetime();
4643 // MRR.
4644 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4645 LifeTime = Qualifiers::OCL_ExplicitNone;
4646 else
4647 LifeTime = Qualifiers::OCL_None;
4648 return true;
4649}
4650
Douglas Gregore97179c2011-09-08 01:46:34 +00004651TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4652 if (!ObjCInstanceTypeDecl)
4653 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4654 getTranslationUnitDecl(),
4655 SourceLocation(),
4656 SourceLocation(),
4657 &Idents.get("instancetype"),
4658 getTrivialTypeSourceInfo(getObjCIdType()));
4659 return ObjCInstanceTypeDecl;
4660}
4661
Anders Carlssone8c49532007-10-29 06:33:42 +00004662// This returns true if a type has been typedefed to BOOL:
4663// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004664static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004665 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004666 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4667 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004669 return false;
4670}
4671
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004672/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004673/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004674CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004675 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4676 return CharUnits::Zero();
4677
Ken Dyck199c3d62010-01-11 17:06:35 +00004678 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004679
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004680 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004681 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004682 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004683 // Treat arrays as pointers, since that's how they're passed in.
4684 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004685 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004686 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004687}
4688
4689static inline
4690std::string charUnitsToString(const CharUnits &CU) {
4691 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004692}
4693
John McCall6b5a61b2011-02-07 10:33:21 +00004694/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004695/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004696std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4697 std::string S;
4698
David Chisnall5e530af2009-11-17 19:33:30 +00004699 const BlockDecl *Decl = Expr->getBlockDecl();
4700 QualType BlockTy =
4701 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4702 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004703 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004704 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4705 BlockTy->getAs<FunctionType>()->getResultType(),
4706 S, true /*Extended*/);
4707 else
4708 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4709 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004710 // Compute size of all parameters.
4711 // Start with computing size of a pointer in number of bytes.
4712 // FIXME: There might(should) be a better way of doing this computation!
4713 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004714 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4715 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004716 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004717 E = Decl->param_end(); PI != E; ++PI) {
4718 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004719 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004720 if (sz.isZero())
4721 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004722 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004723 ParmOffset += sz;
4724 }
4725 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004726 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004727 // Block pointer and offset.
4728 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004729
4730 // Argument types.
4731 ParmOffset = PtrSize;
4732 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4733 Decl->param_end(); PI != E; ++PI) {
4734 ParmVarDecl *PVDecl = *PI;
4735 QualType PType = PVDecl->getOriginalType();
4736 if (const ArrayType *AT =
4737 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4738 // Use array's original type only if it has known number of
4739 // elements.
4740 if (!isa<ConstantArrayType>(AT))
4741 PType = PVDecl->getType();
4742 } else if (PType->isFunctionType())
4743 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004744 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004745 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4746 S, true /*Extended*/);
4747 else
4748 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004749 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004750 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004751 }
John McCall6b5a61b2011-02-07 10:33:21 +00004752
4753 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004754}
4755
Douglas Gregorf968d832011-05-27 01:19:52 +00004756bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004757 std::string& S) {
4758 // Encode result type.
4759 getObjCEncodingForType(Decl->getResultType(), S);
4760 CharUnits ParmOffset;
4761 // Compute size of all parameters.
4762 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4763 E = Decl->param_end(); PI != E; ++PI) {
4764 QualType PType = (*PI)->getType();
4765 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004766 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004767 continue;
4768
David Chisnall5389f482010-12-30 14:05:53 +00004769 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004770 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004771 ParmOffset += sz;
4772 }
4773 S += charUnitsToString(ParmOffset);
4774 ParmOffset = CharUnits::Zero();
4775
4776 // Argument types.
4777 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4778 E = Decl->param_end(); PI != E; ++PI) {
4779 ParmVarDecl *PVDecl = *PI;
4780 QualType PType = PVDecl->getOriginalType();
4781 if (const ArrayType *AT =
4782 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4783 // Use array's original type only if it has known number of
4784 // elements.
4785 if (!isa<ConstantArrayType>(AT))
4786 PType = PVDecl->getType();
4787 } else if (PType->isFunctionType())
4788 PType = PVDecl->getType();
4789 getObjCEncodingForType(PType, S);
4790 S += charUnitsToString(ParmOffset);
4791 ParmOffset += getObjCEncodingTypeSize(PType);
4792 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004793
4794 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004795}
4796
Bob Wilsondc8dab62011-11-30 01:57:58 +00004797/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4798/// method parameter or return type. If Extended, include class names and
4799/// block object types.
4800void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4801 QualType T, std::string& S,
4802 bool Extended) const {
4803 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4804 getObjCEncodingForTypeQualifier(QT, S);
4805 // Encode parameter type.
4806 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4807 true /*OutermostType*/,
4808 false /*EncodingProperty*/,
4809 false /*StructField*/,
4810 Extended /*EncodeBlockParameters*/,
4811 Extended /*EncodeClassNames*/);
4812}
4813
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004814/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004815/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004816bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004817 std::string& S,
4818 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004819 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004820 // Encode return type.
4821 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4822 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004823 // Compute size of all parameters.
4824 // Start with computing size of a pointer in number of bytes.
4825 // FIXME: There might(should) be a better way of doing this computation!
4826 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004827 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004828 // The first two arguments (self and _cmd) are pointers; account for
4829 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004830 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004831 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004832 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004833 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004834 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004835 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004836 continue;
4837
Ken Dyck199c3d62010-01-11 17:06:35 +00004838 assert (sz.isPositive() &&
4839 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004840 ParmOffset += sz;
4841 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004842 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004843 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004844 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004845
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004846 // Argument types.
4847 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004848 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004849 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004850 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004851 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004852 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004853 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4854 // Use array's original type only if it has known number of
4855 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004856 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004857 PType = PVDecl->getType();
4858 } else if (PType->isFunctionType())
4859 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004860 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4861 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004862 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004863 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004864 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004865
4866 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004867}
4868
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004869/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004870/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004871/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4872/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004873/// Property attributes are stored as a comma-delimited C string. The simple
4874/// attributes readonly and bycopy are encoded as single characters. The
4875/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4876/// encoded as single characters, followed by an identifier. Property types
4877/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004878/// these attributes are defined by the following enumeration:
4879/// @code
4880/// enum PropertyAttributes {
4881/// kPropertyReadOnly = 'R', // property is read-only.
4882/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4883/// kPropertyByref = '&', // property is a reference to the value last assigned
4884/// kPropertyDynamic = 'D', // property is dynamic
4885/// kPropertyGetter = 'G', // followed by getter selector name
4886/// kPropertySetter = 'S', // followed by setter selector name
4887/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004888/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004889/// kPropertyWeak = 'W' // 'weak' property
4890/// kPropertyStrong = 'P' // property GC'able
4891/// kPropertyNonAtomic = 'N' // property non-atomic
4892/// };
4893/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004894void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004895 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004896 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004897 // Collect information from the property implementation decl(s).
4898 bool Dynamic = false;
4899 ObjCPropertyImplDecl *SynthesizePID = 0;
4900
4901 // FIXME: Duplicated code due to poor abstraction.
4902 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004903 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004904 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4905 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004906 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004907 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004908 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004909 if (PID->getPropertyDecl() == PD) {
4910 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4911 Dynamic = true;
4912 } else {
4913 SynthesizePID = PID;
4914 }
4915 }
4916 }
4917 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004918 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004919 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004920 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004921 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004922 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004923 if (PID->getPropertyDecl() == PD) {
4924 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4925 Dynamic = true;
4926 } else {
4927 SynthesizePID = PID;
4928 }
4929 }
Mike Stump1eb44332009-09-09 15:08:12 +00004930 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004931 }
4932 }
4933
4934 // FIXME: This is not very efficient.
4935 S = "T";
4936
4937 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004938 // GCC has some special rules regarding encoding of properties which
4939 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004940 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004941 true /* outermost type */,
4942 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004943
4944 if (PD->isReadOnly()) {
4945 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004946 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4947 S += ",C";
4948 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4949 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004950 } else {
4951 switch (PD->getSetterKind()) {
4952 case ObjCPropertyDecl::Assign: break;
4953 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004954 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004955 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004956 }
4957 }
4958
4959 // It really isn't clear at all what this means, since properties
4960 // are "dynamic by default".
4961 if (Dynamic)
4962 S += ",D";
4963
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004964 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4965 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004967 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4968 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004969 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004970 }
4971
4972 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4973 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004974 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004975 }
4976
4977 if (SynthesizePID) {
4978 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4979 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004980 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004981 }
4982
4983 // FIXME: OBJCGC: weak & strong
4984}
4985
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004986/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004987/// Another legacy compatibility encoding: 32-bit longs are encoded as
4988/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004989/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4990///
4991void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004992 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004993 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004994 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004995 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004996 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004997 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004998 PointeeTy = IntTy;
4999 }
5000 }
5001}
5002
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005003void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005004 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005005 // We follow the behavior of gcc, expanding structures which are
5006 // directly pointed to, and expanding embedded structures. Note that
5007 // these rules are sufficient to prevent recursive encoding of the
5008 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005009 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005010 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005011}
5012
John McCall3624e9e2012-12-20 02:45:14 +00005013static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5014 BuiltinType::Kind kind) {
5015 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005016 case BuiltinType::Void: return 'v';
5017 case BuiltinType::Bool: return 'B';
5018 case BuiltinType::Char_U:
5019 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005020 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005021 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005022 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005023 case BuiltinType::UInt: return 'I';
5024 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005025 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005026 case BuiltinType::UInt128: return 'T';
5027 case BuiltinType::ULongLong: return 'Q';
5028 case BuiltinType::Char_S:
5029 case BuiltinType::SChar: return 'c';
5030 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005031 case BuiltinType::WChar_S:
5032 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005033 case BuiltinType::Int: return 'i';
5034 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005035 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005036 case BuiltinType::LongLong: return 'q';
5037 case BuiltinType::Int128: return 't';
5038 case BuiltinType::Float: return 'f';
5039 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005040 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005041 case BuiltinType::NullPtr: return '*'; // like char*
5042
5043 case BuiltinType::Half:
5044 // FIXME: potentially need @encodes for these!
5045 return ' ';
5046
5047 case BuiltinType::ObjCId:
5048 case BuiltinType::ObjCClass:
5049 case BuiltinType::ObjCSel:
5050 llvm_unreachable("@encoding ObjC primitive type");
5051
5052 // OpenCL and placeholder types don't need @encodings.
5053 case BuiltinType::OCLImage1d:
5054 case BuiltinType::OCLImage1dArray:
5055 case BuiltinType::OCLImage1dBuffer:
5056 case BuiltinType::OCLImage2d:
5057 case BuiltinType::OCLImage2dArray:
5058 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005059 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005060 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005061 case BuiltinType::Dependent:
5062#define BUILTIN_TYPE(KIND, ID)
5063#define PLACEHOLDER_TYPE(KIND, ID) \
5064 case BuiltinType::KIND:
5065#include "clang/AST/BuiltinTypes.def"
5066 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005067 }
David Blaikie719e53f2013-01-09 17:48:41 +00005068 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005069}
5070
Douglas Gregor5471bc82011-09-08 17:18:35 +00005071static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5072 EnumDecl *Enum = ET->getDecl();
5073
5074 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5075 if (!Enum->isFixed())
5076 return 'i';
5077
5078 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005079 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5080 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005081}
5082
Jay Foad4ba2a172011-01-12 09:06:06 +00005083static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005084 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005085 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005086 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005087 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5088 // The GNU runtime requires more information; bitfields are encoded as b,
5089 // then the offset (in bits) of the first element, then the type of the
5090 // bitfield, then the size in bits. For example, in this structure:
5091 //
5092 // struct
5093 // {
5094 // int integer;
5095 // int flags:2;
5096 // };
5097 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5098 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5099 // information is not especially sensible, but we're stuck with it for
5100 // compatibility with GCC, although providing it breaks anything that
5101 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005102 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005103 const RecordDecl *RD = FD->getParent();
5104 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005105 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005106 if (const EnumType *ET = T->getAs<EnumType>())
5107 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005108 else {
5109 const BuiltinType *BT = T->castAs<BuiltinType>();
5110 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5111 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005112 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005113 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005114}
5115
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005116// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005117void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5118 bool ExpandPointedToStructures,
5119 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005120 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005121 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005122 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005123 bool StructField,
5124 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005125 bool EncodeClassNames,
5126 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005127 CanQualType CT = getCanonicalType(T);
5128 switch (CT->getTypeClass()) {
5129 case Type::Builtin:
5130 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005131 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005132 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005133 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5134 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5135 else
5136 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005137 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005138
John McCall3624e9e2012-12-20 02:45:14 +00005139 case Type::Complex: {
5140 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005141 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005142 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005143 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005144 return;
5145 }
John McCall3624e9e2012-12-20 02:45:14 +00005146
5147 case Type::Atomic: {
5148 const AtomicType *AT = T->castAs<AtomicType>();
5149 S += 'A';
5150 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5151 false, false);
5152 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005153 }
John McCall3624e9e2012-12-20 02:45:14 +00005154
5155 // encoding for pointer or reference types.
5156 case Type::Pointer:
5157 case Type::LValueReference:
5158 case Type::RValueReference: {
5159 QualType PointeeTy;
5160 if (isa<PointerType>(CT)) {
5161 const PointerType *PT = T->castAs<PointerType>();
5162 if (PT->isObjCSelType()) {
5163 S += ':';
5164 return;
5165 }
5166 PointeeTy = PT->getPointeeType();
5167 } else {
5168 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5169 }
5170
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005171 bool isReadOnly = false;
5172 // For historical/compatibility reasons, the read-only qualifier of the
5173 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5174 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005175 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005176 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005177 if (OutermostType && T.isConstQualified()) {
5178 isReadOnly = true;
5179 S += 'r';
5180 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005181 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005182 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005183 while (P->getAs<PointerType>())
5184 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005185 if (P.isConstQualified()) {
5186 isReadOnly = true;
5187 S += 'r';
5188 }
5189 }
5190 if (isReadOnly) {
5191 // Another legacy compatibility encoding. Some ObjC qualifier and type
5192 // combinations need to be rearranged.
5193 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005194 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005195 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005196 }
Mike Stump1eb44332009-09-09 15:08:12 +00005197
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005198 if (PointeeTy->isCharType()) {
5199 // char pointer types should be encoded as '*' unless it is a
5200 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005201 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005202 S += '*';
5203 return;
5204 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005205 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005206 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5207 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5208 S += '#';
5209 return;
5210 }
5211 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5212 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5213 S += '@';
5214 return;
5215 }
5216 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005217 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005218 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005219 getLegacyIntegralTypeEncoding(PointeeTy);
5220
Mike Stump1eb44332009-09-09 15:08:12 +00005221 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005222 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005223 return;
5224 }
John McCall3624e9e2012-12-20 02:45:14 +00005225
5226 case Type::ConstantArray:
5227 case Type::IncompleteArray:
5228 case Type::VariableArray: {
5229 const ArrayType *AT = cast<ArrayType>(CT);
5230
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005231 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005232 // Incomplete arrays are encoded as a pointer to the array element.
5233 S += '^';
5234
Mike Stump1eb44332009-09-09 15:08:12 +00005235 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005236 false, ExpandStructures, FD);
5237 } else {
5238 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005240 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5241 S += llvm::utostr(CAT->getSize().getZExtValue());
5242 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005243 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005244 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5245 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005246 S += '0';
5247 }
Mike Stump1eb44332009-09-09 15:08:12 +00005248
5249 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005250 false, ExpandStructures, FD);
5251 S += ']';
5252 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005253 return;
5254 }
Mike Stump1eb44332009-09-09 15:08:12 +00005255
John McCall3624e9e2012-12-20 02:45:14 +00005256 case Type::FunctionNoProto:
5257 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005258 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005259 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005260
John McCall3624e9e2012-12-20 02:45:14 +00005261 case Type::Record: {
5262 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005263 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005264 // Anonymous structures print as '?'
5265 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5266 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005267 if (ClassTemplateSpecializationDecl *Spec
5268 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5269 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005270 llvm::raw_string_ostream OS(S);
5271 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005272 TemplateArgs.data(),
5273 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005274 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005275 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005276 } else {
5277 S += '?';
5278 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005279 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005280 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005281 if (!RDecl->isUnion()) {
5282 getObjCEncodingForStructureImpl(RDecl, S, FD);
5283 } else {
5284 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5285 FieldEnd = RDecl->field_end();
5286 Field != FieldEnd; ++Field) {
5287 if (FD) {
5288 S += '"';
5289 S += Field->getNameAsString();
5290 S += '"';
5291 }
Mike Stump1eb44332009-09-09 15:08:12 +00005292
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005293 // Special case bit-fields.
5294 if (Field->isBitField()) {
5295 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005296 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005297 } else {
5298 QualType qt = Field->getType();
5299 getLegacyIntegralTypeEncoding(qt);
5300 getObjCEncodingForTypeImpl(qt, S, false, true,
5301 FD, /*OutermostType*/false,
5302 /*EncodingProperty*/false,
5303 /*StructField*/true);
5304 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005305 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005306 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005307 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005308 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005309 return;
5310 }
Mike Stump1eb44332009-09-09 15:08:12 +00005311
John McCall3624e9e2012-12-20 02:45:14 +00005312 case Type::BlockPointer: {
5313 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005314 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005315 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005316 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005317
5318 S += '<';
5319 // Block return type
5320 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5321 ExpandPointedToStructures, ExpandStructures,
5322 FD,
5323 false /* OutermostType */,
5324 EncodingProperty,
5325 false /* StructField */,
5326 EncodeBlockParameters,
5327 EncodeClassNames);
5328 // Block self
5329 S += "@?";
5330 // Block parameters
5331 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5332 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5333 E = FPT->arg_type_end(); I && (I != E); ++I) {
5334 getObjCEncodingForTypeImpl(*I, S,
5335 ExpandPointedToStructures,
5336 ExpandStructures,
5337 FD,
5338 false /* OutermostType */,
5339 EncodingProperty,
5340 false /* StructField */,
5341 EncodeBlockParameters,
5342 EncodeClassNames);
5343 }
5344 }
5345 S += '>';
5346 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005347 return;
5348 }
Mike Stump1eb44332009-09-09 15:08:12 +00005349
John McCall3624e9e2012-12-20 02:45:14 +00005350 case Type::ObjCObject:
5351 case Type::ObjCInterface: {
5352 // Ignore protocol qualifiers when mangling at this level.
5353 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005354
John McCall3624e9e2012-12-20 02:45:14 +00005355 // The assumption seems to be that this assert will succeed
5356 // because nested levels will have filtered out 'id' and 'Class'.
5357 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005358 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005359 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005360 S += '{';
5361 const IdentifierInfo *II = OI->getIdentifier();
5362 S += II->getName();
5363 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005364 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005365 DeepCollectObjCIvars(OI, true, Ivars);
5366 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005367 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005368 if (Field->isBitField())
5369 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005370 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005371 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5372 false, false, false, false, false,
5373 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005374 }
5375 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005376 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005377 }
Mike Stump1eb44332009-09-09 15:08:12 +00005378
John McCall3624e9e2012-12-20 02:45:14 +00005379 case Type::ObjCObjectPointer: {
5380 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005381 if (OPT->isObjCIdType()) {
5382 S += '@';
5383 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005384 }
Mike Stump1eb44332009-09-09 15:08:12 +00005385
Steve Naroff27d20a22009-10-28 22:03:49 +00005386 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5387 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5388 // Since this is a binary compatibility issue, need to consult with runtime
5389 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005390 S += '#';
5391 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005392 }
Mike Stump1eb44332009-09-09 15:08:12 +00005393
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005394 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005395 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005396 ExpandPointedToStructures,
5397 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005398 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005399 // Note that we do extended encoding of protocol qualifer list
5400 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005401 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005402 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5403 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005404 S += '<';
5405 S += (*I)->getNameAsString();
5406 S += '>';
5407 }
5408 S += '"';
5409 }
5410 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005411 }
Mike Stump1eb44332009-09-09 15:08:12 +00005412
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005413 QualType PointeeTy = OPT->getPointeeType();
5414 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005415 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5416 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005417 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005418 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005419 // {...};
5420 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005421 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005422 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005423 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5424 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5425 DeepCollectObjCIvars(OI, true, Ivars);
5426 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5427 if (cast<FieldDecl>(Ivars[i]) == FD) {
5428 S += '{';
5429 S += OI->getIdentifier()->getName();
5430 S += '}';
5431 return;
5432 }
5433 }
5434 }
Mike Stump1eb44332009-09-09 15:08:12 +00005435 getObjCEncodingForTypeImpl(PointeeTy, S,
5436 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005437 NULL,
5438 false, false, false, false, false,
5439 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005440 return;
5441 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005442
5443 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005444 if (OPT->getInterfaceDecl() &&
5445 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005446 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005447 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005448 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5449 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005450 S += '<';
5451 S += (*I)->getNameAsString();
5452 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005453 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005454 S += '"';
5455 }
5456 return;
5457 }
Mike Stump1eb44332009-09-09 15:08:12 +00005458
John McCall532ec7b2010-05-17 23:56:34 +00005459 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005460 // FIXME: we shoul do better than that. 'M' is available.
5461 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005462 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005463
John McCall3624e9e2012-12-20 02:45:14 +00005464 case Type::Vector:
5465 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005466 // This matches gcc's encoding, even though technically it is
5467 // insufficient.
5468 // FIXME. We should do a better job than gcc.
5469 return;
John McCall3624e9e2012-12-20 02:45:14 +00005470
Richard Smithdc7a4f52013-04-30 13:56:41 +00005471 case Type::Auto:
5472 // We could see an undeduced auto type here during error recovery.
5473 // Just ignore it.
5474 return;
5475
John McCall3624e9e2012-12-20 02:45:14 +00005476#define ABSTRACT_TYPE(KIND, BASE)
5477#define TYPE(KIND, BASE)
5478#define DEPENDENT_TYPE(KIND, BASE) \
5479 case Type::KIND:
5480#define NON_CANONICAL_TYPE(KIND, BASE) \
5481 case Type::KIND:
5482#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5483 case Type::KIND:
5484#include "clang/AST/TypeNodes.def"
5485 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005486 }
John McCall3624e9e2012-12-20 02:45:14 +00005487 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005488}
5489
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005490void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5491 std::string &S,
5492 const FieldDecl *FD,
5493 bool includeVBases) const {
5494 assert(RDecl && "Expected non-null RecordDecl");
5495 assert(!RDecl->isUnion() && "Should not be called for unions");
5496 if (!RDecl->getDefinition())
5497 return;
5498
5499 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5500 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5501 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5502
5503 if (CXXRec) {
5504 for (CXXRecordDecl::base_class_iterator
5505 BI = CXXRec->bases_begin(),
5506 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5507 if (!BI->isVirtual()) {
5508 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005509 if (base->isEmpty())
5510 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005511 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005512 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5513 std::make_pair(offs, base));
5514 }
5515 }
5516 }
5517
5518 unsigned i = 0;
5519 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5520 FieldEnd = RDecl->field_end();
5521 Field != FieldEnd; ++Field, ++i) {
5522 uint64_t offs = layout.getFieldOffset(i);
5523 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005524 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005525 }
5526
5527 if (CXXRec && includeVBases) {
5528 for (CXXRecordDecl::base_class_iterator
5529 BI = CXXRec->vbases_begin(),
5530 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5531 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005532 if (base->isEmpty())
5533 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005534 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005535 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5536 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5537 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005538 }
5539 }
5540
5541 CharUnits size;
5542 if (CXXRec) {
5543 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5544 } else {
5545 size = layout.getSize();
5546 }
5547
5548 uint64_t CurOffs = 0;
5549 std::multimap<uint64_t, NamedDecl *>::iterator
5550 CurLayObj = FieldOrBaseOffsets.begin();
5551
Douglas Gregor58db7a52012-04-27 22:30:01 +00005552 if (CXXRec && CXXRec->isDynamicClass() &&
5553 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005554 if (FD) {
5555 S += "\"_vptr$";
5556 std::string recname = CXXRec->getNameAsString();
5557 if (recname.empty()) recname = "?";
5558 S += recname;
5559 S += '"';
5560 }
5561 S += "^^?";
5562 CurOffs += getTypeSize(VoidPtrTy);
5563 }
5564
5565 if (!RDecl->hasFlexibleArrayMember()) {
5566 // Mark the end of the structure.
5567 uint64_t offs = toBits(size);
5568 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5569 std::make_pair(offs, (NamedDecl*)0));
5570 }
5571
5572 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5573 assert(CurOffs <= CurLayObj->first);
5574
5575 if (CurOffs < CurLayObj->first) {
5576 uint64_t padding = CurLayObj->first - CurOffs;
5577 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5578 // packing/alignment of members is different that normal, in which case
5579 // the encoding will be out-of-sync with the real layout.
5580 // If the runtime switches to just consider the size of types without
5581 // taking into account alignment, we could make padding explicit in the
5582 // encoding (e.g. using arrays of chars). The encoding strings would be
5583 // longer then though.
5584 CurOffs += padding;
5585 }
5586
5587 NamedDecl *dcl = CurLayObj->second;
5588 if (dcl == 0)
5589 break; // reached end of structure.
5590
5591 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5592 // We expand the bases without their virtual bases since those are going
5593 // in the initial structure. Note that this differs from gcc which
5594 // expands virtual bases each time one is encountered in the hierarchy,
5595 // making the encoding type bigger than it really is.
5596 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005597 assert(!base->isEmpty());
5598 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005599 } else {
5600 FieldDecl *field = cast<FieldDecl>(dcl);
5601 if (FD) {
5602 S += '"';
5603 S += field->getNameAsString();
5604 S += '"';
5605 }
5606
5607 if (field->isBitField()) {
5608 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005609 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005610 } else {
5611 QualType qt = field->getType();
5612 getLegacyIntegralTypeEncoding(qt);
5613 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5614 /*OutermostType*/false,
5615 /*EncodingProperty*/false,
5616 /*StructField*/true);
5617 CurOffs += getTypeSize(field->getType());
5618 }
5619 }
5620 }
5621}
5622
Mike Stump1eb44332009-09-09 15:08:12 +00005623void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005624 std::string& S) const {
5625 if (QT & Decl::OBJC_TQ_In)
5626 S += 'n';
5627 if (QT & Decl::OBJC_TQ_Inout)
5628 S += 'N';
5629 if (QT & Decl::OBJC_TQ_Out)
5630 S += 'o';
5631 if (QT & Decl::OBJC_TQ_Bycopy)
5632 S += 'O';
5633 if (QT & Decl::OBJC_TQ_Byref)
5634 S += 'R';
5635 if (QT & Decl::OBJC_TQ_Oneway)
5636 S += 'V';
5637}
5638
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005639TypedefDecl *ASTContext::getObjCIdDecl() const {
5640 if (!ObjCIdDecl) {
5641 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5642 T = getObjCObjectPointerType(T);
5643 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5644 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5645 getTranslationUnitDecl(),
5646 SourceLocation(), SourceLocation(),
5647 &Idents.get("id"), IdInfo);
5648 }
5649
5650 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005651}
5652
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005653TypedefDecl *ASTContext::getObjCSelDecl() const {
5654 if (!ObjCSelDecl) {
5655 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5656 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5657 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5658 getTranslationUnitDecl(),
5659 SourceLocation(), SourceLocation(),
5660 &Idents.get("SEL"), SelInfo);
5661 }
5662 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005663}
5664
Douglas Gregor79d67262011-08-12 05:59:41 +00005665TypedefDecl *ASTContext::getObjCClassDecl() const {
5666 if (!ObjCClassDecl) {
5667 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5668 T = getObjCObjectPointerType(T);
5669 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5670 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5671 getTranslationUnitDecl(),
5672 SourceLocation(), SourceLocation(),
5673 &Idents.get("Class"), ClassInfo);
5674 }
5675
5676 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005677}
5678
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005679ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5680 if (!ObjCProtocolClassDecl) {
5681 ObjCProtocolClassDecl
5682 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5683 SourceLocation(),
5684 &Idents.get("Protocol"),
5685 /*PrevDecl=*/0,
5686 SourceLocation(), true);
5687 }
5688
5689 return ObjCProtocolClassDecl;
5690}
5691
Meador Ingec5613b22012-06-16 03:34:49 +00005692//===----------------------------------------------------------------------===//
5693// __builtin_va_list Construction Functions
5694//===----------------------------------------------------------------------===//
5695
5696static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5697 // typedef char* __builtin_va_list;
5698 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5699 TypeSourceInfo *TInfo
5700 = Context->getTrivialTypeSourceInfo(CharPtrType);
5701
5702 TypedefDecl *VaListTypeDecl
5703 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5704 Context->getTranslationUnitDecl(),
5705 SourceLocation(), SourceLocation(),
5706 &Context->Idents.get("__builtin_va_list"),
5707 TInfo);
5708 return VaListTypeDecl;
5709}
5710
5711static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5712 // typedef void* __builtin_va_list;
5713 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5714 TypeSourceInfo *TInfo
5715 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5716
5717 TypedefDecl *VaListTypeDecl
5718 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5719 Context->getTranslationUnitDecl(),
5720 SourceLocation(), SourceLocation(),
5721 &Context->Idents.get("__builtin_va_list"),
5722 TInfo);
5723 return VaListTypeDecl;
5724}
5725
Tim Northoverc264e162013-01-31 12:13:10 +00005726static TypedefDecl *
5727CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5728 RecordDecl *VaListTagDecl;
5729 if (Context->getLangOpts().CPlusPlus) {
5730 // namespace std { struct __va_list {
5731 NamespaceDecl *NS;
5732 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5733 Context->getTranslationUnitDecl(),
5734 /*Inline*/false, SourceLocation(),
5735 SourceLocation(), &Context->Idents.get("std"),
5736 /*PrevDecl*/0);
5737
5738 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5739 Context->getTranslationUnitDecl(),
5740 SourceLocation(), SourceLocation(),
5741 &Context->Idents.get("__va_list"));
5742 VaListTagDecl->setDeclContext(NS);
5743 } else {
5744 // struct __va_list
5745 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5746 Context->getTranslationUnitDecl(),
5747 &Context->Idents.get("__va_list"));
5748 }
5749
5750 VaListTagDecl->startDefinition();
5751
5752 const size_t NumFields = 5;
5753 QualType FieldTypes[NumFields];
5754 const char *FieldNames[NumFields];
5755
5756 // void *__stack;
5757 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5758 FieldNames[0] = "__stack";
5759
5760 // void *__gr_top;
5761 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5762 FieldNames[1] = "__gr_top";
5763
5764 // void *__vr_top;
5765 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5766 FieldNames[2] = "__vr_top";
5767
5768 // int __gr_offs;
5769 FieldTypes[3] = Context->IntTy;
5770 FieldNames[3] = "__gr_offs";
5771
5772 // int __vr_offs;
5773 FieldTypes[4] = Context->IntTy;
5774 FieldNames[4] = "__vr_offs";
5775
5776 // Create fields
5777 for (unsigned i = 0; i < NumFields; ++i) {
5778 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5779 VaListTagDecl,
5780 SourceLocation(),
5781 SourceLocation(),
5782 &Context->Idents.get(FieldNames[i]),
5783 FieldTypes[i], /*TInfo=*/0,
5784 /*BitWidth=*/0,
5785 /*Mutable=*/false,
5786 ICIS_NoInit);
5787 Field->setAccess(AS_public);
5788 VaListTagDecl->addDecl(Field);
5789 }
5790 VaListTagDecl->completeDefinition();
5791 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5792 Context->VaListTagTy = VaListTagType;
5793
5794 // } __builtin_va_list;
5795 TypedefDecl *VaListTypedefDecl
5796 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5797 Context->getTranslationUnitDecl(),
5798 SourceLocation(), SourceLocation(),
5799 &Context->Idents.get("__builtin_va_list"),
5800 Context->getTrivialTypeSourceInfo(VaListTagType));
5801
5802 return VaListTypedefDecl;
5803}
5804
Meador Ingec5613b22012-06-16 03:34:49 +00005805static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5806 // typedef struct __va_list_tag {
5807 RecordDecl *VaListTagDecl;
5808
5809 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5810 Context->getTranslationUnitDecl(),
5811 &Context->Idents.get("__va_list_tag"));
5812 VaListTagDecl->startDefinition();
5813
5814 const size_t NumFields = 5;
5815 QualType FieldTypes[NumFields];
5816 const char *FieldNames[NumFields];
5817
5818 // unsigned char gpr;
5819 FieldTypes[0] = Context->UnsignedCharTy;
5820 FieldNames[0] = "gpr";
5821
5822 // unsigned char fpr;
5823 FieldTypes[1] = Context->UnsignedCharTy;
5824 FieldNames[1] = "fpr";
5825
5826 // unsigned short reserved;
5827 FieldTypes[2] = Context->UnsignedShortTy;
5828 FieldNames[2] = "reserved";
5829
5830 // void* overflow_arg_area;
5831 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5832 FieldNames[3] = "overflow_arg_area";
5833
5834 // void* reg_save_area;
5835 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5836 FieldNames[4] = "reg_save_area";
5837
5838 // Create fields
5839 for (unsigned i = 0; i < NumFields; ++i) {
5840 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5841 SourceLocation(),
5842 SourceLocation(),
5843 &Context->Idents.get(FieldNames[i]),
5844 FieldTypes[i], /*TInfo=*/0,
5845 /*BitWidth=*/0,
5846 /*Mutable=*/false,
5847 ICIS_NoInit);
5848 Field->setAccess(AS_public);
5849 VaListTagDecl->addDecl(Field);
5850 }
5851 VaListTagDecl->completeDefinition();
5852 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005853 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005854
5855 // } __va_list_tag;
5856 TypedefDecl *VaListTagTypedefDecl
5857 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5858 Context->getTranslationUnitDecl(),
5859 SourceLocation(), SourceLocation(),
5860 &Context->Idents.get("__va_list_tag"),
5861 Context->getTrivialTypeSourceInfo(VaListTagType));
5862 QualType VaListTagTypedefType =
5863 Context->getTypedefType(VaListTagTypedefDecl);
5864
5865 // typedef __va_list_tag __builtin_va_list[1];
5866 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5867 QualType VaListTagArrayType
5868 = Context->getConstantArrayType(VaListTagTypedefType,
5869 Size, ArrayType::Normal, 0);
5870 TypeSourceInfo *TInfo
5871 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5872 TypedefDecl *VaListTypedefDecl
5873 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5874 Context->getTranslationUnitDecl(),
5875 SourceLocation(), SourceLocation(),
5876 &Context->Idents.get("__builtin_va_list"),
5877 TInfo);
5878
5879 return VaListTypedefDecl;
5880}
5881
5882static TypedefDecl *
5883CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5884 // typedef struct __va_list_tag {
5885 RecordDecl *VaListTagDecl;
5886 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5887 Context->getTranslationUnitDecl(),
5888 &Context->Idents.get("__va_list_tag"));
5889 VaListTagDecl->startDefinition();
5890
5891 const size_t NumFields = 4;
5892 QualType FieldTypes[NumFields];
5893 const char *FieldNames[NumFields];
5894
5895 // unsigned gp_offset;
5896 FieldTypes[0] = Context->UnsignedIntTy;
5897 FieldNames[0] = "gp_offset";
5898
5899 // unsigned fp_offset;
5900 FieldTypes[1] = Context->UnsignedIntTy;
5901 FieldNames[1] = "fp_offset";
5902
5903 // void* overflow_arg_area;
5904 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5905 FieldNames[2] = "overflow_arg_area";
5906
5907 // void* reg_save_area;
5908 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5909 FieldNames[3] = "reg_save_area";
5910
5911 // Create fields
5912 for (unsigned i = 0; i < NumFields; ++i) {
5913 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5914 VaListTagDecl,
5915 SourceLocation(),
5916 SourceLocation(),
5917 &Context->Idents.get(FieldNames[i]),
5918 FieldTypes[i], /*TInfo=*/0,
5919 /*BitWidth=*/0,
5920 /*Mutable=*/false,
5921 ICIS_NoInit);
5922 Field->setAccess(AS_public);
5923 VaListTagDecl->addDecl(Field);
5924 }
5925 VaListTagDecl->completeDefinition();
5926 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005927 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005928
5929 // } __va_list_tag;
5930 TypedefDecl *VaListTagTypedefDecl
5931 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5932 Context->getTranslationUnitDecl(),
5933 SourceLocation(), SourceLocation(),
5934 &Context->Idents.get("__va_list_tag"),
5935 Context->getTrivialTypeSourceInfo(VaListTagType));
5936 QualType VaListTagTypedefType =
5937 Context->getTypedefType(VaListTagTypedefDecl);
5938
5939 // typedef __va_list_tag __builtin_va_list[1];
5940 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5941 QualType VaListTagArrayType
5942 = Context->getConstantArrayType(VaListTagTypedefType,
5943 Size, ArrayType::Normal,0);
5944 TypeSourceInfo *TInfo
5945 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5946 TypedefDecl *VaListTypedefDecl
5947 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5948 Context->getTranslationUnitDecl(),
5949 SourceLocation(), SourceLocation(),
5950 &Context->Idents.get("__builtin_va_list"),
5951 TInfo);
5952
5953 return VaListTypedefDecl;
5954}
5955
5956static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5957 // typedef int __builtin_va_list[4];
5958 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5959 QualType IntArrayType
5960 = Context->getConstantArrayType(Context->IntTy,
5961 Size, ArrayType::Normal, 0);
5962 TypedefDecl *VaListTypedefDecl
5963 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5964 Context->getTranslationUnitDecl(),
5965 SourceLocation(), SourceLocation(),
5966 &Context->Idents.get("__builtin_va_list"),
5967 Context->getTrivialTypeSourceInfo(IntArrayType));
5968
5969 return VaListTypedefDecl;
5970}
5971
Logan Chieneae5a8202012-10-10 06:56:20 +00005972static TypedefDecl *
5973CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5974 RecordDecl *VaListDecl;
5975 if (Context->getLangOpts().CPlusPlus) {
5976 // namespace std { struct __va_list {
5977 NamespaceDecl *NS;
5978 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5979 Context->getTranslationUnitDecl(),
5980 /*Inline*/false, SourceLocation(),
5981 SourceLocation(), &Context->Idents.get("std"),
5982 /*PrevDecl*/0);
5983
5984 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5985 Context->getTranslationUnitDecl(),
5986 SourceLocation(), SourceLocation(),
5987 &Context->Idents.get("__va_list"));
5988
5989 VaListDecl->setDeclContext(NS);
5990
5991 } else {
5992 // struct __va_list {
5993 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5994 Context->getTranslationUnitDecl(),
5995 &Context->Idents.get("__va_list"));
5996 }
5997
5998 VaListDecl->startDefinition();
5999
6000 // void * __ap;
6001 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6002 VaListDecl,
6003 SourceLocation(),
6004 SourceLocation(),
6005 &Context->Idents.get("__ap"),
6006 Context->getPointerType(Context->VoidTy),
6007 /*TInfo=*/0,
6008 /*BitWidth=*/0,
6009 /*Mutable=*/false,
6010 ICIS_NoInit);
6011 Field->setAccess(AS_public);
6012 VaListDecl->addDecl(Field);
6013
6014 // };
6015 VaListDecl->completeDefinition();
6016
6017 // typedef struct __va_list __builtin_va_list;
6018 TypeSourceInfo *TInfo
6019 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6020
6021 TypedefDecl *VaListTypeDecl
6022 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6023 Context->getTranslationUnitDecl(),
6024 SourceLocation(), SourceLocation(),
6025 &Context->Idents.get("__builtin_va_list"),
6026 TInfo);
6027
6028 return VaListTypeDecl;
6029}
6030
Ulrich Weigandb8409212013-05-06 16:26:41 +00006031static TypedefDecl *
6032CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6033 // typedef struct __va_list_tag {
6034 RecordDecl *VaListTagDecl;
6035 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6036 Context->getTranslationUnitDecl(),
6037 &Context->Idents.get("__va_list_tag"));
6038 VaListTagDecl->startDefinition();
6039
6040 const size_t NumFields = 4;
6041 QualType FieldTypes[NumFields];
6042 const char *FieldNames[NumFields];
6043
6044 // long __gpr;
6045 FieldTypes[0] = Context->LongTy;
6046 FieldNames[0] = "__gpr";
6047
6048 // long __fpr;
6049 FieldTypes[1] = Context->LongTy;
6050 FieldNames[1] = "__fpr";
6051
6052 // void *__overflow_arg_area;
6053 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6054 FieldNames[2] = "__overflow_arg_area";
6055
6056 // void *__reg_save_area;
6057 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6058 FieldNames[3] = "__reg_save_area";
6059
6060 // Create fields
6061 for (unsigned i = 0; i < NumFields; ++i) {
6062 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6063 VaListTagDecl,
6064 SourceLocation(),
6065 SourceLocation(),
6066 &Context->Idents.get(FieldNames[i]),
6067 FieldTypes[i], /*TInfo=*/0,
6068 /*BitWidth=*/0,
6069 /*Mutable=*/false,
6070 ICIS_NoInit);
6071 Field->setAccess(AS_public);
6072 VaListTagDecl->addDecl(Field);
6073 }
6074 VaListTagDecl->completeDefinition();
6075 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6076 Context->VaListTagTy = VaListTagType;
6077
6078 // } __va_list_tag;
6079 TypedefDecl *VaListTagTypedefDecl
6080 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6081 Context->getTranslationUnitDecl(),
6082 SourceLocation(), SourceLocation(),
6083 &Context->Idents.get("__va_list_tag"),
6084 Context->getTrivialTypeSourceInfo(VaListTagType));
6085 QualType VaListTagTypedefType =
6086 Context->getTypedefType(VaListTagTypedefDecl);
6087
6088 // typedef __va_list_tag __builtin_va_list[1];
6089 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6090 QualType VaListTagArrayType
6091 = Context->getConstantArrayType(VaListTagTypedefType,
6092 Size, ArrayType::Normal,0);
6093 TypeSourceInfo *TInfo
6094 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6095 TypedefDecl *VaListTypedefDecl
6096 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6097 Context->getTranslationUnitDecl(),
6098 SourceLocation(), SourceLocation(),
6099 &Context->Idents.get("__builtin_va_list"),
6100 TInfo);
6101
6102 return VaListTypedefDecl;
6103}
6104
Meador Ingec5613b22012-06-16 03:34:49 +00006105static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6106 TargetInfo::BuiltinVaListKind Kind) {
6107 switch (Kind) {
6108 case TargetInfo::CharPtrBuiltinVaList:
6109 return CreateCharPtrBuiltinVaListDecl(Context);
6110 case TargetInfo::VoidPtrBuiltinVaList:
6111 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006112 case TargetInfo::AArch64ABIBuiltinVaList:
6113 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006114 case TargetInfo::PowerABIBuiltinVaList:
6115 return CreatePowerABIBuiltinVaListDecl(Context);
6116 case TargetInfo::X86_64ABIBuiltinVaList:
6117 return CreateX86_64ABIBuiltinVaListDecl(Context);
6118 case TargetInfo::PNaClABIBuiltinVaList:
6119 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006120 case TargetInfo::AAPCSABIBuiltinVaList:
6121 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006122 case TargetInfo::SystemZBuiltinVaList:
6123 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006124 }
6125
6126 llvm_unreachable("Unhandled __builtin_va_list type kind");
6127}
6128
6129TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6130 if (!BuiltinVaListDecl)
6131 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6132
6133 return BuiltinVaListDecl;
6134}
6135
Meador Ingefb40e3f2012-07-01 15:57:25 +00006136QualType ASTContext::getVaListTagType() const {
6137 // Force the creation of VaListTagTy by building the __builtin_va_list
6138 // declaration.
6139 if (VaListTagTy.isNull())
6140 (void) getBuiltinVaListDecl();
6141
6142 return VaListTagTy;
6143}
6144
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006145void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006146 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006147 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006149 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006150}
6151
John McCall0bd6feb2009-12-02 08:04:21 +00006152/// \brief Retrieve the template name that corresponds to a non-empty
6153/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006154TemplateName
6155ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6156 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006157 unsigned size = End - Begin;
6158 assert(size > 1 && "set is not overloaded!");
6159
6160 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6161 size * sizeof(FunctionTemplateDecl*));
6162 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6163
6164 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006165 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006166 NamedDecl *D = *I;
6167 assert(isa<FunctionTemplateDecl>(D) ||
6168 (isa<UsingShadowDecl>(D) &&
6169 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6170 *Storage++ = D;
6171 }
6172
6173 return TemplateName(OT);
6174}
6175
Douglas Gregor7532dc62009-03-30 22:58:21 +00006176/// \brief Retrieve the template name that represents a qualified
6177/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006178TemplateName
6179ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6180 bool TemplateKeyword,
6181 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006182 assert(NNS && "Missing nested-name-specifier in qualified template name");
6183
Douglas Gregor789b1f62010-02-04 18:10:26 +00006184 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006185 llvm::FoldingSetNodeID ID;
6186 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6187
6188 void *InsertPos = 0;
6189 QualifiedTemplateName *QTN =
6190 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6191 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006192 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6193 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006194 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6195 }
6196
6197 return TemplateName(QTN);
6198}
6199
6200/// \brief Retrieve the template name that represents a dependent
6201/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006202TemplateName
6203ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6204 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006205 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006206 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006207
6208 llvm::FoldingSetNodeID ID;
6209 DependentTemplateName::Profile(ID, NNS, Name);
6210
6211 void *InsertPos = 0;
6212 DependentTemplateName *QTN =
6213 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6214
6215 if (QTN)
6216 return TemplateName(QTN);
6217
6218 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6219 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006220 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6221 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006222 } else {
6223 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006224 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6225 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006226 DependentTemplateName *CheckQTN =
6227 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6228 assert(!CheckQTN && "Dependent type name canonicalization broken");
6229 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006230 }
6231
6232 DependentTemplateNames.InsertNode(QTN, InsertPos);
6233 return TemplateName(QTN);
6234}
6235
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006236/// \brief Retrieve the template name that represents a dependent
6237/// template name such as \c MetaFun::template operator+.
6238TemplateName
6239ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006240 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006241 assert((!NNS || NNS->isDependent()) &&
6242 "Nested name specifier must be dependent");
6243
6244 llvm::FoldingSetNodeID ID;
6245 DependentTemplateName::Profile(ID, NNS, Operator);
6246
6247 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006248 DependentTemplateName *QTN
6249 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006250
6251 if (QTN)
6252 return TemplateName(QTN);
6253
6254 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6255 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006256 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6257 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006258 } else {
6259 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006260 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6261 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006262
6263 DependentTemplateName *CheckQTN
6264 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6265 assert(!CheckQTN && "Dependent template name canonicalization broken");
6266 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006267 }
6268
6269 DependentTemplateNames.InsertNode(QTN, InsertPos);
6270 return TemplateName(QTN);
6271}
6272
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006273TemplateName
John McCall14606042011-06-30 08:33:18 +00006274ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6275 TemplateName replacement) const {
6276 llvm::FoldingSetNodeID ID;
6277 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6278
6279 void *insertPos = 0;
6280 SubstTemplateTemplateParmStorage *subst
6281 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6282
6283 if (!subst) {
6284 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6285 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6286 }
6287
6288 return TemplateName(subst);
6289}
6290
6291TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006292ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6293 const TemplateArgument &ArgPack) const {
6294 ASTContext &Self = const_cast<ASTContext &>(*this);
6295 llvm::FoldingSetNodeID ID;
6296 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6297
6298 void *InsertPos = 0;
6299 SubstTemplateTemplateParmPackStorage *Subst
6300 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6301
6302 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006303 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006304 ArgPack.pack_size(),
6305 ArgPack.pack_begin());
6306 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6307 }
6308
6309 return TemplateName(Subst);
6310}
6311
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006312/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006313/// TargetInfo, produce the corresponding type. The unsigned @p Type
6314/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006315CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006316 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006317 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006318 case TargetInfo::SignedShort: return ShortTy;
6319 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6320 case TargetInfo::SignedInt: return IntTy;
6321 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6322 case TargetInfo::SignedLong: return LongTy;
6323 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6324 case TargetInfo::SignedLongLong: return LongLongTy;
6325 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6326 }
6327
David Blaikieb219cfc2011-09-23 05:06:16 +00006328 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006329}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006330
6331//===----------------------------------------------------------------------===//
6332// Type Predicates.
6333//===----------------------------------------------------------------------===//
6334
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006335/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6336/// garbage collection attribute.
6337///
John McCallae278a32011-01-12 00:34:59 +00006338Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006339 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006340 return Qualifiers::GCNone;
6341
David Blaikie4e4d0842012-03-11 07:00:24 +00006342 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006343 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6344
6345 // Default behaviour under objective-C's gc is for ObjC pointers
6346 // (or pointers to them) be treated as though they were declared
6347 // as __strong.
6348 if (GCAttrs == Qualifiers::GCNone) {
6349 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6350 return Qualifiers::Strong;
6351 else if (Ty->isPointerType())
6352 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6353 } else {
6354 // It's not valid to set GC attributes on anything that isn't a
6355 // pointer.
6356#ifndef NDEBUG
6357 QualType CT = Ty->getCanonicalTypeInternal();
6358 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6359 CT = AT->getElementType();
6360 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6361#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006362 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006363 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006364}
6365
Chris Lattner6ac46a42008-04-07 06:51:04 +00006366//===----------------------------------------------------------------------===//
6367// Type Compatibility Testing
6368//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006369
Mike Stump1eb44332009-09-09 15:08:12 +00006370/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006371/// compatible.
6372static bool areCompatVectorTypes(const VectorType *LHS,
6373 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006374 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006375 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006376 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006377}
6378
Douglas Gregor255210e2010-08-06 10:14:59 +00006379bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6380 QualType SecondVec) {
6381 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6382 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6383
6384 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6385 return true;
6386
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006387 // Treat Neon vector types and most AltiVec vector types as if they are the
6388 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006389 const VectorType *First = FirstVec->getAs<VectorType>();
6390 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006391 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006392 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006393 First->getVectorKind() != VectorType::AltiVecPixel &&
6394 First->getVectorKind() != VectorType::AltiVecBool &&
6395 Second->getVectorKind() != VectorType::AltiVecPixel &&
6396 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006397 return true;
6398
6399 return false;
6400}
6401
Steve Naroff4084c302009-07-23 01:01:38 +00006402//===----------------------------------------------------------------------===//
6403// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6404//===----------------------------------------------------------------------===//
6405
6406/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6407/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006408bool
6409ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6410 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006411 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006412 return true;
6413 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6414 E = rProto->protocol_end(); PI != E; ++PI)
6415 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6416 return true;
6417 return false;
6418}
6419
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006420/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6421/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006422bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6423 QualType rhs) {
6424 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6425 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6426 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6427
6428 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6429 E = lhsQID->qual_end(); I != E; ++I) {
6430 bool match = false;
6431 ObjCProtocolDecl *lhsProto = *I;
6432 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6433 E = rhsOPT->qual_end(); J != E; ++J) {
6434 ObjCProtocolDecl *rhsProto = *J;
6435 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6436 match = true;
6437 break;
6438 }
6439 }
6440 if (!match)
6441 return false;
6442 }
6443 return true;
6444}
6445
Steve Naroff4084c302009-07-23 01:01:38 +00006446/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6447/// ObjCQualifiedIDType.
6448bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6449 bool compare) {
6450 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006451 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006452 lhs->isObjCIdType() || lhs->isObjCClassType())
6453 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006454 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006455 rhs->isObjCIdType() || rhs->isObjCClassType())
6456 return true;
6457
6458 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006459 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006460
Steve Naroff4084c302009-07-23 01:01:38 +00006461 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006462
Steve Naroff4084c302009-07-23 01:01:38 +00006463 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006464 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006465 // make sure we check the class hierarchy.
6466 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6467 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6468 E = lhsQID->qual_end(); I != E; ++I) {
6469 // when comparing an id<P> on lhs with a static type on rhs,
6470 // see if static class implements all of id's protocols, directly or
6471 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006472 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006473 return false;
6474 }
6475 }
6476 // If there are no qualifiers and no interface, we have an 'id'.
6477 return true;
6478 }
Mike Stump1eb44332009-09-09 15:08:12 +00006479 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006480 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6481 E = lhsQID->qual_end(); I != E; ++I) {
6482 ObjCProtocolDecl *lhsProto = *I;
6483 bool match = false;
6484
6485 // when comparing an id<P> on lhs with a static type on rhs,
6486 // see if static class implements all of id's protocols, directly or
6487 // through its super class and categories.
6488 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6489 E = rhsOPT->qual_end(); J != E; ++J) {
6490 ObjCProtocolDecl *rhsProto = *J;
6491 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6492 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6493 match = true;
6494 break;
6495 }
6496 }
Mike Stump1eb44332009-09-09 15:08:12 +00006497 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006498 // make sure we check the class hierarchy.
6499 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6500 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6501 E = lhsQID->qual_end(); I != E; ++I) {
6502 // when comparing an id<P> on lhs with a static type on rhs,
6503 // see if static class implements all of id's protocols, directly or
6504 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006505 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006506 match = true;
6507 break;
6508 }
6509 }
6510 }
6511 if (!match)
6512 return false;
6513 }
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Steve Naroff4084c302009-07-23 01:01:38 +00006515 return true;
6516 }
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Steve Naroff4084c302009-07-23 01:01:38 +00006518 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6519 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6520
Mike Stump1eb44332009-09-09 15:08:12 +00006521 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006522 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006523 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006524 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6525 E = lhsOPT->qual_end(); I != E; ++I) {
6526 ObjCProtocolDecl *lhsProto = *I;
6527 bool match = false;
6528
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006529 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006530 // see if static class implements all of id's protocols, directly or
6531 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006532 // First, lhs protocols in the qualifier list must be found, direct
6533 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006534 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6535 E = rhsQID->qual_end(); J != E; ++J) {
6536 ObjCProtocolDecl *rhsProto = *J;
6537 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6538 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6539 match = true;
6540 break;
6541 }
6542 }
6543 if (!match)
6544 return false;
6545 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006546
6547 // Static class's protocols, or its super class or category protocols
6548 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6549 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6550 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6551 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6552 // This is rather dubious but matches gcc's behavior. If lhs has
6553 // no type qualifier and its class has no static protocol(s)
6554 // assume that it is mismatch.
6555 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6556 return false;
6557 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6558 LHSInheritedProtocols.begin(),
6559 E = LHSInheritedProtocols.end(); I != E; ++I) {
6560 bool match = false;
6561 ObjCProtocolDecl *lhsProto = (*I);
6562 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6563 E = rhsQID->qual_end(); J != E; ++J) {
6564 ObjCProtocolDecl *rhsProto = *J;
6565 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6566 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6567 match = true;
6568 break;
6569 }
6570 }
6571 if (!match)
6572 return false;
6573 }
6574 }
Steve Naroff4084c302009-07-23 01:01:38 +00006575 return true;
6576 }
6577 return false;
6578}
6579
Eli Friedman3d815e72008-08-22 00:56:42 +00006580/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006581/// compatible for assignment from RHS to LHS. This handles validation of any
6582/// protocol qualifiers on the LHS or RHS.
6583///
Steve Naroff14108da2009-07-10 23:34:53 +00006584bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6585 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006586 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6587 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6588
Steve Naroffde2e22d2009-07-15 18:40:39 +00006589 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006590 if (LHS->isObjCUnqualifiedIdOrClass() ||
6591 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006592 return true;
6593
John McCallc12c5bb2010-05-15 11:32:37 +00006594 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006595 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6596 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006597 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006598
6599 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6600 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6601 QualType(RHSOPT,0));
6602
John McCallc12c5bb2010-05-15 11:32:37 +00006603 // If we have 2 user-defined types, fall into that path.
6604 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006605 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006606
Steve Naroff4084c302009-07-23 01:01:38 +00006607 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006608}
6609
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006610/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006611/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006612/// arguments in block literals. When passed as arguments, passing 'A*' where
6613/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6614/// not OK. For the return type, the opposite is not OK.
6615bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6616 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006617 const ObjCObjectPointerType *RHSOPT,
6618 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006619 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006620 return true;
6621
6622 if (LHSOPT->isObjCBuiltinType()) {
6623 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6624 }
6625
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006626 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006627 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6628 QualType(RHSOPT,0),
6629 false);
6630
6631 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6632 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6633 if (LHS && RHS) { // We have 2 user-defined types.
6634 if (LHS != RHS) {
6635 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006636 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006637 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006638 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006639 }
6640 else
6641 return true;
6642 }
6643 return false;
6644}
6645
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006646/// getIntersectionOfProtocols - This routine finds the intersection of set
6647/// of protocols inherited from two distinct objective-c pointer objects.
6648/// It is used to build composite qualifier list of the composite type of
6649/// the conditional expression involving two objective-c pointer objects.
6650static
6651void getIntersectionOfProtocols(ASTContext &Context,
6652 const ObjCObjectPointerType *LHSOPT,
6653 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006654 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006655
John McCallc12c5bb2010-05-15 11:32:37 +00006656 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6657 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6658 assert(LHS->getInterface() && "LHS must have an interface base");
6659 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006660
6661 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6662 unsigned LHSNumProtocols = LHS->getNumProtocols();
6663 if (LHSNumProtocols > 0)
6664 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6665 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006666 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006667 Context.CollectInheritedProtocols(LHS->getInterface(),
6668 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006669 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6670 LHSInheritedProtocols.end());
6671 }
6672
6673 unsigned RHSNumProtocols = RHS->getNumProtocols();
6674 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006675 ObjCProtocolDecl **RHSProtocols =
6676 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006677 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6678 if (InheritedProtocolSet.count(RHSProtocols[i]))
6679 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006680 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006681 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006682 Context.CollectInheritedProtocols(RHS->getInterface(),
6683 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006684 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6685 RHSInheritedProtocols.begin(),
6686 E = RHSInheritedProtocols.end(); I != E; ++I)
6687 if (InheritedProtocolSet.count((*I)))
6688 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006689 }
6690}
6691
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006692/// areCommonBaseCompatible - Returns common base class of the two classes if
6693/// one found. Note that this is O'2 algorithm. But it will be called as the
6694/// last type comparison in a ?-exp of ObjC pointer types before a
6695/// warning is issued. So, its invokation is extremely rare.
6696QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006697 const ObjCObjectPointerType *Lptr,
6698 const ObjCObjectPointerType *Rptr) {
6699 const ObjCObjectType *LHS = Lptr->getObjectType();
6700 const ObjCObjectType *RHS = Rptr->getObjectType();
6701 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6702 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006703 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006704 return QualType();
6705
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006706 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006707 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006708 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006709 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006710 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6711
6712 QualType Result = QualType(LHS, 0);
6713 if (!Protocols.empty())
6714 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6715 Result = getObjCObjectPointerType(Result);
6716 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006717 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006718 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006719
6720 return QualType();
6721}
6722
John McCallc12c5bb2010-05-15 11:32:37 +00006723bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6724 const ObjCObjectType *RHS) {
6725 assert(LHS->getInterface() && "LHS is not an interface type");
6726 assert(RHS->getInterface() && "RHS is not an interface type");
6727
Chris Lattner6ac46a42008-04-07 06:51:04 +00006728 // Verify that the base decls are compatible: the RHS must be a subclass of
6729 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006730 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006731 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006732
Chris Lattner6ac46a42008-04-07 06:51:04 +00006733 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6734 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006735 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006736 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006737
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006738 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6739 // more detailed analysis is required.
6740 if (RHS->getNumProtocols() == 0) {
6741 // OK, if LHS is a superclass of RHS *and*
6742 // this superclass is assignment compatible with LHS.
6743 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006744 bool IsSuperClass =
6745 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6746 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006747 // OK if conversion of LHS to SuperClass results in narrowing of types
6748 // ; i.e., SuperClass may implement at least one of the protocols
6749 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6750 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6751 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006752 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006753 // If super class has no protocols, it is not a match.
6754 if (SuperClassInheritedProtocols.empty())
6755 return false;
6756
6757 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6758 LHSPE = LHS->qual_end();
6759 LHSPI != LHSPE; LHSPI++) {
6760 bool SuperImplementsProtocol = false;
6761 ObjCProtocolDecl *LHSProto = (*LHSPI);
6762
6763 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6764 SuperClassInheritedProtocols.begin(),
6765 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6766 ObjCProtocolDecl *SuperClassProto = (*I);
6767 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6768 SuperImplementsProtocol = true;
6769 break;
6770 }
6771 }
6772 if (!SuperImplementsProtocol)
6773 return false;
6774 }
6775 return true;
6776 }
6777 return false;
6778 }
Mike Stump1eb44332009-09-09 15:08:12 +00006779
John McCallc12c5bb2010-05-15 11:32:37 +00006780 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6781 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006782 LHSPI != LHSPE; LHSPI++) {
6783 bool RHSImplementsProtocol = false;
6784
6785 // If the RHS doesn't implement the protocol on the left, the types
6786 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006787 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6788 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006789 RHSPI != RHSPE; RHSPI++) {
6790 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006791 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006792 break;
6793 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006794 }
6795 // FIXME: For better diagnostics, consider passing back the protocol name.
6796 if (!RHSImplementsProtocol)
6797 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006798 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006799 // The RHS implements all protocols listed on the LHS.
6800 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006801}
6802
Steve Naroff389bf462009-02-12 17:52:19 +00006803bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6804 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006805 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6806 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006807
Steve Naroff14108da2009-07-10 23:34:53 +00006808 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006809 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006810
6811 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6812 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006813}
6814
Douglas Gregor569c3162010-08-07 11:51:51 +00006815bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6816 return canAssignObjCInterfaces(
6817 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6818 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6819}
6820
Mike Stump1eb44332009-09-09 15:08:12 +00006821/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006822/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006823/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006824/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006825bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6826 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006827 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006828 return hasSameType(LHS, RHS);
6829
Douglas Gregor447234d2010-07-29 15:18:02 +00006830 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006831}
6832
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006833bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006834 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006835}
6836
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006837bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6838 return !mergeTypes(LHS, RHS, true).isNull();
6839}
6840
Peter Collingbourne48466752010-10-24 18:30:18 +00006841/// mergeTransparentUnionType - if T is a transparent union type and a member
6842/// of T is compatible with SubType, return the merged type, else return
6843/// QualType()
6844QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6845 bool OfBlockPointer,
6846 bool Unqualified) {
6847 if (const RecordType *UT = T->getAsUnionType()) {
6848 RecordDecl *UD = UT->getDecl();
6849 if (UD->hasAttr<TransparentUnionAttr>()) {
6850 for (RecordDecl::field_iterator it = UD->field_begin(),
6851 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006852 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006853 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6854 if (!MT.isNull())
6855 return MT;
6856 }
6857 }
6858 }
6859
6860 return QualType();
6861}
6862
6863/// mergeFunctionArgumentTypes - merge two types which appear as function
6864/// argument types
6865QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6866 bool OfBlockPointer,
6867 bool Unqualified) {
6868 // GNU extension: two types are compatible if they appear as a function
6869 // argument, one of the types is a transparent union type and the other
6870 // type is compatible with a union member
6871 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6872 Unqualified);
6873 if (!lmerge.isNull())
6874 return lmerge;
6875
6876 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6877 Unqualified);
6878 if (!rmerge.isNull())
6879 return rmerge;
6880
6881 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6882}
6883
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006884QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006885 bool OfBlockPointer,
6886 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006887 const FunctionType *lbase = lhs->getAs<FunctionType>();
6888 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006889 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6890 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006891 bool allLTypes = true;
6892 bool allRTypes = true;
6893
6894 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006895 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006896 if (OfBlockPointer) {
6897 QualType RHS = rbase->getResultType();
6898 QualType LHS = lbase->getResultType();
6899 bool UnqualifiedResult = Unqualified;
6900 if (!UnqualifiedResult)
6901 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006902 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006903 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006904 else
John McCall8cc246c2010-12-15 01:06:38 +00006905 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6906 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006907 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006908
6909 if (Unqualified)
6910 retType = retType.getUnqualifiedType();
6911
6912 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6913 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6914 if (Unqualified) {
6915 LRetType = LRetType.getUnqualifiedType();
6916 RRetType = RRetType.getUnqualifiedType();
6917 }
6918
6919 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006920 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006921 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006922 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006923
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006924 // FIXME: double check this
6925 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6926 // rbase->getRegParmAttr() != 0 &&
6927 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006928 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6929 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006930
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006931 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006932 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006933 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006934
John McCall8cc246c2010-12-15 01:06:38 +00006935 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006936 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6937 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006938 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6939 return QualType();
6940
John McCallf85e1932011-06-15 23:02:42 +00006941 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6942 return QualType();
6943
John McCall8cc246c2010-12-15 01:06:38 +00006944 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6945 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006946
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006947 if (lbaseInfo.getNoReturn() != NoReturn)
6948 allLTypes = false;
6949 if (rbaseInfo.getNoReturn() != NoReturn)
6950 allRTypes = false;
6951
John McCallf85e1932011-06-15 23:02:42 +00006952 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006953
Eli Friedman3d815e72008-08-22 00:56:42 +00006954 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006955 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6956 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006957 unsigned lproto_nargs = lproto->getNumArgs();
6958 unsigned rproto_nargs = rproto->getNumArgs();
6959
6960 // Compatible functions must have the same number of arguments
6961 if (lproto_nargs != rproto_nargs)
6962 return QualType();
6963
6964 // Variadic and non-variadic functions aren't compatible
6965 if (lproto->isVariadic() != rproto->isVariadic())
6966 return QualType();
6967
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006968 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6969 return QualType();
6970
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006971 if (LangOpts.ObjCAutoRefCount &&
6972 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6973 return QualType();
6974
Eli Friedman3d815e72008-08-22 00:56:42 +00006975 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006976 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006977 for (unsigned i = 0; i < lproto_nargs; i++) {
6978 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6979 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006980 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6981 OfBlockPointer,
6982 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006983 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006984
6985 if (Unqualified)
6986 argtype = argtype.getUnqualifiedType();
6987
Eli Friedman3d815e72008-08-22 00:56:42 +00006988 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006989 if (Unqualified) {
6990 largtype = largtype.getUnqualifiedType();
6991 rargtype = rargtype.getUnqualifiedType();
6992 }
6993
Chris Lattner61710852008-10-05 17:34:18 +00006994 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6995 allLTypes = false;
6996 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6997 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006998 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006999
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 if (allLTypes) return lhs;
7001 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007002
7003 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7004 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007005 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007006 }
7007
7008 if (lproto) allRTypes = false;
7009 if (rproto) allLTypes = false;
7010
Douglas Gregor72564e72009-02-26 23:50:07 +00007011 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007012 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007013 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007014 if (proto->isVariadic()) return QualType();
7015 // Check that the types are compatible with the types that
7016 // would result from default argument promotions (C99 6.7.5.3p15).
7017 // The only types actually affected are promotable integer
7018 // types and floats, which would be passed as a different
7019 // type depending on whether the prototype is visible.
7020 unsigned proto_nargs = proto->getNumArgs();
7021 for (unsigned i = 0; i < proto_nargs; ++i) {
7022 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007023
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007024 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007025 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007026 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7027 argTy = Enum->getDecl()->getIntegerType();
7028 if (argTy.isNull())
7029 return QualType();
7030 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007031
Eli Friedman3d815e72008-08-22 00:56:42 +00007032 if (argTy->isPromotableIntegerType() ||
7033 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7034 return QualType();
7035 }
7036
7037 if (allLTypes) return lhs;
7038 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007039
7040 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7041 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007042 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007043 }
7044
7045 if (allLTypes) return lhs;
7046 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007047 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007048}
7049
John McCallb9da7132013-03-21 00:10:07 +00007050/// Given that we have an enum type and a non-enum type, try to merge them.
7051static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7052 QualType other, bool isBlockReturnType) {
7053 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7054 // a signed integer type, or an unsigned integer type.
7055 // Compatibility is based on the underlying type, not the promotion
7056 // type.
7057 QualType underlyingType = ET->getDecl()->getIntegerType();
7058 if (underlyingType.isNull()) return QualType();
7059 if (Context.hasSameType(underlyingType, other))
7060 return other;
7061
7062 // In block return types, we're more permissive and accept any
7063 // integral type of the same size.
7064 if (isBlockReturnType && other->isIntegerType() &&
7065 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7066 return other;
7067
7068 return QualType();
7069}
7070
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007071QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007072 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007073 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007074 // C++ [expr]: If an expression initially has the type "reference to T", the
7075 // type is adjusted to "T" prior to any further analysis, the expression
7076 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007077 // expression is an lvalue unless the reference is an rvalue reference and
7078 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007079 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7080 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007081
7082 if (Unqualified) {
7083 LHS = LHS.getUnqualifiedType();
7084 RHS = RHS.getUnqualifiedType();
7085 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007086
Eli Friedman3d815e72008-08-22 00:56:42 +00007087 QualType LHSCan = getCanonicalType(LHS),
7088 RHSCan = getCanonicalType(RHS);
7089
7090 // If two types are identical, they are compatible.
7091 if (LHSCan == RHSCan)
7092 return LHS;
7093
John McCall0953e762009-09-24 19:53:00 +00007094 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007095 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7096 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007097 if (LQuals != RQuals) {
7098 // If any of these qualifiers are different, we have a type
7099 // mismatch.
7100 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007101 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7102 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007103 return QualType();
7104
7105 // Exactly one GC qualifier difference is allowed: __strong is
7106 // okay if the other type has no GC qualifier but is an Objective
7107 // C object pointer (i.e. implicitly strong by default). We fix
7108 // this by pretending that the unqualified type was actually
7109 // qualified __strong.
7110 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7111 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7112 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7113
7114 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7115 return QualType();
7116
7117 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7118 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7119 }
7120 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7121 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7122 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007123 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007124 }
7125
7126 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007127
Eli Friedman852d63b2009-06-01 01:22:52 +00007128 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7129 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007130
Chris Lattner1adb8832008-01-14 05:45:46 +00007131 // We want to consider the two function types to be the same for these
7132 // comparisons, just force one to the other.
7133 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7134 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007135
7136 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007137 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7138 LHSClass = Type::ConstantArray;
7139 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7140 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007141
John McCallc12c5bb2010-05-15 11:32:37 +00007142 // ObjCInterfaces are just specialized ObjCObjects.
7143 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7144 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7145
Nate Begeman213541a2008-04-18 23:10:10 +00007146 // Canonicalize ExtVector -> Vector.
7147 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7148 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007149
Chris Lattnera36a61f2008-04-07 05:43:21 +00007150 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007151 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007152 // Note that we only have special rules for turning block enum
7153 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007154 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007155 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007156 }
John McCall183700f2009-09-21 23:43:11 +00007157 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007158 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007159 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007160 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007161 if (OfBlockPointer && !BlockReturnType) {
7162 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7163 return LHS;
7164 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7165 return RHS;
7166 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007167
Eli Friedman3d815e72008-08-22 00:56:42 +00007168 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007169 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007170
Steve Naroff4a746782008-01-09 22:43:08 +00007171 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007172 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007173#define TYPE(Class, Base)
7174#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007175#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007176#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7177#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7178#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007179 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007180
Richard Smithdc7a4f52013-04-30 13:56:41 +00007181 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007182 case Type::LValueReference:
7183 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007184 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007185 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007186
John McCallc12c5bb2010-05-15 11:32:37 +00007187 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007188 case Type::IncompleteArray:
7189 case Type::VariableArray:
7190 case Type::FunctionProto:
7191 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007192 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007193
Chris Lattner1adb8832008-01-14 05:45:46 +00007194 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007195 {
7196 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007197 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7198 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007199 if (Unqualified) {
7200 LHSPointee = LHSPointee.getUnqualifiedType();
7201 RHSPointee = RHSPointee.getUnqualifiedType();
7202 }
7203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7204 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007205 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007207 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007209 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007210 return getPointerType(ResultType);
7211 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007212 case Type::BlockPointer:
7213 {
7214 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007215 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7216 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007217 if (Unqualified) {
7218 LHSPointee = LHSPointee.getUnqualifiedType();
7219 RHSPointee = RHSPointee.getUnqualifiedType();
7220 }
7221 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7222 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007223 if (ResultType.isNull()) return QualType();
7224 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7225 return LHS;
7226 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7227 return RHS;
7228 return getBlockPointerType(ResultType);
7229 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007230 case Type::Atomic:
7231 {
7232 // Merge two pointer types, while trying to preserve typedef info
7233 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7234 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7235 if (Unqualified) {
7236 LHSValue = LHSValue.getUnqualifiedType();
7237 RHSValue = RHSValue.getUnqualifiedType();
7238 }
7239 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7240 Unqualified);
7241 if (ResultType.isNull()) return QualType();
7242 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7243 return LHS;
7244 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7245 return RHS;
7246 return getAtomicType(ResultType);
7247 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007248 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007249 {
7250 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7251 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7252 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7253 return QualType();
7254
7255 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7256 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSElem = LHSElem.getUnqualifiedType();
7259 RHSElem = RHSElem.getUnqualifiedType();
7260 }
7261
7262 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007263 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007264 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7267 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007268 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7269 ArrayType::ArraySizeModifier(), 0);
7270 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7271 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007272 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7273 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007274 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7275 return LHS;
7276 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7277 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007278 if (LVAT) {
7279 // FIXME: This isn't correct! But tricky to implement because
7280 // the array's size has to be the size of LHS, but the type
7281 // has to be different.
7282 return LHS;
7283 }
7284 if (RVAT) {
7285 // FIXME: This isn't correct! But tricky to implement because
7286 // the array's size has to be the size of RHS, but the type
7287 // has to be different.
7288 return RHS;
7289 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007290 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7291 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007292 return getIncompleteArrayType(ResultType,
7293 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007294 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007295 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007296 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007297 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007298 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007299 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007300 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007301 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007302 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007303 case Type::Complex:
7304 // Distinct complex types are incompatible.
7305 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007306 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007307 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007308 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7309 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007310 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007311 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007312 case Type::ObjCObject: {
7313 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007314 // FIXME: This should be type compatibility, e.g. whether
7315 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007316 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7317 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7318 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007319 return LHS;
7320
Eli Friedman3d815e72008-08-22 00:56:42 +00007321 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007322 }
Steve Naroff14108da2009-07-10 23:34:53 +00007323 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007324 if (OfBlockPointer) {
7325 if (canAssignObjCInterfacesInBlockPointer(
7326 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007327 RHS->getAs<ObjCObjectPointerType>(),
7328 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007329 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007330 return QualType();
7331 }
John McCall183700f2009-09-21 23:43:11 +00007332 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7333 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007334 return LHS;
7335
Steve Naroffbc76dd02008-12-10 22:14:21 +00007336 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007337 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007338 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007339
David Blaikie7530c032012-01-17 06:56:22 +00007340 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007341}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007342
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007343bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7344 const FunctionProtoType *FromFunctionType,
7345 const FunctionProtoType *ToFunctionType) {
7346 if (FromFunctionType->hasAnyConsumedArgs() !=
7347 ToFunctionType->hasAnyConsumedArgs())
7348 return false;
7349 FunctionProtoType::ExtProtoInfo FromEPI =
7350 FromFunctionType->getExtProtoInfo();
7351 FunctionProtoType::ExtProtoInfo ToEPI =
7352 ToFunctionType->getExtProtoInfo();
7353 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7354 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7355 ArgIdx != NumArgs; ++ArgIdx) {
7356 if (FromEPI.ConsumedArguments[ArgIdx] !=
7357 ToEPI.ConsumedArguments[ArgIdx])
7358 return false;
7359 }
7360 return true;
7361}
7362
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007363/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7364/// 'RHS' attributes and returns the merged version; including for function
7365/// return types.
7366QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7367 QualType LHSCan = getCanonicalType(LHS),
7368 RHSCan = getCanonicalType(RHS);
7369 // If two types are identical, they are compatible.
7370 if (LHSCan == RHSCan)
7371 return LHS;
7372 if (RHSCan->isFunctionType()) {
7373 if (!LHSCan->isFunctionType())
7374 return QualType();
7375 QualType OldReturnType =
7376 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7377 QualType NewReturnType =
7378 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7379 QualType ResReturnType =
7380 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7381 if (ResReturnType.isNull())
7382 return QualType();
7383 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7384 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7385 // In either case, use OldReturnType to build the new function type.
7386 const FunctionType *F = LHS->getAs<FunctionType>();
7387 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007388 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7389 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007390 QualType ResultType =
7391 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007392 return ResultType;
7393 }
7394 }
7395 return QualType();
7396 }
7397
7398 // If the qualifiers are different, the types can still be merged.
7399 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7400 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7401 if (LQuals != RQuals) {
7402 // If any of these qualifiers are different, we have a type mismatch.
7403 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7404 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7405 return QualType();
7406
7407 // Exactly one GC qualifier difference is allowed: __strong is
7408 // okay if the other type has no GC qualifier but is an Objective
7409 // C object pointer (i.e. implicitly strong by default). We fix
7410 // this by pretending that the unqualified type was actually
7411 // qualified __strong.
7412 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7413 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7414 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7415
7416 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7417 return QualType();
7418
7419 if (GC_L == Qualifiers::Strong)
7420 return LHS;
7421 if (GC_R == Qualifiers::Strong)
7422 return RHS;
7423 return QualType();
7424 }
7425
7426 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7427 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7428 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7429 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7430 if (ResQT == LHSBaseQT)
7431 return LHS;
7432 if (ResQT == RHSBaseQT)
7433 return RHS;
7434 }
7435 return QualType();
7436}
7437
Chris Lattner5426bf62008-04-07 07:01:58 +00007438//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007439// Integer Predicates
7440//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007441
Jay Foad4ba2a172011-01-12 09:06:06 +00007442unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007443 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007444 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007445 if (T->isBooleanType())
7446 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007447 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007448 return (unsigned)getTypeSize(T);
7449}
7450
Abramo Bagnara762f1592012-09-09 10:21:24 +00007451QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007452 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007453
7454 // Turn <4 x signed int> -> <4 x unsigned int>
7455 if (const VectorType *VTy = T->getAs<VectorType>())
7456 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007457 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007458
7459 // For enums, we return the unsigned version of the base type.
7460 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007461 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007462
7463 const BuiltinType *BTy = T->getAs<BuiltinType>();
7464 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007465 switch (BTy->getKind()) {
7466 case BuiltinType::Char_S:
7467 case BuiltinType::SChar:
7468 return UnsignedCharTy;
7469 case BuiltinType::Short:
7470 return UnsignedShortTy;
7471 case BuiltinType::Int:
7472 return UnsignedIntTy;
7473 case BuiltinType::Long:
7474 return UnsignedLongTy;
7475 case BuiltinType::LongLong:
7476 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007477 case BuiltinType::Int128:
7478 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007479 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007480 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007481 }
7482}
7483
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007484ASTMutationListener::~ASTMutationListener() { }
7485
Richard Smith9dadfab2013-05-11 05:45:24 +00007486void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7487 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007488
7489//===----------------------------------------------------------------------===//
7490// Builtin Type Computation
7491//===----------------------------------------------------------------------===//
7492
7493/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007494/// pointer over the consumed characters. This returns the resultant type. If
7495/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7496/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7497/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007498///
7499/// RequiresICE is filled in on return to indicate whether the value is required
7500/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007501static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007502 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007503 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007504 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007505 // Modifiers.
7506 int HowLong = 0;
7507 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007508 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007509
Chris Lattner33daae62010-10-01 22:42:38 +00007510 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007511 bool Done = false;
7512 while (!Done) {
7513 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007514 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007515 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007516 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007517 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007518 case 'S':
7519 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7520 assert(!Signed && "Can't use 'S' modifier multiple times!");
7521 Signed = true;
7522 break;
7523 case 'U':
7524 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7525 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7526 Unsigned = true;
7527 break;
7528 case 'L':
7529 assert(HowLong <= 2 && "Can't have LLLL modifier");
7530 ++HowLong;
7531 break;
7532 }
7533 }
7534
7535 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007536
Chris Lattner86df27b2009-06-14 00:45:47 +00007537 // Read the base type.
7538 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007539 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007540 case 'v':
7541 assert(HowLong == 0 && !Signed && !Unsigned &&
7542 "Bad modifiers used with 'v'!");
7543 Type = Context.VoidTy;
7544 break;
7545 case 'f':
7546 assert(HowLong == 0 && !Signed && !Unsigned &&
7547 "Bad modifiers used with 'f'!");
7548 Type = Context.FloatTy;
7549 break;
7550 case 'd':
7551 assert(HowLong < 2 && !Signed && !Unsigned &&
7552 "Bad modifiers used with 'd'!");
7553 if (HowLong)
7554 Type = Context.LongDoubleTy;
7555 else
7556 Type = Context.DoubleTy;
7557 break;
7558 case 's':
7559 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7560 if (Unsigned)
7561 Type = Context.UnsignedShortTy;
7562 else
7563 Type = Context.ShortTy;
7564 break;
7565 case 'i':
7566 if (HowLong == 3)
7567 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7568 else if (HowLong == 2)
7569 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7570 else if (HowLong == 1)
7571 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7572 else
7573 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7574 break;
7575 case 'c':
7576 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7577 if (Signed)
7578 Type = Context.SignedCharTy;
7579 else if (Unsigned)
7580 Type = Context.UnsignedCharTy;
7581 else
7582 Type = Context.CharTy;
7583 break;
7584 case 'b': // boolean
7585 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7586 Type = Context.BoolTy;
7587 break;
7588 case 'z': // size_t.
7589 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7590 Type = Context.getSizeType();
7591 break;
7592 case 'F':
7593 Type = Context.getCFConstantStringType();
7594 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007595 case 'G':
7596 Type = Context.getObjCIdType();
7597 break;
7598 case 'H':
7599 Type = Context.getObjCSelType();
7600 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007601 case 'M':
7602 Type = Context.getObjCSuperType();
7603 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007604 case 'a':
7605 Type = Context.getBuiltinVaListType();
7606 assert(!Type.isNull() && "builtin va list type not initialized!");
7607 break;
7608 case 'A':
7609 // This is a "reference" to a va_list; however, what exactly
7610 // this means depends on how va_list is defined. There are two
7611 // different kinds of va_list: ones passed by value, and ones
7612 // passed by reference. An example of a by-value va_list is
7613 // x86, where va_list is a char*. An example of by-ref va_list
7614 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7615 // we want this argument to be a char*&; for x86-64, we want
7616 // it to be a __va_list_tag*.
7617 Type = Context.getBuiltinVaListType();
7618 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007619 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007620 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007621 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007622 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007623 break;
7624 case 'V': {
7625 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007626 unsigned NumElements = strtoul(Str, &End, 10);
7627 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007628 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007629
Chris Lattner14e0e742010-10-01 22:53:11 +00007630 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7631 RequiresICE, false);
7632 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007633
7634 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007635 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007636 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007637 break;
7638 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007639 case 'E': {
7640 char *End;
7641
7642 unsigned NumElements = strtoul(Str, &End, 10);
7643 assert(End != Str && "Missing vector size");
7644
7645 Str = End;
7646
7647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7648 false);
7649 Type = Context.getExtVectorType(ElementType, NumElements);
7650 break;
7651 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007652 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007653 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7654 false);
7655 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007656 Type = Context.getComplexType(ElementType);
7657 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007658 }
7659 case 'Y' : {
7660 Type = Context.getPointerDiffType();
7661 break;
7662 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007663 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007664 Type = Context.getFILEType();
7665 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007666 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007667 return QualType();
7668 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007669 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007670 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007671 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007672 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007673 else
7674 Type = Context.getjmp_bufType();
7675
Mike Stumpfd612db2009-07-28 23:47:15 +00007676 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007677 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007678 return QualType();
7679 }
7680 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007681 case 'K':
7682 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7683 Type = Context.getucontext_tType();
7684
7685 if (Type.isNull()) {
7686 Error = ASTContext::GE_Missing_ucontext;
7687 return QualType();
7688 }
7689 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007690 case 'p':
7691 Type = Context.getProcessIDType();
7692 break;
Mike Stump782fa302009-07-28 02:25:19 +00007693 }
Mike Stump1eb44332009-09-09 15:08:12 +00007694
Chris Lattner33daae62010-10-01 22:42:38 +00007695 // If there are modifiers and if we're allowed to parse them, go for it.
7696 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007697 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007698 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007699 default: Done = true; --Str; break;
7700 case '*':
7701 case '&': {
7702 // Both pointers and references can have their pointee types
7703 // qualified with an address space.
7704 char *End;
7705 unsigned AddrSpace = strtoul(Str, &End, 10);
7706 if (End != Str && AddrSpace != 0) {
7707 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7708 Str = End;
7709 }
7710 if (c == '*')
7711 Type = Context.getPointerType(Type);
7712 else
7713 Type = Context.getLValueReferenceType(Type);
7714 break;
7715 }
7716 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7717 case 'C':
7718 Type = Type.withConst();
7719 break;
7720 case 'D':
7721 Type = Context.getVolatileType(Type);
7722 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007723 case 'R':
7724 Type = Type.withRestrict();
7725 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007726 }
7727 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007728
Chris Lattner14e0e742010-10-01 22:53:11 +00007729 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007730 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007731
Chris Lattner86df27b2009-06-14 00:45:47 +00007732 return Type;
7733}
7734
7735/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007736QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007737 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007738 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007739 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007740
Chris Lattner5f9e2722011-07-23 10:55:15 +00007741 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007742
Chris Lattner14e0e742010-10-01 22:53:11 +00007743 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007744 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007745 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7746 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007747 if (Error != GE_None)
7748 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007749
7750 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7751
Chris Lattner86df27b2009-06-14 00:45:47 +00007752 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007753 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007754 if (Error != GE_None)
7755 return QualType();
7756
Chris Lattner14e0e742010-10-01 22:53:11 +00007757 // If this argument is required to be an IntegerConstantExpression and the
7758 // caller cares, fill in the bitmask we return.
7759 if (RequiresICE && IntegerConstantArgs)
7760 *IntegerConstantArgs |= 1 << ArgTypes.size();
7761
Chris Lattner86df27b2009-06-14 00:45:47 +00007762 // Do array -> pointer decay. The builtin should use the decayed type.
7763 if (Ty->isArrayType())
7764 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007765
Chris Lattner86df27b2009-06-14 00:45:47 +00007766 ArgTypes.push_back(Ty);
7767 }
7768
7769 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7770 "'.' should only occur at end of builtin type list!");
7771
John McCall00ccbef2010-12-21 00:44:39 +00007772 FunctionType::ExtInfo EI;
7773 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7774
7775 bool Variadic = (TypeStr[0] == '.');
7776
7777 // We really shouldn't be making a no-proto type here, especially in C++.
7778 if (ArgTypes.empty() && Variadic)
7779 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007780
John McCalle23cf432010-12-14 08:05:40 +00007781 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007782 EPI.ExtInfo = EI;
7783 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007784
Jordan Rosebea522f2013-03-08 21:51:21 +00007785 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007786}
Eli Friedmana95d7572009-08-19 07:44:53 +00007787
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007788GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007789 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007790 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007791
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007792 GVALinkage External = GVA_StrongExternal;
7793 switch (FD->getTemplateSpecializationKind()) {
7794 case TSK_Undeclared:
7795 case TSK_ExplicitSpecialization:
7796 External = GVA_StrongExternal;
7797 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007798
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007799 case TSK_ExplicitInstantiationDefinition:
7800 return GVA_ExplicitTemplateInstantiation;
7801
7802 case TSK_ExplicitInstantiationDeclaration:
7803 case TSK_ImplicitInstantiation:
7804 External = GVA_TemplateInstantiation;
7805 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007806 }
7807
7808 if (!FD->isInlined())
7809 return External;
7810
David Blaikie4e4d0842012-03-11 07:00:24 +00007811 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007812 // GNU or C99 inline semantics. Determine whether this symbol should be
7813 // externally visible.
7814 if (FD->isInlineDefinitionExternallyVisible())
7815 return External;
7816
7817 // C99 inline semantics, where the symbol is not externally visible.
7818 return GVA_C99Inline;
7819 }
7820
7821 // C++0x [temp.explicit]p9:
7822 // [ Note: The intent is that an inline function that is the subject of
7823 // an explicit instantiation declaration will still be implicitly
7824 // instantiated when used so that the body can be considered for
7825 // inlining, but that no out-of-line copy of the inline function would be
7826 // generated in the translation unit. -- end note ]
7827 if (FD->getTemplateSpecializationKind()
7828 == TSK_ExplicitInstantiationDeclaration)
7829 return GVA_C99Inline;
7830
7831 return GVA_CXXInline;
7832}
7833
7834GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007835 if (!VD->isExternallyVisible())
7836 return GVA_Internal;
7837
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007838 // If this is a static data member, compute the kind of template
7839 // specialization. Otherwise, this variable is not part of a
7840 // template.
7841 TemplateSpecializationKind TSK = TSK_Undeclared;
7842 if (VD->isStaticDataMember())
7843 TSK = VD->getTemplateSpecializationKind();
7844
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007845 switch (TSK) {
7846 case TSK_Undeclared:
7847 case TSK_ExplicitSpecialization:
7848 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007849
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007850 case TSK_ExplicitInstantiationDeclaration:
7851 llvm_unreachable("Variable should not be instantiated");
7852 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007853
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007854 case TSK_ExplicitInstantiationDefinition:
7855 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007856
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007857 case TSK_ImplicitInstantiation:
7858 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007859 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007860
7861 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007862}
7863
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007864bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7866 if (!VD->isFileVarDecl())
7867 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007868 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7869 // We never need to emit an uninstantiated function template.
7870 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7871 return false;
7872 } else
7873 return false;
7874
7875 // If this is a member of a class template, we do not need to emit it.
7876 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007877 return false;
7878
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007879 // Weak references don't produce any output by themselves.
7880 if (D->hasAttr<WeakRefAttr>())
7881 return false;
7882
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007883 // Aliases and used decls are required.
7884 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7885 return true;
7886
7887 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7888 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007889 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007890 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007891
7892 // Constructors and destructors are required.
7893 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7894 return true;
7895
John McCalld5617ee2013-01-25 22:31:03 +00007896 // The key function for a class is required. This rule only comes
7897 // into play when inline functions can be key functions, though.
7898 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7899 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7900 const CXXRecordDecl *RD = MD->getParent();
7901 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7902 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7903 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7904 return true;
7905 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007906 }
7907 }
7908
7909 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7910
7911 // static, static inline, always_inline, and extern inline functions can
7912 // always be deferred. Normal inline functions can be deferred in C99/C++.
7913 // Implicit template instantiations can also be deferred in C++.
7914 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007915 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007916 return false;
7917 return true;
7918 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007919
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007920 const VarDecl *VD = cast<VarDecl>(D);
7921 assert(VD->isFileVarDecl() && "Expected file scoped var");
7922
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007923 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7924 return false;
7925
Richard Smith5f9a7e32012-11-12 21:38:00 +00007926 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007927 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007928 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7929 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007930
Richard Smith5f9a7e32012-11-12 21:38:00 +00007931 // Variables that have destruction with side-effects are required.
7932 if (VD->getType().isDestructedType())
7933 return true;
7934
7935 // Variables that have initialization with side-effects are required.
7936 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7937 return true;
7938
7939 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007940}
Charles Davis071cc7d2010-08-16 03:33:14 +00007941
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007942CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007943 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007944 return ABI->getDefaultMethodCallConv(isVariadic);
7945}
7946
7947CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007948 if (CC == CC_C && !LangOpts.MRTD &&
7949 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007950 return CC_Default;
7951 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007952}
7953
Jay Foad4ba2a172011-01-12 09:06:06 +00007954bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007955 // Pass through to the C++ ABI object
7956 return ABI->isNearlyEmpty(RD);
7957}
7958
Peter Collingbourne14110472011-01-13 18:57:25 +00007959MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007960 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007961 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007962 case TargetCXXABI::GenericItanium:
7963 case TargetCXXABI::GenericARM:
7964 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007965 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007966 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007967 return createMicrosoftMangleContext(*this, getDiagnostics());
7968 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007969 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007970}
7971
Charles Davis071cc7d2010-08-16 03:33:14 +00007972CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007973
7974size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007975 return ASTRecordLayouts.getMemorySize()
7976 + llvm::capacity_in_bytes(ObjCLayouts)
7977 + llvm::capacity_in_bytes(KeyFunctions)
7978 + llvm::capacity_in_bytes(ObjCImpls)
7979 + llvm::capacity_in_bytes(BlockVarCopyInits)
7980 + llvm::capacity_in_bytes(DeclAttrs)
7981 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7982 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7983 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7984 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7985 + llvm::capacity_in_bytes(OverriddenMethods)
7986 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007987 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007988 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007989}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007990
Eli Friedman5e867c82013-07-10 00:30:46 +00007991void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
7992 if (Number > 1)
7993 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00007994}
7995
Eli Friedman5e867c82013-07-10 00:30:46 +00007996unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
7997 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
7998 MangleNumbers.find(ND);
7999 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008000}
8001
Eli Friedman5e867c82013-07-10 00:30:46 +00008002MangleNumberingContext &
8003ASTContext::getManglingNumberContext(const DeclContext *DC) {
Eli Friedman07369dd2013-07-01 20:22:57 +00008004 return MangleNumberingContexts[DC];
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008005}
8006
Ted Kremenekd211cb72011-10-06 05:00:56 +00008007void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8008 ParamIndices[D] = index;
8009}
8010
8011unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8012 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8013 assert(I != ParamIndices.end() &&
8014 "ParmIndices lacks entry set by ParmVarDecl");
8015 return I->second;
8016}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008017
Richard Smith211c8dd2013-06-05 00:46:14 +00008018APValue *
8019ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8020 bool MayCreate) {
8021 assert(E && E->getStorageDuration() == SD_Static &&
8022 "don't need to cache the computed value for this temporary");
8023 if (MayCreate)
8024 return &MaterializedTemporaryValues[E];
8025
8026 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8027 MaterializedTemporaryValues.find(E);
8028 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8029}
8030
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008031bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8032 const llvm::Triple &T = getTargetInfo().getTriple();
8033 if (!T.isOSDarwin())
8034 return false;
8035
8036 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8037 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8038 uint64_t Size = sizeChars.getQuantity();
8039 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8040 unsigned Align = alignChars.getQuantity();
8041 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8042 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8043}
Reid Klecknercff15122013-06-17 12:56:08 +00008044
8045namespace {
8046
8047 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8048 /// parents as defined by the \c RecursiveASTVisitor.
8049 ///
8050 /// Note that the relationship described here is purely in terms of AST
8051 /// traversal - there are other relationships (for example declaration context)
8052 /// in the AST that are better modeled by special matchers.
8053 ///
8054 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8055 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8056
8057 public:
8058 /// \brief Builds and returns the translation unit's parent map.
8059 ///
8060 /// The caller takes ownership of the returned \c ParentMap.
8061 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8062 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8063 Visitor.TraverseDecl(&TU);
8064 return Visitor.Parents;
8065 }
8066
8067 private:
8068 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8069
8070 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8071 }
8072
8073 bool shouldVisitTemplateInstantiations() const {
8074 return true;
8075 }
8076 bool shouldVisitImplicitCode() const {
8077 return true;
8078 }
8079 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8080 // are not triggered during data recursion.
8081 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8082 return false;
8083 }
8084
8085 template <typename T>
8086 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8087 if (Node == NULL)
8088 return true;
8089 if (ParentStack.size() > 0)
8090 // FIXME: Currently we add the same parent multiple times, for example
8091 // when we visit all subexpressions of template instantiations; this is
8092 // suboptimal, bug benign: the only way to visit those is with
8093 // hasAncestor / hasParent, and those do not create new matches.
8094 // The plan is to enable DynTypedNode to be storable in a map or hash
8095 // map. The main problem there is to implement hash functions /
8096 // comparison operators for all types that DynTypedNode supports that
8097 // do not have pointer identity.
8098 (*Parents)[Node].push_back(ParentStack.back());
8099 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8100 bool Result = (this ->* traverse) (Node);
8101 ParentStack.pop_back();
8102 return Result;
8103 }
8104
8105 bool TraverseDecl(Decl *DeclNode) {
8106 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8107 }
8108
8109 bool TraverseStmt(Stmt *StmtNode) {
8110 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8111 }
8112
8113 ASTContext::ParentMap *Parents;
8114 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8115
8116 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8117 };
8118
8119} // end namespace
8120
8121ASTContext::ParentVector
8122ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8123 assert(Node.getMemoizationData() &&
8124 "Invariant broken: only nodes that support memoization may be "
8125 "used in the parent map.");
8126 if (!AllParents) {
8127 // We always need to run over the whole translation unit, as
8128 // hasAncestor can escape any subtree.
8129 AllParents.reset(
8130 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8131 }
8132 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8133 if (I == AllParents->end()) {
8134 return ParentVector();
8135 }
8136 return I->second;
8137}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008138
8139bool
8140ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8141 const ObjCMethodDecl *MethodImpl) {
8142 // No point trying to match an unavailable/deprecated mothod.
8143 if (MethodDecl->hasAttr<UnavailableAttr>()
8144 || MethodDecl->hasAttr<DeprecatedAttr>())
8145 return false;
8146 if (MethodDecl->getObjCDeclQualifier() !=
8147 MethodImpl->getObjCDeclQualifier())
8148 return false;
8149 if (!hasSameType(MethodDecl->getResultType(),
8150 MethodImpl->getResultType()))
8151 return false;
8152
8153 if (MethodDecl->param_size() != MethodImpl->param_size())
8154 return false;
8155
8156 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8157 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8158 EF = MethodDecl->param_end();
8159 IM != EM && IF != EF; ++IM, ++IF) {
8160 const ParmVarDecl *DeclVar = (*IF);
8161 const ParmVarDecl *ImplVar = (*IM);
8162 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8163 return false;
8164 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8165 return false;
8166 }
8167 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8168
8169}