blob: 63b1b0ead18e16fc9f95d972809c1d175d5ee47e [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
Larisse Voufoef4579c2013-08-06 01:03:05 +00001044// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001045MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001046ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001047 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001048 return getTemplateOrSpecializationInfo(Var)
1049 .dyn_cast<MemberSpecializationInfo *>();
1050}
1051
1052ASTContext::TemplateOrSpecializationInfo
1053ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1054 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1055 TemplateOrInstantiation.find(Var);
1056 if (Pos == TemplateOrInstantiation.end())
1057 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregor7caa6822009-07-24 20:34:43 +00001059 return Pos->second;
1060}
1061
Mike Stump1eb44332009-09-09 15:08:12 +00001062void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001063ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001064 TemplateSpecializationKind TSK,
1065 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001066 assert(Inst->isStaticDataMember() && "Not a static data member");
1067 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001068 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1069 Tmpl, TSK, PointOfInstantiation));
1070}
1071
1072void
1073ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1074 TemplateOrSpecializationInfo TSI) {
1075 assert(!TemplateOrInstantiation[Inst] &&
1076 "Already noted what the variable was instantiated from");
1077 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001078}
1079
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001080FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1081 const FunctionDecl *FD){
1082 assert(FD && "Specialization is 0");
1083 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001084 = ClassScopeSpecializationPattern.find(FD);
1085 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001086 return 0;
1087
1088 return Pos->second;
1089}
1090
1091void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1092 FunctionDecl *Pattern) {
1093 assert(FD && "Specialization is 0");
1094 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001095 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001096}
1097
John McCall7ba107a2009-11-18 02:36:19 +00001098NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001099ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001100 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001101 = InstantiatedFromUsingDecl.find(UUD);
1102 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001103 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlsson0d8df782009-08-29 19:37:28 +00001105 return Pos->second;
1106}
1107
1108void
John McCalled976492009-12-04 22:46:56 +00001109ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1110 assert((isa<UsingDecl>(Pattern) ||
1111 isa<UnresolvedUsingValueDecl>(Pattern) ||
1112 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1113 "pattern decl is not a using decl");
1114 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1115 InstantiatedFromUsingDecl[Inst] = Pattern;
1116}
1117
1118UsingShadowDecl *
1119ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1120 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1121 = InstantiatedFromUsingShadowDecl.find(Inst);
1122 if (Pos == InstantiatedFromUsingShadowDecl.end())
1123 return 0;
1124
1125 return Pos->second;
1126}
1127
1128void
1129ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1130 UsingShadowDecl *Pattern) {
1131 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1132 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001133}
1134
Anders Carlssond8b285f2009-09-01 04:26:58 +00001135FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1136 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1137 = InstantiatedFromUnnamedFieldDecl.find(Field);
1138 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1139 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Anders Carlssond8b285f2009-09-01 04:26:58 +00001141 return Pos->second;
1142}
1143
1144void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1145 FieldDecl *Tmpl) {
1146 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1147 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1148 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1149 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Anders Carlssond8b285f2009-09-01 04:26:58 +00001151 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1152}
1153
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001154ASTContext::overridden_cxx_method_iterator
1155ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1156 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001157 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001158 if (Pos == OverriddenMethods.end())
1159 return 0;
1160
1161 return Pos->second.begin();
1162}
1163
1164ASTContext::overridden_cxx_method_iterator
1165ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1166 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001167 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001168 if (Pos == OverriddenMethods.end())
1169 return 0;
1170
1171 return Pos->second.end();
1172}
1173
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001174unsigned
1175ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1176 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001177 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001178 if (Pos == OverriddenMethods.end())
1179 return 0;
1180
1181 return Pos->second.size();
1182}
1183
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001184void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1185 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001186 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001187 OverriddenMethods[Method].push_back(Overridden);
1188}
1189
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001190void ASTContext::getOverriddenMethods(
1191 const NamedDecl *D,
1192 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001193 assert(D);
1194
1195 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001196 Overridden.append(overridden_methods_begin(CXXMethod),
1197 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001198 return;
1199 }
1200
1201 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1202 if (!Method)
1203 return;
1204
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001205 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1206 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001207 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001208}
1209
Douglas Gregore6649772011-12-03 00:30:27 +00001210void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1211 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1212 assert(!Import->isFromASTFile() && "Non-local import declaration");
1213 if (!FirstLocalImport) {
1214 FirstLocalImport = Import;
1215 LastLocalImport = Import;
1216 return;
1217 }
1218
1219 LastLocalImport->NextLocalImport = Import;
1220 LastLocalImport = Import;
1221}
1222
Chris Lattner464175b2007-07-18 17:52:12 +00001223//===----------------------------------------------------------------------===//
1224// Type Sizing and Analysis
1225//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001226
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001227/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1228/// scalar floating point type.
1229const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001230 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001231 assert(BT && "Not a floating point type!");
1232 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001233 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001234 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001235 case BuiltinType::Float: return Target->getFloatFormat();
1236 case BuiltinType::Double: return Target->getDoubleFormat();
1237 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001238 }
1239}
1240
Ken Dyck8b752f12010-01-27 17:10:57 +00001241/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001242/// specified decl. Note that bitfields do not have a valid alignment, so
1243/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001244/// If @p RefAsPointee, references are treated like their underlying type
1245/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001246CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001247 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001248
John McCall4081a5c2010-10-08 18:24:19 +00001249 bool UseAlignAttrOnly = false;
1250 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1251 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001252
John McCall4081a5c2010-10-08 18:24:19 +00001253 // __attribute__((aligned)) can increase or decrease alignment
1254 // *except* on a struct or struct member, where it only increases
1255 // alignment unless 'packed' is also specified.
1256 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001257 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001258 // ignore that possibility; Sema should diagnose it.
1259 if (isa<FieldDecl>(D)) {
1260 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1261 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1262 } else {
1263 UseAlignAttrOnly = true;
1264 }
1265 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001266 else if (isa<FieldDecl>(D))
1267 UseAlignAttrOnly =
1268 D->hasAttr<PackedAttr>() ||
1269 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001270
John McCallba4f5d52011-01-20 07:57:12 +00001271 // If we're using the align attribute only, just ignore everything
1272 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001273 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001274 // do nothing
1275
John McCall4081a5c2010-10-08 18:24:19 +00001276 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001277 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001278 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001279 if (RefAsPointee)
1280 T = RT->getPointeeType();
1281 else
1282 T = getPointerType(RT->getPointeeType());
1283 }
1284 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001285 // Adjust alignments of declarations with array type by the
1286 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001287 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001288 const ArrayType *arrayType;
1289 if (MinWidth && (arrayType = getAsArrayType(T))) {
1290 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001291 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001292 else if (isa<ConstantArrayType>(arrayType) &&
1293 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001294 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001295
John McCall3b657512011-01-19 10:06:00 +00001296 // Walk through any array types while we're at it.
1297 T = getBaseElementType(arrayType);
1298 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001299 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001300 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1301 if (VD->hasGlobalStorage())
1302 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1303 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001304 }
John McCallba4f5d52011-01-20 07:57:12 +00001305
1306 // Fields can be subject to extra alignment constraints, like if
1307 // the field is packed, the struct is packed, or the struct has a
1308 // a max-field-alignment constraint (#pragma pack). So calculate
1309 // the actual alignment of the field within the struct, and then
1310 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001311 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1312 const RecordDecl *Parent = Field->getParent();
1313 // We can only produce a sensible answer if the record is valid.
1314 if (!Parent->isInvalidDecl()) {
1315 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001316
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001317 // Start with the record's overall alignment.
1318 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001319
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001320 // Use the GCD of that and the offset within the record.
1321 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1322 if (Offset > 0) {
1323 // Alignment is always a power of 2, so the GCD will be a power of 2,
1324 // which means we get to do this crazy thing instead of Euclid's.
1325 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1326 if (LowBitOfOffset < FieldAlign)
1327 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1328 }
1329
1330 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001331 }
Charles Davis05f62472010-02-23 04:52:00 +00001332 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001333 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001334
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001335 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001336}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001337
John McCall929bbfb2012-08-21 04:10:00 +00001338// getTypeInfoDataSizeInChars - Return the size of a type, in
1339// chars. If the type is a record, its data size is returned. This is
1340// the size of the memcpy that's performed when assigning this type
1341// using a trivial copy/move assignment operator.
1342std::pair<CharUnits, CharUnits>
1343ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1344 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1345
1346 // In C++, objects can sometimes be allocated into the tail padding
1347 // of a base-class subobject. We decide whether that's possible
1348 // during class layout, so here we can just trust the layout results.
1349 if (getLangOpts().CPlusPlus) {
1350 if (const RecordType *RT = T->getAs<RecordType>()) {
1351 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1352 sizeAndAlign.first = layout.getDataSize();
1353 }
1354 }
1355
1356 return sizeAndAlign;
1357}
1358
Richard Trieu910f17e2013-05-14 21:59:17 +00001359/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1360/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1361std::pair<CharUnits, CharUnits>
1362static getConstantArrayInfoInChars(const ASTContext &Context,
1363 const ConstantArrayType *CAT) {
1364 std::pair<CharUnits, CharUnits> EltInfo =
1365 Context.getTypeInfoInChars(CAT->getElementType());
1366 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001367 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1368 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001369 "Overflow in array type char size evaluation");
1370 uint64_t Width = EltInfo.first.getQuantity() * Size;
1371 unsigned Align = EltInfo.second.getQuantity();
1372 Width = llvm::RoundUpToAlignment(Width, Align);
1373 return std::make_pair(CharUnits::fromQuantity(Width),
1374 CharUnits::fromQuantity(Align));
1375}
1376
John McCallea1471e2010-05-20 01:18:31 +00001377std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001378ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001379 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1380 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001381 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001382 return std::make_pair(toCharUnitsFromBits(Info.first),
1383 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001384}
1385
1386std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001387ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001388 return getTypeInfoInChars(T.getTypePtr());
1389}
1390
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001391std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1392 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1393 if (it != MemoizedTypeInfo.end())
1394 return it->second;
1395
1396 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1397 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1398 return Info;
1399}
1400
1401/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1402/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001403///
1404/// FIXME: Pointers into different addr spaces could have different sizes and
1405/// alignment requirements: getPointerInfo should take an AddrSpace, this
1406/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001407std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001408ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001409 uint64_t Width=0;
1410 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001411 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001412#define TYPE(Class, Base)
1413#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001414#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001415#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001416#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1417 case Type::Class: \
1418 assert(!T->isDependentType() && "should not see dependent types here"); \
1419 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001420#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001421 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001422
Chris Lattner692233e2007-07-13 22:27:08 +00001423 case Type::FunctionNoProto:
1424 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001425 // GCC extension: alignof(function) = 32 bits
1426 Width = 0;
1427 Align = 32;
1428 break;
1429
Douglas Gregor72564e72009-02-26 23:50:07 +00001430 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001431 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001432 Width = 0;
1433 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1434 break;
1435
Steve Narofffb22d962007-08-30 01:06:46 +00001436 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001437 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Chris Lattner98be4942008-03-05 18:54:05 +00001439 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001440 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001441 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1442 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001443 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001444 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001445 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001446 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001447 }
Nate Begeman213541a2008-04-18 23:10:10 +00001448 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001449 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001450 const VectorType *VT = cast<VectorType>(T);
1451 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1452 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001453 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001454 // If the alignment is not a power of 2, round up to the next power of 2.
1455 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001456 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001457 Align = llvm::NextPowerOf2(Align);
1458 Width = llvm::RoundUpToAlignment(Width, Align);
1459 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001460 // Adjust the alignment based on the target max.
1461 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1462 if (TargetVectorAlign && TargetVectorAlign < Align)
1463 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001464 break;
1465 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001466
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001467 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001468 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001469 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001470 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001471 // GCC extension: alignof(void) = 8 bits.
1472 Width = 0;
1473 Align = 8;
1474 break;
1475
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001476 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001477 Width = Target->getBoolWidth();
1478 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001479 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001480 case BuiltinType::Char_S:
1481 case BuiltinType::Char_U:
1482 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001483 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001484 Width = Target->getCharWidth();
1485 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001486 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001487 case BuiltinType::WChar_S:
1488 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001489 Width = Target->getWCharWidth();
1490 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001491 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001492 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001493 Width = Target->getChar16Width();
1494 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001495 break;
1496 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001497 Width = Target->getChar32Width();
1498 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001499 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001500 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001502 Width = Target->getShortWidth();
1503 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001504 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001505 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001507 Width = Target->getIntWidth();
1508 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001509 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001510 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001511 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001512 Width = Target->getLongWidth();
1513 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001514 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001515 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001516 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001517 Width = Target->getLongLongWidth();
1518 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001519 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001520 case BuiltinType::Int128:
1521 case BuiltinType::UInt128:
1522 Width = 128;
1523 Align = 128; // int128_t is 128-bit aligned on all targets.
1524 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001525 case BuiltinType::Half:
1526 Width = Target->getHalfWidth();
1527 Align = Target->getHalfAlign();
1528 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001529 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001530 Width = Target->getFloatWidth();
1531 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001532 break;
1533 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001534 Width = Target->getDoubleWidth();
1535 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001536 break;
1537 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001538 Width = Target->getLongDoubleWidth();
1539 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001540 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001541 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001542 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1543 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001544 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001545 case BuiltinType::ObjCId:
1546 case BuiltinType::ObjCClass:
1547 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001548 Width = Target->getPointerWidth(0);
1549 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001550 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001551 case BuiltinType::OCLSampler:
1552 // Samplers are modeled as integers.
1553 Width = Target->getIntWidth();
1554 Align = Target->getIntAlign();
1555 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001556 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001557 case BuiltinType::OCLImage1d:
1558 case BuiltinType::OCLImage1dArray:
1559 case BuiltinType::OCLImage1dBuffer:
1560 case BuiltinType::OCLImage2d:
1561 case BuiltinType::OCLImage2dArray:
1562 case BuiltinType::OCLImage3d:
1563 // Currently these types are pointers to opaque types.
1564 Width = Target->getPointerWidth(0);
1565 Align = Target->getPointerAlign(0);
1566 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001567 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001568 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001569 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001570 Width = Target->getPointerWidth(0);
1571 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001572 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001573 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001574 unsigned AS = getTargetAddressSpace(
1575 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001576 Width = Target->getPointerWidth(AS);
1577 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001578 break;
1579 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001580 case Type::LValueReference:
1581 case Type::RValueReference: {
1582 // alignof and sizeof should never enter this code path here, so we go
1583 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001584 unsigned AS = getTargetAddressSpace(
1585 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001586 Width = Target->getPointerWidth(AS);
1587 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001588 break;
1589 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001590 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001591 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(AS);
1593 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001594 break;
1595 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001596 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001597 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001598 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001599 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001600 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001601 case Type::Complex: {
1602 // Complex types have the same alignment as their elements, but twice the
1603 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001604 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001605 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001606 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001607 Align = EltInfo.second;
1608 break;
1609 }
John McCallc12c5bb2010-05-15 11:32:37 +00001610 case Type::ObjCObject:
1611 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001612 case Type::Decayed:
1613 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001614 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001615 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001616 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001617 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001618 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001619 break;
1620 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001621 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001622 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001623 const TagType *TT = cast<TagType>(T);
1624
1625 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001626 Width = 8;
1627 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001628 break;
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Daniel Dunbar1d751182008-11-08 05:48:37 +00001631 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001632 return getTypeInfo(ET->getDecl()->getIntegerType());
1633
Daniel Dunbar1d751182008-11-08 05:48:37 +00001634 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001635 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001636 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001637 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001638 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001639 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001640
Chris Lattner9fcfe922009-10-22 05:17:15 +00001641 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001642 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1643 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001644
Richard Smith34b41d92011-02-20 03:19:35 +00001645 case Type::Auto: {
1646 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001647 assert(!A->getDeducedType().isNull() &&
1648 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001649 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001650 }
1651
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001652 case Type::Paren:
1653 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1654
Douglas Gregor18857642009-04-30 17:32:17 +00001655 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001656 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001657 std::pair<uint64_t, unsigned> Info
1658 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001659 // If the typedef has an aligned attribute on it, it overrides any computed
1660 // alignment we have. This violates the GCC documentation (which says that
1661 // attribute(aligned) can only round up) but matches its implementation.
1662 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1663 Align = AttrAlign;
1664 else
1665 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001666 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001667 break;
Chris Lattner71763312008-04-06 22:05:18 +00001668 }
Douglas Gregor18857642009-04-30 17:32:17 +00001669
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001670 case Type::Elaborated:
1671 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001672
John McCall9d156a72011-01-06 01:58:22 +00001673 case Type::Attributed:
1674 return getTypeInfo(
1675 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1676
Eli Friedmanb001de72011-10-06 23:00:33 +00001677 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001678 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001679 std::pair<uint64_t, unsigned> Info
1680 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1681 Width = Info.first;
1682 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001683
1684 // If the size of the type doesn't exceed the platform's max
1685 // atomic promotion width, make the size and alignment more
1686 // favorable to atomic operations:
1687 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1688 // Round the size up to a power of 2.
1689 if (!llvm::isPowerOf2_64(Width))
1690 Width = llvm::NextPowerOf2(Width);
1691
1692 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001693 Align = static_cast<unsigned>(Width);
1694 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001695 }
1696
Douglas Gregor18857642009-04-30 17:32:17 +00001697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Eli Friedman2be46072011-10-14 20:59:01 +00001699 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001700 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001701}
1702
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001703/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1704CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1705 return CharUnits::fromQuantity(BitSize / getCharWidth());
1706}
1707
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001708/// toBits - Convert a size in characters to a size in characters.
1709int64_t ASTContext::toBits(CharUnits CharSize) const {
1710 return CharSize.getQuantity() * getCharWidth();
1711}
1712
Ken Dyckbdc601b2009-12-22 14:23:30 +00001713/// getTypeSizeInChars - Return the size of the specified type, in characters.
1714/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001715CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001716 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001717}
Jay Foad4ba2a172011-01-12 09:06:06 +00001718CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001719 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001720}
1721
Ken Dyck16e20cc2010-01-26 17:25:18 +00001722/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001723/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001724CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001725 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001726}
Jay Foad4ba2a172011-01-12 09:06:06 +00001727CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001728 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001729}
1730
Chris Lattner34ebde42009-01-27 18:08:34 +00001731/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1732/// type for the current target in bits. This can be different than the ABI
1733/// alignment in cases where it is beneficial for performance to overalign
1734/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001735unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001736 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001737
1738 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001739 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001740 T = CT->getElementType().getTypePtr();
1741 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001742 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1743 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001744 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1745
Chris Lattner34ebde42009-01-27 18:08:34 +00001746 return ABIAlign;
1747}
1748
Ulrich Weigand6b203512013-05-06 16:23:57 +00001749/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1750/// to a global variable of the specified type.
1751unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1752 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1753}
1754
1755/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1756/// should be given to a global variable of the specified type.
1757CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1758 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1759}
1760
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001761/// DeepCollectObjCIvars -
1762/// This routine first collects all declared, but not synthesized, ivars in
1763/// super class and then collects all ivars, including those synthesized for
1764/// current class. This routine is used for implementation of current class
1765/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001766///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001767void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1768 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001769 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001770 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1771 DeepCollectObjCIvars(SuperClass, false, Ivars);
1772 if (!leafClass) {
1773 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1774 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001775 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001776 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001777 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001778 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001779 Iv= Iv->getNextIvar())
1780 Ivars.push_back(Iv);
1781 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001782}
1783
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001784/// CollectInheritedProtocols - Collect all protocols in current class and
1785/// those inherited by it.
1786void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001787 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001788 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001789 // We can use protocol_iterator here instead of
1790 // all_referenced_protocol_iterator since we are walking all categories.
1791 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1792 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001793 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001794 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001795 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001796 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001797 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001798 CollectInheritedProtocols(*P, Protocols);
1799 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001800 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001801
1802 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001803 for (ObjCInterfaceDecl::visible_categories_iterator
1804 Cat = OI->visible_categories_begin(),
1805 CatEnd = OI->visible_categories_end();
1806 Cat != CatEnd; ++Cat) {
1807 CollectInheritedProtocols(*Cat, Protocols);
1808 }
1809
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001810 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1811 while (SD) {
1812 CollectInheritedProtocols(SD, Protocols);
1813 SD = SD->getSuperClass();
1814 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001815 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001816 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001817 PE = OC->protocol_end(); P != PE; ++P) {
1818 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001819 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001820 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1821 PE = Proto->protocol_end(); P != PE; ++P)
1822 CollectInheritedProtocols(*P, Protocols);
1823 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001824 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001825 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1826 PE = OP->protocol_end(); P != PE; ++P) {
1827 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001828 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001829 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1830 PE = Proto->protocol_end(); P != PE; ++P)
1831 CollectInheritedProtocols(*P, Protocols);
1832 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001833 }
1834}
1835
Jay Foad4ba2a172011-01-12 09:06:06 +00001836unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001837 unsigned count = 0;
1838 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001839 for (ObjCInterfaceDecl::known_extensions_iterator
1840 Ext = OI->known_extensions_begin(),
1841 ExtEnd = OI->known_extensions_end();
1842 Ext != ExtEnd; ++Ext) {
1843 count += Ext->ivar_size();
1844 }
1845
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001846 // Count ivar defined in this class's implementation. This
1847 // includes synthesized ivars.
1848 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001849 count += ImplDecl->ivar_size();
1850
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001851 return count;
1852}
1853
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001854bool ASTContext::isSentinelNullExpr(const Expr *E) {
1855 if (!E)
1856 return false;
1857
1858 // nullptr_t is always treated as null.
1859 if (E->getType()->isNullPtrType()) return true;
1860
1861 if (E->getType()->isAnyPointerType() &&
1862 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1863 Expr::NPC_ValueDependentIsNull))
1864 return true;
1865
1866 // Unfortunately, __null has type 'int'.
1867 if (isa<GNUNullExpr>(E)) return true;
1868
1869 return false;
1870}
1871
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001872/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1873ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1874 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1875 I = ObjCImpls.find(D);
1876 if (I != ObjCImpls.end())
1877 return cast<ObjCImplementationDecl>(I->second);
1878 return 0;
1879}
1880/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1881ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1882 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1883 I = ObjCImpls.find(D);
1884 if (I != ObjCImpls.end())
1885 return cast<ObjCCategoryImplDecl>(I->second);
1886 return 0;
1887}
1888
1889/// \brief Set the implementation of ObjCInterfaceDecl.
1890void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1891 ObjCImplementationDecl *ImplD) {
1892 assert(IFaceD && ImplD && "Passed null params");
1893 ObjCImpls[IFaceD] = ImplD;
1894}
1895/// \brief Set the implementation of ObjCCategoryDecl.
1896void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1897 ObjCCategoryImplDecl *ImplD) {
1898 assert(CatD && ImplD && "Passed null params");
1899 ObjCImpls[CatD] = ImplD;
1900}
1901
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001902const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1903 const NamedDecl *ND) const {
1904 if (const ObjCInterfaceDecl *ID =
1905 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001906 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001907 if (const ObjCCategoryDecl *CD =
1908 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001909 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001910 if (const ObjCImplDecl *IMD =
1911 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001912 return IMD->getClassInterface();
1913
1914 return 0;
1915}
1916
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001917/// \brief Get the copy initialization expression of VarDecl,or NULL if
1918/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001919Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001920 assert(VD && "Passed null params");
1921 assert(VD->hasAttr<BlocksAttr>() &&
1922 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001923 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001924 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001925 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1926}
1927
1928/// \brief Set the copy inialization expression of a block var decl.
1929void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1930 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001931 assert(VD->hasAttr<BlocksAttr>() &&
1932 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001933 BlockVarCopyInits[VD] = Init;
1934}
1935
John McCalla93c9342009-12-07 02:54:59 +00001936TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001937 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001938 if (!DataSize)
1939 DataSize = TypeLoc::getFullDataSizeForType(T);
1940 else
1941 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001942 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001943
John McCalla93c9342009-12-07 02:54:59 +00001944 TypeSourceInfo *TInfo =
1945 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1946 new (TInfo) TypeSourceInfo(T);
1947 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001948}
1949
John McCalla93c9342009-12-07 02:54:59 +00001950TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001951 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001952 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001953 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001954 return DI;
1955}
1956
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001957const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001958ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001959 return getObjCLayout(D, 0);
1960}
1961
1962const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001963ASTContext::getASTObjCImplementationLayout(
1964 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001965 return getObjCLayout(D->getClassInterface(), D);
1966}
1967
Chris Lattnera7674d82007-07-13 22:13:22 +00001968//===----------------------------------------------------------------------===//
1969// Type creation/memoization methods
1970//===----------------------------------------------------------------------===//
1971
Jay Foad4ba2a172011-01-12 09:06:06 +00001972QualType
John McCall3b657512011-01-19 10:06:00 +00001973ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1974 unsigned fastQuals = quals.getFastQualifiers();
1975 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001976
1977 // Check if we've already instantiated this type.
1978 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001979 ExtQuals::Profile(ID, baseType, quals);
1980 void *insertPos = 0;
1981 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1982 assert(eq->getQualifiers() == quals);
1983 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001984 }
1985
John McCall3b657512011-01-19 10:06:00 +00001986 // If the base type is not canonical, make the appropriate canonical type.
1987 QualType canon;
1988 if (!baseType->isCanonicalUnqualified()) {
1989 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001990 canonSplit.Quals.addConsistentQualifiers(quals);
1991 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001992
1993 // Re-find the insert position.
1994 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1995 }
1996
1997 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1998 ExtQualNodes.InsertNode(eq, insertPos);
1999 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002000}
2001
Jay Foad4ba2a172011-01-12 09:06:06 +00002002QualType
2003ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002004 QualType CanT = getCanonicalType(T);
2005 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002006 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002007
John McCall0953e762009-09-24 19:53:00 +00002008 // If we are composing extended qualifiers together, merge together
2009 // into one ExtQuals node.
2010 QualifierCollector Quals;
2011 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall0953e762009-09-24 19:53:00 +00002013 // If this type already has an address space specified, it cannot get
2014 // another one.
2015 assert(!Quals.hasAddressSpace() &&
2016 "Type cannot be in multiple addr spaces!");
2017 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002018
John McCall0953e762009-09-24 19:53:00 +00002019 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002020}
2021
Chris Lattnerb7d25532009-02-18 22:53:11 +00002022QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002023 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002024 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002025 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002026 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall7f040a92010-12-24 02:08:15 +00002028 if (const PointerType *ptr = T->getAs<PointerType>()) {
2029 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002030 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002031 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2032 return getPointerType(ResultType);
2033 }
2034 }
Mike Stump1eb44332009-09-09 15:08:12 +00002035
John McCall0953e762009-09-24 19:53:00 +00002036 // If we are composing extended qualifiers together, merge together
2037 // into one ExtQuals node.
2038 QualifierCollector Quals;
2039 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
John McCall0953e762009-09-24 19:53:00 +00002041 // If this type already has an ObjCGC specified, it cannot get
2042 // another one.
2043 assert(!Quals.hasObjCGCAttr() &&
2044 "Type cannot have multiple ObjCGCs!");
2045 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002046
John McCall0953e762009-09-24 19:53:00 +00002047 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002048}
Chris Lattnera7674d82007-07-13 22:13:22 +00002049
John McCalle6a365d2010-12-19 02:44:49 +00002050const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2051 FunctionType::ExtInfo Info) {
2052 if (T->getExtInfo() == Info)
2053 return T;
2054
2055 QualType Result;
2056 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2057 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2058 } else {
2059 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2060 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2061 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002062 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002063 }
2064
2065 return cast<FunctionType>(Result.getTypePtr());
2066}
2067
Richard Smith60e141e2013-05-04 07:00:32 +00002068void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2069 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002070 FD = FD->getMostRecentDecl();
2071 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002072 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2073 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2074 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002075 if (FunctionDecl *Next = FD->getPreviousDecl())
2076 FD = Next;
2077 else
2078 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002079 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002080 if (ASTMutationListener *L = getASTMutationListener())
2081 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002082}
2083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084/// getComplexType - Return the uniqued reference to the type for a complex
2085/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002086QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Unique pointers, to guarantee there is only one pointer of a particular
2088 // structure.
2089 llvm::FoldingSetNodeID ID;
2090 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 void *InsertPos = 0;
2093 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2094 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 // If the pointee type isn't canonical, this won't be a canonical type either,
2097 // so fill in the canonical type field.
2098 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002099 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002100 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // Get the new insert position for the node we care about.
2103 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002104 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 }
John McCall6b304a02009-09-24 23:30:46 +00002106 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 Types.push_back(New);
2108 ComplexTypes.InsertNode(New, InsertPos);
2109 return QualType(New, 0);
2110}
2111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112/// getPointerType - Return the uniqued reference to the type for a pointer to
2113/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002114QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 // Unique pointers, to guarantee there is only one pointer of a particular
2116 // structure.
2117 llvm::FoldingSetNodeID ID;
2118 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 void *InsertPos = 0;
2121 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2122 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 // If the pointee type isn't canonical, this won't be a canonical type either,
2125 // so fill in the canonical type field.
2126 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002127 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002128 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Bob Wilsonc90cc932013-03-15 17:12:43 +00002130 // Get the new insert position for the node we care about.
2131 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2132 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2133 }
John McCall6b304a02009-09-24 23:30:46 +00002134 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 Types.push_back(New);
2136 PointerTypes.InsertNode(New, InsertPos);
2137 return QualType(New, 0);
2138}
2139
Reid Kleckner12df2462013-06-24 17:51:48 +00002140QualType ASTContext::getDecayedType(QualType T) const {
2141 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2142
2143 llvm::FoldingSetNodeID ID;
2144 DecayedType::Profile(ID, T);
2145 void *InsertPos = 0;
2146 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2147 return QualType(DT, 0);
2148
2149 QualType Decayed;
2150
2151 // C99 6.7.5.3p7:
2152 // A declaration of a parameter as "array of type" shall be
2153 // adjusted to "qualified pointer to type", where the type
2154 // qualifiers (if any) are those specified within the [ and ] of
2155 // the array type derivation.
2156 if (T->isArrayType())
2157 Decayed = getArrayDecayedType(T);
2158
2159 // C99 6.7.5.3p8:
2160 // A declaration of a parameter as "function returning type"
2161 // shall be adjusted to "pointer to function returning type", as
2162 // in 6.3.2.1.
2163 if (T->isFunctionType())
2164 Decayed = getPointerType(T);
2165
2166 QualType Canonical = getCanonicalType(Decayed);
2167
2168 // Get the new insert position for the node we care about.
2169 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2171
2172 DecayedType *New =
2173 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2174 Types.push_back(New);
2175 DecayedTypes.InsertNode(New, InsertPos);
2176 return QualType(New, 0);
2177}
2178
Mike Stump1eb44332009-09-09 15:08:12 +00002179/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002180/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002181QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002182 assert(T->isFunctionType() && "block of function types only");
2183 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002184 // structure.
2185 llvm::FoldingSetNodeID ID;
2186 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Steve Naroff5618bd42008-08-27 16:04:49 +00002188 void *InsertPos = 0;
2189 if (BlockPointerType *PT =
2190 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2191 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002192
2193 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002194 // type either so fill in the canonical type field.
2195 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002196 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002197 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Steve Naroff5618bd42008-08-27 16:04:49 +00002199 // Get the new insert position for the node we care about.
2200 BlockPointerType *NewIP =
2201 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002203 }
John McCall6b304a02009-09-24 23:30:46 +00002204 BlockPointerType *New
2205 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002206 Types.push_back(New);
2207 BlockPointerTypes.InsertNode(New, InsertPos);
2208 return QualType(New, 0);
2209}
2210
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002211/// getLValueReferenceType - Return the uniqued reference to the type for an
2212/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002213QualType
2214ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002215 assert(getCanonicalType(T) != OverloadTy &&
2216 "Unresolved overloaded function type");
2217
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 // Unique pointers, to guarantee there is only one pointer of a particular
2219 // structure.
2220 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002221 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002222
2223 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002224 if (LValueReferenceType *RT =
2225 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002227
John McCall54e14c42009-10-22 22:37:11 +00002228 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2229
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 // If the referencee type isn't canonical, this won't be a canonical type
2231 // either, so fill in the canonical type field.
2232 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002233 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2234 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2235 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002236
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002238 LValueReferenceType *NewIP =
2239 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002240 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 }
2242
John McCall6b304a02009-09-24 23:30:46 +00002243 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002244 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2245 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002247 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002248
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002249 return QualType(New, 0);
2250}
2251
2252/// getRValueReferenceType - Return the uniqued reference to the type for an
2253/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002254QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002255 // Unique pointers, to guarantee there is only one pointer of a particular
2256 // structure.
2257 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002258 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259
2260 void *InsertPos = 0;
2261 if (RValueReferenceType *RT =
2262 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2263 return QualType(RT, 0);
2264
John McCall54e14c42009-10-22 22:37:11 +00002265 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2266
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002267 // If the referencee type isn't canonical, this won't be a canonical type
2268 // either, so fill in the canonical type field.
2269 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002270 if (InnerRef || !T.isCanonical()) {
2271 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2272 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002273
2274 // Get the new insert position for the node we care about.
2275 RValueReferenceType *NewIP =
2276 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002277 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002278 }
2279
John McCall6b304a02009-09-24 23:30:46 +00002280 RValueReferenceType *New
2281 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002282 Types.push_back(New);
2283 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 return QualType(New, 0);
2285}
2286
Sebastian Redlf30208a2009-01-24 21:16:55 +00002287/// getMemberPointerType - Return the uniqued reference to the type for a
2288/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002289QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002290 // Unique pointers, to guarantee there is only one pointer of a particular
2291 // structure.
2292 llvm::FoldingSetNodeID ID;
2293 MemberPointerType::Profile(ID, T, Cls);
2294
2295 void *InsertPos = 0;
2296 if (MemberPointerType *PT =
2297 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2298 return QualType(PT, 0);
2299
2300 // If the pointee or class type isn't canonical, this won't be a canonical
2301 // type either, so fill in the canonical type field.
2302 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002303 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002304 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2305
2306 // Get the new insert position for the node we care about.
2307 MemberPointerType *NewIP =
2308 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002309 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002310 }
John McCall6b304a02009-09-24 23:30:46 +00002311 MemberPointerType *New
2312 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002313 Types.push_back(New);
2314 MemberPointerTypes.InsertNode(New, InsertPos);
2315 return QualType(New, 0);
2316}
2317
Mike Stump1eb44332009-09-09 15:08:12 +00002318/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002319/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002320QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002321 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002322 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002323 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002324 assert((EltTy->isDependentType() ||
2325 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002326 "Constant array of VLAs is illegal!");
2327
Chris Lattner38aeec72009-05-13 04:12:56 +00002328 // Convert the array size into a canonical width matching the pointer size for
2329 // the target.
2330 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002331 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002332 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002335 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002338 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002339 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002341
John McCall3b657512011-01-19 10:06:00 +00002342 // If the element type isn't canonical or has qualifiers, this won't
2343 // be a canonical type either, so fill in the canonical type field.
2344 QualType Canon;
2345 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2346 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002347 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002348 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002349 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002350
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002352 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002353 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002354 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 }
Mike Stump1eb44332009-09-09 15:08:12 +00002356
John McCall6b304a02009-09-24 23:30:46 +00002357 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002358 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002359 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 Types.push_back(New);
2361 return QualType(New, 0);
2362}
2363
John McCallce889032011-01-18 08:40:38 +00002364/// getVariableArrayDecayedType - Turns the given type, which may be
2365/// variably-modified, into the corresponding type with all the known
2366/// sizes replaced with [*].
2367QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2368 // Vastly most common case.
2369 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002370
John McCallce889032011-01-18 08:40:38 +00002371 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002372
John McCallce889032011-01-18 08:40:38 +00002373 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002374 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002375 switch (ty->getTypeClass()) {
2376#define TYPE(Class, Base)
2377#define ABSTRACT_TYPE(Class, Base)
2378#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2379#include "clang/AST/TypeNodes.def"
2380 llvm_unreachable("didn't desugar past all non-canonical types?");
2381
2382 // These types should never be variably-modified.
2383 case Type::Builtin:
2384 case Type::Complex:
2385 case Type::Vector:
2386 case Type::ExtVector:
2387 case Type::DependentSizedExtVector:
2388 case Type::ObjCObject:
2389 case Type::ObjCInterface:
2390 case Type::ObjCObjectPointer:
2391 case Type::Record:
2392 case Type::Enum:
2393 case Type::UnresolvedUsing:
2394 case Type::TypeOfExpr:
2395 case Type::TypeOf:
2396 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002397 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002398 case Type::DependentName:
2399 case Type::InjectedClassName:
2400 case Type::TemplateSpecialization:
2401 case Type::DependentTemplateSpecialization:
2402 case Type::TemplateTypeParm:
2403 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002404 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002405 case Type::PackExpansion:
2406 llvm_unreachable("type should never be variably-modified");
2407
2408 // These types can be variably-modified but should never need to
2409 // further decay.
2410 case Type::FunctionNoProto:
2411 case Type::FunctionProto:
2412 case Type::BlockPointer:
2413 case Type::MemberPointer:
2414 return type;
2415
2416 // These types can be variably-modified. All these modifications
2417 // preserve structure except as noted by comments.
2418 // TODO: if we ever care about optimizing VLAs, there are no-op
2419 // optimizations available here.
2420 case Type::Pointer:
2421 result = getPointerType(getVariableArrayDecayedType(
2422 cast<PointerType>(ty)->getPointeeType()));
2423 break;
2424
2425 case Type::LValueReference: {
2426 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2427 result = getLValueReferenceType(
2428 getVariableArrayDecayedType(lv->getPointeeType()),
2429 lv->isSpelledAsLValue());
2430 break;
2431 }
2432
2433 case Type::RValueReference: {
2434 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2435 result = getRValueReferenceType(
2436 getVariableArrayDecayedType(lv->getPointeeType()));
2437 break;
2438 }
2439
Eli Friedmanb001de72011-10-06 23:00:33 +00002440 case Type::Atomic: {
2441 const AtomicType *at = cast<AtomicType>(ty);
2442 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2443 break;
2444 }
2445
John McCallce889032011-01-18 08:40:38 +00002446 case Type::ConstantArray: {
2447 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2448 result = getConstantArrayType(
2449 getVariableArrayDecayedType(cat->getElementType()),
2450 cat->getSize(),
2451 cat->getSizeModifier(),
2452 cat->getIndexTypeCVRQualifiers());
2453 break;
2454 }
2455
2456 case Type::DependentSizedArray: {
2457 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2458 result = getDependentSizedArrayType(
2459 getVariableArrayDecayedType(dat->getElementType()),
2460 dat->getSizeExpr(),
2461 dat->getSizeModifier(),
2462 dat->getIndexTypeCVRQualifiers(),
2463 dat->getBracketsRange());
2464 break;
2465 }
2466
2467 // Turn incomplete types into [*] types.
2468 case Type::IncompleteArray: {
2469 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2470 result = getVariableArrayType(
2471 getVariableArrayDecayedType(iat->getElementType()),
2472 /*size*/ 0,
2473 ArrayType::Normal,
2474 iat->getIndexTypeCVRQualifiers(),
2475 SourceRange());
2476 break;
2477 }
2478
2479 // Turn VLA types into [*] types.
2480 case Type::VariableArray: {
2481 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2482 result = getVariableArrayType(
2483 getVariableArrayDecayedType(vat->getElementType()),
2484 /*size*/ 0,
2485 ArrayType::Star,
2486 vat->getIndexTypeCVRQualifiers(),
2487 vat->getBracketsRange());
2488 break;
2489 }
2490 }
2491
2492 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002493 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002494}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002495
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002496/// getVariableArrayType - Returns a non-unique reference to the type for a
2497/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002498QualType ASTContext::getVariableArrayType(QualType EltTy,
2499 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002500 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002501 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002502 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002503 // Since we don't unique expressions, it isn't possible to unique VLA's
2504 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002505 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002506
John McCall3b657512011-01-19 10:06:00 +00002507 // Be sure to pull qualifiers off the element type.
2508 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2509 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002510 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002511 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002512 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002513 }
2514
John McCall6b304a02009-09-24 23:30:46 +00002515 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002516 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002517
2518 VariableArrayTypes.push_back(New);
2519 Types.push_back(New);
2520 return QualType(New, 0);
2521}
2522
Douglas Gregor898574e2008-12-05 23:32:09 +00002523/// getDependentSizedArrayType - Returns a non-unique reference to
2524/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002525/// type.
John McCall3b657512011-01-19 10:06:00 +00002526QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2527 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002528 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002529 unsigned elementTypeQuals,
2530 SourceRange brackets) const {
2531 assert((!numElements || numElements->isTypeDependent() ||
2532 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002533 "Size must be type- or value-dependent!");
2534
John McCall3b657512011-01-19 10:06:00 +00002535 // Dependently-sized array types that do not have a specified number
2536 // of elements will have their sizes deduced from a dependent
2537 // initializer. We do no canonicalization here at all, which is okay
2538 // because they can't be used in most locations.
2539 if (!numElements) {
2540 DependentSizedArrayType *newType
2541 = new (*this, TypeAlignment)
2542 DependentSizedArrayType(*this, elementType, QualType(),
2543 numElements, ASM, elementTypeQuals,
2544 brackets);
2545 Types.push_back(newType);
2546 return QualType(newType, 0);
2547 }
2548
2549 // Otherwise, we actually build a new type every time, but we
2550 // also build a canonical type.
2551
2552 SplitQualType canonElementType = getCanonicalType(elementType).split();
2553
2554 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002555 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002556 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002557 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002558 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002559
John McCall3b657512011-01-19 10:06:00 +00002560 // Look for an existing type with these properties.
2561 DependentSizedArrayType *canonTy =
2562 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002563
John McCall3b657512011-01-19 10:06:00 +00002564 // If we don't have one, build one.
2565 if (!canonTy) {
2566 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002567 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002568 QualType(), numElements, ASM, elementTypeQuals,
2569 brackets);
2570 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2571 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002572 }
2573
John McCall3b657512011-01-19 10:06:00 +00002574 // Apply qualifiers from the element type to the array.
2575 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002576 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002577
John McCall3b657512011-01-19 10:06:00 +00002578 // If we didn't need extra canonicalization for the element type,
2579 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002580 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002581 return canon;
2582
2583 // Otherwise, we need to build a type which follows the spelling
2584 // of the element type.
2585 DependentSizedArrayType *sugaredType
2586 = new (*this, TypeAlignment)
2587 DependentSizedArrayType(*this, elementType, canon, numElements,
2588 ASM, elementTypeQuals, brackets);
2589 Types.push_back(sugaredType);
2590 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002591}
2592
John McCall3b657512011-01-19 10:06:00 +00002593QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002594 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002595 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002596 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002597 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002598
John McCall3b657512011-01-19 10:06:00 +00002599 void *insertPos = 0;
2600 if (IncompleteArrayType *iat =
2601 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2602 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002603
2604 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002605 // either, so fill in the canonical type field. We also have to pull
2606 // qualifiers off the element type.
2607 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002608
John McCall3b657512011-01-19 10:06:00 +00002609 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2610 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002611 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002612 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002613 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002614
2615 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002616 IncompleteArrayType *existing =
2617 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2618 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002619 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002620
John McCall3b657512011-01-19 10:06:00 +00002621 IncompleteArrayType *newType = new (*this, TypeAlignment)
2622 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002623
John McCall3b657512011-01-19 10:06:00 +00002624 IncompleteArrayTypes.InsertNode(newType, insertPos);
2625 Types.push_back(newType);
2626 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002627}
2628
Steve Naroff73322922007-07-18 18:00:27 +00002629/// getVectorType - Return the unique reference to a vector type of
2630/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002631QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002632 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002633 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Check if we've already instantiated a vector of this type.
2636 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002637 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002638
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 void *InsertPos = 0;
2640 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2641 return QualType(VTP, 0);
2642
2643 // If the element type isn't canonical, this won't be a canonical type either,
2644 // so fill in the canonical type field.
2645 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002646 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002647 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 // Get the new insert position for the node we care about.
2650 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002651 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 }
John McCall6b304a02009-09-24 23:30:46 +00002653 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002654 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 VectorTypes.InsertNode(New, InsertPos);
2656 Types.push_back(New);
2657 return QualType(New, 0);
2658}
2659
Nate Begeman213541a2008-04-18 23:10:10 +00002660/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002661/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002662QualType
2663ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002664 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Steve Naroff73322922007-07-18 18:00:27 +00002666 // Check if we've already instantiated a vector of this type.
2667 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002668 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002669 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002670 void *InsertPos = 0;
2671 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2672 return QualType(VTP, 0);
2673
2674 // If the element type isn't canonical, this won't be a canonical type either,
2675 // so fill in the canonical type field.
2676 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002677 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002678 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Steve Naroff73322922007-07-18 18:00:27 +00002680 // Get the new insert position for the node we care about.
2681 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002682 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002683 }
John McCall6b304a02009-09-24 23:30:46 +00002684 ExtVectorType *New = new (*this, TypeAlignment)
2685 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002686 VectorTypes.InsertNode(New, InsertPos);
2687 Types.push_back(New);
2688 return QualType(New, 0);
2689}
2690
Jay Foad4ba2a172011-01-12 09:06:06 +00002691QualType
2692ASTContext::getDependentSizedExtVectorType(QualType vecType,
2693 Expr *SizeExpr,
2694 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002695 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002696 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002697 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002699 void *InsertPos = 0;
2700 DependentSizedExtVectorType *Canon
2701 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 DependentSizedExtVectorType *New;
2703 if (Canon) {
2704 // We already have a canonical version of this array type; use it as
2705 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002706 New = new (*this, TypeAlignment)
2707 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2708 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002709 } else {
2710 QualType CanonVecTy = getCanonicalType(vecType);
2711 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002712 New = new (*this, TypeAlignment)
2713 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2714 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002715
2716 DependentSizedExtVectorType *CanonCheck
2717 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2718 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2719 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002720 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2721 } else {
2722 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2723 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002724 New = new (*this, TypeAlignment)
2725 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002726 }
2727 }
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002729 Types.push_back(New);
2730 return QualType(New, 0);
2731}
2732
Douglas Gregor72564e72009-02-26 23:50:07 +00002733/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002734///
Jay Foad4ba2a172011-01-12 09:06:06 +00002735QualType
2736ASTContext::getFunctionNoProtoType(QualType ResultTy,
2737 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002738 const CallingConv DefaultCC = Info.getCC();
2739 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2740 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 // Unique functions, to guarantee there is only one function of a particular
2742 // structure.
2743 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002744 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002747 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002748 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002752 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002753 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002754 Canonical =
2755 getFunctionNoProtoType(getCanonicalType(ResultTy),
2756 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002759 FunctionNoProtoType *NewIP =
2760 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002761 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Roman Divackycfe9af22011-03-01 17:40:53 +00002764 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002765 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002766 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002768 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 return QualType(New, 0);
2770}
2771
Douglas Gregor02dd7982013-01-17 23:36:45 +00002772/// \brief Determine whether \p T is canonical as the result type of a function.
2773static bool isCanonicalResultType(QualType T) {
2774 return T.isCanonical() &&
2775 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2776 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2777}
2778
Reid Spencer5f016e22007-07-11 17:01:13 +00002779/// getFunctionType - Return a normal function type with a typed argument
2780/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002781QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002782ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002783 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002784 size_t NumArgs = ArgArray.size();
2785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // Unique functions, to guarantee there is only one function of a particular
2787 // structure.
2788 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002789 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2790 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002791
2792 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002793 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002794 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002796
2797 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002798 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002799 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002800 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002802 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 isCanonical = false;
2804
Roman Divackycfe9af22011-03-01 17:40:53 +00002805 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2806 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2807 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002808
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002810 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002812 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002813 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 CanonicalArgs.reserve(NumArgs);
2815 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002816 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002817
John McCalle23cf432010-12-14 08:05:40 +00002818 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002819 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002820 CanonicalEPI.ExceptionSpecType = EST_None;
2821 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002822 CanonicalEPI.ExtInfo
2823 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2824
Douglas Gregor02dd7982013-01-17 23:36:45 +00002825 // Result types do not have ARC lifetime qualifiers.
2826 QualType CanResultTy = getCanonicalType(ResultTy);
2827 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2828 Qualifiers Qs = CanResultTy.getQualifiers();
2829 Qs.removeObjCLifetime();
2830 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2831 }
2832
Jordan Rosebea522f2013-03-08 21:51:21 +00002833 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002834
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002836 FunctionProtoType *NewIP =
2837 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002838 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002840
John McCallf85e1932011-06-15 23:02:42 +00002841 // FunctionProtoType objects are allocated with extra bytes after
2842 // them for three variable size arrays at the end:
2843 // - parameter types
2844 // - exception types
2845 // - consumed-arguments flags
2846 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002847 // expression, or information used to resolve the exception
2848 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002849 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002850 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002851 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002852 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002853 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002854 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002855 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002856 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002857 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2858 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002859 }
John McCallf85e1932011-06-15 23:02:42 +00002860 if (EPI.ConsumedArguments)
2861 Size += NumArgs * sizeof(bool);
2862
John McCalle23cf432010-12-14 08:05:40 +00002863 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002864 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2865 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002866 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002868 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 return QualType(FTP, 0);
2870}
2871
John McCall3cb0ebd2010-03-10 03:28:59 +00002872#ifndef NDEBUG
2873static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2874 if (!isa<CXXRecordDecl>(D)) return false;
2875 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2876 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2877 return true;
2878 if (RD->getDescribedClassTemplate() &&
2879 !isa<ClassTemplateSpecializationDecl>(RD))
2880 return true;
2881 return false;
2882}
2883#endif
2884
2885/// getInjectedClassNameType - Return the unique reference to the
2886/// injected class name type for the specified templated declaration.
2887QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002888 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002889 assert(NeedsInjectedClassNameType(Decl));
2890 if (Decl->TypeForDecl) {
2891 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002892 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002893 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2894 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2895 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2896 } else {
John McCallf4c73712011-01-19 06:33:43 +00002897 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002898 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002899 Decl->TypeForDecl = newType;
2900 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002901 }
2902 return QualType(Decl->TypeForDecl, 0);
2903}
2904
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002905/// getTypeDeclType - Return the unique reference to the type for the
2906/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002907QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002908 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002909 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Richard Smith162e1c12011-04-15 14:24:37 +00002911 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002912 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002913
John McCallbecb8d52010-03-10 06:48:02 +00002914 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2915 "Template type parameter types are always available.");
2916
John McCall19c85762010-02-16 03:57:14 +00002917 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002918 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002919 "struct/union has previous declaration");
2920 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002921 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002922 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002923 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002924 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002925 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002926 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002927 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002928 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2929 Decl->TypeForDecl = newType;
2930 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002931 } else
John McCallbecb8d52010-03-10 06:48:02 +00002932 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002933
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002934 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002935}
2936
Reid Spencer5f016e22007-07-11 17:01:13 +00002937/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002938/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002939QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002940ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2941 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002944 if (Canonical.isNull())
2945 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002946 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002947 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002948 Decl->TypeForDecl = newType;
2949 Types.push_back(newType);
2950 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002951}
2952
Jay Foad4ba2a172011-01-12 09:06:06 +00002953QualType ASTContext::getRecordType(const RecordDecl *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 RecordDecl *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 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
2963 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002964}
2965
Jay Foad4ba2a172011-01-12 09:06:06 +00002966QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002967 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2968
Douglas Gregoref96ee02012-01-14 16:38:05 +00002969 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002970 if (PrevDecl->TypeForDecl)
2971 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2972
John McCallf4c73712011-01-19 06:33:43 +00002973 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2974 Decl->TypeForDecl = newType;
2975 Types.push_back(newType);
2976 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002977}
2978
John McCall9d156a72011-01-06 01:58:22 +00002979QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2980 QualType modifiedType,
2981 QualType equivalentType) {
2982 llvm::FoldingSetNodeID id;
2983 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2984
2985 void *insertPos = 0;
2986 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2987 if (type) return QualType(type, 0);
2988
2989 QualType canon = getCanonicalType(equivalentType);
2990 type = new (*this, TypeAlignment)
2991 AttributedType(canon, attrKind, modifiedType, equivalentType);
2992
2993 Types.push_back(type);
2994 AttributedTypes.InsertNode(type, insertPos);
2995
2996 return QualType(type, 0);
2997}
2998
2999
John McCall49a832b2009-10-18 09:09:24 +00003000/// \brief Retrieve a substitution-result type.
3001QualType
3002ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00003003 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00003004 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00003005 && "replacement types must always be canonical");
3006
3007 llvm::FoldingSetNodeID ID;
3008 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3009 void *InsertPos = 0;
3010 SubstTemplateTypeParmType *SubstParm
3011 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3012
3013 if (!SubstParm) {
3014 SubstParm = new (*this, TypeAlignment)
3015 SubstTemplateTypeParmType(Parm, Replacement);
3016 Types.push_back(SubstParm);
3017 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3018 }
3019
3020 return QualType(SubstParm, 0);
3021}
3022
Douglas Gregorc3069d62011-01-14 02:55:32 +00003023/// \brief Retrieve a
3024QualType ASTContext::getSubstTemplateTypeParmPackType(
3025 const TemplateTypeParmType *Parm,
3026 const TemplateArgument &ArgPack) {
3027#ifndef NDEBUG
3028 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3029 PEnd = ArgPack.pack_end();
3030 P != PEnd; ++P) {
3031 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3032 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3033 }
3034#endif
3035
3036 llvm::FoldingSetNodeID ID;
3037 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3038 void *InsertPos = 0;
3039 if (SubstTemplateTypeParmPackType *SubstParm
3040 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3041 return QualType(SubstParm, 0);
3042
3043 QualType Canon;
3044 if (!Parm->isCanonicalUnqualified()) {
3045 Canon = getCanonicalType(QualType(Parm, 0));
3046 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3047 ArgPack);
3048 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3049 }
3050
3051 SubstTemplateTypeParmPackType *SubstParm
3052 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3053 ArgPack);
3054 Types.push_back(SubstParm);
3055 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3056 return QualType(SubstParm, 0);
3057}
3058
Douglas Gregorfab9d672009-02-05 23:33:38 +00003059/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003060/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003061/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003062QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003063 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003064 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003065 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003066 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003067 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003068 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003069 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3070
3071 if (TypeParm)
3072 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003074 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003075 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003076 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003077
3078 TemplateTypeParmType *TypeCheck
3079 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3080 assert(!TypeCheck && "Template type parameter canonical type broken");
3081 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003082 } else
John McCall6b304a02009-09-24 23:30:46 +00003083 TypeParm = new (*this, TypeAlignment)
3084 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003085
3086 Types.push_back(TypeParm);
3087 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3088
3089 return QualType(TypeParm, 0);
3090}
3091
John McCall3cb0ebd2010-03-10 03:28:59 +00003092TypeSourceInfo *
3093ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3094 SourceLocation NameLoc,
3095 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003096 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003097 assert(!Name.getAsDependentTemplateName() &&
3098 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003099 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003100
3101 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003102 TemplateSpecializationTypeLoc TL =
3103 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003104 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003105 TL.setTemplateNameLoc(NameLoc);
3106 TL.setLAngleLoc(Args.getLAngleLoc());
3107 TL.setRAngleLoc(Args.getRAngleLoc());
3108 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3109 TL.setArgLocInfo(i, Args[i].getLocInfo());
3110 return DI;
3111}
3112
Mike Stump1eb44332009-09-09 15:08:12 +00003113QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003114ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003115 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003116 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003117 assert(!Template.getAsDependentTemplateName() &&
3118 "No dependent template names here!");
3119
John McCalld5532b62009-11-23 01:53:49 +00003120 unsigned NumArgs = Args.size();
3121
Chris Lattner5f9e2722011-07-23 10:55:15 +00003122 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003123 ArgVec.reserve(NumArgs);
3124 for (unsigned i = 0; i != NumArgs; ++i)
3125 ArgVec.push_back(Args[i].getArgument());
3126
John McCall31f17ec2010-04-27 00:57:59 +00003127 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003128 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003129}
3130
Douglas Gregorb70126a2012-02-03 17:16:23 +00003131#ifndef NDEBUG
3132static bool hasAnyPackExpansions(const TemplateArgument *Args,
3133 unsigned NumArgs) {
3134 for (unsigned I = 0; I != NumArgs; ++I)
3135 if (Args[I].isPackExpansion())
3136 return true;
3137
3138 return true;
3139}
3140#endif
3141
John McCall833ca992009-10-29 08:12:44 +00003142QualType
3143ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003144 const TemplateArgument *Args,
3145 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003146 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003147 assert(!Template.getAsDependentTemplateName() &&
3148 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003149 // Look through qualified template names.
3150 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3151 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003152
Douglas Gregorb70126a2012-02-03 17:16:23 +00003153 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003154 Template.getAsTemplateDecl() &&
3155 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003156 QualType CanonType;
3157 if (!Underlying.isNull())
3158 CanonType = getCanonicalType(Underlying);
3159 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003160 // We can get here with an alias template when the specialization contains
3161 // a pack expansion that does not match up with a parameter pack.
3162 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3163 "Caller must compute aliased type");
3164 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003165 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3166 NumArgs);
3167 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003168
Douglas Gregor1275ae02009-07-28 23:00:59 +00003169 // Allocate the (non-canonical) template specialization type, but don't
3170 // try to unique it: these types typically have location information that
3171 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003172 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3173 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003174 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003175 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003176 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003177 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3178 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Douglas Gregor55f6b142009-02-09 18:46:07 +00003180 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003181 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003182}
3183
Mike Stump1eb44332009-09-09 15:08:12 +00003184QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003185ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3186 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003187 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003188 assert(!Template.getAsDependentTemplateName() &&
3189 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003190
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003191 // Look through qualified template names.
3192 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3193 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003194
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003195 // Build the canonical template specialization type.
3196 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003197 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003198 CanonArgs.reserve(NumArgs);
3199 for (unsigned I = 0; I != NumArgs; ++I)
3200 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3201
3202 // Determine whether this canonical template specialization type already
3203 // exists.
3204 llvm::FoldingSetNodeID ID;
3205 TemplateSpecializationType::Profile(ID, CanonTemplate,
3206 CanonArgs.data(), NumArgs, *this);
3207
3208 void *InsertPos = 0;
3209 TemplateSpecializationType *Spec
3210 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3211
3212 if (!Spec) {
3213 // Allocate a new canonical template specialization type.
3214 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3215 sizeof(TemplateArgument) * NumArgs),
3216 TypeAlignment);
3217 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3218 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003219 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003220 Types.push_back(Spec);
3221 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3222 }
3223
3224 assert(Spec->isDependentType() &&
3225 "Non-dependent template-id type must have a canonical type");
3226 return QualType(Spec, 0);
3227}
3228
3229QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003230ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3231 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003232 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003233 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003234 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003235
3236 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003237 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003238 if (T)
3239 return QualType(T, 0);
3240
Douglas Gregor789b1f62010-02-04 18:10:26 +00003241 QualType Canon = NamedType;
3242 if (!Canon.isCanonical()) {
3243 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003244 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3245 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003246 (void)CheckT;
3247 }
3248
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003249 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003250 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003251 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003252 return QualType(T, 0);
3253}
3254
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003255QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003256ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003257 llvm::FoldingSetNodeID ID;
3258 ParenType::Profile(ID, InnerType);
3259
3260 void *InsertPos = 0;
3261 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3262 if (T)
3263 return QualType(T, 0);
3264
3265 QualType Canon = InnerType;
3266 if (!Canon.isCanonical()) {
3267 Canon = getCanonicalType(InnerType);
3268 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3269 assert(!CheckT && "Paren canonical type broken");
3270 (void)CheckT;
3271 }
3272
3273 T = new (*this) ParenType(InnerType, Canon);
3274 Types.push_back(T);
3275 ParenTypes.InsertNode(T, InsertPos);
3276 return QualType(T, 0);
3277}
3278
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003279QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3280 NestedNameSpecifier *NNS,
3281 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003282 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003283 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3284
3285 if (Canon.isNull()) {
3286 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003287 ElaboratedTypeKeyword CanonKeyword = Keyword;
3288 if (Keyword == ETK_None)
3289 CanonKeyword = ETK_Typename;
3290
3291 if (CanonNNS != NNS || CanonKeyword != Keyword)
3292 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003293 }
3294
3295 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003296 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003297
3298 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003299 DependentNameType *T
3300 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003301 if (T)
3302 return QualType(T, 0);
3303
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003304 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003305 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003306 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003307 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003308}
3309
Mike Stump1eb44332009-09-09 15:08:12 +00003310QualType
John McCall33500952010-06-11 00:33:02 +00003311ASTContext::getDependentTemplateSpecializationType(
3312 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003313 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003314 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003315 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003316 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003317 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003318 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3319 ArgCopy.push_back(Args[I].getArgument());
3320 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3321 ArgCopy.size(),
3322 ArgCopy.data());
3323}
3324
3325QualType
3326ASTContext::getDependentTemplateSpecializationType(
3327 ElaboratedTypeKeyword Keyword,
3328 NestedNameSpecifier *NNS,
3329 const IdentifierInfo *Name,
3330 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003331 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003332 assert((!NNS || NNS->isDependent()) &&
3333 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003334
Douglas Gregor789b1f62010-02-04 18:10:26 +00003335 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003336 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3337 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003338
3339 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003340 DependentTemplateSpecializationType *T
3341 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003342 if (T)
3343 return QualType(T, 0);
3344
John McCall33500952010-06-11 00:33:02 +00003345 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003346
John McCall33500952010-06-11 00:33:02 +00003347 ElaboratedTypeKeyword CanonKeyword = Keyword;
3348 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3349
3350 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003351 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003352 for (unsigned I = 0; I != NumArgs; ++I) {
3353 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3354 if (!CanonArgs[I].structurallyEquals(Args[I]))
3355 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003356 }
3357
John McCall33500952010-06-11 00:33:02 +00003358 QualType Canon;
3359 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3360 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3361 Name, NumArgs,
3362 CanonArgs.data());
3363
3364 // Find the insert position again.
3365 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3366 }
3367
3368 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3369 sizeof(TemplateArgument) * NumArgs),
3370 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003371 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003372 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003373 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003374 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003375 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003376}
3377
Douglas Gregorcded4f62011-01-14 17:04:44 +00003378QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003379 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003380 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003381 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003382
3383 assert(Pattern->containsUnexpandedParameterPack() &&
3384 "Pack expansions must expand one or more parameter packs");
3385 void *InsertPos = 0;
3386 PackExpansionType *T
3387 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3388 if (T)
3389 return QualType(T, 0);
3390
3391 QualType Canon;
3392 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003393 Canon = getCanonicalType(Pattern);
3394 // The canonical type might not contain an unexpanded parameter pack, if it
3395 // contains an alias template specialization which ignores one of its
3396 // parameters.
3397 if (Canon->containsUnexpandedParameterPack()) {
3398 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003399
Richard Smithd8672ef2012-07-16 00:20:35 +00003400 // Find the insert position again, in case we inserted an element into
3401 // PackExpansionTypes and invalidated our insert position.
3402 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3403 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003404 }
3405
Douglas Gregorcded4f62011-01-14 17:04:44 +00003406 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003407 Types.push_back(T);
3408 PackExpansionTypes.InsertNode(T, InsertPos);
3409 return QualType(T, 0);
3410}
3411
Chris Lattner88cb27a2008-04-07 04:56:42 +00003412/// CmpProtocolNames - Comparison predicate for sorting protocols
3413/// alphabetically.
3414static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3415 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003416 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003417}
3418
John McCallc12c5bb2010-05-15 11:32:37 +00003419static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003420 unsigned NumProtocols) {
3421 if (NumProtocols == 0) return true;
3422
Douglas Gregor61cc2962012-01-02 02:00:30 +00003423 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3424 return false;
3425
John McCall54e14c42009-10-22 22:37:11 +00003426 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003427 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3428 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003429 return false;
3430 return true;
3431}
3432
3433static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003434 unsigned &NumProtocols) {
3435 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Chris Lattner88cb27a2008-04-07 04:56:42 +00003437 // Sort protocols, keyed by name.
3438 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3439
Douglas Gregor61cc2962012-01-02 02:00:30 +00003440 // Canonicalize.
3441 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3442 Protocols[I] = Protocols[I]->getCanonicalDecl();
3443
Chris Lattner88cb27a2008-04-07 04:56:42 +00003444 // Remove duplicates.
3445 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3446 NumProtocols = ProtocolsEnd-Protocols;
3447}
3448
John McCallc12c5bb2010-05-15 11:32:37 +00003449QualType ASTContext::getObjCObjectType(QualType BaseType,
3450 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003451 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003452 // If the base type is an interface and there aren't any protocols
3453 // to add, then the interface type will do just fine.
3454 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3455 return BaseType;
3456
3457 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003458 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003459 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003460 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003461 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3462 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003463
John McCallc12c5bb2010-05-15 11:32:37 +00003464 // Build the canonical type, which has the canonical base type and
3465 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003466 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003467 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3468 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3469 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003470 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003471 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003472 unsigned UniqueCount = NumProtocols;
3473
John McCall54e14c42009-10-22 22:37:11 +00003474 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003475 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3476 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003477 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003478 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3479 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003480 }
3481
3482 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003483 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3484 }
3485
3486 unsigned Size = sizeof(ObjCObjectTypeImpl);
3487 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3488 void *Mem = Allocate(Size, TypeAlignment);
3489 ObjCObjectTypeImpl *T =
3490 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3491
3492 Types.push_back(T);
3493 ObjCObjectTypes.InsertNode(T, InsertPos);
3494 return QualType(T, 0);
3495}
3496
3497/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3498/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003499QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003500 llvm::FoldingSetNodeID ID;
3501 ObjCObjectPointerType::Profile(ID, ObjectT);
3502
3503 void *InsertPos = 0;
3504 if (ObjCObjectPointerType *QT =
3505 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3506 return QualType(QT, 0);
3507
3508 // Find the canonical object type.
3509 QualType Canonical;
3510 if (!ObjectT.isCanonical()) {
3511 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3512
3513 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003514 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3515 }
3516
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003517 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003518 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3519 ObjCObjectPointerType *QType =
3520 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003522 Types.push_back(QType);
3523 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003524 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003525}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003526
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003527/// getObjCInterfaceType - Return the unique reference to the type for the
3528/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003529QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3530 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003531 if (Decl->TypeForDecl)
3532 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Douglas Gregor0af55012011-12-16 03:12:41 +00003534 if (PrevDecl) {
3535 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3536 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3537 return QualType(PrevDecl->TypeForDecl, 0);
3538 }
3539
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003540 // Prefer the definition, if there is one.
3541 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3542 Decl = Def;
3543
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003544 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3545 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3546 Decl->TypeForDecl = T;
3547 Types.push_back(T);
3548 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003549}
3550
Douglas Gregor72564e72009-02-26 23:50:07 +00003551/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3552/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003553/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003554/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003555/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003556QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003557 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003558 if (tofExpr->isTypeDependent()) {
3559 llvm::FoldingSetNodeID ID;
3560 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Douglas Gregorb1975722009-07-30 23:18:24 +00003562 void *InsertPos = 0;
3563 DependentTypeOfExprType *Canon
3564 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3565 if (Canon) {
3566 // We already have a "canonical" version of an identical, dependent
3567 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003568 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003569 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003570 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003571 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003572 Canon
3573 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003574 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3575 toe = Canon;
3576 }
3577 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003578 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003579 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003580 }
Steve Naroff9752f252007-08-01 18:02:17 +00003581 Types.push_back(toe);
3582 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003583}
3584
Steve Naroff9752f252007-08-01 18:02:17 +00003585/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3586/// TypeOfType AST's. The only motivation to unique these nodes would be
3587/// memory savings. Since typeof(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
Steve Naroff9752f252007-08-01 18:02:17 +00003589/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003590QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003591 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003592 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003593 Types.push_back(tot);
3594 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003595}
3596
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003597
Anders Carlsson395b4752009-06-24 19:06:50 +00003598/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3599/// DecltypeType AST's. The only motivation to unique these nodes would be
3600/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003601/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003602/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003603QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003604 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003605
3606 // C++0x [temp.type]p2:
3607 // If an expression e involves a template parameter, decltype(e) denotes a
3608 // unique dependent type. Two such decltype-specifiers refer to the same
3609 // type only if their expressions are equivalent (14.5.6.1).
3610 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003611 llvm::FoldingSetNodeID ID;
3612 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003614 void *InsertPos = 0;
3615 DependentDecltypeType *Canon
3616 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3617 if (Canon) {
3618 // We already have a "canonical" version of an equivalent, dependent
3619 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003620 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003621 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003622 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003623 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003624 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003625 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3626 dt = Canon;
3627 }
3628 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003629 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3630 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003631 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003632 Types.push_back(dt);
3633 return QualType(dt, 0);
3634}
3635
Sean Huntca63c202011-05-24 22:41:36 +00003636/// getUnaryTransformationType - We don't unique these, since the memory
3637/// savings are minimal and these are rare.
3638QualType ASTContext::getUnaryTransformType(QualType BaseType,
3639 QualType UnderlyingType,
3640 UnaryTransformType::UTTKind Kind)
3641 const {
3642 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003643 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3644 Kind,
3645 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003646 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003647 Types.push_back(Ty);
3648 return QualType(Ty, 0);
3649}
3650
Richard Smith60e141e2013-05-04 07:00:32 +00003651/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3652/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3653/// canonical deduced-but-dependent 'auto' type.
3654QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003655 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003656 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3657 return getAutoDeductType();
3658
3659 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003660 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003661 llvm::FoldingSetNodeID ID;
3662 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3663 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3664 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003665
Richard Smitha2c36462013-04-26 16:15:35 +00003666 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003667 IsDecltypeAuto,
3668 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003669 Types.push_back(AT);
3670 if (InsertPos)
3671 AutoTypes.InsertNode(AT, InsertPos);
3672 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003673}
3674
Eli Friedmanb001de72011-10-06 23:00:33 +00003675/// getAtomicType - Return the uniqued reference to the atomic type for
3676/// the given value type.
3677QualType ASTContext::getAtomicType(QualType T) const {
3678 // Unique pointers, to guarantee there is only one pointer of a particular
3679 // structure.
3680 llvm::FoldingSetNodeID ID;
3681 AtomicType::Profile(ID, T);
3682
3683 void *InsertPos = 0;
3684 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3685 return QualType(AT, 0);
3686
3687 // If the atomic value type isn't canonical, this won't be a canonical type
3688 // either, so fill in the canonical type field.
3689 QualType Canonical;
3690 if (!T.isCanonical()) {
3691 Canonical = getAtomicType(getCanonicalType(T));
3692
3693 // Get the new insert position for the node we care about.
3694 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3695 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3696 }
3697 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3698 Types.push_back(New);
3699 AtomicTypes.InsertNode(New, InsertPos);
3700 return QualType(New, 0);
3701}
3702
Richard Smithad762fc2011-04-14 22:09:26 +00003703/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3704QualType ASTContext::getAutoDeductType() const {
3705 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003706 AutoDeductTy = QualType(
3707 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3708 /*dependent*/false),
3709 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003710 return AutoDeductTy;
3711}
3712
3713/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3714QualType ASTContext::getAutoRRefDeductType() const {
3715 if (AutoRRefDeductTy.isNull())
3716 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3717 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3718 return AutoRRefDeductTy;
3719}
3720
Reid Spencer5f016e22007-07-11 17:01:13 +00003721/// getTagDeclType - Return the unique reference to the type for the
3722/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003723QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003724 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003725 // FIXME: What is the design on getTagDeclType when it requires casting
3726 // away const? mutable?
3727 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003728}
3729
Mike Stump1eb44332009-09-09 15:08:12 +00003730/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3731/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3732/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003733CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003734 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003735}
3736
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003737/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3738CanQualType ASTContext::getIntMaxType() const {
3739 return getFromTargetType(Target->getIntMaxType());
3740}
3741
3742/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3743CanQualType ASTContext::getUIntMaxType() const {
3744 return getFromTargetType(Target->getUIntMaxType());
3745}
3746
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003747/// getSignedWCharType - Return the type of "signed wchar_t".
3748/// Used when in C++, as a GCC extension.
3749QualType ASTContext::getSignedWCharType() const {
3750 // FIXME: derive from "Target" ?
3751 return WCharTy;
3752}
3753
3754/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3755/// Used when in C++, as a GCC extension.
3756QualType ASTContext::getUnsignedWCharType() const {
3757 // FIXME: derive from "Target" ?
3758 return UnsignedIntTy;
3759}
3760
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003761QualType ASTContext::getIntPtrType() const {
3762 return getFromTargetType(Target->getIntPtrType());
3763}
3764
3765QualType ASTContext::getUIntPtrType() const {
3766 return getCorrespondingUnsignedType(getIntPtrType());
3767}
3768
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003769/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003770/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3771QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003772 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003773}
3774
Eli Friedman6902e412012-11-27 02:58:24 +00003775/// \brief Return the unique type for "pid_t" defined in
3776/// <sys/types.h>. We need this to compute the correct type for vfork().
3777QualType ASTContext::getProcessIDType() const {
3778 return getFromTargetType(Target->getProcessIDType());
3779}
3780
Chris Lattnere6327742008-04-02 05:18:44 +00003781//===----------------------------------------------------------------------===//
3782// Type Operators
3783//===----------------------------------------------------------------------===//
3784
Jay Foad4ba2a172011-01-12 09:06:06 +00003785CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003786 // Push qualifiers into arrays, and then discard any remaining
3787 // qualifiers.
3788 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003789 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003790 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003791 QualType Result;
3792 if (isa<ArrayType>(Ty)) {
3793 Result = getArrayDecayedType(QualType(Ty,0));
3794 } else if (isa<FunctionType>(Ty)) {
3795 Result = getPointerType(QualType(Ty, 0));
3796 } else {
3797 Result = QualType(Ty, 0);
3798 }
3799
3800 return CanQualType::CreateUnsafe(Result);
3801}
3802
John McCall62c28c82011-01-18 07:41:22 +00003803QualType ASTContext::getUnqualifiedArrayType(QualType type,
3804 Qualifiers &quals) {
3805 SplitQualType splitType = type.getSplitUnqualifiedType();
3806
3807 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3808 // the unqualified desugared type and then drops it on the floor.
3809 // We then have to strip that sugar back off with
3810 // getUnqualifiedDesugaredType(), which is silly.
3811 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003812 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003813
3814 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003815 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003816 quals = splitType.Quals;
3817 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003818 }
3819
John McCall62c28c82011-01-18 07:41:22 +00003820 // Otherwise, recurse on the array's element type.
3821 QualType elementType = AT->getElementType();
3822 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3823
3824 // If that didn't change the element type, AT has no qualifiers, so we
3825 // can just use the results in splitType.
3826 if (elementType == unqualElementType) {
3827 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003828 quals = splitType.Quals;
3829 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003830 }
3831
3832 // Otherwise, add in the qualifiers from the outermost type, then
3833 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003834 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003835
Douglas Gregor9dadd942010-05-17 18:45:21 +00003836 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003837 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003838 CAT->getSizeModifier(), 0);
3839 }
3840
Douglas Gregor9dadd942010-05-17 18:45:21 +00003841 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003842 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003843 }
3844
Douglas Gregor9dadd942010-05-17 18:45:21 +00003845 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003846 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003847 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003848 VAT->getSizeModifier(),
3849 VAT->getIndexTypeCVRQualifiers(),
3850 VAT->getBracketsRange());
3851 }
3852
3853 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003854 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003855 DSAT->getSizeModifier(), 0,
3856 SourceRange());
3857}
3858
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003859/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3860/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3861/// they point to and return true. If T1 and T2 aren't pointer types
3862/// or pointer-to-member types, or if they are not similar at this
3863/// level, returns false and leaves T1 and T2 unchanged. Top-level
3864/// qualifiers on T1 and T2 are ignored. This function will typically
3865/// be called in a loop that successively "unwraps" pointer and
3866/// pointer-to-member types to compare them at each level.
3867bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3868 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3869 *T2PtrType = T2->getAs<PointerType>();
3870 if (T1PtrType && T2PtrType) {
3871 T1 = T1PtrType->getPointeeType();
3872 T2 = T2PtrType->getPointeeType();
3873 return true;
3874 }
3875
3876 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3877 *T2MPType = T2->getAs<MemberPointerType>();
3878 if (T1MPType && T2MPType &&
3879 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3880 QualType(T2MPType->getClass(), 0))) {
3881 T1 = T1MPType->getPointeeType();
3882 T2 = T2MPType->getPointeeType();
3883 return true;
3884 }
3885
David Blaikie4e4d0842012-03-11 07:00:24 +00003886 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003887 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3888 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3889 if (T1OPType && T2OPType) {
3890 T1 = T1OPType->getPointeeType();
3891 T2 = T2OPType->getPointeeType();
3892 return true;
3893 }
3894 }
3895
3896 // FIXME: Block pointers, too?
3897
3898 return false;
3899}
3900
Jay Foad4ba2a172011-01-12 09:06:06 +00003901DeclarationNameInfo
3902ASTContext::getNameForTemplate(TemplateName Name,
3903 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003904 switch (Name.getKind()) {
3905 case TemplateName::QualifiedTemplate:
3906 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003907 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003908 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3909 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003910
John McCall14606042011-06-30 08:33:18 +00003911 case TemplateName::OverloadedTemplate: {
3912 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3913 // DNInfo work in progress: CHECKME: what about DNLoc?
3914 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3915 }
3916
3917 case TemplateName::DependentTemplate: {
3918 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003919 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003920 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003921 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3922 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003923 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003924 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3925 // DNInfo work in progress: FIXME: source locations?
3926 DeclarationNameLoc DNLoc;
3927 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3928 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3929 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003930 }
3931 }
3932
John McCall14606042011-06-30 08:33:18 +00003933 case TemplateName::SubstTemplateTemplateParm: {
3934 SubstTemplateTemplateParmStorage *subst
3935 = Name.getAsSubstTemplateTemplateParm();
3936 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3937 NameLoc);
3938 }
3939
3940 case TemplateName::SubstTemplateTemplateParmPack: {
3941 SubstTemplateTemplateParmPackStorage *subst
3942 = Name.getAsSubstTemplateTemplateParmPack();
3943 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3944 NameLoc);
3945 }
3946 }
3947
3948 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003949}
3950
Jay Foad4ba2a172011-01-12 09:06:06 +00003951TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003952 switch (Name.getKind()) {
3953 case TemplateName::QualifiedTemplate:
3954 case TemplateName::Template: {
3955 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003956 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003957 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003958 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3959
3960 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003961 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003962 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003963
John McCall14606042011-06-30 08:33:18 +00003964 case TemplateName::OverloadedTemplate:
3965 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003966
John McCall14606042011-06-30 08:33:18 +00003967 case TemplateName::DependentTemplate: {
3968 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3969 assert(DTN && "Non-dependent template names must refer to template decls.");
3970 return DTN->CanonicalTemplateName;
3971 }
3972
3973 case TemplateName::SubstTemplateTemplateParm: {
3974 SubstTemplateTemplateParmStorage *subst
3975 = Name.getAsSubstTemplateTemplateParm();
3976 return getCanonicalTemplateName(subst->getReplacement());
3977 }
3978
3979 case TemplateName::SubstTemplateTemplateParmPack: {
3980 SubstTemplateTemplateParmPackStorage *subst
3981 = Name.getAsSubstTemplateTemplateParmPack();
3982 TemplateTemplateParmDecl *canonParameter
3983 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3984 TemplateArgument canonArgPack
3985 = getCanonicalTemplateArgument(subst->getArgumentPack());
3986 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3987 }
3988 }
3989
3990 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003991}
3992
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003993bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3994 X = getCanonicalTemplateName(X);
3995 Y = getCanonicalTemplateName(Y);
3996 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3997}
3998
Mike Stump1eb44332009-09-09 15:08:12 +00003999TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00004000ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00004001 switch (Arg.getKind()) {
4002 case TemplateArgument::Null:
4003 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Douglas Gregor1275ae02009-07-28 23:00:59 +00004005 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00004006 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Douglas Gregord2008e22012-04-06 22:40:38 +00004008 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004009 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4010 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004011 }
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Eli Friedmand7a6b162012-09-26 02:36:12 +00004013 case TemplateArgument::NullPtr:
4014 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4015 /*isNullPtr*/true);
4016
Douglas Gregor788cd062009-11-11 01:00:40 +00004017 case TemplateArgument::Template:
4018 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004019
4020 case TemplateArgument::TemplateExpansion:
4021 return TemplateArgument(getCanonicalTemplateName(
4022 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004023 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004024
Douglas Gregor1275ae02009-07-28 23:00:59 +00004025 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004026 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004027
Douglas Gregor1275ae02009-07-28 23:00:59 +00004028 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004029 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Douglas Gregor1275ae02009-07-28 23:00:59 +00004031 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004032 if (Arg.pack_size() == 0)
4033 return Arg;
4034
Douglas Gregor910f8002010-11-07 23:05:16 +00004035 TemplateArgument *CanonArgs
4036 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004037 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004038 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004039 AEnd = Arg.pack_end();
4040 A != AEnd; (void)++A, ++Idx)
4041 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Douglas Gregor910f8002010-11-07 23:05:16 +00004043 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004044 }
4045 }
4046
4047 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004048 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004049}
4050
Douglas Gregord57959a2009-03-27 23:10:48 +00004051NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004052ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004053 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004054 return 0;
4055
4056 switch (NNS->getKind()) {
4057 case NestedNameSpecifier::Identifier:
4058 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004059 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004060 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4061 NNS->getAsIdentifier());
4062
4063 case NestedNameSpecifier::Namespace:
4064 // A namespace is canonical; build a nested-name-specifier with
4065 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004066 return NestedNameSpecifier::Create(*this, 0,
4067 NNS->getAsNamespace()->getOriginalNamespace());
4068
4069 case NestedNameSpecifier::NamespaceAlias:
4070 // A namespace is canonical; build a nested-name-specifier with
4071 // this namespace and no prefix.
4072 return NestedNameSpecifier::Create(*this, 0,
4073 NNS->getAsNamespaceAlias()->getNamespace()
4074 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004075
4076 case NestedNameSpecifier::TypeSpec:
4077 case NestedNameSpecifier::TypeSpecWithTemplate: {
4078 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004079
4080 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4081 // break it apart into its prefix and identifier, then reconsititute those
4082 // as the canonical nested-name-specifier. This is required to canonicalize
4083 // a dependent nested-name-specifier involving typedefs of dependent-name
4084 // types, e.g.,
4085 // typedef typename T::type T1;
4086 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004087 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4088 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004089 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004090
Eli Friedman16412ef2012-03-03 04:09:56 +00004091 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4092 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4093 // first place?
John McCall3b657512011-01-19 10:06:00 +00004094 return NestedNameSpecifier::Create(*this, 0, false,
4095 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004096 }
4097
4098 case NestedNameSpecifier::Global:
4099 // The global specifier is canonical and unique.
4100 return NNS;
4101 }
4102
David Blaikie7530c032012-01-17 06:56:22 +00004103 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004104}
4105
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004106
Jay Foad4ba2a172011-01-12 09:06:06 +00004107const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004108 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004109 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 // Handle the common positive case fast.
4111 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4112 return AT;
4113 }
Mike Stump1eb44332009-09-09 15:08:12 +00004114
John McCall0953e762009-09-24 19:53:00 +00004115 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004116 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004117 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004118
John McCall0953e762009-09-24 19:53:00 +00004119 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 // implements C99 6.7.3p8: "If the specification of an array type includes
4121 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004123 // If we get here, we either have type qualifiers on the type, or we have
4124 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004125 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004126
John McCall3b657512011-01-19 10:06:00 +00004127 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004128 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004130 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004131 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004132 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004133 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004135 // Otherwise, we have an array and we have qualifiers on it. Push the
4136 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004137 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004139 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4140 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4141 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004142 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004143 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4144 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4145 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004146 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004147
Mike Stump1eb44332009-09-09 15:08:12 +00004148 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004149 = dyn_cast<DependentSizedArrayType>(ATy))
4150 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004151 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004152 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004153 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004154 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004155 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004157 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004158 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004159 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004160 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004161 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004162 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004163}
4164
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004165QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004166 if (T->isArrayType() || T->isFunctionType())
4167 return getDecayedType(T);
4168 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004169}
4170
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004171QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004172 T = getVariableArrayDecayedType(T);
4173 T = getAdjustedParameterType(T);
4174 return T.getUnqualifiedType();
4175}
4176
Chris Lattnere6327742008-04-02 05:18:44 +00004177/// getArrayDecayedType - Return the properly qualified result of decaying the
4178/// specified array type to a pointer. This operation is non-trivial when
4179/// handling typedefs etc. The canonical type of "T" must be an array type,
4180/// this returns a pointer to a properly qualified element of the array.
4181///
4182/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004183QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004184 // Get the element type with 'getAsArrayType' so that we don't lose any
4185 // typedefs in the element type of the array. This also handles propagation
4186 // of type qualifiers from the array type into the element type if present
4187 // (C99 6.7.3p8).
4188 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4189 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004190
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004191 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004192
4193 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004194 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004195}
4196
John McCall3b657512011-01-19 10:06:00 +00004197QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4198 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004199}
4200
John McCall3b657512011-01-19 10:06:00 +00004201QualType ASTContext::getBaseElementType(QualType type) const {
4202 Qualifiers qs;
4203 while (true) {
4204 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004205 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004206 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004207
John McCall3b657512011-01-19 10:06:00 +00004208 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004209 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004210 }
Mike Stump1eb44332009-09-09 15:08:12 +00004211
John McCall3b657512011-01-19 10:06:00 +00004212 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004213}
4214
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004215/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004216uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004217ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4218 uint64_t ElementCount = 1;
4219 do {
4220 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004221 CA = dyn_cast_or_null<ConstantArrayType>(
4222 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004223 } while (CA);
4224 return ElementCount;
4225}
4226
Reid Spencer5f016e22007-07-11 17:01:13 +00004227/// getFloatingRank - Return a relative rank for floating point types.
4228/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004229static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004230 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004231 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004232
John McCall183700f2009-09-21 23:43:11 +00004233 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4234 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004235 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004236 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004237 case BuiltinType::Float: return FloatRank;
4238 case BuiltinType::Double: return DoubleRank;
4239 case BuiltinType::LongDouble: return LongDoubleRank;
4240 }
4241}
4242
Mike Stump1eb44332009-09-09 15:08:12 +00004243/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4244/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004245/// 'typeDomain' is a real floating point or complex type.
4246/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004247QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4248 QualType Domain) const {
4249 FloatingRank EltRank = getFloatingRank(Size);
4250 if (Domain->isComplexType()) {
4251 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004252 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004253 case FloatRank: return FloatComplexTy;
4254 case DoubleRank: return DoubleComplexTy;
4255 case LongDoubleRank: return LongDoubleComplexTy;
4256 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004257 }
Chris Lattner1361b112008-04-06 23:58:54 +00004258
4259 assert(Domain->isRealFloatingType() && "Unknown domain!");
4260 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004261 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004262 case FloatRank: return FloatTy;
4263 case DoubleRank: return DoubleTy;
4264 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004265 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004266 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004267}
4268
Chris Lattner7cfeb082008-04-06 23:55:33 +00004269/// getFloatingTypeOrder - Compare the rank of the two specified floating
4270/// point types, ignoring the domain of the type (i.e. 'double' ==
4271/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004272/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004273int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004274 FloatingRank LHSR = getFloatingRank(LHS);
4275 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Chris Lattnera75cea32008-04-06 23:38:49 +00004277 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004278 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004279 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004280 return 1;
4281 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004282}
4283
Chris Lattnerf52ab252008-04-06 22:59:24 +00004284/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4285/// routine will assert if passed a built-in type that isn't an integer or enum,
4286/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004287unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004288 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004289
Chris Lattnerf52ab252008-04-06 22:59:24 +00004290 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004291 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004292 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004293 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004294 case BuiltinType::Char_S:
4295 case BuiltinType::Char_U:
4296 case BuiltinType::SChar:
4297 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004298 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004299 case BuiltinType::Short:
4300 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004301 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004302 case BuiltinType::Int:
4303 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004304 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004305 case BuiltinType::Long:
4306 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004307 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004308 case BuiltinType::LongLong:
4309 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004310 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004311 case BuiltinType::Int128:
4312 case BuiltinType::UInt128:
4313 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004314 }
4315}
4316
Eli Friedman04e83572009-08-20 04:21:42 +00004317/// \brief Whether this is a promotable bitfield reference according
4318/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4319///
4320/// \returns the type this bit-field will promote to, or NULL if no
4321/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004322QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004323 if (E->isTypeDependent() || E->isValueDependent())
4324 return QualType();
4325
John McCall993f43f2013-05-06 21:39:12 +00004326 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004327 if (!Field)
4328 return QualType();
4329
4330 QualType FT = Field->getType();
4331
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004332 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004333 uint64_t IntSize = getTypeSize(IntTy);
4334 // GCC extension compatibility: if the bit-field size is less than or equal
4335 // to the size of int, it gets promoted no matter what its type is.
4336 // For instance, unsigned long bf : 4 gets promoted to signed int.
4337 if (BitWidth < IntSize)
4338 return IntTy;
4339
4340 if (BitWidth == IntSize)
4341 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4342
4343 // Types bigger than int are not subject to promotions, and therefore act
4344 // like the base type.
4345 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4346 // is ridiculous.
4347 return QualType();
4348}
4349
Eli Friedmana95d7572009-08-19 07:44:53 +00004350/// getPromotedIntegerType - Returns the type that Promotable will
4351/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4352/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004353QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004354 assert(!Promotable.isNull());
4355 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004356 if (const EnumType *ET = Promotable->getAs<EnumType>())
4357 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004358
4359 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4360 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4361 // (3.9.1) can be converted to a prvalue of the first of the following
4362 // types that can represent all the values of its underlying type:
4363 // int, unsigned int, long int, unsigned long int, long long int, or
4364 // unsigned long long int [...]
4365 // FIXME: Is there some better way to compute this?
4366 if (BT->getKind() == BuiltinType::WChar_S ||
4367 BT->getKind() == BuiltinType::WChar_U ||
4368 BT->getKind() == BuiltinType::Char16 ||
4369 BT->getKind() == BuiltinType::Char32) {
4370 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4371 uint64_t FromSize = getTypeSize(BT);
4372 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4373 LongLongTy, UnsignedLongLongTy };
4374 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4375 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4376 if (FromSize < ToSize ||
4377 (FromSize == ToSize &&
4378 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4379 return PromoteTypes[Idx];
4380 }
4381 llvm_unreachable("char type should fit into long long");
4382 }
4383 }
4384
4385 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004386 if (Promotable->isSignedIntegerType())
4387 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004388 uint64_t PromotableSize = getIntWidth(Promotable);
4389 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004390 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4391 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4392}
4393
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004394/// \brief Recurses in pointer/array types until it finds an objc retainable
4395/// type and returns its ownership.
4396Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4397 while (!T.isNull()) {
4398 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4399 return T.getObjCLifetime();
4400 if (T->isArrayType())
4401 T = getBaseElementType(T);
4402 else if (const PointerType *PT = T->getAs<PointerType>())
4403 T = PT->getPointeeType();
4404 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004405 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004406 else
4407 break;
4408 }
4409
4410 return Qualifiers::OCL_None;
4411}
4412
Mike Stump1eb44332009-09-09 15:08:12 +00004413/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004414/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004415/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004416int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004417 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4418 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004419 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Chris Lattnerf52ab252008-04-06 22:59:24 +00004421 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4422 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Chris Lattner7cfeb082008-04-06 23:55:33 +00004424 unsigned LHSRank = getIntegerRank(LHSC);
4425 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Chris Lattner7cfeb082008-04-06 23:55:33 +00004427 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4428 if (LHSRank == RHSRank) return 0;
4429 return LHSRank > RHSRank ? 1 : -1;
4430 }
Mike Stump1eb44332009-09-09 15:08:12 +00004431
Chris Lattner7cfeb082008-04-06 23:55:33 +00004432 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4433 if (LHSUnsigned) {
4434 // If the unsigned [LHS] type is larger, return it.
4435 if (LHSRank >= RHSRank)
4436 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Chris Lattner7cfeb082008-04-06 23:55:33 +00004438 // If the signed type can represent all values of the unsigned type, it
4439 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004440 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004441 return -1;
4442 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004443
Chris Lattner7cfeb082008-04-06 23:55:33 +00004444 // If the unsigned [RHS] type is larger, return it.
4445 if (RHSRank >= LHSRank)
4446 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004447
Chris Lattner7cfeb082008-04-06 23:55:33 +00004448 // If the signed type can represent all values of the unsigned type, it
4449 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004450 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004451 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004452}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004453
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004454static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004455CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4456 DeclContext *DC, IdentifierInfo *Id) {
4457 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004458 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004459 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004460 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004461 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004462}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004463
Mike Stump1eb44332009-09-09 15:08:12 +00004464// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004465QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004466 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004467 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004468 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004469 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004470 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004471
Anders Carlssonf06273f2007-11-19 00:25:30 +00004472 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Anders Carlsson71993dd2007-08-17 05:31:46 +00004474 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004475 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004476 // int flags;
4477 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004478 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004479 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004480 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004481 FieldTypes[3] = LongTy;
4482
Anders Carlsson71993dd2007-08-17 05:31:46 +00004483 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004484 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004485 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004486 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004487 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004488 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004489 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004490 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004491 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004492 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004493 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004494 }
4495
Douglas Gregor838db382010-02-11 01:19:42 +00004496 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004497 }
Mike Stump1eb44332009-09-09 15:08:12 +00004498
Anders Carlsson71993dd2007-08-17 05:31:46 +00004499 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004500}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004501
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004502QualType ASTContext::getObjCSuperType() const {
4503 if (ObjCSuperType.isNull()) {
4504 RecordDecl *ObjCSuperTypeDecl =
4505 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4506 TUDecl->addDecl(ObjCSuperTypeDecl);
4507 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4508 }
4509 return ObjCSuperType;
4510}
4511
Douglas Gregor319ac892009-04-23 22:29:11 +00004512void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004513 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004514 assert(Rec && "Invalid CFConstantStringType");
4515 CFConstantStringTypeDecl = Rec->getDecl();
4516}
4517
Jay Foad4ba2a172011-01-12 09:06:06 +00004518QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004519 if (BlockDescriptorType)
4520 return getTagDeclType(BlockDescriptorType);
4521
4522 RecordDecl *T;
4523 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004524 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004525 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004526 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004527
4528 QualType FieldTypes[] = {
4529 UnsignedLongTy,
4530 UnsignedLongTy,
4531 };
4532
Craig Topper3aa29df2013-07-15 08:24:27 +00004533 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004534 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004535 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004536 };
4537
4538 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004539 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004540 SourceLocation(),
4541 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004542 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004543 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004544 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004545 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004546 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004547 T->addDecl(Field);
4548 }
4549
Douglas Gregor838db382010-02-11 01:19:42 +00004550 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004551
4552 BlockDescriptorType = T;
4553
4554 return getTagDeclType(BlockDescriptorType);
4555}
4556
Jay Foad4ba2a172011-01-12 09:06:06 +00004557QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004558 if (BlockDescriptorExtendedType)
4559 return getTagDeclType(BlockDescriptorExtendedType);
4560
4561 RecordDecl *T;
4562 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004563 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004564 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004565 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004566
4567 QualType FieldTypes[] = {
4568 UnsignedLongTy,
4569 UnsignedLongTy,
4570 getPointerType(VoidPtrTy),
4571 getPointerType(VoidPtrTy)
4572 };
4573
Craig Topper3aa29df2013-07-15 08:24:27 +00004574 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004575 "reserved",
4576 "Size",
4577 "CopyFuncPtr",
4578 "DestroyFuncPtr"
4579 };
4580
4581 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004582 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004583 SourceLocation(),
4584 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004585 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004586 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004587 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004588 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004589 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004590 T->addDecl(Field);
4591 }
4592
Douglas Gregor838db382010-02-11 01:19:42 +00004593 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004594
4595 BlockDescriptorExtendedType = T;
4596
4597 return getTagDeclType(BlockDescriptorExtendedType);
4598}
4599
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004600/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4601/// requires copy/dispose. Note that this must match the logic
4602/// in buildByrefHelpers.
4603bool ASTContext::BlockRequiresCopying(QualType Ty,
4604 const VarDecl *D) {
4605 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4606 const Expr *copyExpr = getBlockVarCopyInits(D);
4607 if (!copyExpr && record->hasTrivialDestructor()) return false;
4608
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004609 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004610 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004611
4612 if (!Ty->isObjCRetainableType()) return false;
4613
4614 Qualifiers qs = Ty.getQualifiers();
4615
4616 // If we have lifetime, that dominates.
4617 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4618 assert(getLangOpts().ObjCAutoRefCount);
4619
4620 switch (lifetime) {
4621 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4622
4623 // These are just bits as far as the runtime is concerned.
4624 case Qualifiers::OCL_ExplicitNone:
4625 case Qualifiers::OCL_Autoreleasing:
4626 return false;
4627
4628 // Tell the runtime that this is ARC __weak, called by the
4629 // byref routines.
4630 case Qualifiers::OCL_Weak:
4631 // ARC __strong __block variables need to be retained.
4632 case Qualifiers::OCL_Strong:
4633 return true;
4634 }
4635 llvm_unreachable("fell out of lifetime switch!");
4636 }
4637 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4638 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004639}
4640
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004641bool ASTContext::getByrefLifetime(QualType Ty,
4642 Qualifiers::ObjCLifetime &LifeTime,
4643 bool &HasByrefExtendedLayout) const {
4644
4645 if (!getLangOpts().ObjC1 ||
4646 getLangOpts().getGC() != LangOptions::NonGC)
4647 return false;
4648
4649 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004650 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004651 HasByrefExtendedLayout = true;
4652 LifeTime = Qualifiers::OCL_None;
4653 }
4654 else if (getLangOpts().ObjCAutoRefCount)
4655 LifeTime = Ty.getObjCLifetime();
4656 // MRR.
4657 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4658 LifeTime = Qualifiers::OCL_ExplicitNone;
4659 else
4660 LifeTime = Qualifiers::OCL_None;
4661 return true;
4662}
4663
Douglas Gregore97179c2011-09-08 01:46:34 +00004664TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4665 if (!ObjCInstanceTypeDecl)
4666 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4667 getTranslationUnitDecl(),
4668 SourceLocation(),
4669 SourceLocation(),
4670 &Idents.get("instancetype"),
4671 getTrivialTypeSourceInfo(getObjCIdType()));
4672 return ObjCInstanceTypeDecl;
4673}
4674
Anders Carlssone8c49532007-10-29 06:33:42 +00004675// This returns true if a type has been typedefed to BOOL:
4676// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004677static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004678 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004679 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4680 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004682 return false;
4683}
4684
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004685/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004687CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004688 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4689 return CharUnits::Zero();
4690
Ken Dyck199c3d62010-01-11 17:06:35 +00004691 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004692
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004693 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004694 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004695 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004696 // Treat arrays as pointers, since that's how they're passed in.
4697 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004698 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004699 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004700}
4701
4702static inline
4703std::string charUnitsToString(const CharUnits &CU) {
4704 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004705}
4706
John McCall6b5a61b2011-02-07 10:33:21 +00004707/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004708/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004709std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4710 std::string S;
4711
David Chisnall5e530af2009-11-17 19:33:30 +00004712 const BlockDecl *Decl = Expr->getBlockDecl();
4713 QualType BlockTy =
4714 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4715 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004716 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004717 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4718 BlockTy->getAs<FunctionType>()->getResultType(),
4719 S, true /*Extended*/);
4720 else
4721 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4722 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004723 // Compute size of all parameters.
4724 // Start with computing size of a pointer in number of bytes.
4725 // FIXME: There might(should) be a better way of doing this computation!
4726 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004727 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4728 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004729 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004730 E = Decl->param_end(); PI != E; ++PI) {
4731 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004732 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004733 if (sz.isZero())
4734 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004735 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004736 ParmOffset += sz;
4737 }
4738 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004739 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004740 // Block pointer and offset.
4741 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004742
4743 // Argument types.
4744 ParmOffset = PtrSize;
4745 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4746 Decl->param_end(); PI != E; ++PI) {
4747 ParmVarDecl *PVDecl = *PI;
4748 QualType PType = PVDecl->getOriginalType();
4749 if (const ArrayType *AT =
4750 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4751 // Use array's original type only if it has known number of
4752 // elements.
4753 if (!isa<ConstantArrayType>(AT))
4754 PType = PVDecl->getType();
4755 } else if (PType->isFunctionType())
4756 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004757 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004758 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4759 S, true /*Extended*/);
4760 else
4761 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004762 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004763 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004764 }
John McCall6b5a61b2011-02-07 10:33:21 +00004765
4766 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004767}
4768
Douglas Gregorf968d832011-05-27 01:19:52 +00004769bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004770 std::string& S) {
4771 // Encode result type.
4772 getObjCEncodingForType(Decl->getResultType(), S);
4773 CharUnits ParmOffset;
4774 // Compute size of all parameters.
4775 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4776 E = Decl->param_end(); PI != E; ++PI) {
4777 QualType PType = (*PI)->getType();
4778 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004779 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004780 continue;
4781
David Chisnall5389f482010-12-30 14:05:53 +00004782 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004783 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004784 ParmOffset += sz;
4785 }
4786 S += charUnitsToString(ParmOffset);
4787 ParmOffset = CharUnits::Zero();
4788
4789 // Argument types.
4790 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4791 E = Decl->param_end(); PI != E; ++PI) {
4792 ParmVarDecl *PVDecl = *PI;
4793 QualType PType = PVDecl->getOriginalType();
4794 if (const ArrayType *AT =
4795 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4796 // Use array's original type only if it has known number of
4797 // elements.
4798 if (!isa<ConstantArrayType>(AT))
4799 PType = PVDecl->getType();
4800 } else if (PType->isFunctionType())
4801 PType = PVDecl->getType();
4802 getObjCEncodingForType(PType, S);
4803 S += charUnitsToString(ParmOffset);
4804 ParmOffset += getObjCEncodingTypeSize(PType);
4805 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004806
4807 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004808}
4809
Bob Wilsondc8dab62011-11-30 01:57:58 +00004810/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4811/// method parameter or return type. If Extended, include class names and
4812/// block object types.
4813void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4814 QualType T, std::string& S,
4815 bool Extended) const {
4816 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4817 getObjCEncodingForTypeQualifier(QT, S);
4818 // Encode parameter type.
4819 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4820 true /*OutermostType*/,
4821 false /*EncodingProperty*/,
4822 false /*StructField*/,
4823 Extended /*EncodeBlockParameters*/,
4824 Extended /*EncodeClassNames*/);
4825}
4826
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004827/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004828/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004829bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004830 std::string& S,
4831 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004832 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004833 // Encode return type.
4834 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4835 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004836 // Compute size of all parameters.
4837 // Start with computing size of a pointer in number of bytes.
4838 // FIXME: There might(should) be a better way of doing this computation!
4839 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004840 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004841 // The first two arguments (self and _cmd) are pointers; account for
4842 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004843 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004844 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004845 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004846 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004847 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004848 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004849 continue;
4850
Ken Dyck199c3d62010-01-11 17:06:35 +00004851 assert (sz.isPositive() &&
4852 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004853 ParmOffset += sz;
4854 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004855 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004856 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004857 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004859 // Argument types.
4860 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004861 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004862 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004863 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004864 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004865 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004866 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4867 // Use array's original type only if it has known number of
4868 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004869 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004870 PType = PVDecl->getType();
4871 } else if (PType->isFunctionType())
4872 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004873 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4874 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004875 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004876 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004877 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004878
4879 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004880}
4881
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004882/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004883/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004884/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4885/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004886/// Property attributes are stored as a comma-delimited C string. The simple
4887/// attributes readonly and bycopy are encoded as single characters. The
4888/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4889/// encoded as single characters, followed by an identifier. Property types
4890/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004891/// these attributes are defined by the following enumeration:
4892/// @code
4893/// enum PropertyAttributes {
4894/// kPropertyReadOnly = 'R', // property is read-only.
4895/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4896/// kPropertyByref = '&', // property is a reference to the value last assigned
4897/// kPropertyDynamic = 'D', // property is dynamic
4898/// kPropertyGetter = 'G', // followed by getter selector name
4899/// kPropertySetter = 'S', // followed by setter selector name
4900/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004901/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004902/// kPropertyWeak = 'W' // 'weak' property
4903/// kPropertyStrong = 'P' // property GC'able
4904/// kPropertyNonAtomic = 'N' // property non-atomic
4905/// };
4906/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004907void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004908 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004909 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004910 // Collect information from the property implementation decl(s).
4911 bool Dynamic = false;
4912 ObjCPropertyImplDecl *SynthesizePID = 0;
4913
4914 // FIXME: Duplicated code due to poor abstraction.
4915 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004916 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004917 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4918 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004919 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004920 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004921 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004922 if (PID->getPropertyDecl() == PD) {
4923 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4924 Dynamic = true;
4925 } else {
4926 SynthesizePID = PID;
4927 }
4928 }
4929 }
4930 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004931 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004932 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004933 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004934 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004935 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004936 if (PID->getPropertyDecl() == PD) {
4937 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4938 Dynamic = true;
4939 } else {
4940 SynthesizePID = PID;
4941 }
4942 }
Mike Stump1eb44332009-09-09 15:08:12 +00004943 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004944 }
4945 }
4946
4947 // FIXME: This is not very efficient.
4948 S = "T";
4949
4950 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004951 // GCC has some special rules regarding encoding of properties which
4952 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004953 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004954 true /* outermost type */,
4955 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004956
4957 if (PD->isReadOnly()) {
4958 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004959 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4960 S += ",C";
4961 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4962 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004963 } else {
4964 switch (PD->getSetterKind()) {
4965 case ObjCPropertyDecl::Assign: break;
4966 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004967 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004968 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004969 }
4970 }
4971
4972 // It really isn't clear at all what this means, since properties
4973 // are "dynamic by default".
4974 if (Dynamic)
4975 S += ",D";
4976
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004977 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4978 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004979
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004980 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4981 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004982 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004983 }
4984
4985 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4986 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004987 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004988 }
4989
4990 if (SynthesizePID) {
4991 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4992 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004993 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004994 }
4995
4996 // FIXME: OBJCGC: weak & strong
4997}
4998
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004999/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005000/// Another legacy compatibility encoding: 32-bit longs are encoded as
5001/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005002/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5003///
5004void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005005 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005006 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005007 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005008 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005009 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005010 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005011 PointeeTy = IntTy;
5012 }
5013 }
5014}
5015
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005016void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005017 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005018 // We follow the behavior of gcc, expanding structures which are
5019 // directly pointed to, and expanding embedded structures. Note that
5020 // these rules are sufficient to prevent recursive encoding of the
5021 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005022 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005023 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005024}
5025
John McCall3624e9e2012-12-20 02:45:14 +00005026static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5027 BuiltinType::Kind kind) {
5028 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005029 case BuiltinType::Void: return 'v';
5030 case BuiltinType::Bool: return 'B';
5031 case BuiltinType::Char_U:
5032 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005033 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005034 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005035 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005036 case BuiltinType::UInt: return 'I';
5037 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005038 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005039 case BuiltinType::UInt128: return 'T';
5040 case BuiltinType::ULongLong: return 'Q';
5041 case BuiltinType::Char_S:
5042 case BuiltinType::SChar: return 'c';
5043 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005044 case BuiltinType::WChar_S:
5045 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005046 case BuiltinType::Int: return 'i';
5047 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005048 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005049 case BuiltinType::LongLong: return 'q';
5050 case BuiltinType::Int128: return 't';
5051 case BuiltinType::Float: return 'f';
5052 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005053 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005054 case BuiltinType::NullPtr: return '*'; // like char*
5055
5056 case BuiltinType::Half:
5057 // FIXME: potentially need @encodes for these!
5058 return ' ';
5059
5060 case BuiltinType::ObjCId:
5061 case BuiltinType::ObjCClass:
5062 case BuiltinType::ObjCSel:
5063 llvm_unreachable("@encoding ObjC primitive type");
5064
5065 // OpenCL and placeholder types don't need @encodings.
5066 case BuiltinType::OCLImage1d:
5067 case BuiltinType::OCLImage1dArray:
5068 case BuiltinType::OCLImage1dBuffer:
5069 case BuiltinType::OCLImage2d:
5070 case BuiltinType::OCLImage2dArray:
5071 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005072 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005073 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005074 case BuiltinType::Dependent:
5075#define BUILTIN_TYPE(KIND, ID)
5076#define PLACEHOLDER_TYPE(KIND, ID) \
5077 case BuiltinType::KIND:
5078#include "clang/AST/BuiltinTypes.def"
5079 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005080 }
David Blaikie719e53f2013-01-09 17:48:41 +00005081 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005082}
5083
Douglas Gregor5471bc82011-09-08 17:18:35 +00005084static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5085 EnumDecl *Enum = ET->getDecl();
5086
5087 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5088 if (!Enum->isFixed())
5089 return 'i';
5090
5091 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005092 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5093 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005094}
5095
Jay Foad4ba2a172011-01-12 09:06:06 +00005096static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005097 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005098 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005099 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005100 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5101 // The GNU runtime requires more information; bitfields are encoded as b,
5102 // then the offset (in bits) of the first element, then the type of the
5103 // bitfield, then the size in bits. For example, in this structure:
5104 //
5105 // struct
5106 // {
5107 // int integer;
5108 // int flags:2;
5109 // };
5110 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5111 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5112 // information is not especially sensible, but we're stuck with it for
5113 // compatibility with GCC, although providing it breaks anything that
5114 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005115 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005116 const RecordDecl *RD = FD->getParent();
5117 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005118 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005119 if (const EnumType *ET = T->getAs<EnumType>())
5120 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005121 else {
5122 const BuiltinType *BT = T->castAs<BuiltinType>();
5123 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5124 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005125 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005126 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005127}
5128
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005129// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005130void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5131 bool ExpandPointedToStructures,
5132 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005133 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005134 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005135 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005136 bool StructField,
5137 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005138 bool EncodeClassNames,
5139 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005140 CanQualType CT = getCanonicalType(T);
5141 switch (CT->getTypeClass()) {
5142 case Type::Builtin:
5143 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005144 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005145 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005146 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5147 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5148 else
5149 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005150 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005151
John McCall3624e9e2012-12-20 02:45:14 +00005152 case Type::Complex: {
5153 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005154 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005155 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005156 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005157 return;
5158 }
John McCall3624e9e2012-12-20 02:45:14 +00005159
5160 case Type::Atomic: {
5161 const AtomicType *AT = T->castAs<AtomicType>();
5162 S += 'A';
5163 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5164 false, false);
5165 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005166 }
John McCall3624e9e2012-12-20 02:45:14 +00005167
5168 // encoding for pointer or reference types.
5169 case Type::Pointer:
5170 case Type::LValueReference:
5171 case Type::RValueReference: {
5172 QualType PointeeTy;
5173 if (isa<PointerType>(CT)) {
5174 const PointerType *PT = T->castAs<PointerType>();
5175 if (PT->isObjCSelType()) {
5176 S += ':';
5177 return;
5178 }
5179 PointeeTy = PT->getPointeeType();
5180 } else {
5181 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5182 }
5183
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005184 bool isReadOnly = false;
5185 // For historical/compatibility reasons, the read-only qualifier of the
5186 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5187 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005188 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005189 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005190 if (OutermostType && T.isConstQualified()) {
5191 isReadOnly = true;
5192 S += 'r';
5193 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005194 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005195 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005196 while (P->getAs<PointerType>())
5197 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005198 if (P.isConstQualified()) {
5199 isReadOnly = true;
5200 S += 'r';
5201 }
5202 }
5203 if (isReadOnly) {
5204 // Another legacy compatibility encoding. Some ObjC qualifier and type
5205 // combinations need to be rearranged.
5206 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005207 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005208 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005209 }
Mike Stump1eb44332009-09-09 15:08:12 +00005210
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005211 if (PointeeTy->isCharType()) {
5212 // char pointer types should be encoded as '*' unless it is a
5213 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005214 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005215 S += '*';
5216 return;
5217 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005218 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005219 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5220 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5221 S += '#';
5222 return;
5223 }
5224 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5225 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5226 S += '@';
5227 return;
5228 }
5229 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005230 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005231 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005232 getLegacyIntegralTypeEncoding(PointeeTy);
5233
Mike Stump1eb44332009-09-09 15:08:12 +00005234 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005235 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005236 return;
5237 }
John McCall3624e9e2012-12-20 02:45:14 +00005238
5239 case Type::ConstantArray:
5240 case Type::IncompleteArray:
5241 case Type::VariableArray: {
5242 const ArrayType *AT = cast<ArrayType>(CT);
5243
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005244 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005245 // Incomplete arrays are encoded as a pointer to the array element.
5246 S += '^';
5247
Mike Stump1eb44332009-09-09 15:08:12 +00005248 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 false, ExpandStructures, FD);
5250 } else {
5251 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005252
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005253 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5254 S += llvm::utostr(CAT->getSize().getZExtValue());
5255 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005256 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005257 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5258 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005259 S += '0';
5260 }
Mike Stump1eb44332009-09-09 15:08:12 +00005261
5262 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005263 false, ExpandStructures, FD);
5264 S += ']';
5265 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005266 return;
5267 }
Mike Stump1eb44332009-09-09 15:08:12 +00005268
John McCall3624e9e2012-12-20 02:45:14 +00005269 case Type::FunctionNoProto:
5270 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005271 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005272 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005273
John McCall3624e9e2012-12-20 02:45:14 +00005274 case Type::Record: {
5275 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005276 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005277 // Anonymous structures print as '?'
5278 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5279 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005280 if (ClassTemplateSpecializationDecl *Spec
5281 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5282 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005283 llvm::raw_string_ostream OS(S);
5284 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005285 TemplateArgs.data(),
5286 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005287 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005288 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005289 } else {
5290 S += '?';
5291 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005292 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005293 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005294 if (!RDecl->isUnion()) {
5295 getObjCEncodingForStructureImpl(RDecl, S, FD);
5296 } else {
5297 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5298 FieldEnd = RDecl->field_end();
5299 Field != FieldEnd; ++Field) {
5300 if (FD) {
5301 S += '"';
5302 S += Field->getNameAsString();
5303 S += '"';
5304 }
Mike Stump1eb44332009-09-09 15:08:12 +00005305
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005306 // Special case bit-fields.
5307 if (Field->isBitField()) {
5308 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005309 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005310 } else {
5311 QualType qt = Field->getType();
5312 getLegacyIntegralTypeEncoding(qt);
5313 getObjCEncodingForTypeImpl(qt, S, false, true,
5314 FD, /*OutermostType*/false,
5315 /*EncodingProperty*/false,
5316 /*StructField*/true);
5317 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005318 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005319 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005320 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005321 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005322 return;
5323 }
Mike Stump1eb44332009-09-09 15:08:12 +00005324
John McCall3624e9e2012-12-20 02:45:14 +00005325 case Type::BlockPointer: {
5326 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005327 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005328 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005329 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005330
5331 S += '<';
5332 // Block return type
5333 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5334 ExpandPointedToStructures, ExpandStructures,
5335 FD,
5336 false /* OutermostType */,
5337 EncodingProperty,
5338 false /* StructField */,
5339 EncodeBlockParameters,
5340 EncodeClassNames);
5341 // Block self
5342 S += "@?";
5343 // Block parameters
5344 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5345 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5346 E = FPT->arg_type_end(); I && (I != E); ++I) {
5347 getObjCEncodingForTypeImpl(*I, S,
5348 ExpandPointedToStructures,
5349 ExpandStructures,
5350 FD,
5351 false /* OutermostType */,
5352 EncodingProperty,
5353 false /* StructField */,
5354 EncodeBlockParameters,
5355 EncodeClassNames);
5356 }
5357 }
5358 S += '>';
5359 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005360 return;
5361 }
Mike Stump1eb44332009-09-09 15:08:12 +00005362
John McCall3624e9e2012-12-20 02:45:14 +00005363 case Type::ObjCObject:
5364 case Type::ObjCInterface: {
5365 // Ignore protocol qualifiers when mangling at this level.
5366 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005367
John McCall3624e9e2012-12-20 02:45:14 +00005368 // The assumption seems to be that this assert will succeed
5369 // because nested levels will have filtered out 'id' and 'Class'.
5370 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005371 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005372 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005373 S += '{';
5374 const IdentifierInfo *II = OI->getIdentifier();
5375 S += II->getName();
5376 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005377 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005378 DeepCollectObjCIvars(OI, true, Ivars);
5379 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005380 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005381 if (Field->isBitField())
5382 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005383 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005384 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5385 false, false, false, false, false,
5386 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005387 }
5388 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005389 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005390 }
Mike Stump1eb44332009-09-09 15:08:12 +00005391
John McCall3624e9e2012-12-20 02:45:14 +00005392 case Type::ObjCObjectPointer: {
5393 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005394 if (OPT->isObjCIdType()) {
5395 S += '@';
5396 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398
Steve Naroff27d20a22009-10-28 22:03:49 +00005399 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5400 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5401 // Since this is a binary compatibility issue, need to consult with runtime
5402 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005403 S += '#';
5404 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005405 }
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005407 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005408 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005409 ExpandPointedToStructures,
5410 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005411 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005412 // Note that we do extended encoding of protocol qualifer list
5413 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005414 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005415 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5416 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005417 S += '<';
5418 S += (*I)->getNameAsString();
5419 S += '>';
5420 }
5421 S += '"';
5422 }
5423 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005424 }
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005426 QualType PointeeTy = OPT->getPointeeType();
5427 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005428 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5429 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005430 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005431 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005432 // {...};
5433 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005434 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005435 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005436 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5437 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5438 DeepCollectObjCIvars(OI, true, Ivars);
5439 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5440 if (cast<FieldDecl>(Ivars[i]) == FD) {
5441 S += '{';
5442 S += OI->getIdentifier()->getName();
5443 S += '}';
5444 return;
5445 }
5446 }
5447 }
Mike Stump1eb44332009-09-09 15:08:12 +00005448 getObjCEncodingForTypeImpl(PointeeTy, S,
5449 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005450 NULL,
5451 false, false, false, false, false,
5452 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005453 return;
5454 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005455
5456 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005457 if (OPT->getInterfaceDecl() &&
5458 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005459 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005460 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005461 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5462 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005463 S += '<';
5464 S += (*I)->getNameAsString();
5465 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005466 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005467 S += '"';
5468 }
5469 return;
5470 }
Mike Stump1eb44332009-09-09 15:08:12 +00005471
John McCall532ec7b2010-05-17 23:56:34 +00005472 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005473 // FIXME: we shoul do better than that. 'M' is available.
5474 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005475 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005476
John McCall3624e9e2012-12-20 02:45:14 +00005477 case Type::Vector:
5478 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005479 // This matches gcc's encoding, even though technically it is
5480 // insufficient.
5481 // FIXME. We should do a better job than gcc.
5482 return;
John McCall3624e9e2012-12-20 02:45:14 +00005483
Richard Smithdc7a4f52013-04-30 13:56:41 +00005484 case Type::Auto:
5485 // We could see an undeduced auto type here during error recovery.
5486 // Just ignore it.
5487 return;
5488
John McCall3624e9e2012-12-20 02:45:14 +00005489#define ABSTRACT_TYPE(KIND, BASE)
5490#define TYPE(KIND, BASE)
5491#define DEPENDENT_TYPE(KIND, BASE) \
5492 case Type::KIND:
5493#define NON_CANONICAL_TYPE(KIND, BASE) \
5494 case Type::KIND:
5495#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5496 case Type::KIND:
5497#include "clang/AST/TypeNodes.def"
5498 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005499 }
John McCall3624e9e2012-12-20 02:45:14 +00005500 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005501}
5502
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005503void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5504 std::string &S,
5505 const FieldDecl *FD,
5506 bool includeVBases) const {
5507 assert(RDecl && "Expected non-null RecordDecl");
5508 assert(!RDecl->isUnion() && "Should not be called for unions");
5509 if (!RDecl->getDefinition())
5510 return;
5511
5512 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5513 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5514 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5515
5516 if (CXXRec) {
5517 for (CXXRecordDecl::base_class_iterator
5518 BI = CXXRec->bases_begin(),
5519 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5520 if (!BI->isVirtual()) {
5521 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005522 if (base->isEmpty())
5523 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005524 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005525 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5526 std::make_pair(offs, base));
5527 }
5528 }
5529 }
5530
5531 unsigned i = 0;
5532 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5533 FieldEnd = RDecl->field_end();
5534 Field != FieldEnd; ++Field, ++i) {
5535 uint64_t offs = layout.getFieldOffset(i);
5536 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005537 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005538 }
5539
5540 if (CXXRec && includeVBases) {
5541 for (CXXRecordDecl::base_class_iterator
5542 BI = CXXRec->vbases_begin(),
5543 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5544 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005545 if (base->isEmpty())
5546 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005547 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005548 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5549 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5550 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005551 }
5552 }
5553
5554 CharUnits size;
5555 if (CXXRec) {
5556 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5557 } else {
5558 size = layout.getSize();
5559 }
5560
5561 uint64_t CurOffs = 0;
5562 std::multimap<uint64_t, NamedDecl *>::iterator
5563 CurLayObj = FieldOrBaseOffsets.begin();
5564
Douglas Gregor58db7a52012-04-27 22:30:01 +00005565 if (CXXRec && CXXRec->isDynamicClass() &&
5566 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005567 if (FD) {
5568 S += "\"_vptr$";
5569 std::string recname = CXXRec->getNameAsString();
5570 if (recname.empty()) recname = "?";
5571 S += recname;
5572 S += '"';
5573 }
5574 S += "^^?";
5575 CurOffs += getTypeSize(VoidPtrTy);
5576 }
5577
5578 if (!RDecl->hasFlexibleArrayMember()) {
5579 // Mark the end of the structure.
5580 uint64_t offs = toBits(size);
5581 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5582 std::make_pair(offs, (NamedDecl*)0));
5583 }
5584
5585 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5586 assert(CurOffs <= CurLayObj->first);
5587
5588 if (CurOffs < CurLayObj->first) {
5589 uint64_t padding = CurLayObj->first - CurOffs;
5590 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5591 // packing/alignment of members is different that normal, in which case
5592 // the encoding will be out-of-sync with the real layout.
5593 // If the runtime switches to just consider the size of types without
5594 // taking into account alignment, we could make padding explicit in the
5595 // encoding (e.g. using arrays of chars). The encoding strings would be
5596 // longer then though.
5597 CurOffs += padding;
5598 }
5599
5600 NamedDecl *dcl = CurLayObj->second;
5601 if (dcl == 0)
5602 break; // reached end of structure.
5603
5604 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5605 // We expand the bases without their virtual bases since those are going
5606 // in the initial structure. Note that this differs from gcc which
5607 // expands virtual bases each time one is encountered in the hierarchy,
5608 // making the encoding type bigger than it really is.
5609 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005610 assert(!base->isEmpty());
5611 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005612 } else {
5613 FieldDecl *field = cast<FieldDecl>(dcl);
5614 if (FD) {
5615 S += '"';
5616 S += field->getNameAsString();
5617 S += '"';
5618 }
5619
5620 if (field->isBitField()) {
5621 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005622 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005623 } else {
5624 QualType qt = field->getType();
5625 getLegacyIntegralTypeEncoding(qt);
5626 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5627 /*OutermostType*/false,
5628 /*EncodingProperty*/false,
5629 /*StructField*/true);
5630 CurOffs += getTypeSize(field->getType());
5631 }
5632 }
5633 }
5634}
5635
Mike Stump1eb44332009-09-09 15:08:12 +00005636void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005637 std::string& S) const {
5638 if (QT & Decl::OBJC_TQ_In)
5639 S += 'n';
5640 if (QT & Decl::OBJC_TQ_Inout)
5641 S += 'N';
5642 if (QT & Decl::OBJC_TQ_Out)
5643 S += 'o';
5644 if (QT & Decl::OBJC_TQ_Bycopy)
5645 S += 'O';
5646 if (QT & Decl::OBJC_TQ_Byref)
5647 S += 'R';
5648 if (QT & Decl::OBJC_TQ_Oneway)
5649 S += 'V';
5650}
5651
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005652TypedefDecl *ASTContext::getObjCIdDecl() const {
5653 if (!ObjCIdDecl) {
5654 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5655 T = getObjCObjectPointerType(T);
5656 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5657 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5658 getTranslationUnitDecl(),
5659 SourceLocation(), SourceLocation(),
5660 &Idents.get("id"), IdInfo);
5661 }
5662
5663 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005664}
5665
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005666TypedefDecl *ASTContext::getObjCSelDecl() const {
5667 if (!ObjCSelDecl) {
5668 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5669 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5670 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5671 getTranslationUnitDecl(),
5672 SourceLocation(), SourceLocation(),
5673 &Idents.get("SEL"), SelInfo);
5674 }
5675 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005676}
5677
Douglas Gregor79d67262011-08-12 05:59:41 +00005678TypedefDecl *ASTContext::getObjCClassDecl() const {
5679 if (!ObjCClassDecl) {
5680 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5681 T = getObjCObjectPointerType(T);
5682 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5683 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5684 getTranslationUnitDecl(),
5685 SourceLocation(), SourceLocation(),
5686 &Idents.get("Class"), ClassInfo);
5687 }
5688
5689 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005690}
5691
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005692ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5693 if (!ObjCProtocolClassDecl) {
5694 ObjCProtocolClassDecl
5695 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5696 SourceLocation(),
5697 &Idents.get("Protocol"),
5698 /*PrevDecl=*/0,
5699 SourceLocation(), true);
5700 }
5701
5702 return ObjCProtocolClassDecl;
5703}
5704
Meador Ingec5613b22012-06-16 03:34:49 +00005705//===----------------------------------------------------------------------===//
5706// __builtin_va_list Construction Functions
5707//===----------------------------------------------------------------------===//
5708
5709static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5710 // typedef char* __builtin_va_list;
5711 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5712 TypeSourceInfo *TInfo
5713 = Context->getTrivialTypeSourceInfo(CharPtrType);
5714
5715 TypedefDecl *VaListTypeDecl
5716 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5717 Context->getTranslationUnitDecl(),
5718 SourceLocation(), SourceLocation(),
5719 &Context->Idents.get("__builtin_va_list"),
5720 TInfo);
5721 return VaListTypeDecl;
5722}
5723
5724static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5725 // typedef void* __builtin_va_list;
5726 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5727 TypeSourceInfo *TInfo
5728 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5729
5730 TypedefDecl *VaListTypeDecl
5731 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5732 Context->getTranslationUnitDecl(),
5733 SourceLocation(), SourceLocation(),
5734 &Context->Idents.get("__builtin_va_list"),
5735 TInfo);
5736 return VaListTypeDecl;
5737}
5738
Tim Northoverc264e162013-01-31 12:13:10 +00005739static TypedefDecl *
5740CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5741 RecordDecl *VaListTagDecl;
5742 if (Context->getLangOpts().CPlusPlus) {
5743 // namespace std { struct __va_list {
5744 NamespaceDecl *NS;
5745 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5746 Context->getTranslationUnitDecl(),
5747 /*Inline*/false, SourceLocation(),
5748 SourceLocation(), &Context->Idents.get("std"),
5749 /*PrevDecl*/0);
5750
5751 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5752 Context->getTranslationUnitDecl(),
5753 SourceLocation(), SourceLocation(),
5754 &Context->Idents.get("__va_list"));
5755 VaListTagDecl->setDeclContext(NS);
5756 } else {
5757 // struct __va_list
5758 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5759 Context->getTranslationUnitDecl(),
5760 &Context->Idents.get("__va_list"));
5761 }
5762
5763 VaListTagDecl->startDefinition();
5764
5765 const size_t NumFields = 5;
5766 QualType FieldTypes[NumFields];
5767 const char *FieldNames[NumFields];
5768
5769 // void *__stack;
5770 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5771 FieldNames[0] = "__stack";
5772
5773 // void *__gr_top;
5774 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5775 FieldNames[1] = "__gr_top";
5776
5777 // void *__vr_top;
5778 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5779 FieldNames[2] = "__vr_top";
5780
5781 // int __gr_offs;
5782 FieldTypes[3] = Context->IntTy;
5783 FieldNames[3] = "__gr_offs";
5784
5785 // int __vr_offs;
5786 FieldTypes[4] = Context->IntTy;
5787 FieldNames[4] = "__vr_offs";
5788
5789 // Create fields
5790 for (unsigned i = 0; i < NumFields; ++i) {
5791 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5792 VaListTagDecl,
5793 SourceLocation(),
5794 SourceLocation(),
5795 &Context->Idents.get(FieldNames[i]),
5796 FieldTypes[i], /*TInfo=*/0,
5797 /*BitWidth=*/0,
5798 /*Mutable=*/false,
5799 ICIS_NoInit);
5800 Field->setAccess(AS_public);
5801 VaListTagDecl->addDecl(Field);
5802 }
5803 VaListTagDecl->completeDefinition();
5804 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5805 Context->VaListTagTy = VaListTagType;
5806
5807 // } __builtin_va_list;
5808 TypedefDecl *VaListTypedefDecl
5809 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5810 Context->getTranslationUnitDecl(),
5811 SourceLocation(), SourceLocation(),
5812 &Context->Idents.get("__builtin_va_list"),
5813 Context->getTrivialTypeSourceInfo(VaListTagType));
5814
5815 return VaListTypedefDecl;
5816}
5817
Meador Ingec5613b22012-06-16 03:34:49 +00005818static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5819 // typedef struct __va_list_tag {
5820 RecordDecl *VaListTagDecl;
5821
5822 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5823 Context->getTranslationUnitDecl(),
5824 &Context->Idents.get("__va_list_tag"));
5825 VaListTagDecl->startDefinition();
5826
5827 const size_t NumFields = 5;
5828 QualType FieldTypes[NumFields];
5829 const char *FieldNames[NumFields];
5830
5831 // unsigned char gpr;
5832 FieldTypes[0] = Context->UnsignedCharTy;
5833 FieldNames[0] = "gpr";
5834
5835 // unsigned char fpr;
5836 FieldTypes[1] = Context->UnsignedCharTy;
5837 FieldNames[1] = "fpr";
5838
5839 // unsigned short reserved;
5840 FieldTypes[2] = Context->UnsignedShortTy;
5841 FieldNames[2] = "reserved";
5842
5843 // void* overflow_arg_area;
5844 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5845 FieldNames[3] = "overflow_arg_area";
5846
5847 // void* reg_save_area;
5848 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5849 FieldNames[4] = "reg_save_area";
5850
5851 // Create fields
5852 for (unsigned i = 0; i < NumFields; ++i) {
5853 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5854 SourceLocation(),
5855 SourceLocation(),
5856 &Context->Idents.get(FieldNames[i]),
5857 FieldTypes[i], /*TInfo=*/0,
5858 /*BitWidth=*/0,
5859 /*Mutable=*/false,
5860 ICIS_NoInit);
5861 Field->setAccess(AS_public);
5862 VaListTagDecl->addDecl(Field);
5863 }
5864 VaListTagDecl->completeDefinition();
5865 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005866 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005867
5868 // } __va_list_tag;
5869 TypedefDecl *VaListTagTypedefDecl
5870 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5871 Context->getTranslationUnitDecl(),
5872 SourceLocation(), SourceLocation(),
5873 &Context->Idents.get("__va_list_tag"),
5874 Context->getTrivialTypeSourceInfo(VaListTagType));
5875 QualType VaListTagTypedefType =
5876 Context->getTypedefType(VaListTagTypedefDecl);
5877
5878 // typedef __va_list_tag __builtin_va_list[1];
5879 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5880 QualType VaListTagArrayType
5881 = Context->getConstantArrayType(VaListTagTypedefType,
5882 Size, ArrayType::Normal, 0);
5883 TypeSourceInfo *TInfo
5884 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5885 TypedefDecl *VaListTypedefDecl
5886 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5887 Context->getTranslationUnitDecl(),
5888 SourceLocation(), SourceLocation(),
5889 &Context->Idents.get("__builtin_va_list"),
5890 TInfo);
5891
5892 return VaListTypedefDecl;
5893}
5894
5895static TypedefDecl *
5896CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5897 // typedef struct __va_list_tag {
5898 RecordDecl *VaListTagDecl;
5899 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5900 Context->getTranslationUnitDecl(),
5901 &Context->Idents.get("__va_list_tag"));
5902 VaListTagDecl->startDefinition();
5903
5904 const size_t NumFields = 4;
5905 QualType FieldTypes[NumFields];
5906 const char *FieldNames[NumFields];
5907
5908 // unsigned gp_offset;
5909 FieldTypes[0] = Context->UnsignedIntTy;
5910 FieldNames[0] = "gp_offset";
5911
5912 // unsigned fp_offset;
5913 FieldTypes[1] = Context->UnsignedIntTy;
5914 FieldNames[1] = "fp_offset";
5915
5916 // void* overflow_arg_area;
5917 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5918 FieldNames[2] = "overflow_arg_area";
5919
5920 // void* reg_save_area;
5921 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5922 FieldNames[3] = "reg_save_area";
5923
5924 // Create fields
5925 for (unsigned i = 0; i < NumFields; ++i) {
5926 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5927 VaListTagDecl,
5928 SourceLocation(),
5929 SourceLocation(),
5930 &Context->Idents.get(FieldNames[i]),
5931 FieldTypes[i], /*TInfo=*/0,
5932 /*BitWidth=*/0,
5933 /*Mutable=*/false,
5934 ICIS_NoInit);
5935 Field->setAccess(AS_public);
5936 VaListTagDecl->addDecl(Field);
5937 }
5938 VaListTagDecl->completeDefinition();
5939 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005940 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005941
5942 // } __va_list_tag;
5943 TypedefDecl *VaListTagTypedefDecl
5944 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5945 Context->getTranslationUnitDecl(),
5946 SourceLocation(), SourceLocation(),
5947 &Context->Idents.get("__va_list_tag"),
5948 Context->getTrivialTypeSourceInfo(VaListTagType));
5949 QualType VaListTagTypedefType =
5950 Context->getTypedefType(VaListTagTypedefDecl);
5951
5952 // typedef __va_list_tag __builtin_va_list[1];
5953 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5954 QualType VaListTagArrayType
5955 = Context->getConstantArrayType(VaListTagTypedefType,
5956 Size, ArrayType::Normal,0);
5957 TypeSourceInfo *TInfo
5958 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5959 TypedefDecl *VaListTypedefDecl
5960 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5961 Context->getTranslationUnitDecl(),
5962 SourceLocation(), SourceLocation(),
5963 &Context->Idents.get("__builtin_va_list"),
5964 TInfo);
5965
5966 return VaListTypedefDecl;
5967}
5968
5969static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5970 // typedef int __builtin_va_list[4];
5971 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5972 QualType IntArrayType
5973 = Context->getConstantArrayType(Context->IntTy,
5974 Size, ArrayType::Normal, 0);
5975 TypedefDecl *VaListTypedefDecl
5976 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5977 Context->getTranslationUnitDecl(),
5978 SourceLocation(), SourceLocation(),
5979 &Context->Idents.get("__builtin_va_list"),
5980 Context->getTrivialTypeSourceInfo(IntArrayType));
5981
5982 return VaListTypedefDecl;
5983}
5984
Logan Chieneae5a8202012-10-10 06:56:20 +00005985static TypedefDecl *
5986CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5987 RecordDecl *VaListDecl;
5988 if (Context->getLangOpts().CPlusPlus) {
5989 // namespace std { struct __va_list {
5990 NamespaceDecl *NS;
5991 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5992 Context->getTranslationUnitDecl(),
5993 /*Inline*/false, SourceLocation(),
5994 SourceLocation(), &Context->Idents.get("std"),
5995 /*PrevDecl*/0);
5996
5997 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5998 Context->getTranslationUnitDecl(),
5999 SourceLocation(), SourceLocation(),
6000 &Context->Idents.get("__va_list"));
6001
6002 VaListDecl->setDeclContext(NS);
6003
6004 } else {
6005 // struct __va_list {
6006 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6007 Context->getTranslationUnitDecl(),
6008 &Context->Idents.get("__va_list"));
6009 }
6010
6011 VaListDecl->startDefinition();
6012
6013 // void * __ap;
6014 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6015 VaListDecl,
6016 SourceLocation(),
6017 SourceLocation(),
6018 &Context->Idents.get("__ap"),
6019 Context->getPointerType(Context->VoidTy),
6020 /*TInfo=*/0,
6021 /*BitWidth=*/0,
6022 /*Mutable=*/false,
6023 ICIS_NoInit);
6024 Field->setAccess(AS_public);
6025 VaListDecl->addDecl(Field);
6026
6027 // };
6028 VaListDecl->completeDefinition();
6029
6030 // typedef struct __va_list __builtin_va_list;
6031 TypeSourceInfo *TInfo
6032 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6033
6034 TypedefDecl *VaListTypeDecl
6035 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6036 Context->getTranslationUnitDecl(),
6037 SourceLocation(), SourceLocation(),
6038 &Context->Idents.get("__builtin_va_list"),
6039 TInfo);
6040
6041 return VaListTypeDecl;
6042}
6043
Ulrich Weigandb8409212013-05-06 16:26:41 +00006044static TypedefDecl *
6045CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6046 // typedef struct __va_list_tag {
6047 RecordDecl *VaListTagDecl;
6048 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6049 Context->getTranslationUnitDecl(),
6050 &Context->Idents.get("__va_list_tag"));
6051 VaListTagDecl->startDefinition();
6052
6053 const size_t NumFields = 4;
6054 QualType FieldTypes[NumFields];
6055 const char *FieldNames[NumFields];
6056
6057 // long __gpr;
6058 FieldTypes[0] = Context->LongTy;
6059 FieldNames[0] = "__gpr";
6060
6061 // long __fpr;
6062 FieldTypes[1] = Context->LongTy;
6063 FieldNames[1] = "__fpr";
6064
6065 // void *__overflow_arg_area;
6066 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6067 FieldNames[2] = "__overflow_arg_area";
6068
6069 // void *__reg_save_area;
6070 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6071 FieldNames[3] = "__reg_save_area";
6072
6073 // Create fields
6074 for (unsigned i = 0; i < NumFields; ++i) {
6075 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6076 VaListTagDecl,
6077 SourceLocation(),
6078 SourceLocation(),
6079 &Context->Idents.get(FieldNames[i]),
6080 FieldTypes[i], /*TInfo=*/0,
6081 /*BitWidth=*/0,
6082 /*Mutable=*/false,
6083 ICIS_NoInit);
6084 Field->setAccess(AS_public);
6085 VaListTagDecl->addDecl(Field);
6086 }
6087 VaListTagDecl->completeDefinition();
6088 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6089 Context->VaListTagTy = VaListTagType;
6090
6091 // } __va_list_tag;
6092 TypedefDecl *VaListTagTypedefDecl
6093 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6094 Context->getTranslationUnitDecl(),
6095 SourceLocation(), SourceLocation(),
6096 &Context->Idents.get("__va_list_tag"),
6097 Context->getTrivialTypeSourceInfo(VaListTagType));
6098 QualType VaListTagTypedefType =
6099 Context->getTypedefType(VaListTagTypedefDecl);
6100
6101 // typedef __va_list_tag __builtin_va_list[1];
6102 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6103 QualType VaListTagArrayType
6104 = Context->getConstantArrayType(VaListTagTypedefType,
6105 Size, ArrayType::Normal,0);
6106 TypeSourceInfo *TInfo
6107 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6108 TypedefDecl *VaListTypedefDecl
6109 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6110 Context->getTranslationUnitDecl(),
6111 SourceLocation(), SourceLocation(),
6112 &Context->Idents.get("__builtin_va_list"),
6113 TInfo);
6114
6115 return VaListTypedefDecl;
6116}
6117
Meador Ingec5613b22012-06-16 03:34:49 +00006118static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6119 TargetInfo::BuiltinVaListKind Kind) {
6120 switch (Kind) {
6121 case TargetInfo::CharPtrBuiltinVaList:
6122 return CreateCharPtrBuiltinVaListDecl(Context);
6123 case TargetInfo::VoidPtrBuiltinVaList:
6124 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006125 case TargetInfo::AArch64ABIBuiltinVaList:
6126 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006127 case TargetInfo::PowerABIBuiltinVaList:
6128 return CreatePowerABIBuiltinVaListDecl(Context);
6129 case TargetInfo::X86_64ABIBuiltinVaList:
6130 return CreateX86_64ABIBuiltinVaListDecl(Context);
6131 case TargetInfo::PNaClABIBuiltinVaList:
6132 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006133 case TargetInfo::AAPCSABIBuiltinVaList:
6134 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006135 case TargetInfo::SystemZBuiltinVaList:
6136 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006137 }
6138
6139 llvm_unreachable("Unhandled __builtin_va_list type kind");
6140}
6141
6142TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6143 if (!BuiltinVaListDecl)
6144 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6145
6146 return BuiltinVaListDecl;
6147}
6148
Meador Ingefb40e3f2012-07-01 15:57:25 +00006149QualType ASTContext::getVaListTagType() const {
6150 // Force the creation of VaListTagTy by building the __builtin_va_list
6151 // declaration.
6152 if (VaListTagTy.isNull())
6153 (void) getBuiltinVaListDecl();
6154
6155 return VaListTagTy;
6156}
6157
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006158void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006159 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006160 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006161
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006162 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006163}
6164
John McCall0bd6feb2009-12-02 08:04:21 +00006165/// \brief Retrieve the template name that corresponds to a non-empty
6166/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006167TemplateName
6168ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6169 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006170 unsigned size = End - Begin;
6171 assert(size > 1 && "set is not overloaded!");
6172
6173 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6174 size * sizeof(FunctionTemplateDecl*));
6175 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6176
6177 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006178 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006179 NamedDecl *D = *I;
6180 assert(isa<FunctionTemplateDecl>(D) ||
6181 (isa<UsingShadowDecl>(D) &&
6182 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6183 *Storage++ = D;
6184 }
6185
6186 return TemplateName(OT);
6187}
6188
Douglas Gregor7532dc62009-03-30 22:58:21 +00006189/// \brief Retrieve the template name that represents a qualified
6190/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006191TemplateName
6192ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6193 bool TemplateKeyword,
6194 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006195 assert(NNS && "Missing nested-name-specifier in qualified template name");
6196
Douglas Gregor789b1f62010-02-04 18:10:26 +00006197 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006198 llvm::FoldingSetNodeID ID;
6199 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6200
6201 void *InsertPos = 0;
6202 QualifiedTemplateName *QTN =
6203 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6204 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006205 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6206 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006207 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6208 }
6209
6210 return TemplateName(QTN);
6211}
6212
6213/// \brief Retrieve the template name that represents a dependent
6214/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006215TemplateName
6216ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6217 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006218 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006219 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006220
6221 llvm::FoldingSetNodeID ID;
6222 DependentTemplateName::Profile(ID, NNS, Name);
6223
6224 void *InsertPos = 0;
6225 DependentTemplateName *QTN =
6226 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6227
6228 if (QTN)
6229 return TemplateName(QTN);
6230
6231 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6232 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006233 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6234 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006235 } else {
6236 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006237 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6238 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006239 DependentTemplateName *CheckQTN =
6240 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6241 assert(!CheckQTN && "Dependent type name canonicalization broken");
6242 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006243 }
6244
6245 DependentTemplateNames.InsertNode(QTN, InsertPos);
6246 return TemplateName(QTN);
6247}
6248
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006249/// \brief Retrieve the template name that represents a dependent
6250/// template name such as \c MetaFun::template operator+.
6251TemplateName
6252ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006253 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006254 assert((!NNS || NNS->isDependent()) &&
6255 "Nested name specifier must be dependent");
6256
6257 llvm::FoldingSetNodeID ID;
6258 DependentTemplateName::Profile(ID, NNS, Operator);
6259
6260 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006261 DependentTemplateName *QTN
6262 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006263
6264 if (QTN)
6265 return TemplateName(QTN);
6266
6267 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6268 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006269 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6270 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006271 } else {
6272 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006273 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6274 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006275
6276 DependentTemplateName *CheckQTN
6277 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6278 assert(!CheckQTN && "Dependent template name canonicalization broken");
6279 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006280 }
6281
6282 DependentTemplateNames.InsertNode(QTN, InsertPos);
6283 return TemplateName(QTN);
6284}
6285
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006286TemplateName
John McCall14606042011-06-30 08:33:18 +00006287ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6288 TemplateName replacement) const {
6289 llvm::FoldingSetNodeID ID;
6290 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6291
6292 void *insertPos = 0;
6293 SubstTemplateTemplateParmStorage *subst
6294 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6295
6296 if (!subst) {
6297 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6298 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6299 }
6300
6301 return TemplateName(subst);
6302}
6303
6304TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006305ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6306 const TemplateArgument &ArgPack) const {
6307 ASTContext &Self = const_cast<ASTContext &>(*this);
6308 llvm::FoldingSetNodeID ID;
6309 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6310
6311 void *InsertPos = 0;
6312 SubstTemplateTemplateParmPackStorage *Subst
6313 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6314
6315 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006316 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006317 ArgPack.pack_size(),
6318 ArgPack.pack_begin());
6319 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6320 }
6321
6322 return TemplateName(Subst);
6323}
6324
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006325/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006326/// TargetInfo, produce the corresponding type. The unsigned @p Type
6327/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006328CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006329 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006330 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006331 case TargetInfo::SignedShort: return ShortTy;
6332 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6333 case TargetInfo::SignedInt: return IntTy;
6334 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6335 case TargetInfo::SignedLong: return LongTy;
6336 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6337 case TargetInfo::SignedLongLong: return LongLongTy;
6338 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6339 }
6340
David Blaikieb219cfc2011-09-23 05:06:16 +00006341 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006342}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006343
6344//===----------------------------------------------------------------------===//
6345// Type Predicates.
6346//===----------------------------------------------------------------------===//
6347
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006348/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6349/// garbage collection attribute.
6350///
John McCallae278a32011-01-12 00:34:59 +00006351Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006352 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006353 return Qualifiers::GCNone;
6354
David Blaikie4e4d0842012-03-11 07:00:24 +00006355 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006356 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6357
6358 // Default behaviour under objective-C's gc is for ObjC pointers
6359 // (or pointers to them) be treated as though they were declared
6360 // as __strong.
6361 if (GCAttrs == Qualifiers::GCNone) {
6362 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6363 return Qualifiers::Strong;
6364 else if (Ty->isPointerType())
6365 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6366 } else {
6367 // It's not valid to set GC attributes on anything that isn't a
6368 // pointer.
6369#ifndef NDEBUG
6370 QualType CT = Ty->getCanonicalTypeInternal();
6371 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6372 CT = AT->getElementType();
6373 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6374#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006375 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006376 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006377}
6378
Chris Lattner6ac46a42008-04-07 06:51:04 +00006379//===----------------------------------------------------------------------===//
6380// Type Compatibility Testing
6381//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006382
Mike Stump1eb44332009-09-09 15:08:12 +00006383/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006384/// compatible.
6385static bool areCompatVectorTypes(const VectorType *LHS,
6386 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006387 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006388 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006389 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006390}
6391
Douglas Gregor255210e2010-08-06 10:14:59 +00006392bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6393 QualType SecondVec) {
6394 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6395 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6396
6397 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6398 return true;
6399
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006400 // Treat Neon vector types and most AltiVec vector types as if they are the
6401 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006402 const VectorType *First = FirstVec->getAs<VectorType>();
6403 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006404 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006405 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006406 First->getVectorKind() != VectorType::AltiVecPixel &&
6407 First->getVectorKind() != VectorType::AltiVecBool &&
6408 Second->getVectorKind() != VectorType::AltiVecPixel &&
6409 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006410 return true;
6411
6412 return false;
6413}
6414
Steve Naroff4084c302009-07-23 01:01:38 +00006415//===----------------------------------------------------------------------===//
6416// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6417//===----------------------------------------------------------------------===//
6418
6419/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6420/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006421bool
6422ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6423 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006424 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006425 return true;
6426 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6427 E = rProto->protocol_end(); PI != E; ++PI)
6428 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6429 return true;
6430 return false;
6431}
6432
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006433/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6434/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006435bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6436 QualType rhs) {
6437 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6438 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6439 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6440
6441 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6442 E = lhsQID->qual_end(); I != E; ++I) {
6443 bool match = false;
6444 ObjCProtocolDecl *lhsProto = *I;
6445 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6446 E = rhsOPT->qual_end(); J != E; ++J) {
6447 ObjCProtocolDecl *rhsProto = *J;
6448 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6449 match = true;
6450 break;
6451 }
6452 }
6453 if (!match)
6454 return false;
6455 }
6456 return true;
6457}
6458
Steve Naroff4084c302009-07-23 01:01:38 +00006459/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6460/// ObjCQualifiedIDType.
6461bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6462 bool compare) {
6463 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006464 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006465 lhs->isObjCIdType() || lhs->isObjCClassType())
6466 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006467 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006468 rhs->isObjCIdType() || rhs->isObjCClassType())
6469 return true;
6470
6471 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006472 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006473
Steve Naroff4084c302009-07-23 01:01:38 +00006474 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006475
Steve Naroff4084c302009-07-23 01:01:38 +00006476 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006477 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006478 // make sure we check the class hierarchy.
6479 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6480 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6481 E = lhsQID->qual_end(); I != E; ++I) {
6482 // when comparing an id<P> on lhs with a static type on rhs,
6483 // see if static class implements all of id's protocols, directly or
6484 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006485 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006486 return false;
6487 }
6488 }
6489 // If there are no qualifiers and no interface, we have an 'id'.
6490 return true;
6491 }
Mike Stump1eb44332009-09-09 15:08:12 +00006492 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006493 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6494 E = lhsQID->qual_end(); I != E; ++I) {
6495 ObjCProtocolDecl *lhsProto = *I;
6496 bool match = false;
6497
6498 // when comparing an id<P> on lhs with a static type on rhs,
6499 // see if static class implements all of id's protocols, directly or
6500 // through its super class and categories.
6501 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6502 E = rhsOPT->qual_end(); J != E; ++J) {
6503 ObjCProtocolDecl *rhsProto = *J;
6504 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6505 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6506 match = true;
6507 break;
6508 }
6509 }
Mike Stump1eb44332009-09-09 15:08:12 +00006510 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006511 // make sure we check the class hierarchy.
6512 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6513 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6514 E = lhsQID->qual_end(); I != E; ++I) {
6515 // when comparing an id<P> on lhs with a static type on rhs,
6516 // see if static class implements all of id's protocols, directly or
6517 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006518 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006519 match = true;
6520 break;
6521 }
6522 }
6523 }
6524 if (!match)
6525 return false;
6526 }
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Steve Naroff4084c302009-07-23 01:01:38 +00006528 return true;
6529 }
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Steve Naroff4084c302009-07-23 01:01:38 +00006531 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6532 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6533
Mike Stump1eb44332009-09-09 15:08:12 +00006534 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006535 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006536 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006537 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6538 E = lhsOPT->qual_end(); I != E; ++I) {
6539 ObjCProtocolDecl *lhsProto = *I;
6540 bool match = false;
6541
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006542 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006543 // see if static class implements all of id's protocols, directly or
6544 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006545 // First, lhs protocols in the qualifier list must be found, direct
6546 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006547 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6548 E = rhsQID->qual_end(); J != E; ++J) {
6549 ObjCProtocolDecl *rhsProto = *J;
6550 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6551 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6552 match = true;
6553 break;
6554 }
6555 }
6556 if (!match)
6557 return false;
6558 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006559
6560 // Static class's protocols, or its super class or category protocols
6561 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6562 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6563 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6564 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6565 // This is rather dubious but matches gcc's behavior. If lhs has
6566 // no type qualifier and its class has no static protocol(s)
6567 // assume that it is mismatch.
6568 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6569 return false;
6570 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6571 LHSInheritedProtocols.begin(),
6572 E = LHSInheritedProtocols.end(); I != E; ++I) {
6573 bool match = false;
6574 ObjCProtocolDecl *lhsProto = (*I);
6575 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6576 E = rhsQID->qual_end(); J != E; ++J) {
6577 ObjCProtocolDecl *rhsProto = *J;
6578 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6579 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6580 match = true;
6581 break;
6582 }
6583 }
6584 if (!match)
6585 return false;
6586 }
6587 }
Steve Naroff4084c302009-07-23 01:01:38 +00006588 return true;
6589 }
6590 return false;
6591}
6592
Eli Friedman3d815e72008-08-22 00:56:42 +00006593/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006594/// compatible for assignment from RHS to LHS. This handles validation of any
6595/// protocol qualifiers on the LHS or RHS.
6596///
Steve Naroff14108da2009-07-10 23:34:53 +00006597bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6598 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006599 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6600 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6601
Steve Naroffde2e22d2009-07-15 18:40:39 +00006602 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006603 if (LHS->isObjCUnqualifiedIdOrClass() ||
6604 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006605 return true;
6606
John McCallc12c5bb2010-05-15 11:32:37 +00006607 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006608 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6609 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006610 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006611
6612 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6613 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6614 QualType(RHSOPT,0));
6615
John McCallc12c5bb2010-05-15 11:32:37 +00006616 // If we have 2 user-defined types, fall into that path.
6617 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006618 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006619
Steve Naroff4084c302009-07-23 01:01:38 +00006620 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006621}
6622
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006623/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006624/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006625/// arguments in block literals. When passed as arguments, passing 'A*' where
6626/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6627/// not OK. For the return type, the opposite is not OK.
6628bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6629 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006630 const ObjCObjectPointerType *RHSOPT,
6631 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006632 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006633 return true;
6634
6635 if (LHSOPT->isObjCBuiltinType()) {
6636 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6637 }
6638
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006639 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006640 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6641 QualType(RHSOPT,0),
6642 false);
6643
6644 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6645 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6646 if (LHS && RHS) { // We have 2 user-defined types.
6647 if (LHS != RHS) {
6648 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006649 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006650 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006651 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006652 }
6653 else
6654 return true;
6655 }
6656 return false;
6657}
6658
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006659/// getIntersectionOfProtocols - This routine finds the intersection of set
6660/// of protocols inherited from two distinct objective-c pointer objects.
6661/// It is used to build composite qualifier list of the composite type of
6662/// the conditional expression involving two objective-c pointer objects.
6663static
6664void getIntersectionOfProtocols(ASTContext &Context,
6665 const ObjCObjectPointerType *LHSOPT,
6666 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006667 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006668
John McCallc12c5bb2010-05-15 11:32:37 +00006669 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6670 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6671 assert(LHS->getInterface() && "LHS must have an interface base");
6672 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006673
6674 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6675 unsigned LHSNumProtocols = LHS->getNumProtocols();
6676 if (LHSNumProtocols > 0)
6677 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6678 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006679 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006680 Context.CollectInheritedProtocols(LHS->getInterface(),
6681 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006682 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6683 LHSInheritedProtocols.end());
6684 }
6685
6686 unsigned RHSNumProtocols = RHS->getNumProtocols();
6687 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006688 ObjCProtocolDecl **RHSProtocols =
6689 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006690 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6691 if (InheritedProtocolSet.count(RHSProtocols[i]))
6692 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006693 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006694 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006695 Context.CollectInheritedProtocols(RHS->getInterface(),
6696 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006697 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6698 RHSInheritedProtocols.begin(),
6699 E = RHSInheritedProtocols.end(); I != E; ++I)
6700 if (InheritedProtocolSet.count((*I)))
6701 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006702 }
6703}
6704
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006705/// areCommonBaseCompatible - Returns common base class of the two classes if
6706/// one found. Note that this is O'2 algorithm. But it will be called as the
6707/// last type comparison in a ?-exp of ObjC pointer types before a
6708/// warning is issued. So, its invokation is extremely rare.
6709QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006710 const ObjCObjectPointerType *Lptr,
6711 const ObjCObjectPointerType *Rptr) {
6712 const ObjCObjectType *LHS = Lptr->getObjectType();
6713 const ObjCObjectType *RHS = Rptr->getObjectType();
6714 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6715 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006716 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006717 return QualType();
6718
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006719 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006720 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006721 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006722 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006723 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6724
6725 QualType Result = QualType(LHS, 0);
6726 if (!Protocols.empty())
6727 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6728 Result = getObjCObjectPointerType(Result);
6729 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006730 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006731 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006732
6733 return QualType();
6734}
6735
John McCallc12c5bb2010-05-15 11:32:37 +00006736bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6737 const ObjCObjectType *RHS) {
6738 assert(LHS->getInterface() && "LHS is not an interface type");
6739 assert(RHS->getInterface() && "RHS is not an interface type");
6740
Chris Lattner6ac46a42008-04-07 06:51:04 +00006741 // Verify that the base decls are compatible: the RHS must be a subclass of
6742 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006743 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006744 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006745
Chris Lattner6ac46a42008-04-07 06:51:04 +00006746 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6747 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006748 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006749 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006750
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006751 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6752 // more detailed analysis is required.
6753 if (RHS->getNumProtocols() == 0) {
6754 // OK, if LHS is a superclass of RHS *and*
6755 // this superclass is assignment compatible with LHS.
6756 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006757 bool IsSuperClass =
6758 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6759 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006760 // OK if conversion of LHS to SuperClass results in narrowing of types
6761 // ; i.e., SuperClass may implement at least one of the protocols
6762 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6763 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6764 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006765 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006766 // If super class has no protocols, it is not a match.
6767 if (SuperClassInheritedProtocols.empty())
6768 return false;
6769
6770 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6771 LHSPE = LHS->qual_end();
6772 LHSPI != LHSPE; LHSPI++) {
6773 bool SuperImplementsProtocol = false;
6774 ObjCProtocolDecl *LHSProto = (*LHSPI);
6775
6776 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6777 SuperClassInheritedProtocols.begin(),
6778 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6779 ObjCProtocolDecl *SuperClassProto = (*I);
6780 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6781 SuperImplementsProtocol = true;
6782 break;
6783 }
6784 }
6785 if (!SuperImplementsProtocol)
6786 return false;
6787 }
6788 return true;
6789 }
6790 return false;
6791 }
Mike Stump1eb44332009-09-09 15:08:12 +00006792
John McCallc12c5bb2010-05-15 11:32:37 +00006793 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6794 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006795 LHSPI != LHSPE; LHSPI++) {
6796 bool RHSImplementsProtocol = false;
6797
6798 // If the RHS doesn't implement the protocol on the left, the types
6799 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006800 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6801 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006802 RHSPI != RHSPE; RHSPI++) {
6803 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006804 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006805 break;
6806 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006807 }
6808 // FIXME: For better diagnostics, consider passing back the protocol name.
6809 if (!RHSImplementsProtocol)
6810 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006811 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006812 // The RHS implements all protocols listed on the LHS.
6813 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006814}
6815
Steve Naroff389bf462009-02-12 17:52:19 +00006816bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6817 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006818 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6819 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006820
Steve Naroff14108da2009-07-10 23:34:53 +00006821 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006822 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006823
6824 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6825 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006826}
6827
Douglas Gregor569c3162010-08-07 11:51:51 +00006828bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6829 return canAssignObjCInterfaces(
6830 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6831 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6832}
6833
Mike Stump1eb44332009-09-09 15:08:12 +00006834/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006835/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006836/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006837/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006838bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6839 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006840 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006841 return hasSameType(LHS, RHS);
6842
Douglas Gregor447234d2010-07-29 15:18:02 +00006843 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006844}
6845
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006846bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006847 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006848}
6849
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006850bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6851 return !mergeTypes(LHS, RHS, true).isNull();
6852}
6853
Peter Collingbourne48466752010-10-24 18:30:18 +00006854/// mergeTransparentUnionType - if T is a transparent union type and a member
6855/// of T is compatible with SubType, return the merged type, else return
6856/// QualType()
6857QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6858 bool OfBlockPointer,
6859 bool Unqualified) {
6860 if (const RecordType *UT = T->getAsUnionType()) {
6861 RecordDecl *UD = UT->getDecl();
6862 if (UD->hasAttr<TransparentUnionAttr>()) {
6863 for (RecordDecl::field_iterator it = UD->field_begin(),
6864 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006865 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006866 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6867 if (!MT.isNull())
6868 return MT;
6869 }
6870 }
6871 }
6872
6873 return QualType();
6874}
6875
6876/// mergeFunctionArgumentTypes - merge two types which appear as function
6877/// argument types
6878QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6879 bool OfBlockPointer,
6880 bool Unqualified) {
6881 // GNU extension: two types are compatible if they appear as a function
6882 // argument, one of the types is a transparent union type and the other
6883 // type is compatible with a union member
6884 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6885 Unqualified);
6886 if (!lmerge.isNull())
6887 return lmerge;
6888
6889 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6890 Unqualified);
6891 if (!rmerge.isNull())
6892 return rmerge;
6893
6894 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6895}
6896
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006897QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006898 bool OfBlockPointer,
6899 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006900 const FunctionType *lbase = lhs->getAs<FunctionType>();
6901 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006902 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6903 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006904 bool allLTypes = true;
6905 bool allRTypes = true;
6906
6907 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006908 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006909 if (OfBlockPointer) {
6910 QualType RHS = rbase->getResultType();
6911 QualType LHS = lbase->getResultType();
6912 bool UnqualifiedResult = Unqualified;
6913 if (!UnqualifiedResult)
6914 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006915 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006916 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006917 else
John McCall8cc246c2010-12-15 01:06:38 +00006918 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6919 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006920 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006921
6922 if (Unqualified)
6923 retType = retType.getUnqualifiedType();
6924
6925 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6926 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6927 if (Unqualified) {
6928 LRetType = LRetType.getUnqualifiedType();
6929 RRetType = RRetType.getUnqualifiedType();
6930 }
6931
6932 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006933 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006934 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006935 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006936
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006937 // FIXME: double check this
6938 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6939 // rbase->getRegParmAttr() != 0 &&
6940 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006941 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6942 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006943
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006944 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006945 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006946 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006947
John McCall8cc246c2010-12-15 01:06:38 +00006948 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006949 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6950 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006951 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6952 return QualType();
6953
John McCallf85e1932011-06-15 23:02:42 +00006954 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6955 return QualType();
6956
John McCall8cc246c2010-12-15 01:06:38 +00006957 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6958 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006959
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006960 if (lbaseInfo.getNoReturn() != NoReturn)
6961 allLTypes = false;
6962 if (rbaseInfo.getNoReturn() != NoReturn)
6963 allRTypes = false;
6964
John McCallf85e1932011-06-15 23:02:42 +00006965 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006966
Eli Friedman3d815e72008-08-22 00:56:42 +00006967 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006968 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6969 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006970 unsigned lproto_nargs = lproto->getNumArgs();
6971 unsigned rproto_nargs = rproto->getNumArgs();
6972
6973 // Compatible functions must have the same number of arguments
6974 if (lproto_nargs != rproto_nargs)
6975 return QualType();
6976
6977 // Variadic and non-variadic functions aren't compatible
6978 if (lproto->isVariadic() != rproto->isVariadic())
6979 return QualType();
6980
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006981 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6982 return QualType();
6983
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006984 if (LangOpts.ObjCAutoRefCount &&
6985 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6986 return QualType();
6987
Eli Friedman3d815e72008-08-22 00:56:42 +00006988 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006989 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006990 for (unsigned i = 0; i < lproto_nargs; i++) {
6991 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6992 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006993 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6994 OfBlockPointer,
6995 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006996 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006997
6998 if (Unqualified)
6999 argtype = argtype.getUnqualifiedType();
7000
Eli Friedman3d815e72008-08-22 00:56:42 +00007001 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007002 if (Unqualified) {
7003 largtype = largtype.getUnqualifiedType();
7004 rargtype = rargtype.getUnqualifiedType();
7005 }
7006
Chris Lattner61710852008-10-05 17:34:18 +00007007 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7008 allLTypes = false;
7009 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7010 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007011 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007012
Eli Friedman3d815e72008-08-22 00:56:42 +00007013 if (allLTypes) return lhs;
7014 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007015
7016 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7017 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007018 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007019 }
7020
7021 if (lproto) allRTypes = false;
7022 if (rproto) allLTypes = false;
7023
Douglas Gregor72564e72009-02-26 23:50:07 +00007024 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007025 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007026 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007027 if (proto->isVariadic()) return QualType();
7028 // Check that the types are compatible with the types that
7029 // would result from default argument promotions (C99 6.7.5.3p15).
7030 // The only types actually affected are promotable integer
7031 // types and floats, which would be passed as a different
7032 // type depending on whether the prototype is visible.
7033 unsigned proto_nargs = proto->getNumArgs();
7034 for (unsigned i = 0; i < proto_nargs; ++i) {
7035 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007036
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007037 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007038 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007039 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7040 argTy = Enum->getDecl()->getIntegerType();
7041 if (argTy.isNull())
7042 return QualType();
7043 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007044
Eli Friedman3d815e72008-08-22 00:56:42 +00007045 if (argTy->isPromotableIntegerType() ||
7046 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7047 return QualType();
7048 }
7049
7050 if (allLTypes) return lhs;
7051 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007052
7053 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7054 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007055 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007056 }
7057
7058 if (allLTypes) return lhs;
7059 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007060 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007061}
7062
John McCallb9da7132013-03-21 00:10:07 +00007063/// Given that we have an enum type and a non-enum type, try to merge them.
7064static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7065 QualType other, bool isBlockReturnType) {
7066 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7067 // a signed integer type, or an unsigned integer type.
7068 // Compatibility is based on the underlying type, not the promotion
7069 // type.
7070 QualType underlyingType = ET->getDecl()->getIntegerType();
7071 if (underlyingType.isNull()) return QualType();
7072 if (Context.hasSameType(underlyingType, other))
7073 return other;
7074
7075 // In block return types, we're more permissive and accept any
7076 // integral type of the same size.
7077 if (isBlockReturnType && other->isIntegerType() &&
7078 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7079 return other;
7080
7081 return QualType();
7082}
7083
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007084QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007085 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007086 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007087 // C++ [expr]: If an expression initially has the type "reference to T", the
7088 // type is adjusted to "T" prior to any further analysis, the expression
7089 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007090 // expression is an lvalue unless the reference is an rvalue reference and
7091 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007092 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7093 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007094
7095 if (Unqualified) {
7096 LHS = LHS.getUnqualifiedType();
7097 RHS = RHS.getUnqualifiedType();
7098 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007099
Eli Friedman3d815e72008-08-22 00:56:42 +00007100 QualType LHSCan = getCanonicalType(LHS),
7101 RHSCan = getCanonicalType(RHS);
7102
7103 // If two types are identical, they are compatible.
7104 if (LHSCan == RHSCan)
7105 return LHS;
7106
John McCall0953e762009-09-24 19:53:00 +00007107 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007108 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7109 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007110 if (LQuals != RQuals) {
7111 // If any of these qualifiers are different, we have a type
7112 // mismatch.
7113 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007114 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7115 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007116 return QualType();
7117
7118 // Exactly one GC qualifier difference is allowed: __strong is
7119 // okay if the other type has no GC qualifier but is an Objective
7120 // C object pointer (i.e. implicitly strong by default). We fix
7121 // this by pretending that the unqualified type was actually
7122 // qualified __strong.
7123 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7124 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7125 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7126
7127 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7128 return QualType();
7129
7130 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7131 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7132 }
7133 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7134 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7135 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007136 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007137 }
7138
7139 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007140
Eli Friedman852d63b2009-06-01 01:22:52 +00007141 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7142 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007143
Chris Lattner1adb8832008-01-14 05:45:46 +00007144 // We want to consider the two function types to be the same for these
7145 // comparisons, just force one to the other.
7146 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7147 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007148
7149 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007150 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7151 LHSClass = Type::ConstantArray;
7152 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7153 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007154
John McCallc12c5bb2010-05-15 11:32:37 +00007155 // ObjCInterfaces are just specialized ObjCObjects.
7156 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7157 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7158
Nate Begeman213541a2008-04-18 23:10:10 +00007159 // Canonicalize ExtVector -> Vector.
7160 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7161 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007162
Chris Lattnera36a61f2008-04-07 05:43:21 +00007163 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007164 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007165 // Note that we only have special rules for turning block enum
7166 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007167 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007168 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007169 }
John McCall183700f2009-09-21 23:43:11 +00007170 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007171 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007172 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007173 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007174 if (OfBlockPointer && !BlockReturnType) {
7175 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7176 return LHS;
7177 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7178 return RHS;
7179 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007180
Eli Friedman3d815e72008-08-22 00:56:42 +00007181 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007182 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007183
Steve Naroff4a746782008-01-09 22:43:08 +00007184 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007185 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007186#define TYPE(Class, Base)
7187#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007188#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007189#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7190#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7191#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007192 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007193
Richard Smithdc7a4f52013-04-30 13:56:41 +00007194 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007195 case Type::LValueReference:
7196 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007197 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007198 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007199
John McCallc12c5bb2010-05-15 11:32:37 +00007200 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007201 case Type::IncompleteArray:
7202 case Type::VariableArray:
7203 case Type::FunctionProto:
7204 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007205 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007206
Chris Lattner1adb8832008-01-14 05:45:46 +00007207 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007208 {
7209 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007210 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7211 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007212 if (Unqualified) {
7213 LHSPointee = LHSPointee.getUnqualifiedType();
7214 RHSPointee = RHSPointee.getUnqualifiedType();
7215 }
7216 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7217 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007218 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007219 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007220 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007221 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007222 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007223 return getPointerType(ResultType);
7224 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007225 case Type::BlockPointer:
7226 {
7227 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007228 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7229 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007230 if (Unqualified) {
7231 LHSPointee = LHSPointee.getUnqualifiedType();
7232 RHSPointee = RHSPointee.getUnqualifiedType();
7233 }
7234 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7235 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007236 if (ResultType.isNull()) return QualType();
7237 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7238 return LHS;
7239 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7240 return RHS;
7241 return getBlockPointerType(ResultType);
7242 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007243 case Type::Atomic:
7244 {
7245 // Merge two pointer types, while trying to preserve typedef info
7246 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7247 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7248 if (Unqualified) {
7249 LHSValue = LHSValue.getUnqualifiedType();
7250 RHSValue = RHSValue.getUnqualifiedType();
7251 }
7252 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7253 Unqualified);
7254 if (ResultType.isNull()) return QualType();
7255 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7256 return LHS;
7257 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7258 return RHS;
7259 return getAtomicType(ResultType);
7260 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007261 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007262 {
7263 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7264 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7265 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7266 return QualType();
7267
7268 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7269 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007270 if (Unqualified) {
7271 LHSElem = LHSElem.getUnqualifiedType();
7272 RHSElem = RHSElem.getUnqualifiedType();
7273 }
7274
7275 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007276 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007277 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7278 return LHS;
7279 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7280 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007281 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7282 ArrayType::ArraySizeModifier(), 0);
7283 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7284 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007285 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7286 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007287 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7288 return LHS;
7289 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7290 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007291 if (LVAT) {
7292 // FIXME: This isn't correct! But tricky to implement because
7293 // the array's size has to be the size of LHS, but the type
7294 // has to be different.
7295 return LHS;
7296 }
7297 if (RVAT) {
7298 // FIXME: This isn't correct! But tricky to implement because
7299 // the array's size has to be the size of RHS, but the type
7300 // has to be different.
7301 return RHS;
7302 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007303 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7304 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007305 return getIncompleteArrayType(ResultType,
7306 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007307 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007308 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007309 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007310 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007311 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007312 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007313 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007314 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007315 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007316 case Type::Complex:
7317 // Distinct complex types are incompatible.
7318 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007319 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007320 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007321 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7322 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007323 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007324 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007325 case Type::ObjCObject: {
7326 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007327 // FIXME: This should be type compatibility, e.g. whether
7328 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007329 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7330 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7331 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007332 return LHS;
7333
Eli Friedman3d815e72008-08-22 00:56:42 +00007334 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007335 }
Steve Naroff14108da2009-07-10 23:34:53 +00007336 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007337 if (OfBlockPointer) {
7338 if (canAssignObjCInterfacesInBlockPointer(
7339 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007340 RHS->getAs<ObjCObjectPointerType>(),
7341 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007342 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007343 return QualType();
7344 }
John McCall183700f2009-09-21 23:43:11 +00007345 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7346 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007347 return LHS;
7348
Steve Naroffbc76dd02008-12-10 22:14:21 +00007349 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007350 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007351 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007352
David Blaikie7530c032012-01-17 06:56:22 +00007353 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007354}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007355
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007356bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7357 const FunctionProtoType *FromFunctionType,
7358 const FunctionProtoType *ToFunctionType) {
7359 if (FromFunctionType->hasAnyConsumedArgs() !=
7360 ToFunctionType->hasAnyConsumedArgs())
7361 return false;
7362 FunctionProtoType::ExtProtoInfo FromEPI =
7363 FromFunctionType->getExtProtoInfo();
7364 FunctionProtoType::ExtProtoInfo ToEPI =
7365 ToFunctionType->getExtProtoInfo();
7366 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7367 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7368 ArgIdx != NumArgs; ++ArgIdx) {
7369 if (FromEPI.ConsumedArguments[ArgIdx] !=
7370 ToEPI.ConsumedArguments[ArgIdx])
7371 return false;
7372 }
7373 return true;
7374}
7375
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007376/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7377/// 'RHS' attributes and returns the merged version; including for function
7378/// return types.
7379QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7380 QualType LHSCan = getCanonicalType(LHS),
7381 RHSCan = getCanonicalType(RHS);
7382 // If two types are identical, they are compatible.
7383 if (LHSCan == RHSCan)
7384 return LHS;
7385 if (RHSCan->isFunctionType()) {
7386 if (!LHSCan->isFunctionType())
7387 return QualType();
7388 QualType OldReturnType =
7389 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7390 QualType NewReturnType =
7391 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7392 QualType ResReturnType =
7393 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7394 if (ResReturnType.isNull())
7395 return QualType();
7396 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7397 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7398 // In either case, use OldReturnType to build the new function type.
7399 const FunctionType *F = LHS->getAs<FunctionType>();
7400 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007401 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7402 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007403 QualType ResultType =
7404 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007405 return ResultType;
7406 }
7407 }
7408 return QualType();
7409 }
7410
7411 // If the qualifiers are different, the types can still be merged.
7412 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7413 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7414 if (LQuals != RQuals) {
7415 // If any of these qualifiers are different, we have a type mismatch.
7416 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7417 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7418 return QualType();
7419
7420 // Exactly one GC qualifier difference is allowed: __strong is
7421 // okay if the other type has no GC qualifier but is an Objective
7422 // C object pointer (i.e. implicitly strong by default). We fix
7423 // this by pretending that the unqualified type was actually
7424 // qualified __strong.
7425 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7426 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7427 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7428
7429 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7430 return QualType();
7431
7432 if (GC_L == Qualifiers::Strong)
7433 return LHS;
7434 if (GC_R == Qualifiers::Strong)
7435 return RHS;
7436 return QualType();
7437 }
7438
7439 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7440 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7441 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7442 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7443 if (ResQT == LHSBaseQT)
7444 return LHS;
7445 if (ResQT == RHSBaseQT)
7446 return RHS;
7447 }
7448 return QualType();
7449}
7450
Chris Lattner5426bf62008-04-07 07:01:58 +00007451//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007452// Integer Predicates
7453//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007454
Jay Foad4ba2a172011-01-12 09:06:06 +00007455unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007456 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007457 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007458 if (T->isBooleanType())
7459 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007460 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007461 return (unsigned)getTypeSize(T);
7462}
7463
Abramo Bagnara762f1592012-09-09 10:21:24 +00007464QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007465 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007466
7467 // Turn <4 x signed int> -> <4 x unsigned int>
7468 if (const VectorType *VTy = T->getAs<VectorType>())
7469 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007470 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007471
7472 // For enums, we return the unsigned version of the base type.
7473 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007474 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007475
7476 const BuiltinType *BTy = T->getAs<BuiltinType>();
7477 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007478 switch (BTy->getKind()) {
7479 case BuiltinType::Char_S:
7480 case BuiltinType::SChar:
7481 return UnsignedCharTy;
7482 case BuiltinType::Short:
7483 return UnsignedShortTy;
7484 case BuiltinType::Int:
7485 return UnsignedIntTy;
7486 case BuiltinType::Long:
7487 return UnsignedLongTy;
7488 case BuiltinType::LongLong:
7489 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007490 case BuiltinType::Int128:
7491 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007492 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007493 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007494 }
7495}
7496
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007497ASTMutationListener::~ASTMutationListener() { }
7498
Richard Smith9dadfab2013-05-11 05:45:24 +00007499void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7500 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007501
7502//===----------------------------------------------------------------------===//
7503// Builtin Type Computation
7504//===----------------------------------------------------------------------===//
7505
7506/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007507/// pointer over the consumed characters. This returns the resultant type. If
7508/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7509/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7510/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007511///
7512/// RequiresICE is filled in on return to indicate whether the value is required
7513/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007514static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007515 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007516 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007517 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007518 // Modifiers.
7519 int HowLong = 0;
7520 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007521 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007522
Chris Lattner33daae62010-10-01 22:42:38 +00007523 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007524 bool Done = false;
7525 while (!Done) {
7526 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007527 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007528 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007529 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007530 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007531 case 'S':
7532 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7533 assert(!Signed && "Can't use 'S' modifier multiple times!");
7534 Signed = true;
7535 break;
7536 case 'U':
7537 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7538 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7539 Unsigned = true;
7540 break;
7541 case 'L':
7542 assert(HowLong <= 2 && "Can't have LLLL modifier");
7543 ++HowLong;
7544 break;
7545 }
7546 }
7547
7548 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007549
Chris Lattner86df27b2009-06-14 00:45:47 +00007550 // Read the base type.
7551 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007552 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007553 case 'v':
7554 assert(HowLong == 0 && !Signed && !Unsigned &&
7555 "Bad modifiers used with 'v'!");
7556 Type = Context.VoidTy;
7557 break;
7558 case 'f':
7559 assert(HowLong == 0 && !Signed && !Unsigned &&
7560 "Bad modifiers used with 'f'!");
7561 Type = Context.FloatTy;
7562 break;
7563 case 'd':
7564 assert(HowLong < 2 && !Signed && !Unsigned &&
7565 "Bad modifiers used with 'd'!");
7566 if (HowLong)
7567 Type = Context.LongDoubleTy;
7568 else
7569 Type = Context.DoubleTy;
7570 break;
7571 case 's':
7572 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7573 if (Unsigned)
7574 Type = Context.UnsignedShortTy;
7575 else
7576 Type = Context.ShortTy;
7577 break;
7578 case 'i':
7579 if (HowLong == 3)
7580 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7581 else if (HowLong == 2)
7582 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7583 else if (HowLong == 1)
7584 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7585 else
7586 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7587 break;
7588 case 'c':
7589 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7590 if (Signed)
7591 Type = Context.SignedCharTy;
7592 else if (Unsigned)
7593 Type = Context.UnsignedCharTy;
7594 else
7595 Type = Context.CharTy;
7596 break;
7597 case 'b': // boolean
7598 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7599 Type = Context.BoolTy;
7600 break;
7601 case 'z': // size_t.
7602 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7603 Type = Context.getSizeType();
7604 break;
7605 case 'F':
7606 Type = Context.getCFConstantStringType();
7607 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007608 case 'G':
7609 Type = Context.getObjCIdType();
7610 break;
7611 case 'H':
7612 Type = Context.getObjCSelType();
7613 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007614 case 'M':
7615 Type = Context.getObjCSuperType();
7616 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007617 case 'a':
7618 Type = Context.getBuiltinVaListType();
7619 assert(!Type.isNull() && "builtin va list type not initialized!");
7620 break;
7621 case 'A':
7622 // This is a "reference" to a va_list; however, what exactly
7623 // this means depends on how va_list is defined. There are two
7624 // different kinds of va_list: ones passed by value, and ones
7625 // passed by reference. An example of a by-value va_list is
7626 // x86, where va_list is a char*. An example of by-ref va_list
7627 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7628 // we want this argument to be a char*&; for x86-64, we want
7629 // it to be a __va_list_tag*.
7630 Type = Context.getBuiltinVaListType();
7631 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007632 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007633 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007634 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007635 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007636 break;
7637 case 'V': {
7638 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007639 unsigned NumElements = strtoul(Str, &End, 10);
7640 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007641 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007642
Chris Lattner14e0e742010-10-01 22:53:11 +00007643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7644 RequiresICE, false);
7645 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007646
7647 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007648 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007649 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007650 break;
7651 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007652 case 'E': {
7653 char *End;
7654
7655 unsigned NumElements = strtoul(Str, &End, 10);
7656 assert(End != Str && "Missing vector size");
7657
7658 Str = End;
7659
7660 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7661 false);
7662 Type = Context.getExtVectorType(ElementType, NumElements);
7663 break;
7664 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007665 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007666 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7667 false);
7668 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007669 Type = Context.getComplexType(ElementType);
7670 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007671 }
7672 case 'Y' : {
7673 Type = Context.getPointerDiffType();
7674 break;
7675 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007676 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007677 Type = Context.getFILEType();
7678 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007679 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007680 return QualType();
7681 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007682 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007683 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007684 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007685 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007686 else
7687 Type = Context.getjmp_bufType();
7688
Mike Stumpfd612db2009-07-28 23:47:15 +00007689 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007690 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007691 return QualType();
7692 }
7693 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007694 case 'K':
7695 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7696 Type = Context.getucontext_tType();
7697
7698 if (Type.isNull()) {
7699 Error = ASTContext::GE_Missing_ucontext;
7700 return QualType();
7701 }
7702 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007703 case 'p':
7704 Type = Context.getProcessIDType();
7705 break;
Mike Stump782fa302009-07-28 02:25:19 +00007706 }
Mike Stump1eb44332009-09-09 15:08:12 +00007707
Chris Lattner33daae62010-10-01 22:42:38 +00007708 // If there are modifiers and if we're allowed to parse them, go for it.
7709 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007710 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007711 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007712 default: Done = true; --Str; break;
7713 case '*':
7714 case '&': {
7715 // Both pointers and references can have their pointee types
7716 // qualified with an address space.
7717 char *End;
7718 unsigned AddrSpace = strtoul(Str, &End, 10);
7719 if (End != Str && AddrSpace != 0) {
7720 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7721 Str = End;
7722 }
7723 if (c == '*')
7724 Type = Context.getPointerType(Type);
7725 else
7726 Type = Context.getLValueReferenceType(Type);
7727 break;
7728 }
7729 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7730 case 'C':
7731 Type = Type.withConst();
7732 break;
7733 case 'D':
7734 Type = Context.getVolatileType(Type);
7735 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007736 case 'R':
7737 Type = Type.withRestrict();
7738 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007739 }
7740 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007741
Chris Lattner14e0e742010-10-01 22:53:11 +00007742 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007743 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007744
Chris Lattner86df27b2009-06-14 00:45:47 +00007745 return Type;
7746}
7747
7748/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007749QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007750 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007751 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007752 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007753
Chris Lattner5f9e2722011-07-23 10:55:15 +00007754 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007755
Chris Lattner14e0e742010-10-01 22:53:11 +00007756 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007757 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007758 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7759 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 if (Error != GE_None)
7761 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007762
7763 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7764
Chris Lattner86df27b2009-06-14 00:45:47 +00007765 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007766 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007767 if (Error != GE_None)
7768 return QualType();
7769
Chris Lattner14e0e742010-10-01 22:53:11 +00007770 // If this argument is required to be an IntegerConstantExpression and the
7771 // caller cares, fill in the bitmask we return.
7772 if (RequiresICE && IntegerConstantArgs)
7773 *IntegerConstantArgs |= 1 << ArgTypes.size();
7774
Chris Lattner86df27b2009-06-14 00:45:47 +00007775 // Do array -> pointer decay. The builtin should use the decayed type.
7776 if (Ty->isArrayType())
7777 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007778
Chris Lattner86df27b2009-06-14 00:45:47 +00007779 ArgTypes.push_back(Ty);
7780 }
7781
7782 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7783 "'.' should only occur at end of builtin type list!");
7784
John McCall00ccbef2010-12-21 00:44:39 +00007785 FunctionType::ExtInfo EI;
7786 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7787
7788 bool Variadic = (TypeStr[0] == '.');
7789
7790 // We really shouldn't be making a no-proto type here, especially in C++.
7791 if (ArgTypes.empty() && Variadic)
7792 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007793
John McCalle23cf432010-12-14 08:05:40 +00007794 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007795 EPI.ExtInfo = EI;
7796 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007797
Jordan Rosebea522f2013-03-08 21:51:21 +00007798 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007799}
Eli Friedmana95d7572009-08-19 07:44:53 +00007800
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007801GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007802 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007803 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007804
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007805 GVALinkage External = GVA_StrongExternal;
7806 switch (FD->getTemplateSpecializationKind()) {
7807 case TSK_Undeclared:
7808 case TSK_ExplicitSpecialization:
7809 External = GVA_StrongExternal;
7810 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007811
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007812 case TSK_ExplicitInstantiationDefinition:
7813 return GVA_ExplicitTemplateInstantiation;
7814
7815 case TSK_ExplicitInstantiationDeclaration:
7816 case TSK_ImplicitInstantiation:
7817 External = GVA_TemplateInstantiation;
7818 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007819 }
7820
7821 if (!FD->isInlined())
7822 return External;
David Majnemer13163702013-08-01 17:26:42 +00007823
7824 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7825 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007826 // GNU or C99 inline semantics. Determine whether this symbol should be
7827 // externally visible.
7828 if (FD->isInlineDefinitionExternallyVisible())
7829 return External;
7830
7831 // C99 inline semantics, where the symbol is not externally visible.
7832 return GVA_C99Inline;
7833 }
7834
7835 // C++0x [temp.explicit]p9:
7836 // [ Note: The intent is that an inline function that is the subject of
7837 // an explicit instantiation declaration will still be implicitly
7838 // instantiated when used so that the body can be considered for
7839 // inlining, but that no out-of-line copy of the inline function would be
7840 // generated in the translation unit. -- end note ]
7841 if (FD->getTemplateSpecializationKind()
7842 == TSK_ExplicitInstantiationDeclaration)
7843 return GVA_C99Inline;
7844
7845 return GVA_CXXInline;
7846}
7847
7848GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007849 if (!VD->isExternallyVisible())
7850 return GVA_Internal;
7851
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007852 // If this is a static data member, compute the kind of template
7853 // specialization. Otherwise, this variable is not part of a
7854 // template.
7855 TemplateSpecializationKind TSK = TSK_Undeclared;
7856 if (VD->isStaticDataMember())
7857 TSK = VD->getTemplateSpecializationKind();
7858
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007859 switch (TSK) {
7860 case TSK_Undeclared:
7861 case TSK_ExplicitSpecialization:
7862 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007863
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007864 case TSK_ExplicitInstantiationDeclaration:
7865 llvm_unreachable("Variable should not be instantiated");
7866 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007867
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007868 case TSK_ExplicitInstantiationDefinition:
7869 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007870
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007871 case TSK_ImplicitInstantiation:
7872 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007873 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007874
7875 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007876}
7877
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007878bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007879 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7880 if (!VD->isFileVarDecl())
7881 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007882 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7883 // We never need to emit an uninstantiated function template.
7884 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7885 return false;
7886 } else
7887 return false;
7888
7889 // If this is a member of a class template, we do not need to emit it.
7890 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007891 return false;
7892
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007893 // Weak references don't produce any output by themselves.
7894 if (D->hasAttr<WeakRefAttr>())
7895 return false;
7896
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007897 // Aliases and used decls are required.
7898 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7899 return true;
7900
7901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7902 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007903 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007904 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007905
7906 // Constructors and destructors are required.
7907 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7908 return true;
7909
John McCalld5617ee2013-01-25 22:31:03 +00007910 // The key function for a class is required. This rule only comes
7911 // into play when inline functions can be key functions, though.
7912 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7913 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7914 const CXXRecordDecl *RD = MD->getParent();
7915 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7916 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7917 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7918 return true;
7919 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007920 }
7921 }
7922
7923 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7924
7925 // static, static inline, always_inline, and extern inline functions can
7926 // always be deferred. Normal inline functions can be deferred in C99/C++.
7927 // Implicit template instantiations can also be deferred in C++.
7928 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007929 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007930 return false;
7931 return true;
7932 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007933
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007934 const VarDecl *VD = cast<VarDecl>(D);
7935 assert(VD->isFileVarDecl() && "Expected file scoped var");
7936
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007937 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7938 return false;
7939
Richard Smith5f9a7e32012-11-12 21:38:00 +00007940 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007941 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007942 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7943 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007944
Richard Smith5f9a7e32012-11-12 21:38:00 +00007945 // Variables that have destruction with side-effects are required.
7946 if (VD->getType().isDestructedType())
7947 return true;
7948
7949 // Variables that have initialization with side-effects are required.
7950 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7951 return true;
7952
7953 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007954}
Charles Davis071cc7d2010-08-16 03:33:14 +00007955
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007956CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007957 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007958 return ABI->getDefaultMethodCallConv(isVariadic);
7959}
7960
7961CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007962 if (CC == CC_C && !LangOpts.MRTD &&
7963 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007964 return CC_Default;
7965 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007966}
7967
Jay Foad4ba2a172011-01-12 09:06:06 +00007968bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007969 // Pass through to the C++ ABI object
7970 return ABI->isNearlyEmpty(RD);
7971}
7972
Peter Collingbourne14110472011-01-13 18:57:25 +00007973MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007974 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007975 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007976 case TargetCXXABI::GenericItanium:
7977 case TargetCXXABI::GenericARM:
7978 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007979 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007980 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007981 return createMicrosoftMangleContext(*this, getDiagnostics());
7982 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007983 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007984}
7985
Charles Davis071cc7d2010-08-16 03:33:14 +00007986CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007987
7988size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00007989 return ASTRecordLayouts.getMemorySize() +
7990 llvm::capacity_in_bytes(ObjCLayouts) +
7991 llvm::capacity_in_bytes(KeyFunctions) +
7992 llvm::capacity_in_bytes(ObjCImpls) +
7993 llvm::capacity_in_bytes(BlockVarCopyInits) +
7994 llvm::capacity_in_bytes(DeclAttrs) +
7995 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7996 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7997 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7998 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7999 llvm::capacity_in_bytes(OverriddenMethods) +
8000 llvm::capacity_in_bytes(Types) +
8001 llvm::capacity_in_bytes(VariableArrayTypes) +
8002 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008003}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008004
Eli Friedman5e867c82013-07-10 00:30:46 +00008005void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8006 if (Number > 1)
8007 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00008008}
8009
Eli Friedman5e867c82013-07-10 00:30:46 +00008010unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8011 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8012 MangleNumbers.find(ND);
8013 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008014}
8015
Eli Friedman5e867c82013-07-10 00:30:46 +00008016MangleNumberingContext &
8017ASTContext::getManglingNumberContext(const DeclContext *DC) {
Eli Friedman07369dd2013-07-01 20:22:57 +00008018 return MangleNumberingContexts[DC];
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008019}
8020
Ted Kremenekd211cb72011-10-06 05:00:56 +00008021void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8022 ParamIndices[D] = index;
8023}
8024
8025unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8026 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8027 assert(I != ParamIndices.end() &&
8028 "ParmIndices lacks entry set by ParmVarDecl");
8029 return I->second;
8030}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008031
Richard Smith211c8dd2013-06-05 00:46:14 +00008032APValue *
8033ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8034 bool MayCreate) {
8035 assert(E && E->getStorageDuration() == SD_Static &&
8036 "don't need to cache the computed value for this temporary");
8037 if (MayCreate)
8038 return &MaterializedTemporaryValues[E];
8039
8040 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8041 MaterializedTemporaryValues.find(E);
8042 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8043}
8044
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008045bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8046 const llvm::Triple &T = getTargetInfo().getTriple();
8047 if (!T.isOSDarwin())
8048 return false;
8049
8050 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8051 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8052 uint64_t Size = sizeChars.getQuantity();
8053 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8054 unsigned Align = alignChars.getQuantity();
8055 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8056 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8057}
Reid Klecknercff15122013-06-17 12:56:08 +00008058
8059namespace {
8060
8061 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8062 /// parents as defined by the \c RecursiveASTVisitor.
8063 ///
8064 /// Note that the relationship described here is purely in terms of AST
8065 /// traversal - there are other relationships (for example declaration context)
8066 /// in the AST that are better modeled by special matchers.
8067 ///
8068 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8069 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8070
8071 public:
8072 /// \brief Builds and returns the translation unit's parent map.
8073 ///
8074 /// The caller takes ownership of the returned \c ParentMap.
8075 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8076 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8077 Visitor.TraverseDecl(&TU);
8078 return Visitor.Parents;
8079 }
8080
8081 private:
8082 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8083
8084 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8085 }
8086
8087 bool shouldVisitTemplateInstantiations() const {
8088 return true;
8089 }
8090 bool shouldVisitImplicitCode() const {
8091 return true;
8092 }
8093 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8094 // are not triggered during data recursion.
8095 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8096 return false;
8097 }
8098
8099 template <typename T>
8100 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8101 if (Node == NULL)
8102 return true;
8103 if (ParentStack.size() > 0)
8104 // FIXME: Currently we add the same parent multiple times, for example
8105 // when we visit all subexpressions of template instantiations; this is
8106 // suboptimal, bug benign: the only way to visit those is with
8107 // hasAncestor / hasParent, and those do not create new matches.
8108 // The plan is to enable DynTypedNode to be storable in a map or hash
8109 // map. The main problem there is to implement hash functions /
8110 // comparison operators for all types that DynTypedNode supports that
8111 // do not have pointer identity.
8112 (*Parents)[Node].push_back(ParentStack.back());
8113 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8114 bool Result = (this ->* traverse) (Node);
8115 ParentStack.pop_back();
8116 return Result;
8117 }
8118
8119 bool TraverseDecl(Decl *DeclNode) {
8120 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8121 }
8122
8123 bool TraverseStmt(Stmt *StmtNode) {
8124 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8125 }
8126
8127 ASTContext::ParentMap *Parents;
8128 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8129
8130 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8131 };
8132
8133} // end namespace
8134
8135ASTContext::ParentVector
8136ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8137 assert(Node.getMemoizationData() &&
8138 "Invariant broken: only nodes that support memoization may be "
8139 "used in the parent map.");
8140 if (!AllParents) {
8141 // We always need to run over the whole translation unit, as
8142 // hasAncestor can escape any subtree.
8143 AllParents.reset(
8144 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8145 }
8146 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8147 if (I == AllParents->end()) {
8148 return ParentVector();
8149 }
8150 return I->second;
8151}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008152
8153bool
8154ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8155 const ObjCMethodDecl *MethodImpl) {
8156 // No point trying to match an unavailable/deprecated mothod.
8157 if (MethodDecl->hasAttr<UnavailableAttr>()
8158 || MethodDecl->hasAttr<DeprecatedAttr>())
8159 return false;
8160 if (MethodDecl->getObjCDeclQualifier() !=
8161 MethodImpl->getObjCDeclQualifier())
8162 return false;
8163 if (!hasSameType(MethodDecl->getResultType(),
8164 MethodImpl->getResultType()))
8165 return false;
8166
8167 if (MethodDecl->param_size() != MethodImpl->param_size())
8168 return false;
8169
8170 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8171 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8172 EF = MethodDecl->param_end();
8173 IM != EM && IF != EF; ++IM, ++IF) {
8174 const ParmVarDecl *DeclVar = (*IF);
8175 const ParmVarDecl *ImplVar = (*IM);
8176 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8177 return false;
8178 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8179 return false;
8180 }
8181 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8182
8183}