blob: 65e5e6daaa5d95874886cfa66b4ea9874b4bf019 [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() &&
Fariborz Jahanian8c238be2013-08-06 23:29:00 +0000185 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian15c8e562013-08-07 16:40:29 +0000186 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000187 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 // Check that Doxygen trailing comment comes after the declaration, starts
190 // on the same line and in the same file as the declaration.
191 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
192 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
193 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
194 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000195 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000196 }
197 }
198
199 // The comment just after the declaration was not a trailing comment.
200 // Let's look at the previous comment.
201 if (Comment == RawComments.begin())
202 return NULL;
203 --Comment;
204
205 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000206 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000207 return NULL;
208
209 // Decompose the end of the comment.
210 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000212
213 // If the comment and the declaration aren't in the same file, then they
214 // aren't related.
215 if (DeclLocDecomp.first != CommentEndDecomp.first)
216 return NULL;
217
218 // Get the corresponding buffer.
219 bool Invalid = false;
220 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
221 &Invalid).data();
222 if (Invalid)
223 return NULL;
224
225 // Extract text between the comment and declaration.
226 StringRef Text(Buffer + CommentEndDecomp.second,
227 DeclLocDecomp.second - CommentEndDecomp.second);
228
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000229 // There should be no other declarations or preprocessor directives between
230 // comment and declaration.
Argyrios Kyrtzidisdc663262013-07-26 18:38:12 +0000231 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000232 return NULL;
233
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000234 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000235}
236
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000237namespace {
238/// If we have a 'templated' declaration for a template, adjust 'D' to
239/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000240/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000241const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000243 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000244 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000245 return FTD;
246
247 // Nothing to do if function is not an implicit instantiation.
248 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
249 return D;
250
251 // Function is an implicit instantiation of a function template?
252 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
253 return FTD;
254
255 // Function is instantiated from a member definition of a class template?
256 if (const FunctionDecl *MemberDecl =
257 FD->getInstantiatedFromMemberFunction())
258 return MemberDecl;
259
260 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000261 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
263 // Static data member is instantiated from a member definition of a class
264 // template?
265 if (VD->isStaticDataMember())
266 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
267 return MemberDecl;
268
269 return D;
270 }
271 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
272 // Is this class declaration part of a class template?
273 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
274 return CTD;
275
276 // Class is an implicit instantiation of a class template or partial
277 // specialization?
278 if (const ClassTemplateSpecializationDecl *CTSD =
279 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
280 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
281 return D;
282 llvm::PointerUnion<ClassTemplateDecl *,
283 ClassTemplatePartialSpecializationDecl *>
284 PU = CTSD->getSpecializedTemplateOrPartial();
285 return PU.is<ClassTemplateDecl*>() ?
286 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
287 static_cast<const Decl*>(
288 PU.get<ClassTemplatePartialSpecializationDecl *>());
289 }
290
291 // Class is instantiated from a member definition of a class template?
292 if (const MemberSpecializationInfo *Info =
293 CRD->getMemberSpecializationInfo())
294 return Info->getInstantiatedFrom();
295
296 return D;
297 }
298 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
299 // Enum is instantiated from a member definition of a class template?
300 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
301 return MemberDecl;
302
303 return D;
304 }
305 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 return D;
307}
308} // unnamed namespace
309
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000310const RawComment *ASTContext::getRawCommentForAnyRedecl(
311 const Decl *D,
312 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000313 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000314
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000315 // Check whether we have cached a comment for this declaration already.
316 {
317 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
318 RedeclComments.find(D);
319 if (Pos != RedeclComments.end()) {
320 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000321 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
322 if (OriginalDecl)
323 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000324 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000325 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000326 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000327 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000328
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000329 // Search for comments attached to declarations in the redeclaration chain.
330 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000331 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000332 for (Decl::redecl_iterator I = D->redecls_begin(),
333 E = D->redecls_end();
334 I != E; ++I) {
335 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
336 RedeclComments.find(*I);
337 if (Pos != RedeclComments.end()) {
338 const RawCommentAndCacheFlags &Raw = Pos->second;
339 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
340 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000341 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000342 break;
343 }
344 } else {
345 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RawCommentAndCacheFlags Raw;
348 if (RC) {
349 Raw.setRaw(RC);
350 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
351 } else
352 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000353 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000354 RedeclComments[*I] = Raw;
355 if (RC)
356 break;
357 }
358 }
359
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000360 // If we found a comment, it should be a documentation comment.
361 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000362
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 if (OriginalDecl)
364 *OriginalDecl = OriginalDeclForRC;
365
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000366 // Update cache for every declaration in the redeclaration chain.
367 RawCommentAndCacheFlags Raw;
368 Raw.setRaw(RC);
369 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000370 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000371
372 for (Decl::redecl_iterator I = D->redecls_begin(),
373 E = D->redecls_end();
374 I != E; ++I) {
375 RawCommentAndCacheFlags &R = RedeclComments[*I];
376 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
377 R = Raw;
378 }
379
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000380 return RC;
381}
382
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000383static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
384 SmallVectorImpl<const NamedDecl *> &Redeclared) {
385 const DeclContext *DC = ObjCMethod->getDeclContext();
386 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
387 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
388 if (!ID)
389 return;
390 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000391 for (ObjCInterfaceDecl::known_extensions_iterator
392 Ext = ID->known_extensions_begin(),
393 ExtEnd = ID->known_extensions_end();
394 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000395 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000396 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000397 ObjCMethod->isInstanceMethod()))
398 Redeclared.push_back(RedeclaredMethod);
399 }
400 }
401}
402
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000403comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
404 const Decl *D) const {
405 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
406 ThisDeclInfo->CommentDecl = D;
407 ThisDeclInfo->IsFilled = false;
408 ThisDeclInfo->fill();
409 ThisDeclInfo->CommentDecl = FC->getDecl();
410 comments::FullComment *CFC =
411 new (*this) comments::FullComment(FC->getBlocks(),
412 ThisDeclInfo);
413 return CFC;
414
415}
416
Richard Smith0a74a4c2013-05-21 05:24:00 +0000417comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
418 const RawComment *RC = getRawCommentForDeclNoCache(D);
419 return RC ? RC->parse(*this, 0, D) : 0;
420}
421
Dmitri Gribenko19523542012-09-29 11:40:46 +0000422comments::FullComment *ASTContext::getCommentForDecl(
423 const Decl *D,
424 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000425 if (D->isInvalidDecl())
426 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000427 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000429 const Decl *Canonical = D->getCanonicalDecl();
430 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
431 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000432
433 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000434 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000435 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000436 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 return CFC;
438 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000439 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000440 }
441
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000442 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000443
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000444 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000445 if (!RC) {
446 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000448 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 if (OMD && OMD->isPropertyAccessor())
450 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
451 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
452 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000453 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000454 addRedeclaredMethods(OMD, Overridden);
455 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000456 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
457 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
458 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000459 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000460 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000461 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000462 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000463 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000464 if (const TagType *TT = QT->getAs<TagType>())
465 if (const Decl *TD = TT->getDecl())
466 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000467 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000468 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000469 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
470 while (IC->getSuperClass()) {
471 IC = IC->getSuperClass();
472 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
473 return cloneFullComment(FC, D);
474 }
475 }
476 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
477 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
478 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
479 return cloneFullComment(FC, D);
480 }
481 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
482 if (!(RD = RD->getDefinition()))
483 return NULL;
484 // Check non-virtual bases.
485 for (CXXRecordDecl::base_class_const_iterator I =
486 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000487 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000488 continue;
489 QualType Ty = I->getType();
490 if (Ty.isNull())
491 continue;
492 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
493 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
494 continue;
495
496 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
497 return cloneFullComment(FC, D);
498 }
499 }
500 // Check virtual bases.
501 for (CXXRecordDecl::base_class_const_iterator I =
502 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000503 if (I->getAccessSpecifier() != AS_public)
504 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000505 QualType Ty = I->getType();
506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(VirtualBase= VirtualBase->getDefinition()))
510 continue;
511 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
512 return cloneFullComment(FC, D);
513 }
514 }
515 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000516 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000517 }
518
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000519 // If the RawComment was attached to other redeclaration of this Decl, we
520 // should parse the comment in context of that other Decl. This is important
521 // because comments can contain references to parameter names which can be
522 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000523 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000524 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000525
Dmitri Gribenko19523542012-09-29 11:40:46 +0000526 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000527 ParsedComments[Canonical] = FC;
528 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000529}
530
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000531void
532ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
533 TemplateTemplateParmDecl *Parm) {
534 ID.AddInteger(Parm->getDepth());
535 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000536 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000537
538 TemplateParameterList *Params = Parm->getTemplateParameters();
539 ID.AddInteger(Params->size());
540 for (TemplateParameterList::const_iterator P = Params->begin(),
541 PEnd = Params->end();
542 P != PEnd; ++P) {
543 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
544 ID.AddInteger(0);
545 ID.AddBoolean(TTP->isParameterPack());
546 continue;
547 }
548
549 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
550 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000551 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000552 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 if (NTTP->isExpandedParameterPack()) {
554 ID.AddBoolean(true);
555 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000556 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
557 QualType T = NTTP->getExpansionType(I);
558 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
559 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000560 } else
561 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000562 continue;
563 }
564
565 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
566 ID.AddInteger(2);
567 Profile(ID, TTP);
568 }
569}
570
571TemplateTemplateParmDecl *
572ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000573 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000574 // Check if we already have a canonical template template parameter.
575 llvm::FoldingSetNodeID ID;
576 CanonicalTemplateTemplateParm::Profile(ID, TTP);
577 void *InsertPos = 0;
578 CanonicalTemplateTemplateParm *Canonical
579 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
580 if (Canonical)
581 return Canonical->getParam();
582
583 // Build a canonical template parameter list.
584 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000586 CanonParams.reserve(Params->size());
587 for (TemplateParameterList::const_iterator P = Params->begin(),
588 PEnd = Params->end();
589 P != PEnd; ++P) {
590 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
591 CanonParams.push_back(
592 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000593 SourceLocation(),
594 SourceLocation(),
595 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000596 TTP->getIndex(), 0, false,
597 TTP->isParameterPack()));
598 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
600 QualType T = getCanonicalType(NTTP->getType());
601 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
602 NonTypeTemplateParmDecl *Param;
603 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000604 SmallVector<QualType, 2> ExpandedTypes;
605 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000606 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
607 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
608 ExpandedTInfos.push_back(
609 getTrivialTypeSourceInfo(ExpandedTypes.back()));
610 }
611
612 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000613 SourceLocation(),
614 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000615 NTTP->getDepth(),
616 NTTP->getPosition(), 0,
617 T,
618 TInfo,
619 ExpandedTypes.data(),
620 ExpandedTypes.size(),
621 ExpandedTInfos.data());
622 } else {
623 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000624 SourceLocation(),
625 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000626 NTTP->getDepth(),
627 NTTP->getPosition(), 0,
628 T,
629 NTTP->isParameterPack(),
630 TInfo);
631 }
632 CanonParams.push_back(Param);
633
634 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000635 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
636 cast<TemplateTemplateParmDecl>(*P)));
637 }
638
639 TemplateTemplateParmDecl *CanonTTP
640 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
641 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000642 TTP->getPosition(),
643 TTP->isParameterPack(),
644 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000645 TemplateParameterList::Create(*this, SourceLocation(),
646 SourceLocation(),
647 CanonParams.data(),
648 CanonParams.size(),
649 SourceLocation()));
650
651 // Get the new insert position for the node we care about.
652 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
653 assert(Canonical == 0 && "Shouldn't be in the map!");
654 (void)Canonical;
655
656 // Create the canonical template template parameter entry.
657 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
658 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
659 return CanonTTP;
660}
661
Charles Davis071cc7d2010-08-16 03:33:14 +0000662CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000663 if (!LangOpts.CPlusPlus) return 0;
664
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 switch (T.getCXXABI().getKind()) {
666 case TargetCXXABI::GenericARM:
667 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000668 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000669 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000670 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000671 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000672 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000673 return CreateMicrosoftCXXABI(*this);
674 }
David Blaikie7530c032012-01-17 06:56:22 +0000675 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000676}
677
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000678static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000679 const LangOptions &LOpts) {
680 if (LOpts.FakeAddressSpaceMap) {
681 // The fake address space map must have a distinct entry for each
682 // language-specific address space.
683 static const unsigned FakeAddrSpaceMap[] = {
684 1, // opencl_global
685 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000686 3, // opencl_constant
687 4, // cuda_device
688 5, // cuda_constant
689 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000690 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000692 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000693 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000694 }
695}
696
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000697ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000698 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000699 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000700 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000701 unsigned size_reserve,
702 bool DelayInitialization)
703 : FunctionProtoTypes(this_()),
704 TemplateSpecializationTypes(this_()),
705 DependentTemplateSpecializationTypes(this_()),
706 SubstTemplateTemplateParmPacks(this_()),
707 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000708 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000709 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000710 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000711 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000712 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000714 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
715 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
716 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000717 NullTypeSourceInfo(QualType()),
718 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000719 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000720 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721 Idents(idents), Selectors(sels),
722 BuiltinInfo(builtins),
723 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000724 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000725 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000726 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000727 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000728{
Mike Stump1eb44332009-09-09 15:08:12 +0000729 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000730 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000731
732 if (!DelayInitialization) {
733 assert(t && "No target supplied for ASTContext initialization");
734 InitBuiltinTypes(*t);
735 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000736}
737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000739 // Release the DenseMaps associated with DeclContext objects.
740 // FIXME: Is this the ideal solution?
741 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000742
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000743 // Call all of the deallocation functions on all of their targets.
744 for (DeallocationMap::const_iterator I = Deallocations.begin(),
745 E = Deallocations.end(); I != E; ++I)
746 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
747 (I->first)((I->second)[J]);
748
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000749 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000750 // because they can contain DenseMaps.
751 for (llvm::DenseMap<const ObjCContainerDecl*,
752 const ASTRecordLayout*>::iterator
753 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
754 // Increment in loop to prevent using deallocated memory.
755 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
756 R->Destroy(*this);
757
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000758 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
759 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
760 // Increment in loop to prevent using deallocated memory.
761 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
762 R->Destroy(*this);
763 }
Douglas Gregor63200642010-08-30 16:49:28 +0000764
765 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
766 AEnd = DeclAttrs.end();
767 A != AEnd; ++A)
768 A->second->~AttrVec();
769}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000770
Douglas Gregor00545312010-05-23 18:26:36 +0000771void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000772 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000773}
774
Mike Stump1eb44332009-09-09 15:08:12 +0000775void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000776ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000777 ExternalSource.reset(Source.take());
778}
779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000781 llvm::errs() << "\n*** AST Context Stats:\n";
782 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000783
Douglas Gregordbe833d2009-05-26 14:40:08 +0000784 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000785#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786#define ABSTRACT_TYPE(Name, Parent)
787#include "clang/AST/TypeNodes.def"
788 0 // Extra
789 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
792 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000793 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 }
795
Douglas Gregordbe833d2009-05-26 14:40:08 +0000796 unsigned Idx = 0;
797 unsigned TotalBytes = 0;
798#define TYPE(Name, Parent) \
799 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << " " << counts[Idx] << " " << #Name \
801 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000802 TotalBytes += counts[Idx] * sizeof(Name##Type); \
803 ++Idx;
804#define ABSTRACT_TYPE(Name, Parent)
805#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Chandler Carruthcd92a652011-07-04 05:32:14 +0000807 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
808
Douglas Gregor4923aa22010-07-02 20:37:36 +0000809 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
811 << NumImplicitDefaultConstructors
812 << " implicit default constructors created\n";
813 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
814 << NumImplicitCopyConstructors
815 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
818 << NumImplicitMoveConstructors
819 << " implicit move constructors created\n";
820 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
821 << NumImplicitCopyAssignmentOperators
822 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000823 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000824 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
825 << NumImplicitMoveAssignmentOperators
826 << " implicit move assignment operators created\n";
827 llvm::errs() << NumImplicitDestructorsDeclared << "/"
828 << NumImplicitDestructors
829 << " implicit destructors created\n";
830
Douglas Gregor2cf26342009-04-09 22:27:44 +0000831 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000832 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000833 ExternalSource->PrintStats();
834 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000835
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000836 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000837}
838
Douglas Gregor772eeae2011-08-12 06:49:56 +0000839TypedefDecl *ASTContext::getInt128Decl() const {
840 if (!Int128Decl) {
841 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
842 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
843 getTranslationUnitDecl(),
844 SourceLocation(),
845 SourceLocation(),
846 &Idents.get("__int128_t"),
847 TInfo);
848 }
849
850 return Int128Decl;
851}
852
853TypedefDecl *ASTContext::getUInt128Decl() const {
854 if (!UInt128Decl) {
855 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
856 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
857 getTranslationUnitDecl(),
858 SourceLocation(),
859 SourceLocation(),
860 &Idents.get("__uint128_t"),
861 TInfo);
862 }
863
864 return UInt128Decl;
865}
Reid Spencer5f016e22007-07-11 17:01:13 +0000866
Nico Webercac18ad2013-06-20 21:44:55 +0000867TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000868 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000869 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000870 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
871 TTK_Struct,
872 getTranslationUnitDecl(),
873 SourceLocation(),
874 SourceLocation(),
875 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000876 }
877
878 return Float128StubDecl;
879}
880
John McCalle27ec8a2009-10-23 23:03:21 +0000881void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000882 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000883 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000884 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000887void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
888 assert((!this->Target || this->Target == &Target) &&
889 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000892 this->Target = &Target;
893
894 ABI.reset(createCXXABI(Target));
895 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 // C99 6.2.5p19.
898 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // C99 6.2.5p2.
901 InitBuiltinType(BoolTy, BuiltinType::Bool);
902 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000903 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 InitBuiltinType(CharTy, BuiltinType::Char_S);
905 else
906 InitBuiltinType(CharTy, BuiltinType::Char_U);
907 // C99 6.2.5p4.
908 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
909 InitBuiltinType(ShortTy, BuiltinType::Short);
910 InitBuiltinType(IntTy, BuiltinType::Int);
911 InitBuiltinType(LongTy, BuiltinType::Long);
912 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 // C99 6.2.5p6.
915 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
916 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
917 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
918 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
919 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 // C99 6.2.5p10.
922 InitBuiltinType(FloatTy, BuiltinType::Float);
923 InitBuiltinType(DoubleTy, BuiltinType::Double);
924 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000925
Chris Lattner2df9ced2009-04-30 02:43:43 +0000926 // GNU extension, 128-bit integers.
927 InitBuiltinType(Int128Ty, BuiltinType::Int128);
928 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
929
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000930 // C++ 3.9.1p5
931 if (TargetInfo::isTypeSigned(Target.getWCharType()))
932 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
933 else // -fshort-wchar makes wchar_t be unsigned.
934 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
935 if (LangOpts.CPlusPlus && LangOpts.WChar)
936 WideCharTy = WCharTy;
937 else {
938 // C99 (or C++ using -fno-wchar).
939 WideCharTy = getFromTargetType(Target.getWCharType());
940 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000941
James Molloy392da482012-05-04 10:55:22 +0000942 WIntTy = getFromTargetType(Target.getWIntType());
943
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000944 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
945 InitBuiltinType(Char16Ty, BuiltinType::Char16);
946 else // C99
947 Char16Ty = getFromTargetType(Target.getChar16Type());
948
949 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
950 InitBuiltinType(Char32Ty, BuiltinType::Char32);
951 else // C99
952 Char32Ty = getFromTargetType(Target.getChar32Type());
953
Douglas Gregor898574e2008-12-05 23:32:09 +0000954 // Placeholder type for type-dependent expressions whose type is
955 // completely unknown. No code should ever check a type against
956 // DependentTy and users should never see it; however, it is here to
957 // help diagnose failures to properly check for type-dependent
958 // expressions.
959 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960
John McCall2a984ca2010-10-12 00:20:44 +0000961 // Placeholder type for functions.
962 InitBuiltinType(OverloadTy, BuiltinType::Overload);
963
John McCall864c0412011-04-26 20:42:42 +0000964 // Placeholder type for bound members.
965 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
966
John McCall3c3b7f92011-10-25 17:37:35 +0000967 // Placeholder type for pseudo-objects.
968 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
969
John McCall1de4d4e2011-04-07 08:22:57 +0000970 // "any" type; useful for debugger-like clients.
971 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
972
John McCall0ddaeb92011-10-17 18:09:15 +0000973 // Placeholder type for unbridged ARC casts.
974 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
975
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000976 // Placeholder type for builtin functions.
977 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
978
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 // C99 6.2.5p11.
980 FloatComplexTy = getComplexType(FloatTy);
981 DoubleComplexTy = getComplexType(DoubleTy);
982 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000983
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000984 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000985 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
986 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000987 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000988
989 if (LangOpts.OpenCL) {
990 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
991 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
992 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
993 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
994 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
995 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000996
Guy Benyei21f18c42013-02-07 10:55:47 +0000997 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000998 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000999 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001000
1001 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001002 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1003 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001006
1007 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001009 // void * type
1010 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001011
1012 // nullptr type (C++0x 2.14.7)
1013 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001014
1015 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1016 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001017
1018 // Builtin type used to help define __builtin_va_list.
1019 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001020}
1021
David Blaikied6471f72011-09-25 23:23:43 +00001022DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001023 return SourceMgr.getDiagnostics();
1024}
1025
Douglas Gregor63200642010-08-30 16:49:28 +00001026AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1027 AttrVec *&Result = DeclAttrs[D];
1028 if (!Result) {
1029 void *Mem = Allocate(sizeof(AttrVec));
1030 Result = new (Mem) AttrVec;
1031 }
1032
1033 return *Result;
1034}
1035
1036/// \brief Erase the attributes corresponding to the given declaration.
1037void ASTContext::eraseDeclAttrs(const Decl *D) {
1038 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1039 if (Pos != DeclAttrs.end()) {
1040 Pos->second->~AttrVec();
1041 DeclAttrs.erase(Pos);
1042 }
1043}
1044
Larisse Voufoef4579c2013-08-06 01:03:05 +00001045// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001046MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001047ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001048 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001049 return getTemplateOrSpecializationInfo(Var)
1050 .dyn_cast<MemberSpecializationInfo *>();
1051}
1052
1053ASTContext::TemplateOrSpecializationInfo
1054ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1055 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1056 TemplateOrInstantiation.find(Var);
1057 if (Pos == TemplateOrInstantiation.end())
1058 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregor7caa6822009-07-24 20:34:43 +00001060 return Pos->second;
1061}
1062
Mike Stump1eb44332009-09-09 15:08:12 +00001063void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001064ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001065 TemplateSpecializationKind TSK,
1066 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001067 assert(Inst->isStaticDataMember() && "Not a static data member");
1068 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001069 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1070 Tmpl, TSK, PointOfInstantiation));
1071}
1072
1073void
1074ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1075 TemplateOrSpecializationInfo TSI) {
1076 assert(!TemplateOrInstantiation[Inst] &&
1077 "Already noted what the variable was instantiated from");
1078 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001079}
1080
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001081FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1082 const FunctionDecl *FD){
1083 assert(FD && "Specialization is 0");
1084 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001085 = ClassScopeSpecializationPattern.find(FD);
1086 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001087 return 0;
1088
1089 return Pos->second;
1090}
1091
1092void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1093 FunctionDecl *Pattern) {
1094 assert(FD && "Specialization is 0");
1095 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001096 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001097}
1098
John McCall7ba107a2009-11-18 02:36:19 +00001099NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001100ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001101 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001102 = InstantiatedFromUsingDecl.find(UUD);
1103 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001104 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Anders Carlsson0d8df782009-08-29 19:37:28 +00001106 return Pos->second;
1107}
1108
1109void
John McCalled976492009-12-04 22:46:56 +00001110ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1111 assert((isa<UsingDecl>(Pattern) ||
1112 isa<UnresolvedUsingValueDecl>(Pattern) ||
1113 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1114 "pattern decl is not a using decl");
1115 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1116 InstantiatedFromUsingDecl[Inst] = Pattern;
1117}
1118
1119UsingShadowDecl *
1120ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1121 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1122 = InstantiatedFromUsingShadowDecl.find(Inst);
1123 if (Pos == InstantiatedFromUsingShadowDecl.end())
1124 return 0;
1125
1126 return Pos->second;
1127}
1128
1129void
1130ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1131 UsingShadowDecl *Pattern) {
1132 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1133 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001134}
1135
Anders Carlssond8b285f2009-09-01 04:26:58 +00001136FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1137 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1138 = InstantiatedFromUnnamedFieldDecl.find(Field);
1139 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1140 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Anders Carlssond8b285f2009-09-01 04:26:58 +00001142 return Pos->second;
1143}
1144
1145void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1146 FieldDecl *Tmpl) {
1147 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1148 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1149 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1150 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Anders Carlssond8b285f2009-09-01 04:26:58 +00001152 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1153}
1154
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001155ASTContext::overridden_cxx_method_iterator
1156ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1157 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001158 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001159 if (Pos == OverriddenMethods.end())
1160 return 0;
1161
1162 return Pos->second.begin();
1163}
1164
1165ASTContext::overridden_cxx_method_iterator
1166ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1167 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001168 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001169 if (Pos == OverriddenMethods.end())
1170 return 0;
1171
1172 return Pos->second.end();
1173}
1174
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001175unsigned
1176ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1177 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001178 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001179 if (Pos == OverriddenMethods.end())
1180 return 0;
1181
1182 return Pos->second.size();
1183}
1184
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001185void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1186 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001187 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001188 OverriddenMethods[Method].push_back(Overridden);
1189}
1190
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001191void ASTContext::getOverriddenMethods(
1192 const NamedDecl *D,
1193 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001194 assert(D);
1195
1196 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001197 Overridden.append(overridden_methods_begin(CXXMethod),
1198 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001199 return;
1200 }
1201
1202 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1203 if (!Method)
1204 return;
1205
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001206 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1207 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001208 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001209}
1210
Douglas Gregore6649772011-12-03 00:30:27 +00001211void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1212 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1213 assert(!Import->isFromASTFile() && "Non-local import declaration");
1214 if (!FirstLocalImport) {
1215 FirstLocalImport = Import;
1216 LastLocalImport = Import;
1217 return;
1218 }
1219
1220 LastLocalImport->NextLocalImport = Import;
1221 LastLocalImport = Import;
1222}
1223
Chris Lattner464175b2007-07-18 17:52:12 +00001224//===----------------------------------------------------------------------===//
1225// Type Sizing and Analysis
1226//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001227
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001228/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1229/// scalar floating point type.
1230const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001231 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001232 assert(BT && "Not a floating point type!");
1233 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001234 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001235 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001236 case BuiltinType::Float: return Target->getFloatFormat();
1237 case BuiltinType::Double: return Target->getDoubleFormat();
1238 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001239 }
1240}
1241
Ken Dyck8b752f12010-01-27 17:10:57 +00001242/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001243/// specified decl. Note that bitfields do not have a valid alignment, so
1244/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001245/// If @p RefAsPointee, references are treated like their underlying type
1246/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001247CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001248 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001249
John McCall4081a5c2010-10-08 18:24:19 +00001250 bool UseAlignAttrOnly = false;
1251 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1252 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001253
John McCall4081a5c2010-10-08 18:24:19 +00001254 // __attribute__((aligned)) can increase or decrease alignment
1255 // *except* on a struct or struct member, where it only increases
1256 // alignment unless 'packed' is also specified.
1257 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001258 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001259 // ignore that possibility; Sema should diagnose it.
1260 if (isa<FieldDecl>(D)) {
1261 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1262 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1263 } else {
1264 UseAlignAttrOnly = true;
1265 }
1266 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001267 else if (isa<FieldDecl>(D))
1268 UseAlignAttrOnly =
1269 D->hasAttr<PackedAttr>() ||
1270 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001271
John McCallba4f5d52011-01-20 07:57:12 +00001272 // If we're using the align attribute only, just ignore everything
1273 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001274 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001275 // do nothing
1276
John McCall4081a5c2010-10-08 18:24:19 +00001277 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001278 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001279 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001280 if (RefAsPointee)
1281 T = RT->getPointeeType();
1282 else
1283 T = getPointerType(RT->getPointeeType());
1284 }
1285 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001286 // Adjust alignments of declarations with array type by the
1287 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001288 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001289 const ArrayType *arrayType;
1290 if (MinWidth && (arrayType = getAsArrayType(T))) {
1291 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001292 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001293 else if (isa<ConstantArrayType>(arrayType) &&
1294 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001295 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001296
John McCall3b657512011-01-19 10:06:00 +00001297 // Walk through any array types while we're at it.
1298 T = getBaseElementType(arrayType);
1299 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001300 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001301 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1302 if (VD->hasGlobalStorage())
1303 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1304 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001305 }
John McCallba4f5d52011-01-20 07:57:12 +00001306
1307 // Fields can be subject to extra alignment constraints, like if
1308 // the field is packed, the struct is packed, or the struct has a
1309 // a max-field-alignment constraint (#pragma pack). So calculate
1310 // the actual alignment of the field within the struct, and then
1311 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001312 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1313 const RecordDecl *Parent = Field->getParent();
1314 // We can only produce a sensible answer if the record is valid.
1315 if (!Parent->isInvalidDecl()) {
1316 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001317
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001318 // Start with the record's overall alignment.
1319 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001320
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001321 // Use the GCD of that and the offset within the record.
1322 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1323 if (Offset > 0) {
1324 // Alignment is always a power of 2, so the GCD will be a power of 2,
1325 // which means we get to do this crazy thing instead of Euclid's.
1326 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1327 if (LowBitOfOffset < FieldAlign)
1328 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1329 }
1330
1331 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001332 }
Charles Davis05f62472010-02-23 04:52:00 +00001333 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001334 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001335
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001336 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001337}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001338
John McCall929bbfb2012-08-21 04:10:00 +00001339// getTypeInfoDataSizeInChars - Return the size of a type, in
1340// chars. If the type is a record, its data size is returned. This is
1341// the size of the memcpy that's performed when assigning this type
1342// using a trivial copy/move assignment operator.
1343std::pair<CharUnits, CharUnits>
1344ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1345 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1346
1347 // In C++, objects can sometimes be allocated into the tail padding
1348 // of a base-class subobject. We decide whether that's possible
1349 // during class layout, so here we can just trust the layout results.
1350 if (getLangOpts().CPlusPlus) {
1351 if (const RecordType *RT = T->getAs<RecordType>()) {
1352 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1353 sizeAndAlign.first = layout.getDataSize();
1354 }
1355 }
1356
1357 return sizeAndAlign;
1358}
1359
Richard Trieu910f17e2013-05-14 21:59:17 +00001360/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1361/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1362std::pair<CharUnits, CharUnits>
1363static getConstantArrayInfoInChars(const ASTContext &Context,
1364 const ConstantArrayType *CAT) {
1365 std::pair<CharUnits, CharUnits> EltInfo =
1366 Context.getTypeInfoInChars(CAT->getElementType());
1367 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001368 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1369 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001370 "Overflow in array type char size evaluation");
1371 uint64_t Width = EltInfo.first.getQuantity() * Size;
1372 unsigned Align = EltInfo.second.getQuantity();
1373 Width = llvm::RoundUpToAlignment(Width, Align);
1374 return std::make_pair(CharUnits::fromQuantity(Width),
1375 CharUnits::fromQuantity(Align));
1376}
1377
John McCallea1471e2010-05-20 01:18:31 +00001378std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001379ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001380 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1381 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001382 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001383 return std::make_pair(toCharUnitsFromBits(Info.first),
1384 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001385}
1386
1387std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001388ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001389 return getTypeInfoInChars(T.getTypePtr());
1390}
1391
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001392std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1393 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1394 if (it != MemoizedTypeInfo.end())
1395 return it->second;
1396
1397 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1398 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1399 return Info;
1400}
1401
1402/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1403/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001404///
1405/// FIXME: Pointers into different addr spaces could have different sizes and
1406/// alignment requirements: getPointerInfo should take an AddrSpace, this
1407/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001408std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001409ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001410 uint64_t Width=0;
1411 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001412 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001413#define TYPE(Class, Base)
1414#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001415#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001416#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001417#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1418 case Type::Class: \
1419 assert(!T->isDependentType() && "should not see dependent types here"); \
1420 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001421#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001422 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001423
Chris Lattner692233e2007-07-13 22:27:08 +00001424 case Type::FunctionNoProto:
1425 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001426 // GCC extension: alignof(function) = 32 bits
1427 Width = 0;
1428 Align = 32;
1429 break;
1430
Douglas Gregor72564e72009-02-26 23:50:07 +00001431 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001432 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001433 Width = 0;
1434 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1435 break;
1436
Steve Narofffb22d962007-08-30 01:06:46 +00001437 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001438 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner98be4942008-03-05 18:54:05 +00001440 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001441 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001442 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1443 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001444 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001445 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001446 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001447 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001448 }
Nate Begeman213541a2008-04-18 23:10:10 +00001449 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001450 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001451 const VectorType *VT = cast<VectorType>(T);
1452 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1453 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001454 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001455 // If the alignment is not a power of 2, round up to the next power of 2.
1456 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001457 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001458 Align = llvm::NextPowerOf2(Align);
1459 Width = llvm::RoundUpToAlignment(Width, Align);
1460 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001461 // Adjust the alignment based on the target max.
1462 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1463 if (TargetVectorAlign && TargetVectorAlign < Align)
1464 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001465 break;
1466 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001467
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001468 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001469 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001470 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001471 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001472 // GCC extension: alignof(void) = 8 bits.
1473 Width = 0;
1474 Align = 8;
1475 break;
1476
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001477 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001478 Width = Target->getBoolWidth();
1479 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001480 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001481 case BuiltinType::Char_S:
1482 case BuiltinType::Char_U:
1483 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001484 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001485 Width = Target->getCharWidth();
1486 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001487 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001488 case BuiltinType::WChar_S:
1489 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001490 Width = Target->getWCharWidth();
1491 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001492 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001493 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001494 Width = Target->getChar16Width();
1495 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001496 break;
1497 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001498 Width = Target->getChar32Width();
1499 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001500 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001501 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001502 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getShortWidth();
1504 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001506 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001507 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001508 Width = Target->getIntWidth();
1509 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001511 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001512 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001513 Width = Target->getLongWidth();
1514 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001515 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001516 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001517 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001518 Width = Target->getLongLongWidth();
1519 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001521 case BuiltinType::Int128:
1522 case BuiltinType::UInt128:
1523 Width = 128;
1524 Align = 128; // int128_t is 128-bit aligned on all targets.
1525 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001526 case BuiltinType::Half:
1527 Width = Target->getHalfWidth();
1528 Align = Target->getHalfAlign();
1529 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001530 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001531 Width = Target->getFloatWidth();
1532 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001533 break;
1534 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getDoubleWidth();
1536 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001537 break;
1538 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001539 Width = Target->getLongDoubleWidth();
1540 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001541 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001542 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001543 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1544 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001545 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001546 case BuiltinType::ObjCId:
1547 case BuiltinType::ObjCClass:
1548 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001549 Width = Target->getPointerWidth(0);
1550 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001551 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001552 case BuiltinType::OCLSampler:
1553 // Samplers are modeled as integers.
1554 Width = Target->getIntWidth();
1555 Align = Target->getIntAlign();
1556 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001557 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001558 case BuiltinType::OCLImage1d:
1559 case BuiltinType::OCLImage1dArray:
1560 case BuiltinType::OCLImage1dBuffer:
1561 case BuiltinType::OCLImage2d:
1562 case BuiltinType::OCLImage2dArray:
1563 case BuiltinType::OCLImage3d:
1564 // Currently these types are pointers to opaque types.
1565 Width = Target->getPointerWidth(0);
1566 Align = Target->getPointerAlign(0);
1567 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001568 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001569 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001570 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001571 Width = Target->getPointerWidth(0);
1572 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001573 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001574 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001575 unsigned AS = getTargetAddressSpace(
1576 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001577 Width = Target->getPointerWidth(AS);
1578 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001579 break;
1580 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001581 case Type::LValueReference:
1582 case Type::RValueReference: {
1583 // alignof and sizeof should never enter this code path here, so we go
1584 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001585 unsigned AS = getTargetAddressSpace(
1586 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001587 Width = Target->getPointerWidth(AS);
1588 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001589 break;
1590 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001591 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001592 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001593 Width = Target->getPointerWidth(AS);
1594 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001595 break;
1596 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001597 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001598 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001599 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001600 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001601 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001602 case Type::Complex: {
1603 // Complex types have the same alignment as their elements, but twice the
1604 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001605 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001606 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001607 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001608 Align = EltInfo.second;
1609 break;
1610 }
John McCallc12c5bb2010-05-15 11:32:37 +00001611 case Type::ObjCObject:
1612 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001613 case Type::Decayed:
1614 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001615 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001616 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001617 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001618 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001619 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001620 break;
1621 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001622 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001623 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001624 const TagType *TT = cast<TagType>(T);
1625
1626 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001627 Width = 8;
1628 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001629 break;
1630 }
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Daniel Dunbar1d751182008-11-08 05:48:37 +00001632 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001633 return getTypeInfo(ET->getDecl()->getIntegerType());
1634
Daniel Dunbar1d751182008-11-08 05:48:37 +00001635 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001636 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001637 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001638 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001639 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001640 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001641
Chris Lattner9fcfe922009-10-22 05:17:15 +00001642 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001643 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1644 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001645
Richard Smith34b41d92011-02-20 03:19:35 +00001646 case Type::Auto: {
1647 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001648 assert(!A->getDeducedType().isNull() &&
1649 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001650 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001651 }
1652
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001653 case Type::Paren:
1654 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1655
Douglas Gregor18857642009-04-30 17:32:17 +00001656 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001657 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001658 std::pair<uint64_t, unsigned> Info
1659 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001660 // If the typedef has an aligned attribute on it, it overrides any computed
1661 // alignment we have. This violates the GCC documentation (which says that
1662 // attribute(aligned) can only round up) but matches its implementation.
1663 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1664 Align = AttrAlign;
1665 else
1666 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001667 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001668 break;
Chris Lattner71763312008-04-06 22:05:18 +00001669 }
Douglas Gregor18857642009-04-30 17:32:17 +00001670
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001671 case Type::Elaborated:
1672 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001673
John McCall9d156a72011-01-06 01:58:22 +00001674 case Type::Attributed:
1675 return getTypeInfo(
1676 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1677
Eli Friedmanb001de72011-10-06 23:00:33 +00001678 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001679 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001680 std::pair<uint64_t, unsigned> Info
1681 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1682 Width = Info.first;
1683 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001684
1685 // If the size of the type doesn't exceed the platform's max
1686 // atomic promotion width, make the size and alignment more
1687 // favorable to atomic operations:
1688 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1689 // Round the size up to a power of 2.
1690 if (!llvm::isPowerOf2_64(Width))
1691 Width = llvm::NextPowerOf2(Width);
1692
1693 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001694 Align = static_cast<unsigned>(Width);
1695 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001696 }
1697
Douglas Gregor18857642009-04-30 17:32:17 +00001698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Eli Friedman2be46072011-10-14 20:59:01 +00001700 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001701 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001702}
1703
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001704/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1705CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1706 return CharUnits::fromQuantity(BitSize / getCharWidth());
1707}
1708
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001709/// toBits - Convert a size in characters to a size in characters.
1710int64_t ASTContext::toBits(CharUnits CharSize) const {
1711 return CharSize.getQuantity() * getCharWidth();
1712}
1713
Ken Dyckbdc601b2009-12-22 14:23:30 +00001714/// getTypeSizeInChars - Return the size of the specified type, in characters.
1715/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001716CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001717 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001718}
Jay Foad4ba2a172011-01-12 09:06:06 +00001719CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001720 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001721}
1722
Ken Dyck16e20cc2010-01-26 17:25:18 +00001723/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001724/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001725CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001726 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001727}
Jay Foad4ba2a172011-01-12 09:06:06 +00001728CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001729 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001730}
1731
Chris Lattner34ebde42009-01-27 18:08:34 +00001732/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1733/// type for the current target in bits. This can be different than the ABI
1734/// alignment in cases where it is beneficial for performance to overalign
1735/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001736unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001737 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001738
1739 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001740 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001741 T = CT->getElementType().getTypePtr();
1742 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001743 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1744 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001745 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1746
Chris Lattner34ebde42009-01-27 18:08:34 +00001747 return ABIAlign;
1748}
1749
Ulrich Weigand6b203512013-05-06 16:23:57 +00001750/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1751/// to a global variable of the specified type.
1752unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1753 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1754}
1755
1756/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1757/// should be given to a global variable of the specified type.
1758CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1759 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1760}
1761
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001762/// DeepCollectObjCIvars -
1763/// This routine first collects all declared, but not synthesized, ivars in
1764/// super class and then collects all ivars, including those synthesized for
1765/// current class. This routine is used for implementation of current class
1766/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001767///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001768void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1769 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001770 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001771 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1772 DeepCollectObjCIvars(SuperClass, false, Ivars);
1773 if (!leafClass) {
1774 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1775 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001776 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001777 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001778 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001779 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001780 Iv= Iv->getNextIvar())
1781 Ivars.push_back(Iv);
1782 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001783}
1784
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001785/// CollectInheritedProtocols - Collect all protocols in current class and
1786/// those inherited by it.
1787void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001788 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001789 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001790 // We can use protocol_iterator here instead of
1791 // all_referenced_protocol_iterator since we are walking all categories.
1792 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1793 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001794 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001795 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001796 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001797 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001798 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001799 CollectInheritedProtocols(*P, Protocols);
1800 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001801 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001802
1803 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001804 for (ObjCInterfaceDecl::visible_categories_iterator
1805 Cat = OI->visible_categories_begin(),
1806 CatEnd = OI->visible_categories_end();
1807 Cat != CatEnd; ++Cat) {
1808 CollectInheritedProtocols(*Cat, Protocols);
1809 }
1810
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001811 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1812 while (SD) {
1813 CollectInheritedProtocols(SD, Protocols);
1814 SD = SD->getSuperClass();
1815 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001816 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001817 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001818 PE = OC->protocol_end(); P != PE; ++P) {
1819 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001820 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001821 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1822 PE = Proto->protocol_end(); P != PE; ++P)
1823 CollectInheritedProtocols(*P, Protocols);
1824 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001825 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001826 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1827 PE = OP->protocol_end(); P != PE; ++P) {
1828 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001829 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001830 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1831 PE = Proto->protocol_end(); P != PE; ++P)
1832 CollectInheritedProtocols(*P, Protocols);
1833 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001834 }
1835}
1836
Jay Foad4ba2a172011-01-12 09:06:06 +00001837unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001838 unsigned count = 0;
1839 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001840 for (ObjCInterfaceDecl::known_extensions_iterator
1841 Ext = OI->known_extensions_begin(),
1842 ExtEnd = OI->known_extensions_end();
1843 Ext != ExtEnd; ++Ext) {
1844 count += Ext->ivar_size();
1845 }
1846
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001847 // Count ivar defined in this class's implementation. This
1848 // includes synthesized ivars.
1849 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001850 count += ImplDecl->ivar_size();
1851
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001852 return count;
1853}
1854
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001855bool ASTContext::isSentinelNullExpr(const Expr *E) {
1856 if (!E)
1857 return false;
1858
1859 // nullptr_t is always treated as null.
1860 if (E->getType()->isNullPtrType()) return true;
1861
1862 if (E->getType()->isAnyPointerType() &&
1863 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1864 Expr::NPC_ValueDependentIsNull))
1865 return true;
1866
1867 // Unfortunately, __null has type 'int'.
1868 if (isa<GNUNullExpr>(E)) return true;
1869
1870 return false;
1871}
1872
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001873/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1874ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1875 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1876 I = ObjCImpls.find(D);
1877 if (I != ObjCImpls.end())
1878 return cast<ObjCImplementationDecl>(I->second);
1879 return 0;
1880}
1881/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1882ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1883 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1884 I = ObjCImpls.find(D);
1885 if (I != ObjCImpls.end())
1886 return cast<ObjCCategoryImplDecl>(I->second);
1887 return 0;
1888}
1889
1890/// \brief Set the implementation of ObjCInterfaceDecl.
1891void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1892 ObjCImplementationDecl *ImplD) {
1893 assert(IFaceD && ImplD && "Passed null params");
1894 ObjCImpls[IFaceD] = ImplD;
1895}
1896/// \brief Set the implementation of ObjCCategoryDecl.
1897void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1898 ObjCCategoryImplDecl *ImplD) {
1899 assert(CatD && ImplD && "Passed null params");
1900 ObjCImpls[CatD] = ImplD;
1901}
1902
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001903const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1904 const NamedDecl *ND) const {
1905 if (const ObjCInterfaceDecl *ID =
1906 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001907 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001908 if (const ObjCCategoryDecl *CD =
1909 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001910 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001911 if (const ObjCImplDecl *IMD =
1912 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001913 return IMD->getClassInterface();
1914
1915 return 0;
1916}
1917
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001918/// \brief Get the copy initialization expression of VarDecl,or NULL if
1919/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001920Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001921 assert(VD && "Passed null params");
1922 assert(VD->hasAttr<BlocksAttr>() &&
1923 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001924 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001925 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001926 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1927}
1928
1929/// \brief Set the copy inialization expression of a block var decl.
1930void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1931 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001932 assert(VD->hasAttr<BlocksAttr>() &&
1933 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001934 BlockVarCopyInits[VD] = Init;
1935}
1936
John McCalla93c9342009-12-07 02:54:59 +00001937TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001938 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001939 if (!DataSize)
1940 DataSize = TypeLoc::getFullDataSizeForType(T);
1941 else
1942 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001943 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001944
John McCalla93c9342009-12-07 02:54:59 +00001945 TypeSourceInfo *TInfo =
1946 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1947 new (TInfo) TypeSourceInfo(T);
1948 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001949}
1950
John McCalla93c9342009-12-07 02:54:59 +00001951TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001952 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001953 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001954 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001955 return DI;
1956}
1957
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001958const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001959ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001960 return getObjCLayout(D, 0);
1961}
1962
1963const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001964ASTContext::getASTObjCImplementationLayout(
1965 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001966 return getObjCLayout(D->getClassInterface(), D);
1967}
1968
Chris Lattnera7674d82007-07-13 22:13:22 +00001969//===----------------------------------------------------------------------===//
1970// Type creation/memoization methods
1971//===----------------------------------------------------------------------===//
1972
Jay Foad4ba2a172011-01-12 09:06:06 +00001973QualType
John McCall3b657512011-01-19 10:06:00 +00001974ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1975 unsigned fastQuals = quals.getFastQualifiers();
1976 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001977
1978 // Check if we've already instantiated this type.
1979 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001980 ExtQuals::Profile(ID, baseType, quals);
1981 void *insertPos = 0;
1982 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1983 assert(eq->getQualifiers() == quals);
1984 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001985 }
1986
John McCall3b657512011-01-19 10:06:00 +00001987 // If the base type is not canonical, make the appropriate canonical type.
1988 QualType canon;
1989 if (!baseType->isCanonicalUnqualified()) {
1990 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001991 canonSplit.Quals.addConsistentQualifiers(quals);
1992 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001993
1994 // Re-find the insert position.
1995 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1996 }
1997
1998 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1999 ExtQualNodes.InsertNode(eq, insertPos);
2000 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002001}
2002
Jay Foad4ba2a172011-01-12 09:06:06 +00002003QualType
2004ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002005 QualType CanT = getCanonicalType(T);
2006 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002007 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002008
John McCall0953e762009-09-24 19:53:00 +00002009 // If we are composing extended qualifiers together, merge together
2010 // into one ExtQuals node.
2011 QualifierCollector Quals;
2012 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
John McCall0953e762009-09-24 19:53:00 +00002014 // If this type already has an address space specified, it cannot get
2015 // another one.
2016 assert(!Quals.hasAddressSpace() &&
2017 "Type cannot be in multiple addr spaces!");
2018 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCall0953e762009-09-24 19:53:00 +00002020 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002021}
2022
Chris Lattnerb7d25532009-02-18 22:53:11 +00002023QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002024 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002025 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002026 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002027 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
John McCall7f040a92010-12-24 02:08:15 +00002029 if (const PointerType *ptr = T->getAs<PointerType>()) {
2030 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002031 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002032 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2033 return getPointerType(ResultType);
2034 }
2035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
John McCall0953e762009-09-24 19:53:00 +00002037 // If we are composing extended qualifiers together, merge together
2038 // into one ExtQuals node.
2039 QualifierCollector Quals;
2040 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCall0953e762009-09-24 19:53:00 +00002042 // If this type already has an ObjCGC specified, it cannot get
2043 // another one.
2044 assert(!Quals.hasObjCGCAttr() &&
2045 "Type cannot have multiple ObjCGCs!");
2046 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
John McCall0953e762009-09-24 19:53:00 +00002048 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002049}
Chris Lattnera7674d82007-07-13 22:13:22 +00002050
John McCalle6a365d2010-12-19 02:44:49 +00002051const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2052 FunctionType::ExtInfo Info) {
2053 if (T->getExtInfo() == Info)
2054 return T;
2055
2056 QualType Result;
2057 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2058 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2059 } else {
2060 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2061 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2062 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002063 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002064 }
2065
2066 return cast<FunctionType>(Result.getTypePtr());
2067}
2068
Richard Smith60e141e2013-05-04 07:00:32 +00002069void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2070 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002071 FD = FD->getMostRecentDecl();
2072 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002073 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2074 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2075 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002076 if (FunctionDecl *Next = FD->getPreviousDecl())
2077 FD = Next;
2078 else
2079 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002080 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002081 if (ASTMutationListener *L = getASTMutationListener())
2082 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002083}
2084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085/// getComplexType - Return the uniqued reference to the type for a complex
2086/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002087QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 // Unique pointers, to guarantee there is only one pointer of a particular
2089 // structure.
2090 llvm::FoldingSetNodeID ID;
2091 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 void *InsertPos = 0;
2094 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2095 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 // If the pointee type isn't canonical, this won't be a canonical type either,
2098 // so fill in the canonical type field.
2099 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002100 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002101 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // Get the new insert position for the node we care about.
2104 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002105 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 }
John McCall6b304a02009-09-24 23:30:46 +00002107 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 Types.push_back(New);
2109 ComplexTypes.InsertNode(New, InsertPos);
2110 return QualType(New, 0);
2111}
2112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113/// getPointerType - Return the uniqued reference to the type for a pointer to
2114/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002115QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // Unique pointers, to guarantee there is only one pointer of a particular
2117 // structure.
2118 llvm::FoldingSetNodeID ID;
2119 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 void *InsertPos = 0;
2122 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // If the pointee type isn't canonical, this won't be a canonical type either,
2126 // so fill in the canonical type field.
2127 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002128 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002129 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Bob Wilsonc90cc932013-03-15 17:12:43 +00002131 // Get the new insert position for the node we care about.
2132 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2133 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2134 }
John McCall6b304a02009-09-24 23:30:46 +00002135 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 Types.push_back(New);
2137 PointerTypes.InsertNode(New, InsertPos);
2138 return QualType(New, 0);
2139}
2140
Reid Kleckner12df2462013-06-24 17:51:48 +00002141QualType ASTContext::getDecayedType(QualType T) const {
2142 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2143
2144 llvm::FoldingSetNodeID ID;
2145 DecayedType::Profile(ID, T);
2146 void *InsertPos = 0;
2147 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2148 return QualType(DT, 0);
2149
2150 QualType Decayed;
2151
2152 // C99 6.7.5.3p7:
2153 // A declaration of a parameter as "array of type" shall be
2154 // adjusted to "qualified pointer to type", where the type
2155 // qualifiers (if any) are those specified within the [ and ] of
2156 // the array type derivation.
2157 if (T->isArrayType())
2158 Decayed = getArrayDecayedType(T);
2159
2160 // C99 6.7.5.3p8:
2161 // A declaration of a parameter as "function returning type"
2162 // shall be adjusted to "pointer to function returning type", as
2163 // in 6.3.2.1.
2164 if (T->isFunctionType())
2165 Decayed = getPointerType(T);
2166
2167 QualType Canonical = getCanonicalType(Decayed);
2168
2169 // Get the new insert position for the node we care about.
2170 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2171 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2172
2173 DecayedType *New =
2174 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2175 Types.push_back(New);
2176 DecayedTypes.InsertNode(New, InsertPos);
2177 return QualType(New, 0);
2178}
2179
Mike Stump1eb44332009-09-09 15:08:12 +00002180/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002181/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002182QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002183 assert(T->isFunctionType() && "block of function types only");
2184 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002185 // structure.
2186 llvm::FoldingSetNodeID ID;
2187 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Steve Naroff5618bd42008-08-27 16:04:49 +00002189 void *InsertPos = 0;
2190 if (BlockPointerType *PT =
2191 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2192 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
2194 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002195 // type either so fill in the canonical type field.
2196 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002197 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002198 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Steve Naroff5618bd42008-08-27 16:04:49 +00002200 // Get the new insert position for the node we care about.
2201 BlockPointerType *NewIP =
2202 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002203 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002204 }
John McCall6b304a02009-09-24 23:30:46 +00002205 BlockPointerType *New
2206 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002207 Types.push_back(New);
2208 BlockPointerTypes.InsertNode(New, InsertPos);
2209 return QualType(New, 0);
2210}
2211
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002212/// getLValueReferenceType - Return the uniqued reference to the type for an
2213/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002214QualType
2215ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002216 assert(getCanonicalType(T) != OverloadTy &&
2217 "Unresolved overloaded function type");
2218
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 // Unique pointers, to guarantee there is only one pointer of a particular
2220 // structure.
2221 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002222 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002223
2224 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002225 if (LValueReferenceType *RT =
2226 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002228
John McCall54e14c42009-10-22 22:37:11 +00002229 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2230
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 // If the referencee type isn't canonical, this won't be a canonical type
2232 // either, so fill in the canonical type field.
2233 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002234 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2235 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2236 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002237
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002239 LValueReferenceType *NewIP =
2240 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002241 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 }
2243
John McCall6b304a02009-09-24 23:30:46 +00002244 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002245 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2246 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002248 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002249
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002250 return QualType(New, 0);
2251}
2252
2253/// getRValueReferenceType - Return the uniqued reference to the type for an
2254/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002255QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002256 // Unique pointers, to guarantee there is only one pointer of a particular
2257 // structure.
2258 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002259 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002260
2261 void *InsertPos = 0;
2262 if (RValueReferenceType *RT =
2263 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2264 return QualType(RT, 0);
2265
John McCall54e14c42009-10-22 22:37:11 +00002266 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2267
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002268 // If the referencee type isn't canonical, this won't be a canonical type
2269 // either, so fill in the canonical type field.
2270 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002271 if (InnerRef || !T.isCanonical()) {
2272 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2273 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002274
2275 // Get the new insert position for the node we care about.
2276 RValueReferenceType *NewIP =
2277 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002278 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002279 }
2280
John McCall6b304a02009-09-24 23:30:46 +00002281 RValueReferenceType *New
2282 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002283 Types.push_back(New);
2284 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 return QualType(New, 0);
2286}
2287
Sebastian Redlf30208a2009-01-24 21:16:55 +00002288/// getMemberPointerType - Return the uniqued reference to the type for a
2289/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002290QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002291 // Unique pointers, to guarantee there is only one pointer of a particular
2292 // structure.
2293 llvm::FoldingSetNodeID ID;
2294 MemberPointerType::Profile(ID, T, Cls);
2295
2296 void *InsertPos = 0;
2297 if (MemberPointerType *PT =
2298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2299 return QualType(PT, 0);
2300
2301 // If the pointee or class type isn't canonical, this won't be a canonical
2302 // type either, so fill in the canonical type field.
2303 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002304 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002305 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2306
2307 // Get the new insert position for the node we care about.
2308 MemberPointerType *NewIP =
2309 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002310 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002311 }
John McCall6b304a02009-09-24 23:30:46 +00002312 MemberPointerType *New
2313 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002314 Types.push_back(New);
2315 MemberPointerTypes.InsertNode(New, InsertPos);
2316 return QualType(New, 0);
2317}
2318
Mike Stump1eb44332009-09-09 15:08:12 +00002319/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002320/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002321QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002322 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002323 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002324 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002325 assert((EltTy->isDependentType() ||
2326 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002327 "Constant array of VLAs is illegal!");
2328
Chris Lattner38aeec72009-05-13 04:12:56 +00002329 // Convert the array size into a canonical width matching the pointer size for
2330 // the target.
2331 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002332 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002333 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002336 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002339 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002340 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002342
John McCall3b657512011-01-19 10:06:00 +00002343 // If the element type isn't canonical or has qualifiers, this won't
2344 // be a canonical type either, so fill in the canonical type field.
2345 QualType Canon;
2346 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2347 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002348 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002349 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002350 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002353 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002354 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002355 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 }
Mike Stump1eb44332009-09-09 15:08:12 +00002357
John McCall6b304a02009-09-24 23:30:46 +00002358 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002359 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002360 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 Types.push_back(New);
2362 return QualType(New, 0);
2363}
2364
John McCallce889032011-01-18 08:40:38 +00002365/// getVariableArrayDecayedType - Turns the given type, which may be
2366/// variably-modified, into the corresponding type with all the known
2367/// sizes replaced with [*].
2368QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2369 // Vastly most common case.
2370 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002371
John McCallce889032011-01-18 08:40:38 +00002372 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002373
John McCallce889032011-01-18 08:40:38 +00002374 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002375 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002376 switch (ty->getTypeClass()) {
2377#define TYPE(Class, Base)
2378#define ABSTRACT_TYPE(Class, Base)
2379#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2380#include "clang/AST/TypeNodes.def"
2381 llvm_unreachable("didn't desugar past all non-canonical types?");
2382
2383 // These types should never be variably-modified.
2384 case Type::Builtin:
2385 case Type::Complex:
2386 case Type::Vector:
2387 case Type::ExtVector:
2388 case Type::DependentSizedExtVector:
2389 case Type::ObjCObject:
2390 case Type::ObjCInterface:
2391 case Type::ObjCObjectPointer:
2392 case Type::Record:
2393 case Type::Enum:
2394 case Type::UnresolvedUsing:
2395 case Type::TypeOfExpr:
2396 case Type::TypeOf:
2397 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002398 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002399 case Type::DependentName:
2400 case Type::InjectedClassName:
2401 case Type::TemplateSpecialization:
2402 case Type::DependentTemplateSpecialization:
2403 case Type::TemplateTypeParm:
2404 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002405 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002406 case Type::PackExpansion:
2407 llvm_unreachable("type should never be variably-modified");
2408
2409 // These types can be variably-modified but should never need to
2410 // further decay.
2411 case Type::FunctionNoProto:
2412 case Type::FunctionProto:
2413 case Type::BlockPointer:
2414 case Type::MemberPointer:
2415 return type;
2416
2417 // These types can be variably-modified. All these modifications
2418 // preserve structure except as noted by comments.
2419 // TODO: if we ever care about optimizing VLAs, there are no-op
2420 // optimizations available here.
2421 case Type::Pointer:
2422 result = getPointerType(getVariableArrayDecayedType(
2423 cast<PointerType>(ty)->getPointeeType()));
2424 break;
2425
2426 case Type::LValueReference: {
2427 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2428 result = getLValueReferenceType(
2429 getVariableArrayDecayedType(lv->getPointeeType()),
2430 lv->isSpelledAsLValue());
2431 break;
2432 }
2433
2434 case Type::RValueReference: {
2435 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2436 result = getRValueReferenceType(
2437 getVariableArrayDecayedType(lv->getPointeeType()));
2438 break;
2439 }
2440
Eli Friedmanb001de72011-10-06 23:00:33 +00002441 case Type::Atomic: {
2442 const AtomicType *at = cast<AtomicType>(ty);
2443 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2444 break;
2445 }
2446
John McCallce889032011-01-18 08:40:38 +00002447 case Type::ConstantArray: {
2448 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2449 result = getConstantArrayType(
2450 getVariableArrayDecayedType(cat->getElementType()),
2451 cat->getSize(),
2452 cat->getSizeModifier(),
2453 cat->getIndexTypeCVRQualifiers());
2454 break;
2455 }
2456
2457 case Type::DependentSizedArray: {
2458 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2459 result = getDependentSizedArrayType(
2460 getVariableArrayDecayedType(dat->getElementType()),
2461 dat->getSizeExpr(),
2462 dat->getSizeModifier(),
2463 dat->getIndexTypeCVRQualifiers(),
2464 dat->getBracketsRange());
2465 break;
2466 }
2467
2468 // Turn incomplete types into [*] types.
2469 case Type::IncompleteArray: {
2470 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2471 result = getVariableArrayType(
2472 getVariableArrayDecayedType(iat->getElementType()),
2473 /*size*/ 0,
2474 ArrayType::Normal,
2475 iat->getIndexTypeCVRQualifiers(),
2476 SourceRange());
2477 break;
2478 }
2479
2480 // Turn VLA types into [*] types.
2481 case Type::VariableArray: {
2482 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2483 result = getVariableArrayType(
2484 getVariableArrayDecayedType(vat->getElementType()),
2485 /*size*/ 0,
2486 ArrayType::Star,
2487 vat->getIndexTypeCVRQualifiers(),
2488 vat->getBracketsRange());
2489 break;
2490 }
2491 }
2492
2493 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002494 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002495}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002496
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002497/// getVariableArrayType - Returns a non-unique reference to the type for a
2498/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002499QualType ASTContext::getVariableArrayType(QualType EltTy,
2500 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002501 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002502 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002503 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002504 // Since we don't unique expressions, it isn't possible to unique VLA's
2505 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002506 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002507
John McCall3b657512011-01-19 10:06:00 +00002508 // Be sure to pull qualifiers off the element type.
2509 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2510 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002511 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002512 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002513 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002514 }
2515
John McCall6b304a02009-09-24 23:30:46 +00002516 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002517 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002518
2519 VariableArrayTypes.push_back(New);
2520 Types.push_back(New);
2521 return QualType(New, 0);
2522}
2523
Douglas Gregor898574e2008-12-05 23:32:09 +00002524/// getDependentSizedArrayType - Returns a non-unique reference to
2525/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002526/// type.
John McCall3b657512011-01-19 10:06:00 +00002527QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2528 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002529 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002530 unsigned elementTypeQuals,
2531 SourceRange brackets) const {
2532 assert((!numElements || numElements->isTypeDependent() ||
2533 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002534 "Size must be type- or value-dependent!");
2535
John McCall3b657512011-01-19 10:06:00 +00002536 // Dependently-sized array types that do not have a specified number
2537 // of elements will have their sizes deduced from a dependent
2538 // initializer. We do no canonicalization here at all, which is okay
2539 // because they can't be used in most locations.
2540 if (!numElements) {
2541 DependentSizedArrayType *newType
2542 = new (*this, TypeAlignment)
2543 DependentSizedArrayType(*this, elementType, QualType(),
2544 numElements, ASM, elementTypeQuals,
2545 brackets);
2546 Types.push_back(newType);
2547 return QualType(newType, 0);
2548 }
2549
2550 // Otherwise, we actually build a new type every time, but we
2551 // also build a canonical type.
2552
2553 SplitQualType canonElementType = getCanonicalType(elementType).split();
2554
2555 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002556 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002557 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002558 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002559 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002560
John McCall3b657512011-01-19 10:06:00 +00002561 // Look for an existing type with these properties.
2562 DependentSizedArrayType *canonTy =
2563 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002564
John McCall3b657512011-01-19 10:06:00 +00002565 // If we don't have one, build one.
2566 if (!canonTy) {
2567 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002568 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002569 QualType(), numElements, ASM, elementTypeQuals,
2570 brackets);
2571 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2572 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002573 }
2574
John McCall3b657512011-01-19 10:06:00 +00002575 // Apply qualifiers from the element type to the array.
2576 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002577 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002578
John McCall3b657512011-01-19 10:06:00 +00002579 // If we didn't need extra canonicalization for the element type,
2580 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002581 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002582 return canon;
2583
2584 // Otherwise, we need to build a type which follows the spelling
2585 // of the element type.
2586 DependentSizedArrayType *sugaredType
2587 = new (*this, TypeAlignment)
2588 DependentSizedArrayType(*this, elementType, canon, numElements,
2589 ASM, elementTypeQuals, brackets);
2590 Types.push_back(sugaredType);
2591 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002592}
2593
John McCall3b657512011-01-19 10:06:00 +00002594QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002595 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002596 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002597 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002598 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002599
John McCall3b657512011-01-19 10:06:00 +00002600 void *insertPos = 0;
2601 if (IncompleteArrayType *iat =
2602 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2603 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002604
2605 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002606 // either, so fill in the canonical type field. We also have to pull
2607 // qualifiers off the element type.
2608 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002609
John McCall3b657512011-01-19 10:06:00 +00002610 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2611 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002612 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002613 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002614 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002615
2616 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002617 IncompleteArrayType *existing =
2618 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2619 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002620 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002621
John McCall3b657512011-01-19 10:06:00 +00002622 IncompleteArrayType *newType = new (*this, TypeAlignment)
2623 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002624
John McCall3b657512011-01-19 10:06:00 +00002625 IncompleteArrayTypes.InsertNode(newType, insertPos);
2626 Types.push_back(newType);
2627 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002628}
2629
Steve Naroff73322922007-07-18 18:00:27 +00002630/// getVectorType - Return the unique reference to a vector type of
2631/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002632QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002633 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002634 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 // Check if we've already instantiated a vector of this type.
2637 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002638 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002639
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 void *InsertPos = 0;
2641 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2642 return QualType(VTP, 0);
2643
2644 // If the element type isn't canonical, this won't be a canonical type either,
2645 // so fill in the canonical type field.
2646 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002647 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002648 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 // Get the new insert position for the node we care about.
2651 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002652 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 }
John McCall6b304a02009-09-24 23:30:46 +00002654 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002655 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 VectorTypes.InsertNode(New, InsertPos);
2657 Types.push_back(New);
2658 return QualType(New, 0);
2659}
2660
Nate Begeman213541a2008-04-18 23:10:10 +00002661/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002662/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002663QualType
2664ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002665 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Steve Naroff73322922007-07-18 18:00:27 +00002667 // Check if we've already instantiated a vector of this type.
2668 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002669 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002670 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002671 void *InsertPos = 0;
2672 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2673 return QualType(VTP, 0);
2674
2675 // If the element type isn't canonical, this won't be a canonical type either,
2676 // so fill in the canonical type field.
2677 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002678 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002679 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Steve Naroff73322922007-07-18 18:00:27 +00002681 // Get the new insert position for the node we care about.
2682 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002683 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002684 }
John McCall6b304a02009-09-24 23:30:46 +00002685 ExtVectorType *New = new (*this, TypeAlignment)
2686 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002687 VectorTypes.InsertNode(New, InsertPos);
2688 Types.push_back(New);
2689 return QualType(New, 0);
2690}
2691
Jay Foad4ba2a172011-01-12 09:06:06 +00002692QualType
2693ASTContext::getDependentSizedExtVectorType(QualType vecType,
2694 Expr *SizeExpr,
2695 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002696 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002697 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002698 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002700 void *InsertPos = 0;
2701 DependentSizedExtVectorType *Canon
2702 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2703 DependentSizedExtVectorType *New;
2704 if (Canon) {
2705 // We already have a canonical version of this array type; use it as
2706 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002707 New = new (*this, TypeAlignment)
2708 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2709 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002710 } else {
2711 QualType CanonVecTy = getCanonicalType(vecType);
2712 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002713 New = new (*this, TypeAlignment)
2714 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2715 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002716
2717 DependentSizedExtVectorType *CanonCheck
2718 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2719 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2720 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002721 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2722 } else {
2723 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2724 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002725 New = new (*this, TypeAlignment)
2726 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002727 }
2728 }
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002730 Types.push_back(New);
2731 return QualType(New, 0);
2732}
2733
Douglas Gregor72564e72009-02-26 23:50:07 +00002734/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002735///
Jay Foad4ba2a172011-01-12 09:06:06 +00002736QualType
2737ASTContext::getFunctionNoProtoType(QualType ResultTy,
2738 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002739 const CallingConv DefaultCC = Info.getCC();
2740 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2741 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 // Unique functions, to guarantee there is only one function of a particular
2743 // structure.
2744 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002745 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002748 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002749 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002753 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002754 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002755 Canonical =
2756 getFunctionNoProtoType(getCanonicalType(ResultTy),
2757 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002760 FunctionNoProtoType *NewIP =
2761 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002762 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 }
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Roman Divackycfe9af22011-03-01 17:40:53 +00002765 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002766 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002767 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002769 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 return QualType(New, 0);
2771}
2772
Douglas Gregor02dd7982013-01-17 23:36:45 +00002773/// \brief Determine whether \p T is canonical as the result type of a function.
2774static bool isCanonicalResultType(QualType T) {
2775 return T.isCanonical() &&
2776 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2777 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2778}
2779
Reid Spencer5f016e22007-07-11 17:01:13 +00002780/// getFunctionType - Return a normal function type with a typed argument
2781/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002782QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002783ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002784 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002785 size_t NumArgs = ArgArray.size();
2786
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 // Unique functions, to guarantee there is only one function of a particular
2788 // structure.
2789 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002790 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2791 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002792
2793 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002794 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002795 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002797
2798 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002799 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002800 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002801 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002803 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 isCanonical = false;
2805
Roman Divackycfe9af22011-03-01 17:40:53 +00002806 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2807 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2808 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002809
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002811 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002813 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002814 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 CanonicalArgs.reserve(NumArgs);
2816 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002817 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002818
John McCalle23cf432010-12-14 08:05:40 +00002819 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002820 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002821 CanonicalEPI.ExceptionSpecType = EST_None;
2822 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002823 CanonicalEPI.ExtInfo
2824 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2825
Douglas Gregor02dd7982013-01-17 23:36:45 +00002826 // Result types do not have ARC lifetime qualifiers.
2827 QualType CanResultTy = getCanonicalType(ResultTy);
2828 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2829 Qualifiers Qs = CanResultTy.getQualifiers();
2830 Qs.removeObjCLifetime();
2831 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2832 }
2833
Jordan Rosebea522f2013-03-08 21:51:21 +00002834 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002835
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002837 FunctionProtoType *NewIP =
2838 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002839 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002841
John McCallf85e1932011-06-15 23:02:42 +00002842 // FunctionProtoType objects are allocated with extra bytes after
2843 // them for three variable size arrays at the end:
2844 // - parameter types
2845 // - exception types
2846 // - consumed-arguments flags
2847 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002848 // expression, or information used to resolve the exception
2849 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002850 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002851 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002852 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002853 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002854 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002855 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002856 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002857 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002858 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2859 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002860 }
John McCallf85e1932011-06-15 23:02:42 +00002861 if (EPI.ConsumedArguments)
2862 Size += NumArgs * sizeof(bool);
2863
John McCalle23cf432010-12-14 08:05:40 +00002864 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002865 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2866 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002867 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002869 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 return QualType(FTP, 0);
2871}
2872
John McCall3cb0ebd2010-03-10 03:28:59 +00002873#ifndef NDEBUG
2874static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2875 if (!isa<CXXRecordDecl>(D)) return false;
2876 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2877 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2878 return true;
2879 if (RD->getDescribedClassTemplate() &&
2880 !isa<ClassTemplateSpecializationDecl>(RD))
2881 return true;
2882 return false;
2883}
2884#endif
2885
2886/// getInjectedClassNameType - Return the unique reference to the
2887/// injected class name type for the specified templated declaration.
2888QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002889 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002890 assert(NeedsInjectedClassNameType(Decl));
2891 if (Decl->TypeForDecl) {
2892 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002893 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002894 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2895 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2896 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2897 } else {
John McCallf4c73712011-01-19 06:33:43 +00002898 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002899 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002900 Decl->TypeForDecl = newType;
2901 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002902 }
2903 return QualType(Decl->TypeForDecl, 0);
2904}
2905
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002906/// getTypeDeclType - Return the unique reference to the type for the
2907/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002908QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002909 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002910 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Richard Smith162e1c12011-04-15 14:24:37 +00002912 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002913 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002914
John McCallbecb8d52010-03-10 06:48:02 +00002915 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2916 "Template type parameter types are always available.");
2917
John McCall19c85762010-02-16 03:57:14 +00002918 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002919 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002920 "struct/union has previous declaration");
2921 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002922 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002923 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002924 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002925 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002926 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002927 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002928 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002929 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2930 Decl->TypeForDecl = newType;
2931 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002932 } else
John McCallbecb8d52010-03-10 06:48:02 +00002933 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002934
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002935 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002936}
2937
Reid Spencer5f016e22007-07-11 17:01:13 +00002938/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002939/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002940QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002941ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2942 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002943 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002945 if (Canonical.isNull())
2946 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002947 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002948 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002949 Decl->TypeForDecl = newType;
2950 Types.push_back(newType);
2951 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002952}
2953
Jay Foad4ba2a172011-01-12 09:06:06 +00002954QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002955 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2956
Douglas Gregoref96ee02012-01-14 16:38:05 +00002957 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002958 if (PrevDecl->TypeForDecl)
2959 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2960
John McCallf4c73712011-01-19 06:33:43 +00002961 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2962 Decl->TypeForDecl = newType;
2963 Types.push_back(newType);
2964 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002965}
2966
Jay Foad4ba2a172011-01-12 09:06:06 +00002967QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002968 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2969
Douglas Gregoref96ee02012-01-14 16:38:05 +00002970 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002971 if (PrevDecl->TypeForDecl)
2972 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2973
John McCallf4c73712011-01-19 06:33:43 +00002974 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2975 Decl->TypeForDecl = newType;
2976 Types.push_back(newType);
2977 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002978}
2979
John McCall9d156a72011-01-06 01:58:22 +00002980QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2981 QualType modifiedType,
2982 QualType equivalentType) {
2983 llvm::FoldingSetNodeID id;
2984 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2985
2986 void *insertPos = 0;
2987 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2988 if (type) return QualType(type, 0);
2989
2990 QualType canon = getCanonicalType(equivalentType);
2991 type = new (*this, TypeAlignment)
2992 AttributedType(canon, attrKind, modifiedType, equivalentType);
2993
2994 Types.push_back(type);
2995 AttributedTypes.InsertNode(type, insertPos);
2996
2997 return QualType(type, 0);
2998}
2999
3000
John McCall49a832b2009-10-18 09:09:24 +00003001/// \brief Retrieve a substitution-result type.
3002QualType
3003ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00003004 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00003005 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00003006 && "replacement types must always be canonical");
3007
3008 llvm::FoldingSetNodeID ID;
3009 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3010 void *InsertPos = 0;
3011 SubstTemplateTypeParmType *SubstParm
3012 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3013
3014 if (!SubstParm) {
3015 SubstParm = new (*this, TypeAlignment)
3016 SubstTemplateTypeParmType(Parm, Replacement);
3017 Types.push_back(SubstParm);
3018 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3019 }
3020
3021 return QualType(SubstParm, 0);
3022}
3023
Douglas Gregorc3069d62011-01-14 02:55:32 +00003024/// \brief Retrieve a
3025QualType ASTContext::getSubstTemplateTypeParmPackType(
3026 const TemplateTypeParmType *Parm,
3027 const TemplateArgument &ArgPack) {
3028#ifndef NDEBUG
3029 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3030 PEnd = ArgPack.pack_end();
3031 P != PEnd; ++P) {
3032 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3033 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3034 }
3035#endif
3036
3037 llvm::FoldingSetNodeID ID;
3038 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3039 void *InsertPos = 0;
3040 if (SubstTemplateTypeParmPackType *SubstParm
3041 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3042 return QualType(SubstParm, 0);
3043
3044 QualType Canon;
3045 if (!Parm->isCanonicalUnqualified()) {
3046 Canon = getCanonicalType(QualType(Parm, 0));
3047 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3048 ArgPack);
3049 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3050 }
3051
3052 SubstTemplateTypeParmPackType *SubstParm
3053 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3054 ArgPack);
3055 Types.push_back(SubstParm);
3056 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3057 return QualType(SubstParm, 0);
3058}
3059
Douglas Gregorfab9d672009-02-05 23:33:38 +00003060/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003061/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003062/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003063QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003064 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003065 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003066 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003067 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003068 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003069 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003070 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3071
3072 if (TypeParm)
3073 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003075 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003076 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003077 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003078
3079 TemplateTypeParmType *TypeCheck
3080 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 assert(!TypeCheck && "Template type parameter canonical type broken");
3082 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003083 } else
John McCall6b304a02009-09-24 23:30:46 +00003084 TypeParm = new (*this, TypeAlignment)
3085 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003086
3087 Types.push_back(TypeParm);
3088 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3089
3090 return QualType(TypeParm, 0);
3091}
3092
John McCall3cb0ebd2010-03-10 03:28:59 +00003093TypeSourceInfo *
3094ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3095 SourceLocation NameLoc,
3096 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003097 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003098 assert(!Name.getAsDependentTemplateName() &&
3099 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003100 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003101
3102 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003103 TemplateSpecializationTypeLoc TL =
3104 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003105 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003106 TL.setTemplateNameLoc(NameLoc);
3107 TL.setLAngleLoc(Args.getLAngleLoc());
3108 TL.setRAngleLoc(Args.getRAngleLoc());
3109 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3110 TL.setArgLocInfo(i, Args[i].getLocInfo());
3111 return DI;
3112}
3113
Mike Stump1eb44332009-09-09 15:08:12 +00003114QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003115ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003116 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003117 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003118 assert(!Template.getAsDependentTemplateName() &&
3119 "No dependent template names here!");
3120
John McCalld5532b62009-11-23 01:53:49 +00003121 unsigned NumArgs = Args.size();
3122
Chris Lattner5f9e2722011-07-23 10:55:15 +00003123 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003124 ArgVec.reserve(NumArgs);
3125 for (unsigned i = 0; i != NumArgs; ++i)
3126 ArgVec.push_back(Args[i].getArgument());
3127
John McCall31f17ec2010-04-27 00:57:59 +00003128 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003129 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003130}
3131
Douglas Gregorb70126a2012-02-03 17:16:23 +00003132#ifndef NDEBUG
3133static bool hasAnyPackExpansions(const TemplateArgument *Args,
3134 unsigned NumArgs) {
3135 for (unsigned I = 0; I != NumArgs; ++I)
3136 if (Args[I].isPackExpansion())
3137 return true;
3138
3139 return true;
3140}
3141#endif
3142
John McCall833ca992009-10-29 08:12:44 +00003143QualType
3144ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003145 const TemplateArgument *Args,
3146 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003147 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003148 assert(!Template.getAsDependentTemplateName() &&
3149 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003150 // Look through qualified template names.
3151 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3152 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003153
Douglas Gregorb70126a2012-02-03 17:16:23 +00003154 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003155 Template.getAsTemplateDecl() &&
3156 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003157 QualType CanonType;
3158 if (!Underlying.isNull())
3159 CanonType = getCanonicalType(Underlying);
3160 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003161 // We can get here with an alias template when the specialization contains
3162 // a pack expansion that does not match up with a parameter pack.
3163 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3164 "Caller must compute aliased type");
3165 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003166 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3167 NumArgs);
3168 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003169
Douglas Gregor1275ae02009-07-28 23:00:59 +00003170 // Allocate the (non-canonical) template specialization type, but don't
3171 // try to unique it: these types typically have location information that
3172 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003173 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3174 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003175 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003176 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003177 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003178 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3179 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Douglas Gregor55f6b142009-02-09 18:46:07 +00003181 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003182 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003183}
3184
Mike Stump1eb44332009-09-09 15:08:12 +00003185QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003186ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3187 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003188 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003189 assert(!Template.getAsDependentTemplateName() &&
3190 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003191
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003192 // Look through qualified template names.
3193 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3194 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003195
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003196 // Build the canonical template specialization type.
3197 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003198 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003199 CanonArgs.reserve(NumArgs);
3200 for (unsigned I = 0; I != NumArgs; ++I)
3201 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3202
3203 // Determine whether this canonical template specialization type already
3204 // exists.
3205 llvm::FoldingSetNodeID ID;
3206 TemplateSpecializationType::Profile(ID, CanonTemplate,
3207 CanonArgs.data(), NumArgs, *this);
3208
3209 void *InsertPos = 0;
3210 TemplateSpecializationType *Spec
3211 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3212
3213 if (!Spec) {
3214 // Allocate a new canonical template specialization type.
3215 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3216 sizeof(TemplateArgument) * NumArgs),
3217 TypeAlignment);
3218 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3219 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003220 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003221 Types.push_back(Spec);
3222 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3223 }
3224
3225 assert(Spec->isDependentType() &&
3226 "Non-dependent template-id type must have a canonical type");
3227 return QualType(Spec, 0);
3228}
3229
3230QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003231ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3232 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003233 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003234 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003235 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003236
3237 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003238 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003239 if (T)
3240 return QualType(T, 0);
3241
Douglas Gregor789b1f62010-02-04 18:10:26 +00003242 QualType Canon = NamedType;
3243 if (!Canon.isCanonical()) {
3244 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003245 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003247 (void)CheckT;
3248 }
3249
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003250 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003251 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003252 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003253 return QualType(T, 0);
3254}
3255
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003256QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003257ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003258 llvm::FoldingSetNodeID ID;
3259 ParenType::Profile(ID, InnerType);
3260
3261 void *InsertPos = 0;
3262 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3263 if (T)
3264 return QualType(T, 0);
3265
3266 QualType Canon = InnerType;
3267 if (!Canon.isCanonical()) {
3268 Canon = getCanonicalType(InnerType);
3269 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3270 assert(!CheckT && "Paren canonical type broken");
3271 (void)CheckT;
3272 }
3273
3274 T = new (*this) ParenType(InnerType, Canon);
3275 Types.push_back(T);
3276 ParenTypes.InsertNode(T, InsertPos);
3277 return QualType(T, 0);
3278}
3279
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003280QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3281 NestedNameSpecifier *NNS,
3282 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003283 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003284 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3285
3286 if (Canon.isNull()) {
3287 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003288 ElaboratedTypeKeyword CanonKeyword = Keyword;
3289 if (Keyword == ETK_None)
3290 CanonKeyword = ETK_Typename;
3291
3292 if (CanonNNS != NNS || CanonKeyword != Keyword)
3293 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003294 }
3295
3296 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003297 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003298
3299 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003300 DependentNameType *T
3301 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003302 if (T)
3303 return QualType(T, 0);
3304
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003305 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003306 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003307 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003308 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003309}
3310
Mike Stump1eb44332009-09-09 15:08:12 +00003311QualType
John McCall33500952010-06-11 00:33:02 +00003312ASTContext::getDependentTemplateSpecializationType(
3313 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003314 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003315 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003316 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003317 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003318 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003319 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3320 ArgCopy.push_back(Args[I].getArgument());
3321 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3322 ArgCopy.size(),
3323 ArgCopy.data());
3324}
3325
3326QualType
3327ASTContext::getDependentTemplateSpecializationType(
3328 ElaboratedTypeKeyword Keyword,
3329 NestedNameSpecifier *NNS,
3330 const IdentifierInfo *Name,
3331 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003332 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003333 assert((!NNS || NNS->isDependent()) &&
3334 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003335
Douglas Gregor789b1f62010-02-04 18:10:26 +00003336 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003337 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3338 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003339
3340 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003341 DependentTemplateSpecializationType *T
3342 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003343 if (T)
3344 return QualType(T, 0);
3345
John McCall33500952010-06-11 00:33:02 +00003346 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003347
John McCall33500952010-06-11 00:33:02 +00003348 ElaboratedTypeKeyword CanonKeyword = Keyword;
3349 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3350
3351 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003352 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003353 for (unsigned I = 0; I != NumArgs; ++I) {
3354 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3355 if (!CanonArgs[I].structurallyEquals(Args[I]))
3356 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003357 }
3358
John McCall33500952010-06-11 00:33:02 +00003359 QualType Canon;
3360 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3361 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3362 Name, NumArgs,
3363 CanonArgs.data());
3364
3365 // Find the insert position again.
3366 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3367 }
3368
3369 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3370 sizeof(TemplateArgument) * NumArgs),
3371 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003372 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003373 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003374 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003375 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003376 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003377}
3378
Douglas Gregorcded4f62011-01-14 17:04:44 +00003379QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003380 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003381 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003382 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003383
3384 assert(Pattern->containsUnexpandedParameterPack() &&
3385 "Pack expansions must expand one or more parameter packs");
3386 void *InsertPos = 0;
3387 PackExpansionType *T
3388 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3389 if (T)
3390 return QualType(T, 0);
3391
3392 QualType Canon;
3393 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003394 Canon = getCanonicalType(Pattern);
3395 // The canonical type might not contain an unexpanded parameter pack, if it
3396 // contains an alias template specialization which ignores one of its
3397 // parameters.
3398 if (Canon->containsUnexpandedParameterPack()) {
3399 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003400
Richard Smithd8672ef2012-07-16 00:20:35 +00003401 // Find the insert position again, in case we inserted an element into
3402 // PackExpansionTypes and invalidated our insert position.
3403 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3404 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003405 }
3406
Douglas Gregorcded4f62011-01-14 17:04:44 +00003407 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003408 Types.push_back(T);
3409 PackExpansionTypes.InsertNode(T, InsertPos);
3410 return QualType(T, 0);
3411}
3412
Chris Lattner88cb27a2008-04-07 04:56:42 +00003413/// CmpProtocolNames - Comparison predicate for sorting protocols
3414/// alphabetically.
3415static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3416 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003417 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003418}
3419
John McCallc12c5bb2010-05-15 11:32:37 +00003420static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003421 unsigned NumProtocols) {
3422 if (NumProtocols == 0) return true;
3423
Douglas Gregor61cc2962012-01-02 02:00:30 +00003424 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3425 return false;
3426
John McCall54e14c42009-10-22 22:37:11 +00003427 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003428 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3429 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003430 return false;
3431 return true;
3432}
3433
3434static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003435 unsigned &NumProtocols) {
3436 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Chris Lattner88cb27a2008-04-07 04:56:42 +00003438 // Sort protocols, keyed by name.
3439 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3440
Douglas Gregor61cc2962012-01-02 02:00:30 +00003441 // Canonicalize.
3442 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3443 Protocols[I] = Protocols[I]->getCanonicalDecl();
3444
Chris Lattner88cb27a2008-04-07 04:56:42 +00003445 // Remove duplicates.
3446 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3447 NumProtocols = ProtocolsEnd-Protocols;
3448}
3449
John McCallc12c5bb2010-05-15 11:32:37 +00003450QualType ASTContext::getObjCObjectType(QualType BaseType,
3451 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003452 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003453 // If the base type is an interface and there aren't any protocols
3454 // to add, then the interface type will do just fine.
3455 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3456 return BaseType;
3457
3458 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003459 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003460 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003461 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003462 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3463 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003464
John McCallc12c5bb2010-05-15 11:32:37 +00003465 // Build the canonical type, which has the canonical base type and
3466 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003467 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003468 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3469 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3470 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003471 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003472 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003473 unsigned UniqueCount = NumProtocols;
3474
John McCall54e14c42009-10-22 22:37:11 +00003475 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003476 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3477 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003478 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003479 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3480 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003481 }
3482
3483 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003484 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3485 }
3486
3487 unsigned Size = sizeof(ObjCObjectTypeImpl);
3488 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3489 void *Mem = Allocate(Size, TypeAlignment);
3490 ObjCObjectTypeImpl *T =
3491 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3492
3493 Types.push_back(T);
3494 ObjCObjectTypes.InsertNode(T, InsertPos);
3495 return QualType(T, 0);
3496}
3497
3498/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3499/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003500QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003501 llvm::FoldingSetNodeID ID;
3502 ObjCObjectPointerType::Profile(ID, ObjectT);
3503
3504 void *InsertPos = 0;
3505 if (ObjCObjectPointerType *QT =
3506 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3507 return QualType(QT, 0);
3508
3509 // Find the canonical object type.
3510 QualType Canonical;
3511 if (!ObjectT.isCanonical()) {
3512 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3513
3514 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003515 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3516 }
3517
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003518 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003519 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3520 ObjCObjectPointerType *QType =
3521 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003523 Types.push_back(QType);
3524 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003525 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003526}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003527
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003528/// getObjCInterfaceType - Return the unique reference to the type for the
3529/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003530QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3531 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003532 if (Decl->TypeForDecl)
3533 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003534
Douglas Gregor0af55012011-12-16 03:12:41 +00003535 if (PrevDecl) {
3536 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3537 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3538 return QualType(PrevDecl->TypeForDecl, 0);
3539 }
3540
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003541 // Prefer the definition, if there is one.
3542 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3543 Decl = Def;
3544
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003545 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3546 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3547 Decl->TypeForDecl = T;
3548 Types.push_back(T);
3549 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003550}
3551
Douglas Gregor72564e72009-02-26 23:50:07 +00003552/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3553/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003554/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003555/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003556/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003557QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003558 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003559 if (tofExpr->isTypeDependent()) {
3560 llvm::FoldingSetNodeID ID;
3561 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Douglas Gregorb1975722009-07-30 23:18:24 +00003563 void *InsertPos = 0;
3564 DependentTypeOfExprType *Canon
3565 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3566 if (Canon) {
3567 // We already have a "canonical" version of an identical, dependent
3568 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003569 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003570 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003571 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003572 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003573 Canon
3574 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003575 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3576 toe = Canon;
3577 }
3578 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003579 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003580 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003581 }
Steve Naroff9752f252007-08-01 18:02:17 +00003582 Types.push_back(toe);
3583 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003584}
3585
Steve Naroff9752f252007-08-01 18:02:17 +00003586/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3587/// TypeOfType AST's. The only motivation to unique these nodes would be
3588/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003589/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003590/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003591QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003592 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003593 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003594 Types.push_back(tot);
3595 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003596}
3597
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003598
Anders Carlsson395b4752009-06-24 19:06:50 +00003599/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3600/// DecltypeType AST's. The only motivation to unique these nodes would be
3601/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003602/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003603/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003604QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003605 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003606
3607 // C++0x [temp.type]p2:
3608 // If an expression e involves a template parameter, decltype(e) denotes a
3609 // unique dependent type. Two such decltype-specifiers refer to the same
3610 // type only if their expressions are equivalent (14.5.6.1).
3611 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003612 llvm::FoldingSetNodeID ID;
3613 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003615 void *InsertPos = 0;
3616 DependentDecltypeType *Canon
3617 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3618 if (Canon) {
3619 // We already have a "canonical" version of an equivalent, dependent
3620 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003621 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003622 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003623 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003624 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003625 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003626 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3627 dt = Canon;
3628 }
3629 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003630 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3631 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003632 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003633 Types.push_back(dt);
3634 return QualType(dt, 0);
3635}
3636
Sean Huntca63c202011-05-24 22:41:36 +00003637/// getUnaryTransformationType - We don't unique these, since the memory
3638/// savings are minimal and these are rare.
3639QualType ASTContext::getUnaryTransformType(QualType BaseType,
3640 QualType UnderlyingType,
3641 UnaryTransformType::UTTKind Kind)
3642 const {
3643 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003644 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3645 Kind,
3646 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003647 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003648 Types.push_back(Ty);
3649 return QualType(Ty, 0);
3650}
3651
Richard Smith60e141e2013-05-04 07:00:32 +00003652/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3653/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3654/// canonical deduced-but-dependent 'auto' type.
3655QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003656 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003657 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3658 return getAutoDeductType();
3659
3660 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003661 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003662 llvm::FoldingSetNodeID ID;
3663 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3664 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3665 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003666
Richard Smitha2c36462013-04-26 16:15:35 +00003667 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003668 IsDecltypeAuto,
3669 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003670 Types.push_back(AT);
3671 if (InsertPos)
3672 AutoTypes.InsertNode(AT, InsertPos);
3673 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003674}
3675
Eli Friedmanb001de72011-10-06 23:00:33 +00003676/// getAtomicType - Return the uniqued reference to the atomic type for
3677/// the given value type.
3678QualType ASTContext::getAtomicType(QualType T) const {
3679 // Unique pointers, to guarantee there is only one pointer of a particular
3680 // structure.
3681 llvm::FoldingSetNodeID ID;
3682 AtomicType::Profile(ID, T);
3683
3684 void *InsertPos = 0;
3685 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3686 return QualType(AT, 0);
3687
3688 // If the atomic value type isn't canonical, this won't be a canonical type
3689 // either, so fill in the canonical type field.
3690 QualType Canonical;
3691 if (!T.isCanonical()) {
3692 Canonical = getAtomicType(getCanonicalType(T));
3693
3694 // Get the new insert position for the node we care about.
3695 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3696 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3697 }
3698 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3699 Types.push_back(New);
3700 AtomicTypes.InsertNode(New, InsertPos);
3701 return QualType(New, 0);
3702}
3703
Richard Smithad762fc2011-04-14 22:09:26 +00003704/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3705QualType ASTContext::getAutoDeductType() const {
3706 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003707 AutoDeductTy = QualType(
3708 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3709 /*dependent*/false),
3710 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003711 return AutoDeductTy;
3712}
3713
3714/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3715QualType ASTContext::getAutoRRefDeductType() const {
3716 if (AutoRRefDeductTy.isNull())
3717 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3718 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3719 return AutoRRefDeductTy;
3720}
3721
Reid Spencer5f016e22007-07-11 17:01:13 +00003722/// getTagDeclType - Return the unique reference to the type for the
3723/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003724QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003725 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003726 // FIXME: What is the design on getTagDeclType when it requires casting
3727 // away const? mutable?
3728 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003729}
3730
Mike Stump1eb44332009-09-09 15:08:12 +00003731/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3732/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3733/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003734CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003735 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003736}
3737
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003738/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3739CanQualType ASTContext::getIntMaxType() const {
3740 return getFromTargetType(Target->getIntMaxType());
3741}
3742
3743/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3744CanQualType ASTContext::getUIntMaxType() const {
3745 return getFromTargetType(Target->getUIntMaxType());
3746}
3747
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003748/// getSignedWCharType - Return the type of "signed wchar_t".
3749/// Used when in C++, as a GCC extension.
3750QualType ASTContext::getSignedWCharType() const {
3751 // FIXME: derive from "Target" ?
3752 return WCharTy;
3753}
3754
3755/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3756/// Used when in C++, as a GCC extension.
3757QualType ASTContext::getUnsignedWCharType() const {
3758 // FIXME: derive from "Target" ?
3759 return UnsignedIntTy;
3760}
3761
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003762QualType ASTContext::getIntPtrType() const {
3763 return getFromTargetType(Target->getIntPtrType());
3764}
3765
3766QualType ASTContext::getUIntPtrType() const {
3767 return getCorrespondingUnsignedType(getIntPtrType());
3768}
3769
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003770/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003771/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3772QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003773 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003774}
3775
Eli Friedman6902e412012-11-27 02:58:24 +00003776/// \brief Return the unique type for "pid_t" defined in
3777/// <sys/types.h>. We need this to compute the correct type for vfork().
3778QualType ASTContext::getProcessIDType() const {
3779 return getFromTargetType(Target->getProcessIDType());
3780}
3781
Chris Lattnere6327742008-04-02 05:18:44 +00003782//===----------------------------------------------------------------------===//
3783// Type Operators
3784//===----------------------------------------------------------------------===//
3785
Jay Foad4ba2a172011-01-12 09:06:06 +00003786CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003787 // Push qualifiers into arrays, and then discard any remaining
3788 // qualifiers.
3789 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003790 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003791 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003792 QualType Result;
3793 if (isa<ArrayType>(Ty)) {
3794 Result = getArrayDecayedType(QualType(Ty,0));
3795 } else if (isa<FunctionType>(Ty)) {
3796 Result = getPointerType(QualType(Ty, 0));
3797 } else {
3798 Result = QualType(Ty, 0);
3799 }
3800
3801 return CanQualType::CreateUnsafe(Result);
3802}
3803
John McCall62c28c82011-01-18 07:41:22 +00003804QualType ASTContext::getUnqualifiedArrayType(QualType type,
3805 Qualifiers &quals) {
3806 SplitQualType splitType = type.getSplitUnqualifiedType();
3807
3808 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3809 // the unqualified desugared type and then drops it on the floor.
3810 // We then have to strip that sugar back off with
3811 // getUnqualifiedDesugaredType(), which is silly.
3812 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003813 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003814
3815 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003816 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003817 quals = splitType.Quals;
3818 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003819 }
3820
John McCall62c28c82011-01-18 07:41:22 +00003821 // Otherwise, recurse on the array's element type.
3822 QualType elementType = AT->getElementType();
3823 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3824
3825 // If that didn't change the element type, AT has no qualifiers, so we
3826 // can just use the results in splitType.
3827 if (elementType == unqualElementType) {
3828 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003829 quals = splitType.Quals;
3830 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003831 }
3832
3833 // Otherwise, add in the qualifiers from the outermost type, then
3834 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003835 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003836
Douglas Gregor9dadd942010-05-17 18:45:21 +00003837 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003838 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003839 CAT->getSizeModifier(), 0);
3840 }
3841
Douglas Gregor9dadd942010-05-17 18:45:21 +00003842 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003843 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003844 }
3845
Douglas Gregor9dadd942010-05-17 18:45:21 +00003846 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003847 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003848 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003849 VAT->getSizeModifier(),
3850 VAT->getIndexTypeCVRQualifiers(),
3851 VAT->getBracketsRange());
3852 }
3853
3854 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003855 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003856 DSAT->getSizeModifier(), 0,
3857 SourceRange());
3858}
3859
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003860/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3861/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3862/// they point to and return true. If T1 and T2 aren't pointer types
3863/// or pointer-to-member types, or if they are not similar at this
3864/// level, returns false and leaves T1 and T2 unchanged. Top-level
3865/// qualifiers on T1 and T2 are ignored. This function will typically
3866/// be called in a loop that successively "unwraps" pointer and
3867/// pointer-to-member types to compare them at each level.
3868bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3869 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3870 *T2PtrType = T2->getAs<PointerType>();
3871 if (T1PtrType && T2PtrType) {
3872 T1 = T1PtrType->getPointeeType();
3873 T2 = T2PtrType->getPointeeType();
3874 return true;
3875 }
3876
3877 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3878 *T2MPType = T2->getAs<MemberPointerType>();
3879 if (T1MPType && T2MPType &&
3880 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3881 QualType(T2MPType->getClass(), 0))) {
3882 T1 = T1MPType->getPointeeType();
3883 T2 = T2MPType->getPointeeType();
3884 return true;
3885 }
3886
David Blaikie4e4d0842012-03-11 07:00:24 +00003887 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003888 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3889 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3890 if (T1OPType && T2OPType) {
3891 T1 = T1OPType->getPointeeType();
3892 T2 = T2OPType->getPointeeType();
3893 return true;
3894 }
3895 }
3896
3897 // FIXME: Block pointers, too?
3898
3899 return false;
3900}
3901
Jay Foad4ba2a172011-01-12 09:06:06 +00003902DeclarationNameInfo
3903ASTContext::getNameForTemplate(TemplateName Name,
3904 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003905 switch (Name.getKind()) {
3906 case TemplateName::QualifiedTemplate:
3907 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003908 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003909 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3910 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003911
John McCall14606042011-06-30 08:33:18 +00003912 case TemplateName::OverloadedTemplate: {
3913 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3914 // DNInfo work in progress: CHECKME: what about DNLoc?
3915 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3916 }
3917
3918 case TemplateName::DependentTemplate: {
3919 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003920 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003921 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003922 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3923 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003924 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003925 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3926 // DNInfo work in progress: FIXME: source locations?
3927 DeclarationNameLoc DNLoc;
3928 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3929 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3930 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003931 }
3932 }
3933
John McCall14606042011-06-30 08:33:18 +00003934 case TemplateName::SubstTemplateTemplateParm: {
3935 SubstTemplateTemplateParmStorage *subst
3936 = Name.getAsSubstTemplateTemplateParm();
3937 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3938 NameLoc);
3939 }
3940
3941 case TemplateName::SubstTemplateTemplateParmPack: {
3942 SubstTemplateTemplateParmPackStorage *subst
3943 = Name.getAsSubstTemplateTemplateParmPack();
3944 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3945 NameLoc);
3946 }
3947 }
3948
3949 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003950}
3951
Jay Foad4ba2a172011-01-12 09:06:06 +00003952TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003953 switch (Name.getKind()) {
3954 case TemplateName::QualifiedTemplate:
3955 case TemplateName::Template: {
3956 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003957 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003958 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003959 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3960
3961 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003962 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003963 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003964
John McCall14606042011-06-30 08:33:18 +00003965 case TemplateName::OverloadedTemplate:
3966 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003967
John McCall14606042011-06-30 08:33:18 +00003968 case TemplateName::DependentTemplate: {
3969 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3970 assert(DTN && "Non-dependent template names must refer to template decls.");
3971 return DTN->CanonicalTemplateName;
3972 }
3973
3974 case TemplateName::SubstTemplateTemplateParm: {
3975 SubstTemplateTemplateParmStorage *subst
3976 = Name.getAsSubstTemplateTemplateParm();
3977 return getCanonicalTemplateName(subst->getReplacement());
3978 }
3979
3980 case TemplateName::SubstTemplateTemplateParmPack: {
3981 SubstTemplateTemplateParmPackStorage *subst
3982 = Name.getAsSubstTemplateTemplateParmPack();
3983 TemplateTemplateParmDecl *canonParameter
3984 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3985 TemplateArgument canonArgPack
3986 = getCanonicalTemplateArgument(subst->getArgumentPack());
3987 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3988 }
3989 }
3990
3991 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003992}
3993
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003994bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3995 X = getCanonicalTemplateName(X);
3996 Y = getCanonicalTemplateName(Y);
3997 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3998}
3999
Mike Stump1eb44332009-09-09 15:08:12 +00004000TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00004001ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00004002 switch (Arg.getKind()) {
4003 case TemplateArgument::Null:
4004 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Douglas Gregor1275ae02009-07-28 23:00:59 +00004006 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00004007 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Douglas Gregord2008e22012-04-06 22:40:38 +00004009 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004010 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4011 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004012 }
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Eli Friedmand7a6b162012-09-26 02:36:12 +00004014 case TemplateArgument::NullPtr:
4015 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4016 /*isNullPtr*/true);
4017
Douglas Gregor788cd062009-11-11 01:00:40 +00004018 case TemplateArgument::Template:
4019 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004020
4021 case TemplateArgument::TemplateExpansion:
4022 return TemplateArgument(getCanonicalTemplateName(
4023 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004024 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004025
Douglas Gregor1275ae02009-07-28 23:00:59 +00004026 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004027 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Douglas Gregor1275ae02009-07-28 23:00:59 +00004029 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004030 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Douglas Gregor1275ae02009-07-28 23:00:59 +00004032 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004033 if (Arg.pack_size() == 0)
4034 return Arg;
4035
Douglas Gregor910f8002010-11-07 23:05:16 +00004036 TemplateArgument *CanonArgs
4037 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004038 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004039 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004040 AEnd = Arg.pack_end();
4041 A != AEnd; (void)++A, ++Idx)
4042 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Douglas Gregor910f8002010-11-07 23:05:16 +00004044 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004045 }
4046 }
4047
4048 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004049 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004050}
4051
Douglas Gregord57959a2009-03-27 23:10:48 +00004052NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004053ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004054 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004055 return 0;
4056
4057 switch (NNS->getKind()) {
4058 case NestedNameSpecifier::Identifier:
4059 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004060 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004061 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4062 NNS->getAsIdentifier());
4063
4064 case NestedNameSpecifier::Namespace:
4065 // A namespace is canonical; build a nested-name-specifier with
4066 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004067 return NestedNameSpecifier::Create(*this, 0,
4068 NNS->getAsNamespace()->getOriginalNamespace());
4069
4070 case NestedNameSpecifier::NamespaceAlias:
4071 // A namespace is canonical; build a nested-name-specifier with
4072 // this namespace and no prefix.
4073 return NestedNameSpecifier::Create(*this, 0,
4074 NNS->getAsNamespaceAlias()->getNamespace()
4075 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004076
4077 case NestedNameSpecifier::TypeSpec:
4078 case NestedNameSpecifier::TypeSpecWithTemplate: {
4079 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004080
4081 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4082 // break it apart into its prefix and identifier, then reconsititute those
4083 // as the canonical nested-name-specifier. This is required to canonicalize
4084 // a dependent nested-name-specifier involving typedefs of dependent-name
4085 // types, e.g.,
4086 // typedef typename T::type T1;
4087 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004088 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4089 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004090 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004091
Eli Friedman16412ef2012-03-03 04:09:56 +00004092 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4093 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4094 // first place?
John McCall3b657512011-01-19 10:06:00 +00004095 return NestedNameSpecifier::Create(*this, 0, false,
4096 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004097 }
4098
4099 case NestedNameSpecifier::Global:
4100 // The global specifier is canonical and unique.
4101 return NNS;
4102 }
4103
David Blaikie7530c032012-01-17 06:56:22 +00004104 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004105}
4106
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004107
Jay Foad4ba2a172011-01-12 09:06:06 +00004108const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004109 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004110 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004111 // Handle the common positive case fast.
4112 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4113 return AT;
4114 }
Mike Stump1eb44332009-09-09 15:08:12 +00004115
John McCall0953e762009-09-24 19:53:00 +00004116 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004117 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004118 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
John McCall0953e762009-09-24 19:53:00 +00004120 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004121 // implements C99 6.7.3p8: "If the specification of an array type includes
4122 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004124 // If we get here, we either have type qualifiers on the type, or we have
4125 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004126 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004127
John McCall3b657512011-01-19 10:06:00 +00004128 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004129 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004131 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004132 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004133 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004134 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004135
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004136 // Otherwise, we have an array and we have qualifiers on it. Push the
4137 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004138 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004140 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4141 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4142 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004143 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004144 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4145 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4146 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004147 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004148
Mike Stump1eb44332009-09-09 15:08:12 +00004149 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004150 = dyn_cast<DependentSizedArrayType>(ATy))
4151 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004152 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004153 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004154 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004155 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004156 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004158 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004159 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004160 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004161 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004162 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004163 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004164}
4165
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004166QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004167 if (T->isArrayType() || T->isFunctionType())
4168 return getDecayedType(T);
4169 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004170}
4171
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004172QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004173 T = getVariableArrayDecayedType(T);
4174 T = getAdjustedParameterType(T);
4175 return T.getUnqualifiedType();
4176}
4177
Chris Lattnere6327742008-04-02 05:18:44 +00004178/// getArrayDecayedType - Return the properly qualified result of decaying the
4179/// specified array type to a pointer. This operation is non-trivial when
4180/// handling typedefs etc. The canonical type of "T" must be an array type,
4181/// this returns a pointer to a properly qualified element of the array.
4182///
4183/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004184QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004185 // Get the element type with 'getAsArrayType' so that we don't lose any
4186 // typedefs in the element type of the array. This also handles propagation
4187 // of type qualifiers from the array type into the element type if present
4188 // (C99 6.7.3p8).
4189 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4190 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004192 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004193
4194 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004195 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004196}
4197
John McCall3b657512011-01-19 10:06:00 +00004198QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4199 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004200}
4201
John McCall3b657512011-01-19 10:06:00 +00004202QualType ASTContext::getBaseElementType(QualType type) const {
4203 Qualifiers qs;
4204 while (true) {
4205 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004206 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004207 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004208
John McCall3b657512011-01-19 10:06:00 +00004209 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004210 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004211 }
Mike Stump1eb44332009-09-09 15:08:12 +00004212
John McCall3b657512011-01-19 10:06:00 +00004213 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004214}
4215
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004216/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004217uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004218ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4219 uint64_t ElementCount = 1;
4220 do {
4221 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004222 CA = dyn_cast_or_null<ConstantArrayType>(
4223 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004224 } while (CA);
4225 return ElementCount;
4226}
4227
Reid Spencer5f016e22007-07-11 17:01:13 +00004228/// getFloatingRank - Return a relative rank for floating point types.
4229/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004230static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004231 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004232 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004233
John McCall183700f2009-09-21 23:43:11 +00004234 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4235 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004236 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004237 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004238 case BuiltinType::Float: return FloatRank;
4239 case BuiltinType::Double: return DoubleRank;
4240 case BuiltinType::LongDouble: return LongDoubleRank;
4241 }
4242}
4243
Mike Stump1eb44332009-09-09 15:08:12 +00004244/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4245/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004246/// 'typeDomain' is a real floating point or complex type.
4247/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004248QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4249 QualType Domain) const {
4250 FloatingRank EltRank = getFloatingRank(Size);
4251 if (Domain->isComplexType()) {
4252 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004253 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004254 case FloatRank: return FloatComplexTy;
4255 case DoubleRank: return DoubleComplexTy;
4256 case LongDoubleRank: return LongDoubleComplexTy;
4257 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004258 }
Chris Lattner1361b112008-04-06 23:58:54 +00004259
4260 assert(Domain->isRealFloatingType() && "Unknown domain!");
4261 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004262 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004263 case FloatRank: return FloatTy;
4264 case DoubleRank: return DoubleTy;
4265 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004266 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004267 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004268}
4269
Chris Lattner7cfeb082008-04-06 23:55:33 +00004270/// getFloatingTypeOrder - Compare the rank of the two specified floating
4271/// point types, ignoring the domain of the type (i.e. 'double' ==
4272/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004273/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004274int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004275 FloatingRank LHSR = getFloatingRank(LHS);
4276 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Chris Lattnera75cea32008-04-06 23:38:49 +00004278 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004279 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004280 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004281 return 1;
4282 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004283}
4284
Chris Lattnerf52ab252008-04-06 22:59:24 +00004285/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4286/// routine will assert if passed a built-in type that isn't an integer or enum,
4287/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004288unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004289 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004290
Chris Lattnerf52ab252008-04-06 22:59:24 +00004291 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004292 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004293 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004294 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::Char_S:
4296 case BuiltinType::Char_U:
4297 case BuiltinType::SChar:
4298 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004299 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004300 case BuiltinType::Short:
4301 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004302 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004303 case BuiltinType::Int:
4304 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004305 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004306 case BuiltinType::Long:
4307 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004308 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004309 case BuiltinType::LongLong:
4310 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004311 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004312 case BuiltinType::Int128:
4313 case BuiltinType::UInt128:
4314 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004315 }
4316}
4317
Eli Friedman04e83572009-08-20 04:21:42 +00004318/// \brief Whether this is a promotable bitfield reference according
4319/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4320///
4321/// \returns the type this bit-field will promote to, or NULL if no
4322/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004323QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004324 if (E->isTypeDependent() || E->isValueDependent())
4325 return QualType();
4326
John McCall993f43f2013-05-06 21:39:12 +00004327 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004328 if (!Field)
4329 return QualType();
4330
4331 QualType FT = Field->getType();
4332
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004333 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004334 uint64_t IntSize = getTypeSize(IntTy);
4335 // GCC extension compatibility: if the bit-field size is less than or equal
4336 // to the size of int, it gets promoted no matter what its type is.
4337 // For instance, unsigned long bf : 4 gets promoted to signed int.
4338 if (BitWidth < IntSize)
4339 return IntTy;
4340
4341 if (BitWidth == IntSize)
4342 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4343
4344 // Types bigger than int are not subject to promotions, and therefore act
4345 // like the base type.
4346 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4347 // is ridiculous.
4348 return QualType();
4349}
4350
Eli Friedmana95d7572009-08-19 07:44:53 +00004351/// getPromotedIntegerType - Returns the type that Promotable will
4352/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4353/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004354QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004355 assert(!Promotable.isNull());
4356 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004357 if (const EnumType *ET = Promotable->getAs<EnumType>())
4358 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004359
4360 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4361 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4362 // (3.9.1) can be converted to a prvalue of the first of the following
4363 // types that can represent all the values of its underlying type:
4364 // int, unsigned int, long int, unsigned long int, long long int, or
4365 // unsigned long long int [...]
4366 // FIXME: Is there some better way to compute this?
4367 if (BT->getKind() == BuiltinType::WChar_S ||
4368 BT->getKind() == BuiltinType::WChar_U ||
4369 BT->getKind() == BuiltinType::Char16 ||
4370 BT->getKind() == BuiltinType::Char32) {
4371 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4372 uint64_t FromSize = getTypeSize(BT);
4373 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4374 LongLongTy, UnsignedLongLongTy };
4375 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4376 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4377 if (FromSize < ToSize ||
4378 (FromSize == ToSize &&
4379 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4380 return PromoteTypes[Idx];
4381 }
4382 llvm_unreachable("char type should fit into long long");
4383 }
4384 }
4385
4386 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004387 if (Promotable->isSignedIntegerType())
4388 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004389 uint64_t PromotableSize = getIntWidth(Promotable);
4390 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004391 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4392 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4393}
4394
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004395/// \brief Recurses in pointer/array types until it finds an objc retainable
4396/// type and returns its ownership.
4397Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4398 while (!T.isNull()) {
4399 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4400 return T.getObjCLifetime();
4401 if (T->isArrayType())
4402 T = getBaseElementType(T);
4403 else if (const PointerType *PT = T->getAs<PointerType>())
4404 T = PT->getPointeeType();
4405 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004406 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004407 else
4408 break;
4409 }
4410
4411 return Qualifiers::OCL_None;
4412}
4413
Mike Stump1eb44332009-09-09 15:08:12 +00004414/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004415/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004416/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004417int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004418 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4419 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004420 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Chris Lattnerf52ab252008-04-06 22:59:24 +00004422 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4423 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Chris Lattner7cfeb082008-04-06 23:55:33 +00004425 unsigned LHSRank = getIntegerRank(LHSC);
4426 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Chris Lattner7cfeb082008-04-06 23:55:33 +00004428 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4429 if (LHSRank == RHSRank) return 0;
4430 return LHSRank > RHSRank ? 1 : -1;
4431 }
Mike Stump1eb44332009-09-09 15:08:12 +00004432
Chris Lattner7cfeb082008-04-06 23:55:33 +00004433 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4434 if (LHSUnsigned) {
4435 // If the unsigned [LHS] type is larger, return it.
4436 if (LHSRank >= RHSRank)
4437 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004438
Chris Lattner7cfeb082008-04-06 23:55:33 +00004439 // If the signed type can represent all values of the unsigned type, it
4440 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004441 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004442 return -1;
4443 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004444
Chris Lattner7cfeb082008-04-06 23:55:33 +00004445 // If the unsigned [RHS] type is larger, return it.
4446 if (RHSRank >= LHSRank)
4447 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004448
Chris Lattner7cfeb082008-04-06 23:55:33 +00004449 // If the signed type can represent all values of the unsigned type, it
4450 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004451 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004452 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004453}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004454
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004455static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004456CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4457 DeclContext *DC, IdentifierInfo *Id) {
4458 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004459 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004460 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004461 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004462 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004463}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004464
Mike Stump1eb44332009-09-09 15:08:12 +00004465// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004466QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004467 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004468 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004469 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004470 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004471 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004472
Anders Carlssonf06273f2007-11-19 00:25:30 +00004473 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004474
Anders Carlsson71993dd2007-08-17 05:31:46 +00004475 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004476 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004477 // int flags;
4478 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004479 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004480 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004481 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004482 FieldTypes[3] = LongTy;
4483
Anders Carlsson71993dd2007-08-17 05:31:46 +00004484 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004485 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004486 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004487 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004488 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004489 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004490 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004491 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004492 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004493 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004494 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004495 }
4496
Douglas Gregor838db382010-02-11 01:19:42 +00004497 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004498 }
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Anders Carlsson71993dd2007-08-17 05:31:46 +00004500 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004501}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004502
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004503QualType ASTContext::getObjCSuperType() const {
4504 if (ObjCSuperType.isNull()) {
4505 RecordDecl *ObjCSuperTypeDecl =
4506 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4507 TUDecl->addDecl(ObjCSuperTypeDecl);
4508 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4509 }
4510 return ObjCSuperType;
4511}
4512
Douglas Gregor319ac892009-04-23 22:29:11 +00004513void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004514 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004515 assert(Rec && "Invalid CFConstantStringType");
4516 CFConstantStringTypeDecl = Rec->getDecl();
4517}
4518
Jay Foad4ba2a172011-01-12 09:06:06 +00004519QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004520 if (BlockDescriptorType)
4521 return getTagDeclType(BlockDescriptorType);
4522
4523 RecordDecl *T;
4524 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004525 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004526 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004527 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004528
4529 QualType FieldTypes[] = {
4530 UnsignedLongTy,
4531 UnsignedLongTy,
4532 };
4533
Craig Topper3aa29df2013-07-15 08:24:27 +00004534 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004535 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004536 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004537 };
4538
4539 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004540 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004541 SourceLocation(),
4542 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004543 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004544 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004545 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004546 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004547 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004548 T->addDecl(Field);
4549 }
4550
Douglas Gregor838db382010-02-11 01:19:42 +00004551 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004552
4553 BlockDescriptorType = T;
4554
4555 return getTagDeclType(BlockDescriptorType);
4556}
4557
Jay Foad4ba2a172011-01-12 09:06:06 +00004558QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004559 if (BlockDescriptorExtendedType)
4560 return getTagDeclType(BlockDescriptorExtendedType);
4561
4562 RecordDecl *T;
4563 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004564 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004565 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004566 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004567
4568 QualType FieldTypes[] = {
4569 UnsignedLongTy,
4570 UnsignedLongTy,
4571 getPointerType(VoidPtrTy),
4572 getPointerType(VoidPtrTy)
4573 };
4574
Craig Topper3aa29df2013-07-15 08:24:27 +00004575 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004576 "reserved",
4577 "Size",
4578 "CopyFuncPtr",
4579 "DestroyFuncPtr"
4580 };
4581
4582 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004583 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004584 SourceLocation(),
4585 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004586 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004587 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004588 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004589 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004590 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004591 T->addDecl(Field);
4592 }
4593
Douglas Gregor838db382010-02-11 01:19:42 +00004594 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004595
4596 BlockDescriptorExtendedType = T;
4597
4598 return getTagDeclType(BlockDescriptorExtendedType);
4599}
4600
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004601/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4602/// requires copy/dispose. Note that this must match the logic
4603/// in buildByrefHelpers.
4604bool ASTContext::BlockRequiresCopying(QualType Ty,
4605 const VarDecl *D) {
4606 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4607 const Expr *copyExpr = getBlockVarCopyInits(D);
4608 if (!copyExpr && record->hasTrivialDestructor()) return false;
4609
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004610 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004611 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004612
4613 if (!Ty->isObjCRetainableType()) return false;
4614
4615 Qualifiers qs = Ty.getQualifiers();
4616
4617 // If we have lifetime, that dominates.
4618 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4619 assert(getLangOpts().ObjCAutoRefCount);
4620
4621 switch (lifetime) {
4622 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4623
4624 // These are just bits as far as the runtime is concerned.
4625 case Qualifiers::OCL_ExplicitNone:
4626 case Qualifiers::OCL_Autoreleasing:
4627 return false;
4628
4629 // Tell the runtime that this is ARC __weak, called by the
4630 // byref routines.
4631 case Qualifiers::OCL_Weak:
4632 // ARC __strong __block variables need to be retained.
4633 case Qualifiers::OCL_Strong:
4634 return true;
4635 }
4636 llvm_unreachable("fell out of lifetime switch!");
4637 }
4638 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4639 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004640}
4641
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004642bool ASTContext::getByrefLifetime(QualType Ty,
4643 Qualifiers::ObjCLifetime &LifeTime,
4644 bool &HasByrefExtendedLayout) const {
4645
4646 if (!getLangOpts().ObjC1 ||
4647 getLangOpts().getGC() != LangOptions::NonGC)
4648 return false;
4649
4650 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004651 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004652 HasByrefExtendedLayout = true;
4653 LifeTime = Qualifiers::OCL_None;
4654 }
4655 else if (getLangOpts().ObjCAutoRefCount)
4656 LifeTime = Ty.getObjCLifetime();
4657 // MRR.
4658 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4659 LifeTime = Qualifiers::OCL_ExplicitNone;
4660 else
4661 LifeTime = Qualifiers::OCL_None;
4662 return true;
4663}
4664
Douglas Gregore97179c2011-09-08 01:46:34 +00004665TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4666 if (!ObjCInstanceTypeDecl)
4667 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4668 getTranslationUnitDecl(),
4669 SourceLocation(),
4670 SourceLocation(),
4671 &Idents.get("instancetype"),
4672 getTrivialTypeSourceInfo(getObjCIdType()));
4673 return ObjCInstanceTypeDecl;
4674}
4675
Anders Carlssone8c49532007-10-29 06:33:42 +00004676// This returns true if a type has been typedefed to BOOL:
4677// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004678static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004679 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004680 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4681 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004683 return false;
4684}
4685
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004686/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004687/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004688CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004689 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4690 return CharUnits::Zero();
4691
Ken Dyck199c3d62010-01-11 17:06:35 +00004692 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004694 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004695 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004696 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004697 // Treat arrays as pointers, since that's how they're passed in.
4698 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004699 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004700 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004701}
4702
4703static inline
4704std::string charUnitsToString(const CharUnits &CU) {
4705 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004706}
4707
John McCall6b5a61b2011-02-07 10:33:21 +00004708/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004709/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004710std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4711 std::string S;
4712
David Chisnall5e530af2009-11-17 19:33:30 +00004713 const BlockDecl *Decl = Expr->getBlockDecl();
4714 QualType BlockTy =
4715 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4716 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004717 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004718 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4719 BlockTy->getAs<FunctionType>()->getResultType(),
4720 S, true /*Extended*/);
4721 else
4722 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4723 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004724 // Compute size of all parameters.
4725 // Start with computing size of a pointer in number of bytes.
4726 // FIXME: There might(should) be a better way of doing this computation!
4727 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004728 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4729 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004730 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004731 E = Decl->param_end(); PI != E; ++PI) {
4732 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004733 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004734 if (sz.isZero())
4735 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004736 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004737 ParmOffset += sz;
4738 }
4739 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004740 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004741 // Block pointer and offset.
4742 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004743
4744 // Argument types.
4745 ParmOffset = PtrSize;
4746 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4747 Decl->param_end(); PI != E; ++PI) {
4748 ParmVarDecl *PVDecl = *PI;
4749 QualType PType = PVDecl->getOriginalType();
4750 if (const ArrayType *AT =
4751 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4752 // Use array's original type only if it has known number of
4753 // elements.
4754 if (!isa<ConstantArrayType>(AT))
4755 PType = PVDecl->getType();
4756 } else if (PType->isFunctionType())
4757 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004758 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004759 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4760 S, true /*Extended*/);
4761 else
4762 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004763 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004764 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004765 }
John McCall6b5a61b2011-02-07 10:33:21 +00004766
4767 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004768}
4769
Douglas Gregorf968d832011-05-27 01:19:52 +00004770bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004771 std::string& S) {
4772 // Encode result type.
4773 getObjCEncodingForType(Decl->getResultType(), S);
4774 CharUnits ParmOffset;
4775 // Compute size of all parameters.
4776 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4777 E = Decl->param_end(); PI != E; ++PI) {
4778 QualType PType = (*PI)->getType();
4779 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004780 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004781 continue;
4782
David Chisnall5389f482010-12-30 14:05:53 +00004783 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004784 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004785 ParmOffset += sz;
4786 }
4787 S += charUnitsToString(ParmOffset);
4788 ParmOffset = CharUnits::Zero();
4789
4790 // Argument types.
4791 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4792 E = Decl->param_end(); PI != E; ++PI) {
4793 ParmVarDecl *PVDecl = *PI;
4794 QualType PType = PVDecl->getOriginalType();
4795 if (const ArrayType *AT =
4796 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4797 // Use array's original type only if it has known number of
4798 // elements.
4799 if (!isa<ConstantArrayType>(AT))
4800 PType = PVDecl->getType();
4801 } else if (PType->isFunctionType())
4802 PType = PVDecl->getType();
4803 getObjCEncodingForType(PType, S);
4804 S += charUnitsToString(ParmOffset);
4805 ParmOffset += getObjCEncodingTypeSize(PType);
4806 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004807
4808 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004809}
4810
Bob Wilsondc8dab62011-11-30 01:57:58 +00004811/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4812/// method parameter or return type. If Extended, include class names and
4813/// block object types.
4814void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4815 QualType T, std::string& S,
4816 bool Extended) const {
4817 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4818 getObjCEncodingForTypeQualifier(QT, S);
4819 // Encode parameter type.
4820 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4821 true /*OutermostType*/,
4822 false /*EncodingProperty*/,
4823 false /*StructField*/,
4824 Extended /*EncodeBlockParameters*/,
4825 Extended /*EncodeClassNames*/);
4826}
4827
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004828/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004829/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004830bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004831 std::string& S,
4832 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004833 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004834 // Encode return type.
4835 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4836 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004837 // Compute size of all parameters.
4838 // Start with computing size of a pointer in number of bytes.
4839 // FIXME: There might(should) be a better way of doing this computation!
4840 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004841 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004842 // The first two arguments (self and _cmd) are pointers; account for
4843 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004844 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004845 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004846 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004847 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004848 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004849 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004850 continue;
4851
Ken Dyck199c3d62010-01-11 17:06:35 +00004852 assert (sz.isPositive() &&
4853 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004854 ParmOffset += sz;
4855 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004856 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004857 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004858 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004860 // Argument types.
4861 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004862 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004863 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004864 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004865 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004866 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004867 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4868 // Use array's original type only if it has known number of
4869 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004870 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004871 PType = PVDecl->getType();
4872 } else if (PType->isFunctionType())
4873 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004874 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4875 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004876 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004877 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004878 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004879
4880 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004881}
4882
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004883/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004884/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004885/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4886/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004887/// Property attributes are stored as a comma-delimited C string. The simple
4888/// attributes readonly and bycopy are encoded as single characters. The
4889/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4890/// encoded as single characters, followed by an identifier. Property types
4891/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004892/// these attributes are defined by the following enumeration:
4893/// @code
4894/// enum PropertyAttributes {
4895/// kPropertyReadOnly = 'R', // property is read-only.
4896/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4897/// kPropertyByref = '&', // property is a reference to the value last assigned
4898/// kPropertyDynamic = 'D', // property is dynamic
4899/// kPropertyGetter = 'G', // followed by getter selector name
4900/// kPropertySetter = 'S', // followed by setter selector name
4901/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004902/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004903/// kPropertyWeak = 'W' // 'weak' property
4904/// kPropertyStrong = 'P' // property GC'able
4905/// kPropertyNonAtomic = 'N' // property non-atomic
4906/// };
4907/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004908void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004909 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004910 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004911 // Collect information from the property implementation decl(s).
4912 bool Dynamic = false;
4913 ObjCPropertyImplDecl *SynthesizePID = 0;
4914
4915 // FIXME: Duplicated code due to poor abstraction.
4916 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004917 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004918 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4919 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004920 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004921 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004922 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004923 if (PID->getPropertyDecl() == PD) {
4924 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4925 Dynamic = true;
4926 } else {
4927 SynthesizePID = PID;
4928 }
4929 }
4930 }
4931 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004932 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004933 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004934 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004935 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004936 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004937 if (PID->getPropertyDecl() == PD) {
4938 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4939 Dynamic = true;
4940 } else {
4941 SynthesizePID = PID;
4942 }
4943 }
Mike Stump1eb44332009-09-09 15:08:12 +00004944 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004945 }
4946 }
4947
4948 // FIXME: This is not very efficient.
4949 S = "T";
4950
4951 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004952 // GCC has some special rules regarding encoding of properties which
4953 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004954 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004955 true /* outermost type */,
4956 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004957
4958 if (PD->isReadOnly()) {
4959 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004960 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4961 S += ",C";
4962 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4963 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004964 } else {
4965 switch (PD->getSetterKind()) {
4966 case ObjCPropertyDecl::Assign: break;
4967 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004968 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004969 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004970 }
4971 }
4972
4973 // It really isn't clear at all what this means, since properties
4974 // are "dynamic by default".
4975 if (Dynamic)
4976 S += ",D";
4977
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004978 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4979 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004980
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004981 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4982 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004983 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004984 }
4985
4986 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4987 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004988 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004989 }
4990
4991 if (SynthesizePID) {
4992 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4993 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004994 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004995 }
4996
4997 // FIXME: OBJCGC: weak & strong
4998}
4999
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005000/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005001/// Another legacy compatibility encoding: 32-bit longs are encoded as
5002/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005003/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5004///
5005void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005006 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005007 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005008 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005009 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005010 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005011 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005012 PointeeTy = IntTy;
5013 }
5014 }
5015}
5016
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005017void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005018 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005019 // We follow the behavior of gcc, expanding structures which are
5020 // directly pointed to, and expanding embedded structures. Note that
5021 // these rules are sufficient to prevent recursive encoding of the
5022 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005023 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005024 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005025}
5026
John McCall3624e9e2012-12-20 02:45:14 +00005027static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5028 BuiltinType::Kind kind) {
5029 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005030 case BuiltinType::Void: return 'v';
5031 case BuiltinType::Bool: return 'B';
5032 case BuiltinType::Char_U:
5033 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005034 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005035 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005036 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005037 case BuiltinType::UInt: return 'I';
5038 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005039 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005040 case BuiltinType::UInt128: return 'T';
5041 case BuiltinType::ULongLong: return 'Q';
5042 case BuiltinType::Char_S:
5043 case BuiltinType::SChar: return 'c';
5044 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005045 case BuiltinType::WChar_S:
5046 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005047 case BuiltinType::Int: return 'i';
5048 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005049 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005050 case BuiltinType::LongLong: return 'q';
5051 case BuiltinType::Int128: return 't';
5052 case BuiltinType::Float: return 'f';
5053 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005054 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005055 case BuiltinType::NullPtr: return '*'; // like char*
5056
5057 case BuiltinType::Half:
5058 // FIXME: potentially need @encodes for these!
5059 return ' ';
5060
5061 case BuiltinType::ObjCId:
5062 case BuiltinType::ObjCClass:
5063 case BuiltinType::ObjCSel:
5064 llvm_unreachable("@encoding ObjC primitive type");
5065
5066 // OpenCL and placeholder types don't need @encodings.
5067 case BuiltinType::OCLImage1d:
5068 case BuiltinType::OCLImage1dArray:
5069 case BuiltinType::OCLImage1dBuffer:
5070 case BuiltinType::OCLImage2d:
5071 case BuiltinType::OCLImage2dArray:
5072 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005073 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005074 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005075 case BuiltinType::Dependent:
5076#define BUILTIN_TYPE(KIND, ID)
5077#define PLACEHOLDER_TYPE(KIND, ID) \
5078 case BuiltinType::KIND:
5079#include "clang/AST/BuiltinTypes.def"
5080 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005081 }
David Blaikie719e53f2013-01-09 17:48:41 +00005082 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005083}
5084
Douglas Gregor5471bc82011-09-08 17:18:35 +00005085static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5086 EnumDecl *Enum = ET->getDecl();
5087
5088 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5089 if (!Enum->isFixed())
5090 return 'i';
5091
5092 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005093 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5094 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005095}
5096
Jay Foad4ba2a172011-01-12 09:06:06 +00005097static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005098 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005099 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005100 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005101 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5102 // The GNU runtime requires more information; bitfields are encoded as b,
5103 // then the offset (in bits) of the first element, then the type of the
5104 // bitfield, then the size in bits. For example, in this structure:
5105 //
5106 // struct
5107 // {
5108 // int integer;
5109 // int flags:2;
5110 // };
5111 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5112 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5113 // information is not especially sensible, but we're stuck with it for
5114 // compatibility with GCC, although providing it breaks anything that
5115 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005116 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005117 const RecordDecl *RD = FD->getParent();
5118 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005119 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005120 if (const EnumType *ET = T->getAs<EnumType>())
5121 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005122 else {
5123 const BuiltinType *BT = T->castAs<BuiltinType>();
5124 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5125 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005126 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005127 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005128}
5129
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005130// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005131void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5132 bool ExpandPointedToStructures,
5133 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005134 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005135 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005136 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005137 bool StructField,
5138 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005139 bool EncodeClassNames,
5140 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005141 CanQualType CT = getCanonicalType(T);
5142 switch (CT->getTypeClass()) {
5143 case Type::Builtin:
5144 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005145 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005146 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005147 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5148 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5149 else
5150 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005151 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005152
John McCall3624e9e2012-12-20 02:45:14 +00005153 case Type::Complex: {
5154 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005155 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005156 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005157 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005158 return;
5159 }
John McCall3624e9e2012-12-20 02:45:14 +00005160
5161 case Type::Atomic: {
5162 const AtomicType *AT = T->castAs<AtomicType>();
5163 S += 'A';
5164 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5165 false, false);
5166 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005167 }
John McCall3624e9e2012-12-20 02:45:14 +00005168
5169 // encoding for pointer or reference types.
5170 case Type::Pointer:
5171 case Type::LValueReference:
5172 case Type::RValueReference: {
5173 QualType PointeeTy;
5174 if (isa<PointerType>(CT)) {
5175 const PointerType *PT = T->castAs<PointerType>();
5176 if (PT->isObjCSelType()) {
5177 S += ':';
5178 return;
5179 }
5180 PointeeTy = PT->getPointeeType();
5181 } else {
5182 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5183 }
5184
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005185 bool isReadOnly = false;
5186 // For historical/compatibility reasons, the read-only qualifier of the
5187 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5188 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005189 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005190 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005191 if (OutermostType && T.isConstQualified()) {
5192 isReadOnly = true;
5193 S += 'r';
5194 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005195 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005196 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005197 while (P->getAs<PointerType>())
5198 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005199 if (P.isConstQualified()) {
5200 isReadOnly = true;
5201 S += 'r';
5202 }
5203 }
5204 if (isReadOnly) {
5205 // Another legacy compatibility encoding. Some ObjC qualifier and type
5206 // combinations need to be rearranged.
5207 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005208 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005209 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005210 }
Mike Stump1eb44332009-09-09 15:08:12 +00005211
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005212 if (PointeeTy->isCharType()) {
5213 // char pointer types should be encoded as '*' unless it is a
5214 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005215 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005216 S += '*';
5217 return;
5218 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005219 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005220 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5221 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5222 S += '#';
5223 return;
5224 }
5225 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5226 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5227 S += '@';
5228 return;
5229 }
5230 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005231 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005232 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005233 getLegacyIntegralTypeEncoding(PointeeTy);
5234
Mike Stump1eb44332009-09-09 15:08:12 +00005235 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005236 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005237 return;
5238 }
John McCall3624e9e2012-12-20 02:45:14 +00005239
5240 case Type::ConstantArray:
5241 case Type::IncompleteArray:
5242 case Type::VariableArray: {
5243 const ArrayType *AT = cast<ArrayType>(CT);
5244
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005245 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005246 // Incomplete arrays are encoded as a pointer to the array element.
5247 S += '^';
5248
Mike Stump1eb44332009-09-09 15:08:12 +00005249 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005250 false, ExpandStructures, FD);
5251 } else {
5252 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005254 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5255 S += llvm::utostr(CAT->getSize().getZExtValue());
5256 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005257 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005258 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5259 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005260 S += '0';
5261 }
Mike Stump1eb44332009-09-09 15:08:12 +00005262
5263 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005264 false, ExpandStructures, FD);
5265 S += ']';
5266 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005267 return;
5268 }
Mike Stump1eb44332009-09-09 15:08:12 +00005269
John McCall3624e9e2012-12-20 02:45:14 +00005270 case Type::FunctionNoProto:
5271 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005272 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005273 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005274
John McCall3624e9e2012-12-20 02:45:14 +00005275 case Type::Record: {
5276 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005277 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005278 // Anonymous structures print as '?'
5279 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5280 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005281 if (ClassTemplateSpecializationDecl *Spec
5282 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5283 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005284 llvm::raw_string_ostream OS(S);
5285 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005286 TemplateArgs.data(),
5287 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005288 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005289 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005290 } else {
5291 S += '?';
5292 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005293 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005294 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005295 if (!RDecl->isUnion()) {
5296 getObjCEncodingForStructureImpl(RDecl, S, FD);
5297 } else {
5298 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5299 FieldEnd = RDecl->field_end();
5300 Field != FieldEnd; ++Field) {
5301 if (FD) {
5302 S += '"';
5303 S += Field->getNameAsString();
5304 S += '"';
5305 }
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005307 // Special case bit-fields.
5308 if (Field->isBitField()) {
5309 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005310 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005311 } else {
5312 QualType qt = Field->getType();
5313 getLegacyIntegralTypeEncoding(qt);
5314 getObjCEncodingForTypeImpl(qt, S, false, true,
5315 FD, /*OutermostType*/false,
5316 /*EncodingProperty*/false,
5317 /*StructField*/true);
5318 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005319 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005320 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005321 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005322 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005323 return;
5324 }
Mike Stump1eb44332009-09-09 15:08:12 +00005325
John McCall3624e9e2012-12-20 02:45:14 +00005326 case Type::BlockPointer: {
5327 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005328 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005329 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005330 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005331
5332 S += '<';
5333 // Block return type
5334 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5335 ExpandPointedToStructures, ExpandStructures,
5336 FD,
5337 false /* OutermostType */,
5338 EncodingProperty,
5339 false /* StructField */,
5340 EncodeBlockParameters,
5341 EncodeClassNames);
5342 // Block self
5343 S += "@?";
5344 // Block parameters
5345 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5346 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5347 E = FPT->arg_type_end(); I && (I != E); ++I) {
5348 getObjCEncodingForTypeImpl(*I, S,
5349 ExpandPointedToStructures,
5350 ExpandStructures,
5351 FD,
5352 false /* OutermostType */,
5353 EncodingProperty,
5354 false /* StructField */,
5355 EncodeBlockParameters,
5356 EncodeClassNames);
5357 }
5358 }
5359 S += '>';
5360 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005361 return;
5362 }
Mike Stump1eb44332009-09-09 15:08:12 +00005363
John McCall3624e9e2012-12-20 02:45:14 +00005364 case Type::ObjCObject:
5365 case Type::ObjCInterface: {
5366 // Ignore protocol qualifiers when mangling at this level.
5367 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005368
John McCall3624e9e2012-12-20 02:45:14 +00005369 // The assumption seems to be that this assert will succeed
5370 // because nested levels will have filtered out 'id' and 'Class'.
5371 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005372 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005373 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005374 S += '{';
5375 const IdentifierInfo *II = OI->getIdentifier();
5376 S += II->getName();
5377 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005378 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005379 DeepCollectObjCIvars(OI, true, Ivars);
5380 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005381 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005382 if (Field->isBitField())
5383 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005384 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005385 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5386 false, false, false, false, false,
5387 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005388 }
5389 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005390 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005391 }
Mike Stump1eb44332009-09-09 15:08:12 +00005392
John McCall3624e9e2012-12-20 02:45:14 +00005393 case Type::ObjCObjectPointer: {
5394 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005395 if (OPT->isObjCIdType()) {
5396 S += '@';
5397 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005398 }
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Steve Naroff27d20a22009-10-28 22:03:49 +00005400 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5401 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5402 // Since this is a binary compatibility issue, need to consult with runtime
5403 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005404 S += '#';
5405 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005406 }
Mike Stump1eb44332009-09-09 15:08:12 +00005407
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005408 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005409 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005410 ExpandPointedToStructures,
5411 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005412 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005413 // Note that we do extended encoding of protocol qualifer list
5414 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005415 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005416 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5417 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005418 S += '<';
5419 S += (*I)->getNameAsString();
5420 S += '>';
5421 }
5422 S += '"';
5423 }
5424 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005425 }
Mike Stump1eb44332009-09-09 15:08:12 +00005426
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005427 QualType PointeeTy = OPT->getPointeeType();
5428 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005429 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5430 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005431 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005432 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005433 // {...};
5434 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005435 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005436 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005437 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5438 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5439 DeepCollectObjCIvars(OI, true, Ivars);
5440 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5441 if (cast<FieldDecl>(Ivars[i]) == FD) {
5442 S += '{';
5443 S += OI->getIdentifier()->getName();
5444 S += '}';
5445 return;
5446 }
5447 }
5448 }
Mike Stump1eb44332009-09-09 15:08:12 +00005449 getObjCEncodingForTypeImpl(PointeeTy, S,
5450 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005451 NULL,
5452 false, false, false, false, false,
5453 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005454 return;
5455 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005456
5457 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005458 if (OPT->getInterfaceDecl() &&
5459 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005460 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005461 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005462 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5463 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005464 S += '<';
5465 S += (*I)->getNameAsString();
5466 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005467 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005468 S += '"';
5469 }
5470 return;
5471 }
Mike Stump1eb44332009-09-09 15:08:12 +00005472
John McCall532ec7b2010-05-17 23:56:34 +00005473 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005474 // FIXME: we shoul do better than that. 'M' is available.
5475 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005476 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005477
John McCall3624e9e2012-12-20 02:45:14 +00005478 case Type::Vector:
5479 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005480 // This matches gcc's encoding, even though technically it is
5481 // insufficient.
5482 // FIXME. We should do a better job than gcc.
5483 return;
John McCall3624e9e2012-12-20 02:45:14 +00005484
Richard Smithdc7a4f52013-04-30 13:56:41 +00005485 case Type::Auto:
5486 // We could see an undeduced auto type here during error recovery.
5487 // Just ignore it.
5488 return;
5489
John McCall3624e9e2012-12-20 02:45:14 +00005490#define ABSTRACT_TYPE(KIND, BASE)
5491#define TYPE(KIND, BASE)
5492#define DEPENDENT_TYPE(KIND, BASE) \
5493 case Type::KIND:
5494#define NON_CANONICAL_TYPE(KIND, BASE) \
5495 case Type::KIND:
5496#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5497 case Type::KIND:
5498#include "clang/AST/TypeNodes.def"
5499 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005500 }
John McCall3624e9e2012-12-20 02:45:14 +00005501 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005502}
5503
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005504void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5505 std::string &S,
5506 const FieldDecl *FD,
5507 bool includeVBases) const {
5508 assert(RDecl && "Expected non-null RecordDecl");
5509 assert(!RDecl->isUnion() && "Should not be called for unions");
5510 if (!RDecl->getDefinition())
5511 return;
5512
5513 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5514 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5515 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5516
5517 if (CXXRec) {
5518 for (CXXRecordDecl::base_class_iterator
5519 BI = CXXRec->bases_begin(),
5520 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5521 if (!BI->isVirtual()) {
5522 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005523 if (base->isEmpty())
5524 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005525 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005526 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5527 std::make_pair(offs, base));
5528 }
5529 }
5530 }
5531
5532 unsigned i = 0;
5533 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5534 FieldEnd = RDecl->field_end();
5535 Field != FieldEnd; ++Field, ++i) {
5536 uint64_t offs = layout.getFieldOffset(i);
5537 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005538 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005539 }
5540
5541 if (CXXRec && includeVBases) {
5542 for (CXXRecordDecl::base_class_iterator
5543 BI = CXXRec->vbases_begin(),
5544 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5545 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005546 if (base->isEmpty())
5547 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005548 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005549 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5550 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5551 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005552 }
5553 }
5554
5555 CharUnits size;
5556 if (CXXRec) {
5557 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5558 } else {
5559 size = layout.getSize();
5560 }
5561
5562 uint64_t CurOffs = 0;
5563 std::multimap<uint64_t, NamedDecl *>::iterator
5564 CurLayObj = FieldOrBaseOffsets.begin();
5565
Douglas Gregor58db7a52012-04-27 22:30:01 +00005566 if (CXXRec && CXXRec->isDynamicClass() &&
5567 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005568 if (FD) {
5569 S += "\"_vptr$";
5570 std::string recname = CXXRec->getNameAsString();
5571 if (recname.empty()) recname = "?";
5572 S += recname;
5573 S += '"';
5574 }
5575 S += "^^?";
5576 CurOffs += getTypeSize(VoidPtrTy);
5577 }
5578
5579 if (!RDecl->hasFlexibleArrayMember()) {
5580 // Mark the end of the structure.
5581 uint64_t offs = toBits(size);
5582 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5583 std::make_pair(offs, (NamedDecl*)0));
5584 }
5585
5586 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5587 assert(CurOffs <= CurLayObj->first);
5588
5589 if (CurOffs < CurLayObj->first) {
5590 uint64_t padding = CurLayObj->first - CurOffs;
5591 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5592 // packing/alignment of members is different that normal, in which case
5593 // the encoding will be out-of-sync with the real layout.
5594 // If the runtime switches to just consider the size of types without
5595 // taking into account alignment, we could make padding explicit in the
5596 // encoding (e.g. using arrays of chars). The encoding strings would be
5597 // longer then though.
5598 CurOffs += padding;
5599 }
5600
5601 NamedDecl *dcl = CurLayObj->second;
5602 if (dcl == 0)
5603 break; // reached end of structure.
5604
5605 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5606 // We expand the bases without their virtual bases since those are going
5607 // in the initial structure. Note that this differs from gcc which
5608 // expands virtual bases each time one is encountered in the hierarchy,
5609 // making the encoding type bigger than it really is.
5610 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005611 assert(!base->isEmpty());
5612 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005613 } else {
5614 FieldDecl *field = cast<FieldDecl>(dcl);
5615 if (FD) {
5616 S += '"';
5617 S += field->getNameAsString();
5618 S += '"';
5619 }
5620
5621 if (field->isBitField()) {
5622 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005623 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005624 } else {
5625 QualType qt = field->getType();
5626 getLegacyIntegralTypeEncoding(qt);
5627 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5628 /*OutermostType*/false,
5629 /*EncodingProperty*/false,
5630 /*StructField*/true);
5631 CurOffs += getTypeSize(field->getType());
5632 }
5633 }
5634 }
5635}
5636
Mike Stump1eb44332009-09-09 15:08:12 +00005637void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005638 std::string& S) const {
5639 if (QT & Decl::OBJC_TQ_In)
5640 S += 'n';
5641 if (QT & Decl::OBJC_TQ_Inout)
5642 S += 'N';
5643 if (QT & Decl::OBJC_TQ_Out)
5644 S += 'o';
5645 if (QT & Decl::OBJC_TQ_Bycopy)
5646 S += 'O';
5647 if (QT & Decl::OBJC_TQ_Byref)
5648 S += 'R';
5649 if (QT & Decl::OBJC_TQ_Oneway)
5650 S += 'V';
5651}
5652
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005653TypedefDecl *ASTContext::getObjCIdDecl() const {
5654 if (!ObjCIdDecl) {
5655 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5656 T = getObjCObjectPointerType(T);
5657 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5658 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5659 getTranslationUnitDecl(),
5660 SourceLocation(), SourceLocation(),
5661 &Idents.get("id"), IdInfo);
5662 }
5663
5664 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005665}
5666
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005667TypedefDecl *ASTContext::getObjCSelDecl() const {
5668 if (!ObjCSelDecl) {
5669 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5670 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5671 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5672 getTranslationUnitDecl(),
5673 SourceLocation(), SourceLocation(),
5674 &Idents.get("SEL"), SelInfo);
5675 }
5676 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005677}
5678
Douglas Gregor79d67262011-08-12 05:59:41 +00005679TypedefDecl *ASTContext::getObjCClassDecl() const {
5680 if (!ObjCClassDecl) {
5681 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5682 T = getObjCObjectPointerType(T);
5683 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5684 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5685 getTranslationUnitDecl(),
5686 SourceLocation(), SourceLocation(),
5687 &Idents.get("Class"), ClassInfo);
5688 }
5689
5690 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005691}
5692
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005693ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5694 if (!ObjCProtocolClassDecl) {
5695 ObjCProtocolClassDecl
5696 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5697 SourceLocation(),
5698 &Idents.get("Protocol"),
5699 /*PrevDecl=*/0,
5700 SourceLocation(), true);
5701 }
5702
5703 return ObjCProtocolClassDecl;
5704}
5705
Meador Ingec5613b22012-06-16 03:34:49 +00005706//===----------------------------------------------------------------------===//
5707// __builtin_va_list Construction Functions
5708//===----------------------------------------------------------------------===//
5709
5710static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5711 // typedef char* __builtin_va_list;
5712 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5713 TypeSourceInfo *TInfo
5714 = Context->getTrivialTypeSourceInfo(CharPtrType);
5715
5716 TypedefDecl *VaListTypeDecl
5717 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5718 Context->getTranslationUnitDecl(),
5719 SourceLocation(), SourceLocation(),
5720 &Context->Idents.get("__builtin_va_list"),
5721 TInfo);
5722 return VaListTypeDecl;
5723}
5724
5725static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5726 // typedef void* __builtin_va_list;
5727 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5728 TypeSourceInfo *TInfo
5729 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5730
5731 TypedefDecl *VaListTypeDecl
5732 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5733 Context->getTranslationUnitDecl(),
5734 SourceLocation(), SourceLocation(),
5735 &Context->Idents.get("__builtin_va_list"),
5736 TInfo);
5737 return VaListTypeDecl;
5738}
5739
Tim Northoverc264e162013-01-31 12:13:10 +00005740static TypedefDecl *
5741CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5742 RecordDecl *VaListTagDecl;
5743 if (Context->getLangOpts().CPlusPlus) {
5744 // namespace std { struct __va_list {
5745 NamespaceDecl *NS;
5746 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5747 Context->getTranslationUnitDecl(),
5748 /*Inline*/false, SourceLocation(),
5749 SourceLocation(), &Context->Idents.get("std"),
5750 /*PrevDecl*/0);
5751
5752 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5753 Context->getTranslationUnitDecl(),
5754 SourceLocation(), SourceLocation(),
5755 &Context->Idents.get("__va_list"));
5756 VaListTagDecl->setDeclContext(NS);
5757 } else {
5758 // struct __va_list
5759 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5760 Context->getTranslationUnitDecl(),
5761 &Context->Idents.get("__va_list"));
5762 }
5763
5764 VaListTagDecl->startDefinition();
5765
5766 const size_t NumFields = 5;
5767 QualType FieldTypes[NumFields];
5768 const char *FieldNames[NumFields];
5769
5770 // void *__stack;
5771 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5772 FieldNames[0] = "__stack";
5773
5774 // void *__gr_top;
5775 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5776 FieldNames[1] = "__gr_top";
5777
5778 // void *__vr_top;
5779 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5780 FieldNames[2] = "__vr_top";
5781
5782 // int __gr_offs;
5783 FieldTypes[3] = Context->IntTy;
5784 FieldNames[3] = "__gr_offs";
5785
5786 // int __vr_offs;
5787 FieldTypes[4] = Context->IntTy;
5788 FieldNames[4] = "__vr_offs";
5789
5790 // Create fields
5791 for (unsigned i = 0; i < NumFields; ++i) {
5792 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5793 VaListTagDecl,
5794 SourceLocation(),
5795 SourceLocation(),
5796 &Context->Idents.get(FieldNames[i]),
5797 FieldTypes[i], /*TInfo=*/0,
5798 /*BitWidth=*/0,
5799 /*Mutable=*/false,
5800 ICIS_NoInit);
5801 Field->setAccess(AS_public);
5802 VaListTagDecl->addDecl(Field);
5803 }
5804 VaListTagDecl->completeDefinition();
5805 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5806 Context->VaListTagTy = VaListTagType;
5807
5808 // } __builtin_va_list;
5809 TypedefDecl *VaListTypedefDecl
5810 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5811 Context->getTranslationUnitDecl(),
5812 SourceLocation(), SourceLocation(),
5813 &Context->Idents.get("__builtin_va_list"),
5814 Context->getTrivialTypeSourceInfo(VaListTagType));
5815
5816 return VaListTypedefDecl;
5817}
5818
Meador Ingec5613b22012-06-16 03:34:49 +00005819static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5820 // typedef struct __va_list_tag {
5821 RecordDecl *VaListTagDecl;
5822
5823 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5824 Context->getTranslationUnitDecl(),
5825 &Context->Idents.get("__va_list_tag"));
5826 VaListTagDecl->startDefinition();
5827
5828 const size_t NumFields = 5;
5829 QualType FieldTypes[NumFields];
5830 const char *FieldNames[NumFields];
5831
5832 // unsigned char gpr;
5833 FieldTypes[0] = Context->UnsignedCharTy;
5834 FieldNames[0] = "gpr";
5835
5836 // unsigned char fpr;
5837 FieldTypes[1] = Context->UnsignedCharTy;
5838 FieldNames[1] = "fpr";
5839
5840 // unsigned short reserved;
5841 FieldTypes[2] = Context->UnsignedShortTy;
5842 FieldNames[2] = "reserved";
5843
5844 // void* overflow_arg_area;
5845 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5846 FieldNames[3] = "overflow_arg_area";
5847
5848 // void* reg_save_area;
5849 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5850 FieldNames[4] = "reg_save_area";
5851
5852 // Create fields
5853 for (unsigned i = 0; i < NumFields; ++i) {
5854 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5855 SourceLocation(),
5856 SourceLocation(),
5857 &Context->Idents.get(FieldNames[i]),
5858 FieldTypes[i], /*TInfo=*/0,
5859 /*BitWidth=*/0,
5860 /*Mutable=*/false,
5861 ICIS_NoInit);
5862 Field->setAccess(AS_public);
5863 VaListTagDecl->addDecl(Field);
5864 }
5865 VaListTagDecl->completeDefinition();
5866 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005867 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005868
5869 // } __va_list_tag;
5870 TypedefDecl *VaListTagTypedefDecl
5871 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5872 Context->getTranslationUnitDecl(),
5873 SourceLocation(), SourceLocation(),
5874 &Context->Idents.get("__va_list_tag"),
5875 Context->getTrivialTypeSourceInfo(VaListTagType));
5876 QualType VaListTagTypedefType =
5877 Context->getTypedefType(VaListTagTypedefDecl);
5878
5879 // typedef __va_list_tag __builtin_va_list[1];
5880 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5881 QualType VaListTagArrayType
5882 = Context->getConstantArrayType(VaListTagTypedefType,
5883 Size, ArrayType::Normal, 0);
5884 TypeSourceInfo *TInfo
5885 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5886 TypedefDecl *VaListTypedefDecl
5887 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5888 Context->getTranslationUnitDecl(),
5889 SourceLocation(), SourceLocation(),
5890 &Context->Idents.get("__builtin_va_list"),
5891 TInfo);
5892
5893 return VaListTypedefDecl;
5894}
5895
5896static TypedefDecl *
5897CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5898 // typedef struct __va_list_tag {
5899 RecordDecl *VaListTagDecl;
5900 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5901 Context->getTranslationUnitDecl(),
5902 &Context->Idents.get("__va_list_tag"));
5903 VaListTagDecl->startDefinition();
5904
5905 const size_t NumFields = 4;
5906 QualType FieldTypes[NumFields];
5907 const char *FieldNames[NumFields];
5908
5909 // unsigned gp_offset;
5910 FieldTypes[0] = Context->UnsignedIntTy;
5911 FieldNames[0] = "gp_offset";
5912
5913 // unsigned fp_offset;
5914 FieldTypes[1] = Context->UnsignedIntTy;
5915 FieldNames[1] = "fp_offset";
5916
5917 // void* overflow_arg_area;
5918 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5919 FieldNames[2] = "overflow_arg_area";
5920
5921 // void* reg_save_area;
5922 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5923 FieldNames[3] = "reg_save_area";
5924
5925 // Create fields
5926 for (unsigned i = 0; i < NumFields; ++i) {
5927 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5928 VaListTagDecl,
5929 SourceLocation(),
5930 SourceLocation(),
5931 &Context->Idents.get(FieldNames[i]),
5932 FieldTypes[i], /*TInfo=*/0,
5933 /*BitWidth=*/0,
5934 /*Mutable=*/false,
5935 ICIS_NoInit);
5936 Field->setAccess(AS_public);
5937 VaListTagDecl->addDecl(Field);
5938 }
5939 VaListTagDecl->completeDefinition();
5940 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005941 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005942
5943 // } __va_list_tag;
5944 TypedefDecl *VaListTagTypedefDecl
5945 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5946 Context->getTranslationUnitDecl(),
5947 SourceLocation(), SourceLocation(),
5948 &Context->Idents.get("__va_list_tag"),
5949 Context->getTrivialTypeSourceInfo(VaListTagType));
5950 QualType VaListTagTypedefType =
5951 Context->getTypedefType(VaListTagTypedefDecl);
5952
5953 // typedef __va_list_tag __builtin_va_list[1];
5954 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5955 QualType VaListTagArrayType
5956 = Context->getConstantArrayType(VaListTagTypedefType,
5957 Size, ArrayType::Normal,0);
5958 TypeSourceInfo *TInfo
5959 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5960 TypedefDecl *VaListTypedefDecl
5961 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5962 Context->getTranslationUnitDecl(),
5963 SourceLocation(), SourceLocation(),
5964 &Context->Idents.get("__builtin_va_list"),
5965 TInfo);
5966
5967 return VaListTypedefDecl;
5968}
5969
5970static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5971 // typedef int __builtin_va_list[4];
5972 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5973 QualType IntArrayType
5974 = Context->getConstantArrayType(Context->IntTy,
5975 Size, ArrayType::Normal, 0);
5976 TypedefDecl *VaListTypedefDecl
5977 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5978 Context->getTranslationUnitDecl(),
5979 SourceLocation(), SourceLocation(),
5980 &Context->Idents.get("__builtin_va_list"),
5981 Context->getTrivialTypeSourceInfo(IntArrayType));
5982
5983 return VaListTypedefDecl;
5984}
5985
Logan Chieneae5a8202012-10-10 06:56:20 +00005986static TypedefDecl *
5987CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5988 RecordDecl *VaListDecl;
5989 if (Context->getLangOpts().CPlusPlus) {
5990 // namespace std { struct __va_list {
5991 NamespaceDecl *NS;
5992 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5993 Context->getTranslationUnitDecl(),
5994 /*Inline*/false, SourceLocation(),
5995 SourceLocation(), &Context->Idents.get("std"),
5996 /*PrevDecl*/0);
5997
5998 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5999 Context->getTranslationUnitDecl(),
6000 SourceLocation(), SourceLocation(),
6001 &Context->Idents.get("__va_list"));
6002
6003 VaListDecl->setDeclContext(NS);
6004
6005 } else {
6006 // struct __va_list {
6007 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6008 Context->getTranslationUnitDecl(),
6009 &Context->Idents.get("__va_list"));
6010 }
6011
6012 VaListDecl->startDefinition();
6013
6014 // void * __ap;
6015 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6016 VaListDecl,
6017 SourceLocation(),
6018 SourceLocation(),
6019 &Context->Idents.get("__ap"),
6020 Context->getPointerType(Context->VoidTy),
6021 /*TInfo=*/0,
6022 /*BitWidth=*/0,
6023 /*Mutable=*/false,
6024 ICIS_NoInit);
6025 Field->setAccess(AS_public);
6026 VaListDecl->addDecl(Field);
6027
6028 // };
6029 VaListDecl->completeDefinition();
6030
6031 // typedef struct __va_list __builtin_va_list;
6032 TypeSourceInfo *TInfo
6033 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6034
6035 TypedefDecl *VaListTypeDecl
6036 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6037 Context->getTranslationUnitDecl(),
6038 SourceLocation(), SourceLocation(),
6039 &Context->Idents.get("__builtin_va_list"),
6040 TInfo);
6041
6042 return VaListTypeDecl;
6043}
6044
Ulrich Weigandb8409212013-05-06 16:26:41 +00006045static TypedefDecl *
6046CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6047 // typedef struct __va_list_tag {
6048 RecordDecl *VaListTagDecl;
6049 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6050 Context->getTranslationUnitDecl(),
6051 &Context->Idents.get("__va_list_tag"));
6052 VaListTagDecl->startDefinition();
6053
6054 const size_t NumFields = 4;
6055 QualType FieldTypes[NumFields];
6056 const char *FieldNames[NumFields];
6057
6058 // long __gpr;
6059 FieldTypes[0] = Context->LongTy;
6060 FieldNames[0] = "__gpr";
6061
6062 // long __fpr;
6063 FieldTypes[1] = Context->LongTy;
6064 FieldNames[1] = "__fpr";
6065
6066 // void *__overflow_arg_area;
6067 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6068 FieldNames[2] = "__overflow_arg_area";
6069
6070 // void *__reg_save_area;
6071 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6072 FieldNames[3] = "__reg_save_area";
6073
6074 // Create fields
6075 for (unsigned i = 0; i < NumFields; ++i) {
6076 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6077 VaListTagDecl,
6078 SourceLocation(),
6079 SourceLocation(),
6080 &Context->Idents.get(FieldNames[i]),
6081 FieldTypes[i], /*TInfo=*/0,
6082 /*BitWidth=*/0,
6083 /*Mutable=*/false,
6084 ICIS_NoInit);
6085 Field->setAccess(AS_public);
6086 VaListTagDecl->addDecl(Field);
6087 }
6088 VaListTagDecl->completeDefinition();
6089 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6090 Context->VaListTagTy = VaListTagType;
6091
6092 // } __va_list_tag;
6093 TypedefDecl *VaListTagTypedefDecl
6094 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6095 Context->getTranslationUnitDecl(),
6096 SourceLocation(), SourceLocation(),
6097 &Context->Idents.get("__va_list_tag"),
6098 Context->getTrivialTypeSourceInfo(VaListTagType));
6099 QualType VaListTagTypedefType =
6100 Context->getTypedefType(VaListTagTypedefDecl);
6101
6102 // typedef __va_list_tag __builtin_va_list[1];
6103 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6104 QualType VaListTagArrayType
6105 = Context->getConstantArrayType(VaListTagTypedefType,
6106 Size, ArrayType::Normal,0);
6107 TypeSourceInfo *TInfo
6108 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6109 TypedefDecl *VaListTypedefDecl
6110 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6111 Context->getTranslationUnitDecl(),
6112 SourceLocation(), SourceLocation(),
6113 &Context->Idents.get("__builtin_va_list"),
6114 TInfo);
6115
6116 return VaListTypedefDecl;
6117}
6118
Meador Ingec5613b22012-06-16 03:34:49 +00006119static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6120 TargetInfo::BuiltinVaListKind Kind) {
6121 switch (Kind) {
6122 case TargetInfo::CharPtrBuiltinVaList:
6123 return CreateCharPtrBuiltinVaListDecl(Context);
6124 case TargetInfo::VoidPtrBuiltinVaList:
6125 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006126 case TargetInfo::AArch64ABIBuiltinVaList:
6127 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006128 case TargetInfo::PowerABIBuiltinVaList:
6129 return CreatePowerABIBuiltinVaListDecl(Context);
6130 case TargetInfo::X86_64ABIBuiltinVaList:
6131 return CreateX86_64ABIBuiltinVaListDecl(Context);
6132 case TargetInfo::PNaClABIBuiltinVaList:
6133 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006134 case TargetInfo::AAPCSABIBuiltinVaList:
6135 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006136 case TargetInfo::SystemZBuiltinVaList:
6137 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006138 }
6139
6140 llvm_unreachable("Unhandled __builtin_va_list type kind");
6141}
6142
6143TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6144 if (!BuiltinVaListDecl)
6145 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6146
6147 return BuiltinVaListDecl;
6148}
6149
Meador Ingefb40e3f2012-07-01 15:57:25 +00006150QualType ASTContext::getVaListTagType() const {
6151 // Force the creation of VaListTagTy by building the __builtin_va_list
6152 // declaration.
6153 if (VaListTagTy.isNull())
6154 (void) getBuiltinVaListDecl();
6155
6156 return VaListTagTy;
6157}
6158
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006159void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006160 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006161 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006163 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006164}
6165
John McCall0bd6feb2009-12-02 08:04:21 +00006166/// \brief Retrieve the template name that corresponds to a non-empty
6167/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006168TemplateName
6169ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6170 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006171 unsigned size = End - Begin;
6172 assert(size > 1 && "set is not overloaded!");
6173
6174 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6175 size * sizeof(FunctionTemplateDecl*));
6176 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6177
6178 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006179 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006180 NamedDecl *D = *I;
6181 assert(isa<FunctionTemplateDecl>(D) ||
6182 (isa<UsingShadowDecl>(D) &&
6183 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6184 *Storage++ = D;
6185 }
6186
6187 return TemplateName(OT);
6188}
6189
Douglas Gregor7532dc62009-03-30 22:58:21 +00006190/// \brief Retrieve the template name that represents a qualified
6191/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006192TemplateName
6193ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6194 bool TemplateKeyword,
6195 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006196 assert(NNS && "Missing nested-name-specifier in qualified template name");
6197
Douglas Gregor789b1f62010-02-04 18:10:26 +00006198 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006199 llvm::FoldingSetNodeID ID;
6200 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6201
6202 void *InsertPos = 0;
6203 QualifiedTemplateName *QTN =
6204 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6205 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006206 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6207 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006208 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6209 }
6210
6211 return TemplateName(QTN);
6212}
6213
6214/// \brief Retrieve the template name that represents a dependent
6215/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006216TemplateName
6217ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6218 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006219 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006220 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006221
6222 llvm::FoldingSetNodeID ID;
6223 DependentTemplateName::Profile(ID, NNS, Name);
6224
6225 void *InsertPos = 0;
6226 DependentTemplateName *QTN =
6227 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6228
6229 if (QTN)
6230 return TemplateName(QTN);
6231
6232 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6233 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006234 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6235 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006236 } else {
6237 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006238 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6239 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006240 DependentTemplateName *CheckQTN =
6241 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6242 assert(!CheckQTN && "Dependent type name canonicalization broken");
6243 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006244 }
6245
6246 DependentTemplateNames.InsertNode(QTN, InsertPos);
6247 return TemplateName(QTN);
6248}
6249
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006250/// \brief Retrieve the template name that represents a dependent
6251/// template name such as \c MetaFun::template operator+.
6252TemplateName
6253ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006254 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006255 assert((!NNS || NNS->isDependent()) &&
6256 "Nested name specifier must be dependent");
6257
6258 llvm::FoldingSetNodeID ID;
6259 DependentTemplateName::Profile(ID, NNS, Operator);
6260
6261 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006262 DependentTemplateName *QTN
6263 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006264
6265 if (QTN)
6266 return TemplateName(QTN);
6267
6268 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6269 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006270 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6271 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006272 } else {
6273 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006274 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6275 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006276
6277 DependentTemplateName *CheckQTN
6278 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6279 assert(!CheckQTN && "Dependent template name canonicalization broken");
6280 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006281 }
6282
6283 DependentTemplateNames.InsertNode(QTN, InsertPos);
6284 return TemplateName(QTN);
6285}
6286
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006287TemplateName
John McCall14606042011-06-30 08:33:18 +00006288ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6289 TemplateName replacement) const {
6290 llvm::FoldingSetNodeID ID;
6291 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6292
6293 void *insertPos = 0;
6294 SubstTemplateTemplateParmStorage *subst
6295 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6296
6297 if (!subst) {
6298 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6299 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6300 }
6301
6302 return TemplateName(subst);
6303}
6304
6305TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006306ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6307 const TemplateArgument &ArgPack) const {
6308 ASTContext &Self = const_cast<ASTContext &>(*this);
6309 llvm::FoldingSetNodeID ID;
6310 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6311
6312 void *InsertPos = 0;
6313 SubstTemplateTemplateParmPackStorage *Subst
6314 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6315
6316 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006317 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006318 ArgPack.pack_size(),
6319 ArgPack.pack_begin());
6320 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6321 }
6322
6323 return TemplateName(Subst);
6324}
6325
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006326/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006327/// TargetInfo, produce the corresponding type. The unsigned @p Type
6328/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006329CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006330 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006331 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006332 case TargetInfo::SignedShort: return ShortTy;
6333 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6334 case TargetInfo::SignedInt: return IntTy;
6335 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6336 case TargetInfo::SignedLong: return LongTy;
6337 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6338 case TargetInfo::SignedLongLong: return LongLongTy;
6339 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6340 }
6341
David Blaikieb219cfc2011-09-23 05:06:16 +00006342 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006343}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006344
6345//===----------------------------------------------------------------------===//
6346// Type Predicates.
6347//===----------------------------------------------------------------------===//
6348
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006349/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6350/// garbage collection attribute.
6351///
John McCallae278a32011-01-12 00:34:59 +00006352Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006353 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006354 return Qualifiers::GCNone;
6355
David Blaikie4e4d0842012-03-11 07:00:24 +00006356 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006357 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6358
6359 // Default behaviour under objective-C's gc is for ObjC pointers
6360 // (or pointers to them) be treated as though they were declared
6361 // as __strong.
6362 if (GCAttrs == Qualifiers::GCNone) {
6363 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6364 return Qualifiers::Strong;
6365 else if (Ty->isPointerType())
6366 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6367 } else {
6368 // It's not valid to set GC attributes on anything that isn't a
6369 // pointer.
6370#ifndef NDEBUG
6371 QualType CT = Ty->getCanonicalTypeInternal();
6372 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6373 CT = AT->getElementType();
6374 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6375#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006376 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006377 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006378}
6379
Chris Lattner6ac46a42008-04-07 06:51:04 +00006380//===----------------------------------------------------------------------===//
6381// Type Compatibility Testing
6382//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006383
Mike Stump1eb44332009-09-09 15:08:12 +00006384/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006385/// compatible.
6386static bool areCompatVectorTypes(const VectorType *LHS,
6387 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006388 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006389 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006390 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006391}
6392
Douglas Gregor255210e2010-08-06 10:14:59 +00006393bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6394 QualType SecondVec) {
6395 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6396 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6397
6398 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6399 return true;
6400
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006401 // Treat Neon vector types and most AltiVec vector types as if they are the
6402 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006403 const VectorType *First = FirstVec->getAs<VectorType>();
6404 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006405 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006406 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006407 First->getVectorKind() != VectorType::AltiVecPixel &&
6408 First->getVectorKind() != VectorType::AltiVecBool &&
6409 Second->getVectorKind() != VectorType::AltiVecPixel &&
6410 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006411 return true;
6412
6413 return false;
6414}
6415
Steve Naroff4084c302009-07-23 01:01:38 +00006416//===----------------------------------------------------------------------===//
6417// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6418//===----------------------------------------------------------------------===//
6419
6420/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6421/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006422bool
6423ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6424 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006425 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006426 return true;
6427 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6428 E = rProto->protocol_end(); PI != E; ++PI)
6429 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6430 return true;
6431 return false;
6432}
6433
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006434/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6435/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006436bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6437 QualType rhs) {
6438 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6439 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6440 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6441
6442 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6443 E = lhsQID->qual_end(); I != E; ++I) {
6444 bool match = false;
6445 ObjCProtocolDecl *lhsProto = *I;
6446 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6447 E = rhsOPT->qual_end(); J != E; ++J) {
6448 ObjCProtocolDecl *rhsProto = *J;
6449 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6450 match = true;
6451 break;
6452 }
6453 }
6454 if (!match)
6455 return false;
6456 }
6457 return true;
6458}
6459
Steve Naroff4084c302009-07-23 01:01:38 +00006460/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6461/// ObjCQualifiedIDType.
6462bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6463 bool compare) {
6464 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006465 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006466 lhs->isObjCIdType() || lhs->isObjCClassType())
6467 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006468 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006469 rhs->isObjCIdType() || rhs->isObjCClassType())
6470 return true;
6471
6472 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006473 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006474
Steve Naroff4084c302009-07-23 01:01:38 +00006475 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006476
Steve Naroff4084c302009-07-23 01:01:38 +00006477 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006478 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006479 // make sure we check the class hierarchy.
6480 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6481 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6482 E = lhsQID->qual_end(); I != E; ++I) {
6483 // when comparing an id<P> on lhs with a static type on rhs,
6484 // see if static class implements all of id's protocols, directly or
6485 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006486 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006487 return false;
6488 }
6489 }
6490 // If there are no qualifiers and no interface, we have an 'id'.
6491 return true;
6492 }
Mike Stump1eb44332009-09-09 15:08:12 +00006493 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006494 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6495 E = lhsQID->qual_end(); I != E; ++I) {
6496 ObjCProtocolDecl *lhsProto = *I;
6497 bool match = false;
6498
6499 // when comparing an id<P> on lhs with a static type on rhs,
6500 // see if static class implements all of id's protocols, directly or
6501 // through its super class and categories.
6502 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6503 E = rhsOPT->qual_end(); J != E; ++J) {
6504 ObjCProtocolDecl *rhsProto = *J;
6505 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6506 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6507 match = true;
6508 break;
6509 }
6510 }
Mike Stump1eb44332009-09-09 15:08:12 +00006511 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006512 // make sure we check the class hierarchy.
6513 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6514 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6515 E = lhsQID->qual_end(); I != E; ++I) {
6516 // when comparing an id<P> on lhs with a static type on rhs,
6517 // see if static class implements all of id's protocols, directly or
6518 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006519 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006520 match = true;
6521 break;
6522 }
6523 }
6524 }
6525 if (!match)
6526 return false;
6527 }
Mike Stump1eb44332009-09-09 15:08:12 +00006528
Steve Naroff4084c302009-07-23 01:01:38 +00006529 return true;
6530 }
Mike Stump1eb44332009-09-09 15:08:12 +00006531
Steve Naroff4084c302009-07-23 01:01:38 +00006532 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6533 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6534
Mike Stump1eb44332009-09-09 15:08:12 +00006535 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006536 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006537 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006538 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6539 E = lhsOPT->qual_end(); I != E; ++I) {
6540 ObjCProtocolDecl *lhsProto = *I;
6541 bool match = false;
6542
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006543 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006544 // see if static class implements all of id's protocols, directly or
6545 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006546 // First, lhs protocols in the qualifier list must be found, direct
6547 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006548 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6549 E = rhsQID->qual_end(); J != E; ++J) {
6550 ObjCProtocolDecl *rhsProto = *J;
6551 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6552 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6553 match = true;
6554 break;
6555 }
6556 }
6557 if (!match)
6558 return false;
6559 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006560
6561 // Static class's protocols, or its super class or category protocols
6562 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6563 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6564 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6565 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6566 // This is rather dubious but matches gcc's behavior. If lhs has
6567 // no type qualifier and its class has no static protocol(s)
6568 // assume that it is mismatch.
6569 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6570 return false;
6571 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6572 LHSInheritedProtocols.begin(),
6573 E = LHSInheritedProtocols.end(); I != E; ++I) {
6574 bool match = false;
6575 ObjCProtocolDecl *lhsProto = (*I);
6576 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6577 E = rhsQID->qual_end(); J != E; ++J) {
6578 ObjCProtocolDecl *rhsProto = *J;
6579 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6580 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6581 match = true;
6582 break;
6583 }
6584 }
6585 if (!match)
6586 return false;
6587 }
6588 }
Steve Naroff4084c302009-07-23 01:01:38 +00006589 return true;
6590 }
6591 return false;
6592}
6593
Eli Friedman3d815e72008-08-22 00:56:42 +00006594/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006595/// compatible for assignment from RHS to LHS. This handles validation of any
6596/// protocol qualifiers on the LHS or RHS.
6597///
Steve Naroff14108da2009-07-10 23:34:53 +00006598bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6599 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006600 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6601 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6602
Steve Naroffde2e22d2009-07-15 18:40:39 +00006603 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006604 if (LHS->isObjCUnqualifiedIdOrClass() ||
6605 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006606 return true;
6607
John McCallc12c5bb2010-05-15 11:32:37 +00006608 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006609 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6610 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006611 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006612
6613 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6614 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6615 QualType(RHSOPT,0));
6616
John McCallc12c5bb2010-05-15 11:32:37 +00006617 // If we have 2 user-defined types, fall into that path.
6618 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006619 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006620
Steve Naroff4084c302009-07-23 01:01:38 +00006621 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006622}
6623
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006624/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006625/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006626/// arguments in block literals. When passed as arguments, passing 'A*' where
6627/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6628/// not OK. For the return type, the opposite is not OK.
6629bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6630 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006631 const ObjCObjectPointerType *RHSOPT,
6632 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006633 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006634 return true;
6635
6636 if (LHSOPT->isObjCBuiltinType()) {
6637 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6638 }
6639
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006640 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006641 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6642 QualType(RHSOPT,0),
6643 false);
6644
6645 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6646 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6647 if (LHS && RHS) { // We have 2 user-defined types.
6648 if (LHS != RHS) {
6649 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006650 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006651 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006652 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006653 }
6654 else
6655 return true;
6656 }
6657 return false;
6658}
6659
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006660/// getIntersectionOfProtocols - This routine finds the intersection of set
6661/// of protocols inherited from two distinct objective-c pointer objects.
6662/// It is used to build composite qualifier list of the composite type of
6663/// the conditional expression involving two objective-c pointer objects.
6664static
6665void getIntersectionOfProtocols(ASTContext &Context,
6666 const ObjCObjectPointerType *LHSOPT,
6667 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006668 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006669
John McCallc12c5bb2010-05-15 11:32:37 +00006670 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6671 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6672 assert(LHS->getInterface() && "LHS must have an interface base");
6673 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006674
6675 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6676 unsigned LHSNumProtocols = LHS->getNumProtocols();
6677 if (LHSNumProtocols > 0)
6678 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6679 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006680 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006681 Context.CollectInheritedProtocols(LHS->getInterface(),
6682 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006683 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6684 LHSInheritedProtocols.end());
6685 }
6686
6687 unsigned RHSNumProtocols = RHS->getNumProtocols();
6688 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006689 ObjCProtocolDecl **RHSProtocols =
6690 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006691 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6692 if (InheritedProtocolSet.count(RHSProtocols[i]))
6693 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006694 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006695 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006696 Context.CollectInheritedProtocols(RHS->getInterface(),
6697 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006698 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6699 RHSInheritedProtocols.begin(),
6700 E = RHSInheritedProtocols.end(); I != E; ++I)
6701 if (InheritedProtocolSet.count((*I)))
6702 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006703 }
6704}
6705
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006706/// areCommonBaseCompatible - Returns common base class of the two classes if
6707/// one found. Note that this is O'2 algorithm. But it will be called as the
6708/// last type comparison in a ?-exp of ObjC pointer types before a
6709/// warning is issued. So, its invokation is extremely rare.
6710QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006711 const ObjCObjectPointerType *Lptr,
6712 const ObjCObjectPointerType *Rptr) {
6713 const ObjCObjectType *LHS = Lptr->getObjectType();
6714 const ObjCObjectType *RHS = Rptr->getObjectType();
6715 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6716 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006717 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006718 return QualType();
6719
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006720 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006721 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006722 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006723 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006724 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6725
6726 QualType Result = QualType(LHS, 0);
6727 if (!Protocols.empty())
6728 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6729 Result = getObjCObjectPointerType(Result);
6730 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006731 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006732 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006733
6734 return QualType();
6735}
6736
John McCallc12c5bb2010-05-15 11:32:37 +00006737bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6738 const ObjCObjectType *RHS) {
6739 assert(LHS->getInterface() && "LHS is not an interface type");
6740 assert(RHS->getInterface() && "RHS is not an interface type");
6741
Chris Lattner6ac46a42008-04-07 06:51:04 +00006742 // Verify that the base decls are compatible: the RHS must be a subclass of
6743 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006744 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006745 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006746
Chris Lattner6ac46a42008-04-07 06:51:04 +00006747 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6748 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006749 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006750 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006751
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006752 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6753 // more detailed analysis is required.
6754 if (RHS->getNumProtocols() == 0) {
6755 // OK, if LHS is a superclass of RHS *and*
6756 // this superclass is assignment compatible with LHS.
6757 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006758 bool IsSuperClass =
6759 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6760 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006761 // OK if conversion of LHS to SuperClass results in narrowing of types
6762 // ; i.e., SuperClass may implement at least one of the protocols
6763 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6764 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6765 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006766 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006767 // If super class has no protocols, it is not a match.
6768 if (SuperClassInheritedProtocols.empty())
6769 return false;
6770
6771 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6772 LHSPE = LHS->qual_end();
6773 LHSPI != LHSPE; LHSPI++) {
6774 bool SuperImplementsProtocol = false;
6775 ObjCProtocolDecl *LHSProto = (*LHSPI);
6776
6777 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6778 SuperClassInheritedProtocols.begin(),
6779 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6780 ObjCProtocolDecl *SuperClassProto = (*I);
6781 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6782 SuperImplementsProtocol = true;
6783 break;
6784 }
6785 }
6786 if (!SuperImplementsProtocol)
6787 return false;
6788 }
6789 return true;
6790 }
6791 return false;
6792 }
Mike Stump1eb44332009-09-09 15:08:12 +00006793
John McCallc12c5bb2010-05-15 11:32:37 +00006794 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6795 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006796 LHSPI != LHSPE; LHSPI++) {
6797 bool RHSImplementsProtocol = false;
6798
6799 // If the RHS doesn't implement the protocol on the left, the types
6800 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006801 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6802 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006803 RHSPI != RHSPE; RHSPI++) {
6804 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006805 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006806 break;
6807 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006808 }
6809 // FIXME: For better diagnostics, consider passing back the protocol name.
6810 if (!RHSImplementsProtocol)
6811 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006812 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006813 // The RHS implements all protocols listed on the LHS.
6814 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006815}
6816
Steve Naroff389bf462009-02-12 17:52:19 +00006817bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6818 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006819 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6820 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006821
Steve Naroff14108da2009-07-10 23:34:53 +00006822 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006823 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006824
6825 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6826 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006827}
6828
Douglas Gregor569c3162010-08-07 11:51:51 +00006829bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6830 return canAssignObjCInterfaces(
6831 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6832 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6833}
6834
Mike Stump1eb44332009-09-09 15:08:12 +00006835/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006836/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006837/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006838/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006839bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6840 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006841 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006842 return hasSameType(LHS, RHS);
6843
Douglas Gregor447234d2010-07-29 15:18:02 +00006844 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006845}
6846
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006847bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006848 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006849}
6850
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006851bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6852 return !mergeTypes(LHS, RHS, true).isNull();
6853}
6854
Peter Collingbourne48466752010-10-24 18:30:18 +00006855/// mergeTransparentUnionType - if T is a transparent union type and a member
6856/// of T is compatible with SubType, return the merged type, else return
6857/// QualType()
6858QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6859 bool OfBlockPointer,
6860 bool Unqualified) {
6861 if (const RecordType *UT = T->getAsUnionType()) {
6862 RecordDecl *UD = UT->getDecl();
6863 if (UD->hasAttr<TransparentUnionAttr>()) {
6864 for (RecordDecl::field_iterator it = UD->field_begin(),
6865 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006866 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006867 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6868 if (!MT.isNull())
6869 return MT;
6870 }
6871 }
6872 }
6873
6874 return QualType();
6875}
6876
6877/// mergeFunctionArgumentTypes - merge two types which appear as function
6878/// argument types
6879QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6880 bool OfBlockPointer,
6881 bool Unqualified) {
6882 // GNU extension: two types are compatible if they appear as a function
6883 // argument, one of the types is a transparent union type and the other
6884 // type is compatible with a union member
6885 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6886 Unqualified);
6887 if (!lmerge.isNull())
6888 return lmerge;
6889
6890 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6891 Unqualified);
6892 if (!rmerge.isNull())
6893 return rmerge;
6894
6895 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6896}
6897
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006898QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006899 bool OfBlockPointer,
6900 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006901 const FunctionType *lbase = lhs->getAs<FunctionType>();
6902 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006903 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6904 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006905 bool allLTypes = true;
6906 bool allRTypes = true;
6907
6908 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006909 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006910 if (OfBlockPointer) {
6911 QualType RHS = rbase->getResultType();
6912 QualType LHS = lbase->getResultType();
6913 bool UnqualifiedResult = Unqualified;
6914 if (!UnqualifiedResult)
6915 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006916 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006917 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006918 else
John McCall8cc246c2010-12-15 01:06:38 +00006919 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6920 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006921 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006922
6923 if (Unqualified)
6924 retType = retType.getUnqualifiedType();
6925
6926 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6927 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6928 if (Unqualified) {
6929 LRetType = LRetType.getUnqualifiedType();
6930 RRetType = RRetType.getUnqualifiedType();
6931 }
6932
6933 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006934 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006935 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006936 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006937
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006938 // FIXME: double check this
6939 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6940 // rbase->getRegParmAttr() != 0 &&
6941 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006942 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6943 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006944
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006945 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006946 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006947 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006948
John McCall8cc246c2010-12-15 01:06:38 +00006949 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006950 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6951 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006952 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6953 return QualType();
6954
John McCallf85e1932011-06-15 23:02:42 +00006955 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6956 return QualType();
6957
John McCall8cc246c2010-12-15 01:06:38 +00006958 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6959 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006960
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006961 if (lbaseInfo.getNoReturn() != NoReturn)
6962 allLTypes = false;
6963 if (rbaseInfo.getNoReturn() != NoReturn)
6964 allRTypes = false;
6965
John McCallf85e1932011-06-15 23:02:42 +00006966 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006967
Eli Friedman3d815e72008-08-22 00:56:42 +00006968 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006969 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6970 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006971 unsigned lproto_nargs = lproto->getNumArgs();
6972 unsigned rproto_nargs = rproto->getNumArgs();
6973
6974 // Compatible functions must have the same number of arguments
6975 if (lproto_nargs != rproto_nargs)
6976 return QualType();
6977
6978 // Variadic and non-variadic functions aren't compatible
6979 if (lproto->isVariadic() != rproto->isVariadic())
6980 return QualType();
6981
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006982 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6983 return QualType();
6984
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006985 if (LangOpts.ObjCAutoRefCount &&
6986 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6987 return QualType();
6988
Eli Friedman3d815e72008-08-22 00:56:42 +00006989 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006990 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006991 for (unsigned i = 0; i < lproto_nargs; i++) {
6992 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6993 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006994 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6995 OfBlockPointer,
6996 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006997 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006998
6999 if (Unqualified)
7000 argtype = argtype.getUnqualifiedType();
7001
Eli Friedman3d815e72008-08-22 00:56:42 +00007002 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007003 if (Unqualified) {
7004 largtype = largtype.getUnqualifiedType();
7005 rargtype = rargtype.getUnqualifiedType();
7006 }
7007
Chris Lattner61710852008-10-05 17:34:18 +00007008 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7009 allLTypes = false;
7010 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7011 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007012 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007013
Eli Friedman3d815e72008-08-22 00:56:42 +00007014 if (allLTypes) return lhs;
7015 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007016
7017 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7018 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007019 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007020 }
7021
7022 if (lproto) allRTypes = false;
7023 if (rproto) allLTypes = false;
7024
Douglas Gregor72564e72009-02-26 23:50:07 +00007025 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007026 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007027 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007028 if (proto->isVariadic()) return QualType();
7029 // Check that the types are compatible with the types that
7030 // would result from default argument promotions (C99 6.7.5.3p15).
7031 // The only types actually affected are promotable integer
7032 // types and floats, which would be passed as a different
7033 // type depending on whether the prototype is visible.
7034 unsigned proto_nargs = proto->getNumArgs();
7035 for (unsigned i = 0; i < proto_nargs; ++i) {
7036 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007037
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007038 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007039 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007040 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7041 argTy = Enum->getDecl()->getIntegerType();
7042 if (argTy.isNull())
7043 return QualType();
7044 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007045
Eli Friedman3d815e72008-08-22 00:56:42 +00007046 if (argTy->isPromotableIntegerType() ||
7047 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7048 return QualType();
7049 }
7050
7051 if (allLTypes) return lhs;
7052 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007053
7054 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7055 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007056 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007057 }
7058
7059 if (allLTypes) return lhs;
7060 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007061 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007062}
7063
John McCallb9da7132013-03-21 00:10:07 +00007064/// Given that we have an enum type and a non-enum type, try to merge them.
7065static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7066 QualType other, bool isBlockReturnType) {
7067 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7068 // a signed integer type, or an unsigned integer type.
7069 // Compatibility is based on the underlying type, not the promotion
7070 // type.
7071 QualType underlyingType = ET->getDecl()->getIntegerType();
7072 if (underlyingType.isNull()) return QualType();
7073 if (Context.hasSameType(underlyingType, other))
7074 return other;
7075
7076 // In block return types, we're more permissive and accept any
7077 // integral type of the same size.
7078 if (isBlockReturnType && other->isIntegerType() &&
7079 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7080 return other;
7081
7082 return QualType();
7083}
7084
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007085QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007086 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007087 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007088 // C++ [expr]: If an expression initially has the type "reference to T", the
7089 // type is adjusted to "T" prior to any further analysis, the expression
7090 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007091 // expression is an lvalue unless the reference is an rvalue reference and
7092 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007093 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7094 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007095
7096 if (Unqualified) {
7097 LHS = LHS.getUnqualifiedType();
7098 RHS = RHS.getUnqualifiedType();
7099 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007100
Eli Friedman3d815e72008-08-22 00:56:42 +00007101 QualType LHSCan = getCanonicalType(LHS),
7102 RHSCan = getCanonicalType(RHS);
7103
7104 // If two types are identical, they are compatible.
7105 if (LHSCan == RHSCan)
7106 return LHS;
7107
John McCall0953e762009-09-24 19:53:00 +00007108 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007109 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7110 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007111 if (LQuals != RQuals) {
7112 // If any of these qualifiers are different, we have a type
7113 // mismatch.
7114 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007115 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7116 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007117 return QualType();
7118
7119 // Exactly one GC qualifier difference is allowed: __strong is
7120 // okay if the other type has no GC qualifier but is an Objective
7121 // C object pointer (i.e. implicitly strong by default). We fix
7122 // this by pretending that the unqualified type was actually
7123 // qualified __strong.
7124 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7125 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7126 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7127
7128 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7129 return QualType();
7130
7131 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7132 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7133 }
7134 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7135 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7136 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007137 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007138 }
7139
7140 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007141
Eli Friedman852d63b2009-06-01 01:22:52 +00007142 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7143 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007144
Chris Lattner1adb8832008-01-14 05:45:46 +00007145 // We want to consider the two function types to be the same for these
7146 // comparisons, just force one to the other.
7147 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7148 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007149
7150 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007151 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7152 LHSClass = Type::ConstantArray;
7153 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7154 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007155
John McCallc12c5bb2010-05-15 11:32:37 +00007156 // ObjCInterfaces are just specialized ObjCObjects.
7157 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7158 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7159
Nate Begeman213541a2008-04-18 23:10:10 +00007160 // Canonicalize ExtVector -> Vector.
7161 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7162 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007163
Chris Lattnera36a61f2008-04-07 05:43:21 +00007164 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007165 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007166 // Note that we only have special rules for turning block enum
7167 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007168 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007169 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007170 }
John McCall183700f2009-09-21 23:43:11 +00007171 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007172 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007173 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007174 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007175 if (OfBlockPointer && !BlockReturnType) {
7176 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7177 return LHS;
7178 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7179 return RHS;
7180 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007181
Eli Friedman3d815e72008-08-22 00:56:42 +00007182 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007183 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007184
Steve Naroff4a746782008-01-09 22:43:08 +00007185 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007186 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007187#define TYPE(Class, Base)
7188#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007189#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007190#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7191#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7192#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007193 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007194
Richard Smithdc7a4f52013-04-30 13:56:41 +00007195 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007196 case Type::LValueReference:
7197 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007198 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007199 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007200
John McCallc12c5bb2010-05-15 11:32:37 +00007201 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007202 case Type::IncompleteArray:
7203 case Type::VariableArray:
7204 case Type::FunctionProto:
7205 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007206 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007207
Chris Lattner1adb8832008-01-14 05:45:46 +00007208 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007209 {
7210 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007211 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7212 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007213 if (Unqualified) {
7214 LHSPointee = LHSPointee.getUnqualifiedType();
7215 RHSPointee = RHSPointee.getUnqualifiedType();
7216 }
7217 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7218 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007219 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007220 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007221 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007222 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007223 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007224 return getPointerType(ResultType);
7225 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007226 case Type::BlockPointer:
7227 {
7228 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007229 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7230 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007231 if (Unqualified) {
7232 LHSPointee = LHSPointee.getUnqualifiedType();
7233 RHSPointee = RHSPointee.getUnqualifiedType();
7234 }
7235 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7236 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007237 if (ResultType.isNull()) return QualType();
7238 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7239 return LHS;
7240 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7241 return RHS;
7242 return getBlockPointerType(ResultType);
7243 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007244 case Type::Atomic:
7245 {
7246 // Merge two pointer types, while trying to preserve typedef info
7247 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7248 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7249 if (Unqualified) {
7250 LHSValue = LHSValue.getUnqualifiedType();
7251 RHSValue = RHSValue.getUnqualifiedType();
7252 }
7253 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7254 Unqualified);
7255 if (ResultType.isNull()) return QualType();
7256 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7257 return LHS;
7258 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7259 return RHS;
7260 return getAtomicType(ResultType);
7261 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007262 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007263 {
7264 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7265 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7266 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7267 return QualType();
7268
7269 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7270 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007271 if (Unqualified) {
7272 LHSElem = LHSElem.getUnqualifiedType();
7273 RHSElem = RHSElem.getUnqualifiedType();
7274 }
7275
7276 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007277 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007278 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7279 return LHS;
7280 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7281 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007282 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7283 ArrayType::ArraySizeModifier(), 0);
7284 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7285 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007286 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7287 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007288 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7289 return LHS;
7290 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7291 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007292 if (LVAT) {
7293 // FIXME: This isn't correct! But tricky to implement because
7294 // the array's size has to be the size of LHS, but the type
7295 // has to be different.
7296 return LHS;
7297 }
7298 if (RVAT) {
7299 // FIXME: This isn't correct! But tricky to implement because
7300 // the array's size has to be the size of RHS, but the type
7301 // has to be different.
7302 return RHS;
7303 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007304 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7305 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007306 return getIncompleteArrayType(ResultType,
7307 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007308 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007309 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007310 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007311 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007312 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007313 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007314 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007315 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007316 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007317 case Type::Complex:
7318 // Distinct complex types are incompatible.
7319 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007320 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007321 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007322 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7323 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007324 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007325 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007326 case Type::ObjCObject: {
7327 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007328 // FIXME: This should be type compatibility, e.g. whether
7329 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007330 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7331 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7332 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007333 return LHS;
7334
Eli Friedman3d815e72008-08-22 00:56:42 +00007335 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007336 }
Steve Naroff14108da2009-07-10 23:34:53 +00007337 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007338 if (OfBlockPointer) {
7339 if (canAssignObjCInterfacesInBlockPointer(
7340 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007341 RHS->getAs<ObjCObjectPointerType>(),
7342 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007343 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007344 return QualType();
7345 }
John McCall183700f2009-09-21 23:43:11 +00007346 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7347 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007348 return LHS;
7349
Steve Naroffbc76dd02008-12-10 22:14:21 +00007350 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007351 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007352 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007353
David Blaikie7530c032012-01-17 06:56:22 +00007354 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007355}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007356
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007357bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7358 const FunctionProtoType *FromFunctionType,
7359 const FunctionProtoType *ToFunctionType) {
7360 if (FromFunctionType->hasAnyConsumedArgs() !=
7361 ToFunctionType->hasAnyConsumedArgs())
7362 return false;
7363 FunctionProtoType::ExtProtoInfo FromEPI =
7364 FromFunctionType->getExtProtoInfo();
7365 FunctionProtoType::ExtProtoInfo ToEPI =
7366 ToFunctionType->getExtProtoInfo();
7367 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7368 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7369 ArgIdx != NumArgs; ++ArgIdx) {
7370 if (FromEPI.ConsumedArguments[ArgIdx] !=
7371 ToEPI.ConsumedArguments[ArgIdx])
7372 return false;
7373 }
7374 return true;
7375}
7376
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007377/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7378/// 'RHS' attributes and returns the merged version; including for function
7379/// return types.
7380QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7381 QualType LHSCan = getCanonicalType(LHS),
7382 RHSCan = getCanonicalType(RHS);
7383 // If two types are identical, they are compatible.
7384 if (LHSCan == RHSCan)
7385 return LHS;
7386 if (RHSCan->isFunctionType()) {
7387 if (!LHSCan->isFunctionType())
7388 return QualType();
7389 QualType OldReturnType =
7390 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7391 QualType NewReturnType =
7392 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7393 QualType ResReturnType =
7394 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7395 if (ResReturnType.isNull())
7396 return QualType();
7397 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7398 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7399 // In either case, use OldReturnType to build the new function type.
7400 const FunctionType *F = LHS->getAs<FunctionType>();
7401 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007402 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7403 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007404 QualType ResultType =
7405 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007406 return ResultType;
7407 }
7408 }
7409 return QualType();
7410 }
7411
7412 // If the qualifiers are different, the types can still be merged.
7413 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7414 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7415 if (LQuals != RQuals) {
7416 // If any of these qualifiers are different, we have a type mismatch.
7417 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7418 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7419 return QualType();
7420
7421 // Exactly one GC qualifier difference is allowed: __strong is
7422 // okay if the other type has no GC qualifier but is an Objective
7423 // C object pointer (i.e. implicitly strong by default). We fix
7424 // this by pretending that the unqualified type was actually
7425 // qualified __strong.
7426 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7427 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7428 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7429
7430 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7431 return QualType();
7432
7433 if (GC_L == Qualifiers::Strong)
7434 return LHS;
7435 if (GC_R == Qualifiers::Strong)
7436 return RHS;
7437 return QualType();
7438 }
7439
7440 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7441 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7442 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7443 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7444 if (ResQT == LHSBaseQT)
7445 return LHS;
7446 if (ResQT == RHSBaseQT)
7447 return RHS;
7448 }
7449 return QualType();
7450}
7451
Chris Lattner5426bf62008-04-07 07:01:58 +00007452//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007453// Integer Predicates
7454//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007455
Jay Foad4ba2a172011-01-12 09:06:06 +00007456unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007457 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007458 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007459 if (T->isBooleanType())
7460 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007461 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007462 return (unsigned)getTypeSize(T);
7463}
7464
Abramo Bagnara762f1592012-09-09 10:21:24 +00007465QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007466 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007467
7468 // Turn <4 x signed int> -> <4 x unsigned int>
7469 if (const VectorType *VTy = T->getAs<VectorType>())
7470 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007471 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007472
7473 // For enums, we return the unsigned version of the base type.
7474 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007475 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007476
7477 const BuiltinType *BTy = T->getAs<BuiltinType>();
7478 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007479 switch (BTy->getKind()) {
7480 case BuiltinType::Char_S:
7481 case BuiltinType::SChar:
7482 return UnsignedCharTy;
7483 case BuiltinType::Short:
7484 return UnsignedShortTy;
7485 case BuiltinType::Int:
7486 return UnsignedIntTy;
7487 case BuiltinType::Long:
7488 return UnsignedLongTy;
7489 case BuiltinType::LongLong:
7490 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007491 case BuiltinType::Int128:
7492 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007493 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007494 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007495 }
7496}
7497
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007498ASTMutationListener::~ASTMutationListener() { }
7499
Richard Smith9dadfab2013-05-11 05:45:24 +00007500void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7501 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007502
7503//===----------------------------------------------------------------------===//
7504// Builtin Type Computation
7505//===----------------------------------------------------------------------===//
7506
7507/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007508/// pointer over the consumed characters. This returns the resultant type. If
7509/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7510/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7511/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007512///
7513/// RequiresICE is filled in on return to indicate whether the value is required
7514/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007515static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007516 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007517 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007518 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007519 // Modifiers.
7520 int HowLong = 0;
7521 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007522 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007523
Chris Lattner33daae62010-10-01 22:42:38 +00007524 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007525 bool Done = false;
7526 while (!Done) {
7527 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007528 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007529 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007530 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007531 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007532 case 'S':
7533 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7534 assert(!Signed && "Can't use 'S' modifier multiple times!");
7535 Signed = true;
7536 break;
7537 case 'U':
7538 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7539 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7540 Unsigned = true;
7541 break;
7542 case 'L':
7543 assert(HowLong <= 2 && "Can't have LLLL modifier");
7544 ++HowLong;
7545 break;
7546 }
7547 }
7548
7549 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007550
Chris Lattner86df27b2009-06-14 00:45:47 +00007551 // Read the base type.
7552 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007553 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007554 case 'v':
7555 assert(HowLong == 0 && !Signed && !Unsigned &&
7556 "Bad modifiers used with 'v'!");
7557 Type = Context.VoidTy;
7558 break;
7559 case 'f':
7560 assert(HowLong == 0 && !Signed && !Unsigned &&
7561 "Bad modifiers used with 'f'!");
7562 Type = Context.FloatTy;
7563 break;
7564 case 'd':
7565 assert(HowLong < 2 && !Signed && !Unsigned &&
7566 "Bad modifiers used with 'd'!");
7567 if (HowLong)
7568 Type = Context.LongDoubleTy;
7569 else
7570 Type = Context.DoubleTy;
7571 break;
7572 case 's':
7573 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7574 if (Unsigned)
7575 Type = Context.UnsignedShortTy;
7576 else
7577 Type = Context.ShortTy;
7578 break;
7579 case 'i':
7580 if (HowLong == 3)
7581 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7582 else if (HowLong == 2)
7583 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7584 else if (HowLong == 1)
7585 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7586 else
7587 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7588 break;
7589 case 'c':
7590 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7591 if (Signed)
7592 Type = Context.SignedCharTy;
7593 else if (Unsigned)
7594 Type = Context.UnsignedCharTy;
7595 else
7596 Type = Context.CharTy;
7597 break;
7598 case 'b': // boolean
7599 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7600 Type = Context.BoolTy;
7601 break;
7602 case 'z': // size_t.
7603 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7604 Type = Context.getSizeType();
7605 break;
7606 case 'F':
7607 Type = Context.getCFConstantStringType();
7608 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007609 case 'G':
7610 Type = Context.getObjCIdType();
7611 break;
7612 case 'H':
7613 Type = Context.getObjCSelType();
7614 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007615 case 'M':
7616 Type = Context.getObjCSuperType();
7617 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007618 case 'a':
7619 Type = Context.getBuiltinVaListType();
7620 assert(!Type.isNull() && "builtin va list type not initialized!");
7621 break;
7622 case 'A':
7623 // This is a "reference" to a va_list; however, what exactly
7624 // this means depends on how va_list is defined. There are two
7625 // different kinds of va_list: ones passed by value, and ones
7626 // passed by reference. An example of a by-value va_list is
7627 // x86, where va_list is a char*. An example of by-ref va_list
7628 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7629 // we want this argument to be a char*&; for x86-64, we want
7630 // it to be a __va_list_tag*.
7631 Type = Context.getBuiltinVaListType();
7632 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007633 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007635 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007636 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007637 break;
7638 case 'V': {
7639 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007640 unsigned NumElements = strtoul(Str, &End, 10);
7641 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007642 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007643
Chris Lattner14e0e742010-10-01 22:53:11 +00007644 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7645 RequiresICE, false);
7646 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007647
7648 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007649 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007650 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007651 break;
7652 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007653 case 'E': {
7654 char *End;
7655
7656 unsigned NumElements = strtoul(Str, &End, 10);
7657 assert(End != Str && "Missing vector size");
7658
7659 Str = End;
7660
7661 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7662 false);
7663 Type = Context.getExtVectorType(ElementType, NumElements);
7664 break;
7665 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007666 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007667 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7668 false);
7669 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007670 Type = Context.getComplexType(ElementType);
7671 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007672 }
7673 case 'Y' : {
7674 Type = Context.getPointerDiffType();
7675 break;
7676 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007677 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007678 Type = Context.getFILEType();
7679 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007680 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007681 return QualType();
7682 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007683 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007684 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007685 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007686 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007687 else
7688 Type = Context.getjmp_bufType();
7689
Mike Stumpfd612db2009-07-28 23:47:15 +00007690 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007691 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007692 return QualType();
7693 }
7694 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007695 case 'K':
7696 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7697 Type = Context.getucontext_tType();
7698
7699 if (Type.isNull()) {
7700 Error = ASTContext::GE_Missing_ucontext;
7701 return QualType();
7702 }
7703 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007704 case 'p':
7705 Type = Context.getProcessIDType();
7706 break;
Mike Stump782fa302009-07-28 02:25:19 +00007707 }
Mike Stump1eb44332009-09-09 15:08:12 +00007708
Chris Lattner33daae62010-10-01 22:42:38 +00007709 // If there are modifiers and if we're allowed to parse them, go for it.
7710 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007711 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007712 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007713 default: Done = true; --Str; break;
7714 case '*':
7715 case '&': {
7716 // Both pointers and references can have their pointee types
7717 // qualified with an address space.
7718 char *End;
7719 unsigned AddrSpace = strtoul(Str, &End, 10);
7720 if (End != Str && AddrSpace != 0) {
7721 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7722 Str = End;
7723 }
7724 if (c == '*')
7725 Type = Context.getPointerType(Type);
7726 else
7727 Type = Context.getLValueReferenceType(Type);
7728 break;
7729 }
7730 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7731 case 'C':
7732 Type = Type.withConst();
7733 break;
7734 case 'D':
7735 Type = Context.getVolatileType(Type);
7736 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007737 case 'R':
7738 Type = Type.withRestrict();
7739 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007740 }
7741 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007742
Chris Lattner14e0e742010-10-01 22:53:11 +00007743 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007744 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007745
Chris Lattner86df27b2009-06-14 00:45:47 +00007746 return Type;
7747}
7748
7749/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007750QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007751 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007752 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007753 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007754
Chris Lattner5f9e2722011-07-23 10:55:15 +00007755 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007756
Chris Lattner14e0e742010-10-01 22:53:11 +00007757 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007758 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007759 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7760 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007761 if (Error != GE_None)
7762 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007763
7764 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7765
Chris Lattner86df27b2009-06-14 00:45:47 +00007766 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007767 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007768 if (Error != GE_None)
7769 return QualType();
7770
Chris Lattner14e0e742010-10-01 22:53:11 +00007771 // If this argument is required to be an IntegerConstantExpression and the
7772 // caller cares, fill in the bitmask we return.
7773 if (RequiresICE && IntegerConstantArgs)
7774 *IntegerConstantArgs |= 1 << ArgTypes.size();
7775
Chris Lattner86df27b2009-06-14 00:45:47 +00007776 // Do array -> pointer decay. The builtin should use the decayed type.
7777 if (Ty->isArrayType())
7778 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007779
Chris Lattner86df27b2009-06-14 00:45:47 +00007780 ArgTypes.push_back(Ty);
7781 }
7782
7783 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7784 "'.' should only occur at end of builtin type list!");
7785
John McCall00ccbef2010-12-21 00:44:39 +00007786 FunctionType::ExtInfo EI;
7787 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7788
7789 bool Variadic = (TypeStr[0] == '.');
7790
7791 // We really shouldn't be making a no-proto type here, especially in C++.
7792 if (ArgTypes.empty() && Variadic)
7793 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007794
John McCalle23cf432010-12-14 08:05:40 +00007795 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007796 EPI.ExtInfo = EI;
7797 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007798
Jordan Rosebea522f2013-03-08 21:51:21 +00007799 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007800}
Eli Friedmana95d7572009-08-19 07:44:53 +00007801
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007802GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007803 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007804 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007805
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007806 GVALinkage External = GVA_StrongExternal;
7807 switch (FD->getTemplateSpecializationKind()) {
7808 case TSK_Undeclared:
7809 case TSK_ExplicitSpecialization:
7810 External = GVA_StrongExternal;
7811 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007812
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007813 case TSK_ExplicitInstantiationDefinition:
7814 return GVA_ExplicitTemplateInstantiation;
7815
7816 case TSK_ExplicitInstantiationDeclaration:
7817 case TSK_ImplicitInstantiation:
7818 External = GVA_TemplateInstantiation;
7819 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007820 }
7821
7822 if (!FD->isInlined())
7823 return External;
David Majnemer13163702013-08-01 17:26:42 +00007824
7825 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7826 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007827 // GNU or C99 inline semantics. Determine whether this symbol should be
7828 // externally visible.
7829 if (FD->isInlineDefinitionExternallyVisible())
7830 return External;
7831
7832 // C99 inline semantics, where the symbol is not externally visible.
7833 return GVA_C99Inline;
7834 }
7835
7836 // C++0x [temp.explicit]p9:
7837 // [ Note: The intent is that an inline function that is the subject of
7838 // an explicit instantiation declaration will still be implicitly
7839 // instantiated when used so that the body can be considered for
7840 // inlining, but that no out-of-line copy of the inline function would be
7841 // generated in the translation unit. -- end note ]
7842 if (FD->getTemplateSpecializationKind()
7843 == TSK_ExplicitInstantiationDeclaration)
7844 return GVA_C99Inline;
7845
7846 return GVA_CXXInline;
7847}
7848
7849GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007850 if (!VD->isExternallyVisible())
7851 return GVA_Internal;
7852
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007853 // If this is a static data member, compute the kind of template
7854 // specialization. Otherwise, this variable is not part of a
7855 // template.
7856 TemplateSpecializationKind TSK = TSK_Undeclared;
7857 if (VD->isStaticDataMember())
7858 TSK = VD->getTemplateSpecializationKind();
7859
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007860 switch (TSK) {
7861 case TSK_Undeclared:
7862 case TSK_ExplicitSpecialization:
7863 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007864
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007865 case TSK_ExplicitInstantiationDeclaration:
7866 llvm_unreachable("Variable should not be instantiated");
7867 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007868
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007869 case TSK_ExplicitInstantiationDefinition:
7870 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007871
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007872 case TSK_ImplicitInstantiation:
7873 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007874 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007875
7876 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007877}
7878
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007879bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007880 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7881 if (!VD->isFileVarDecl())
7882 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007883 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7884 // We never need to emit an uninstantiated function template.
7885 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7886 return false;
7887 } else
7888 return false;
7889
7890 // If this is a member of a class template, we do not need to emit it.
7891 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007892 return false;
7893
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007894 // Weak references don't produce any output by themselves.
7895 if (D->hasAttr<WeakRefAttr>())
7896 return false;
7897
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007898 // Aliases and used decls are required.
7899 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7900 return true;
7901
7902 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7903 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007904 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007905 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007906
7907 // Constructors and destructors are required.
7908 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7909 return true;
7910
John McCalld5617ee2013-01-25 22:31:03 +00007911 // The key function for a class is required. This rule only comes
7912 // into play when inline functions can be key functions, though.
7913 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7914 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7915 const CXXRecordDecl *RD = MD->getParent();
7916 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7917 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7918 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7919 return true;
7920 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007921 }
7922 }
7923
7924 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7925
7926 // static, static inline, always_inline, and extern inline functions can
7927 // always be deferred. Normal inline functions can be deferred in C99/C++.
7928 // Implicit template instantiations can also be deferred in C++.
7929 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007930 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007931 return false;
7932 return true;
7933 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007934
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007935 const VarDecl *VD = cast<VarDecl>(D);
7936 assert(VD->isFileVarDecl() && "Expected file scoped var");
7937
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007938 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7939 return false;
7940
Richard Smith5f9a7e32012-11-12 21:38:00 +00007941 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007942 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007943 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7944 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007945
Richard Smith5f9a7e32012-11-12 21:38:00 +00007946 // Variables that have destruction with side-effects are required.
7947 if (VD->getType().isDestructedType())
7948 return true;
7949
7950 // Variables that have initialization with side-effects are required.
7951 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7952 return true;
7953
7954 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007955}
Charles Davis071cc7d2010-08-16 03:33:14 +00007956
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007957CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007958 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007959 return ABI->getDefaultMethodCallConv(isVariadic);
7960}
7961
7962CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007963 if (CC == CC_C && !LangOpts.MRTD &&
7964 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007965 return CC_Default;
7966 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007967}
7968
Jay Foad4ba2a172011-01-12 09:06:06 +00007969bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007970 // Pass through to the C++ ABI object
7971 return ABI->isNearlyEmpty(RD);
7972}
7973
Peter Collingbourne14110472011-01-13 18:57:25 +00007974MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007975 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007976 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007977 case TargetCXXABI::GenericItanium:
7978 case TargetCXXABI::GenericARM:
7979 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007980 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007981 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007982 return createMicrosoftMangleContext(*this, getDiagnostics());
7983 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007984 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007985}
7986
Charles Davis071cc7d2010-08-16 03:33:14 +00007987CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007988
7989size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00007990 return ASTRecordLayouts.getMemorySize() +
7991 llvm::capacity_in_bytes(ObjCLayouts) +
7992 llvm::capacity_in_bytes(KeyFunctions) +
7993 llvm::capacity_in_bytes(ObjCImpls) +
7994 llvm::capacity_in_bytes(BlockVarCopyInits) +
7995 llvm::capacity_in_bytes(DeclAttrs) +
7996 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7997 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7998 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7999 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8000 llvm::capacity_in_bytes(OverriddenMethods) +
8001 llvm::capacity_in_bytes(Types) +
8002 llvm::capacity_in_bytes(VariableArrayTypes) +
8003 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008004}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008005
Eli Friedman5e867c82013-07-10 00:30:46 +00008006void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8007 if (Number > 1)
8008 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00008009}
8010
Eli Friedman5e867c82013-07-10 00:30:46 +00008011unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8012 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8013 MangleNumbers.find(ND);
8014 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008015}
8016
Eli Friedman5e867c82013-07-10 00:30:46 +00008017MangleNumberingContext &
8018ASTContext::getManglingNumberContext(const DeclContext *DC) {
Eli Friedman07369dd2013-07-01 20:22:57 +00008019 return MangleNumberingContexts[DC];
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008020}
8021
Ted Kremenekd211cb72011-10-06 05:00:56 +00008022void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8023 ParamIndices[D] = index;
8024}
8025
8026unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8027 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8028 assert(I != ParamIndices.end() &&
8029 "ParmIndices lacks entry set by ParmVarDecl");
8030 return I->second;
8031}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008032
Richard Smith211c8dd2013-06-05 00:46:14 +00008033APValue *
8034ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8035 bool MayCreate) {
8036 assert(E && E->getStorageDuration() == SD_Static &&
8037 "don't need to cache the computed value for this temporary");
8038 if (MayCreate)
8039 return &MaterializedTemporaryValues[E];
8040
8041 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8042 MaterializedTemporaryValues.find(E);
8043 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8044}
8045
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008046bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8047 const llvm::Triple &T = getTargetInfo().getTriple();
8048 if (!T.isOSDarwin())
8049 return false;
8050
8051 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8052 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8053 uint64_t Size = sizeChars.getQuantity();
8054 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8055 unsigned Align = alignChars.getQuantity();
8056 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8057 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8058}
Reid Klecknercff15122013-06-17 12:56:08 +00008059
8060namespace {
8061
8062 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8063 /// parents as defined by the \c RecursiveASTVisitor.
8064 ///
8065 /// Note that the relationship described here is purely in terms of AST
8066 /// traversal - there are other relationships (for example declaration context)
8067 /// in the AST that are better modeled by special matchers.
8068 ///
8069 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8070 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8071
8072 public:
8073 /// \brief Builds and returns the translation unit's parent map.
8074 ///
8075 /// The caller takes ownership of the returned \c ParentMap.
8076 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8077 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8078 Visitor.TraverseDecl(&TU);
8079 return Visitor.Parents;
8080 }
8081
8082 private:
8083 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8084
8085 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8086 }
8087
8088 bool shouldVisitTemplateInstantiations() const {
8089 return true;
8090 }
8091 bool shouldVisitImplicitCode() const {
8092 return true;
8093 }
8094 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8095 // are not triggered during data recursion.
8096 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8097 return false;
8098 }
8099
8100 template <typename T>
8101 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8102 if (Node == NULL)
8103 return true;
8104 if (ParentStack.size() > 0)
8105 // FIXME: Currently we add the same parent multiple times, for example
8106 // when we visit all subexpressions of template instantiations; this is
8107 // suboptimal, bug benign: the only way to visit those is with
8108 // hasAncestor / hasParent, and those do not create new matches.
8109 // The plan is to enable DynTypedNode to be storable in a map or hash
8110 // map. The main problem there is to implement hash functions /
8111 // comparison operators for all types that DynTypedNode supports that
8112 // do not have pointer identity.
8113 (*Parents)[Node].push_back(ParentStack.back());
8114 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8115 bool Result = (this ->* traverse) (Node);
8116 ParentStack.pop_back();
8117 return Result;
8118 }
8119
8120 bool TraverseDecl(Decl *DeclNode) {
8121 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8122 }
8123
8124 bool TraverseStmt(Stmt *StmtNode) {
8125 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8126 }
8127
8128 ASTContext::ParentMap *Parents;
8129 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8130
8131 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8132 };
8133
8134} // end namespace
8135
8136ASTContext::ParentVector
8137ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8138 assert(Node.getMemoizationData() &&
8139 "Invariant broken: only nodes that support memoization may be "
8140 "used in the parent map.");
8141 if (!AllParents) {
8142 // We always need to run over the whole translation unit, as
8143 // hasAncestor can escape any subtree.
8144 AllParents.reset(
8145 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8146 }
8147 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8148 if (I == AllParents->end()) {
8149 return ParentVector();
8150 }
8151 return I->second;
8152}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008153
8154bool
8155ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8156 const ObjCMethodDecl *MethodImpl) {
8157 // No point trying to match an unavailable/deprecated mothod.
8158 if (MethodDecl->hasAttr<UnavailableAttr>()
8159 || MethodDecl->hasAttr<DeprecatedAttr>())
8160 return false;
8161 if (MethodDecl->getObjCDeclQualifier() !=
8162 MethodImpl->getObjCDeclQualifier())
8163 return false;
8164 if (!hasSameType(MethodDecl->getResultType(),
8165 MethodImpl->getResultType()))
8166 return false;
8167
8168 if (MethodDecl->param_size() != MethodImpl->param_size())
8169 return false;
8170
8171 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8172 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8173 EF = MethodDecl->param_end();
8174 IM != EM && IF != EF; ++IM, ++IF) {
8175 const ParmVarDecl *DeclVar = (*IF);
8176 const ParmVarDecl *ImplVar = (*IM);
8177 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8178 return false;
8179 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8180 return false;
8181 }
8182 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8183
8184}