blob: c76ed5fdb98025635479e4a34c051888bcb02366 [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();
136 else
137 DeclLoc = D->getLocation();
138
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000139 // If the declaration doesn't map directly to a location in a file, we
140 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000141 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
142 return NULL;
143
144 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000145 ArrayRef<RawComment *>::iterator Comment;
146 {
147 // When searching for comments during parsing, the comment we are looking
148 // for is usually among the last two comments we parsed -- check them
149 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000150 RawComment CommentAtDeclLoc(
151 SourceMgr, SourceRange(DeclLoc), false,
152 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000153 BeforeThanCompare<RawComment> Compare(SourceMgr);
154 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
155 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
156 if (!Found && RawComments.size() >= 2) {
157 MaybeBeforeDecl--;
158 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
159 }
160
161 if (Found) {
162 Comment = MaybeBeforeDecl + 1;
163 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
164 &CommentAtDeclLoc, Compare));
165 } else {
166 // Slow path.
167 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
168 &CommentAtDeclLoc, Compare);
169 }
170 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171
172 // Decompose the location for the declaration and find the beginning of the
173 // file buffer.
174 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
175
176 // First check whether we have a trailing comment.
177 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000178 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000179 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000180 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 // Check that Doxygen trailing comment comes after the declaration, starts
183 // on the same line and in the same file as the declaration.
184 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
185 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
186 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
187 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 }
190 }
191
192 // The comment just after the declaration was not a trailing comment.
193 // Let's look at the previous comment.
194 if (Comment == RawComments.begin())
195 return NULL;
196 --Comment;
197
198 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000199 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000200 return NULL;
201
202 // Decompose the end of the comment.
203 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000204 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000205
206 // If the comment and the declaration aren't in the same file, then they
207 // aren't related.
208 if (DeclLocDecomp.first != CommentEndDecomp.first)
209 return NULL;
210
211 // Get the corresponding buffer.
212 bool Invalid = false;
213 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
214 &Invalid).data();
215 if (Invalid)
216 return NULL;
217
218 // Extract text between the comment and declaration.
219 StringRef Text(Buffer + CommentEndDecomp.second,
220 DeclLocDecomp.second - CommentEndDecomp.second);
221
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000222 // There should be no other declarations or preprocessor directives between
223 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000224 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000225 return NULL;
226
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000227 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000228}
229
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000230namespace {
231/// If we have a 'templated' declaration for a template, adjust 'D' to
232/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000233/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000234const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000236 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000237 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000238 return FTD;
239
240 // Nothing to do if function is not an implicit instantiation.
241 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
242 return D;
243
244 // Function is an implicit instantiation of a function template?
245 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
246 return FTD;
247
248 // Function is instantiated from a member definition of a class template?
249 if (const FunctionDecl *MemberDecl =
250 FD->getInstantiatedFromMemberFunction())
251 return MemberDecl;
252
253 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000254 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
256 // Static data member is instantiated from a member definition of a class
257 // template?
258 if (VD->isStaticDataMember())
259 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
260 return MemberDecl;
261
262 return D;
263 }
264 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
265 // Is this class declaration part of a class template?
266 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
267 return CTD;
268
269 // Class is an implicit instantiation of a class template or partial
270 // specialization?
271 if (const ClassTemplateSpecializationDecl *CTSD =
272 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
273 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
274 return D;
275 llvm::PointerUnion<ClassTemplateDecl *,
276 ClassTemplatePartialSpecializationDecl *>
277 PU = CTSD->getSpecializedTemplateOrPartial();
278 return PU.is<ClassTemplateDecl*>() ?
279 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
280 static_cast<const Decl*>(
281 PU.get<ClassTemplatePartialSpecializationDecl *>());
282 }
283
284 // Class is instantiated from a member definition of a class template?
285 if (const MemberSpecializationInfo *Info =
286 CRD->getMemberSpecializationInfo())
287 return Info->getInstantiatedFrom();
288
289 return D;
290 }
291 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
292 // Enum is instantiated from a member definition of a class template?
293 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
294 return MemberDecl;
295
296 return D;
297 }
298 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000299 return D;
300}
301} // unnamed namespace
302
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000303const RawComment *ASTContext::getRawCommentForAnyRedecl(
304 const Decl *D,
305 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000307
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000308 // Check whether we have cached a comment for this declaration already.
309 {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(D);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 if (OriginalDecl)
316 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000320 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000321
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 // Search for comments attached to declarations in the redeclaration chain.
323 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000324 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 for (Decl::redecl_iterator I = D->redecls_begin(),
326 E = D->redecls_end();
327 I != E; ++I) {
328 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
329 RedeclComments.find(*I);
330 if (Pos != RedeclComments.end()) {
331 const RawCommentAndCacheFlags &Raw = Pos->second;
332 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
333 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000334 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000335 break;
336 }
337 } else {
338 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000339 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000340 RawCommentAndCacheFlags Raw;
341 if (RC) {
342 Raw.setRaw(RC);
343 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
344 } else
345 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RedeclComments[*I] = Raw;
348 if (RC)
349 break;
350 }
351 }
352
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000353 // If we found a comment, it should be a documentation comment.
354 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000356 if (OriginalDecl)
357 *OriginalDecl = OriginalDeclForRC;
358
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000359 // Update cache for every declaration in the redeclaration chain.
360 RawCommentAndCacheFlags Raw;
361 Raw.setRaw(RC);
362 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000364
365 for (Decl::redecl_iterator I = D->redecls_begin(),
366 E = D->redecls_end();
367 I != E; ++I) {
368 RawCommentAndCacheFlags &R = RedeclComments[*I];
369 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
370 R = Raw;
371 }
372
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000373 return RC;
374}
375
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000376static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
377 SmallVectorImpl<const NamedDecl *> &Redeclared) {
378 const DeclContext *DC = ObjCMethod->getDeclContext();
379 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
380 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
381 if (!ID)
382 return;
383 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000384 for (ObjCInterfaceDecl::known_extensions_iterator
385 Ext = ID->known_extensions_begin(),
386 ExtEnd = ID->known_extensions_end();
387 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000388 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000389 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000390 ObjCMethod->isInstanceMethod()))
391 Redeclared.push_back(RedeclaredMethod);
392 }
393 }
394}
395
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000396comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
397 const Decl *D) const {
398 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
399 ThisDeclInfo->CommentDecl = D;
400 ThisDeclInfo->IsFilled = false;
401 ThisDeclInfo->fill();
402 ThisDeclInfo->CommentDecl = FC->getDecl();
403 comments::FullComment *CFC =
404 new (*this) comments::FullComment(FC->getBlocks(),
405 ThisDeclInfo);
406 return CFC;
407
408}
409
Richard Smith0a74a4c2013-05-21 05:24:00 +0000410comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
411 const RawComment *RC = getRawCommentForDeclNoCache(D);
412 return RC ? RC->parse(*this, 0, D) : 0;
413}
414
Dmitri Gribenko19523542012-09-29 11:40:46 +0000415comments::FullComment *ASTContext::getCommentForDecl(
416 const Decl *D,
417 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000418 if (D->isInvalidDecl())
419 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000420 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000422 const Decl *Canonical = D->getCanonicalDecl();
423 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
424 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000425
426 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000427 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000429 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000430 return CFC;
431 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000432 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433 }
434
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000435 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000437 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 if (!RC) {
439 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000440 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000441 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000442 if (OMD && OMD->isPropertyAccessor())
443 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
444 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000446 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 addRedeclaredMethods(OMD, Overridden);
448 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
450 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000452 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000453 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000454 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000455 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000456 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000457 if (const TagType *TT = QT->getAs<TagType>())
458 if (const Decl *TD = TT->getDecl())
459 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000460 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000461 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000462 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
463 while (IC->getSuperClass()) {
464 IC = IC->getSuperClass();
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 }
469 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
470 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
475 if (!(RD = RD->getDefinition()))
476 return NULL;
477 // Check non-virtual bases.
478 for (CXXRecordDecl::base_class_const_iterator I =
479 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000480 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000481 continue;
482 QualType Ty = I->getType();
483 if (Ty.isNull())
484 continue;
485 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
486 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
487 continue;
488
489 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 // Check virtual bases.
494 for (CXXRecordDecl::base_class_const_iterator I =
495 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000496 if (I->getAccessSpecifier() != AS_public)
497 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000498 QualType Ty = I->getType();
499 if (Ty.isNull())
500 continue;
501 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
502 if (!(VirtualBase= VirtualBase->getDefinition()))
503 continue;
504 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
505 return cloneFullComment(FC, D);
506 }
507 }
508 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000509 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000510 }
511
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000512 // If the RawComment was attached to other redeclaration of this Decl, we
513 // should parse the comment in context of that other Decl. This is important
514 // because comments can contain references to parameter names which can be
515 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000516 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000517 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000518
Dmitri Gribenko19523542012-09-29 11:40:46 +0000519 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000520 ParsedComments[Canonical] = FC;
521 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000522}
523
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000524void
525ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
526 TemplateTemplateParmDecl *Parm) {
527 ID.AddInteger(Parm->getDepth());
528 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000529 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000530
531 TemplateParameterList *Params = Parm->getTemplateParameters();
532 ID.AddInteger(Params->size());
533 for (TemplateParameterList::const_iterator P = Params->begin(),
534 PEnd = Params->end();
535 P != PEnd; ++P) {
536 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
537 ID.AddInteger(0);
538 ID.AddBoolean(TTP->isParameterPack());
539 continue;
540 }
541
542 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
543 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000544 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000545 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 if (NTTP->isExpandedParameterPack()) {
547 ID.AddBoolean(true);
548 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000549 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
550 QualType T = NTTP->getExpansionType(I);
551 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
552 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 } else
554 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000555 continue;
556 }
557
558 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
559 ID.AddInteger(2);
560 Profile(ID, TTP);
561 }
562}
563
564TemplateTemplateParmDecl *
565ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000566 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000567 // Check if we already have a canonical template template parameter.
568 llvm::FoldingSetNodeID ID;
569 CanonicalTemplateTemplateParm::Profile(ID, TTP);
570 void *InsertPos = 0;
571 CanonicalTemplateTemplateParm *Canonical
572 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
573 if (Canonical)
574 return Canonical->getParam();
575
576 // Build a canonical template parameter list.
577 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000579 CanonParams.reserve(Params->size());
580 for (TemplateParameterList::const_iterator P = Params->begin(),
581 PEnd = Params->end();
582 P != PEnd; ++P) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
584 CanonParams.push_back(
585 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000586 SourceLocation(),
587 SourceLocation(),
588 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000589 TTP->getIndex(), 0, false,
590 TTP->isParameterPack()));
591 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000592 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
593 QualType T = getCanonicalType(NTTP->getType());
594 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
595 NonTypeTemplateParmDecl *Param;
596 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVector<QualType, 2> ExpandedTypes;
598 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
600 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
601 ExpandedTInfos.push_back(
602 getTrivialTypeSourceInfo(ExpandedTypes.back()));
603 }
604
605 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000606 SourceLocation(),
607 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000608 NTTP->getDepth(),
609 NTTP->getPosition(), 0,
610 T,
611 TInfo,
612 ExpandedTypes.data(),
613 ExpandedTypes.size(),
614 ExpandedTInfos.data());
615 } else {
616 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000617 SourceLocation(),
618 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000619 NTTP->getDepth(),
620 NTTP->getPosition(), 0,
621 T,
622 NTTP->isParameterPack(),
623 TInfo);
624 }
625 CanonParams.push_back(Param);
626
627 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000628 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
629 cast<TemplateTemplateParmDecl>(*P)));
630 }
631
632 TemplateTemplateParmDecl *CanonTTP
633 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
634 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000635 TTP->getPosition(),
636 TTP->isParameterPack(),
637 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000638 TemplateParameterList::Create(*this, SourceLocation(),
639 SourceLocation(),
640 CanonParams.data(),
641 CanonParams.size(),
642 SourceLocation()));
643
644 // Get the new insert position for the node we care about.
645 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 assert(Canonical == 0 && "Shouldn't be in the map!");
647 (void)Canonical;
648
649 // Create the canonical template template parameter entry.
650 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
651 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
652 return CanonTTP;
653}
654
Charles Davis071cc7d2010-08-16 03:33:14 +0000655CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000656 if (!LangOpts.CPlusPlus) return 0;
657
John McCallb8b2c9d2013-01-25 22:30:49 +0000658 switch (T.getCXXABI().getKind()) {
659 case TargetCXXABI::GenericARM:
660 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000661 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000662 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000663 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000664 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000666 return CreateMicrosoftCXXABI(*this);
667 }
David Blaikie7530c032012-01-17 06:56:22 +0000668 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000669}
670
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000671static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000672 const LangOptions &LOpts) {
673 if (LOpts.FakeAddressSpaceMap) {
674 // The fake address space map must have a distinct entry for each
675 // language-specific address space.
676 static const unsigned FakeAddrSpaceMap[] = {
677 1, // opencl_global
678 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000679 3, // opencl_constant
680 4, // cuda_device
681 5, // cuda_constant
682 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000683 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000684 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000685 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000687 }
688}
689
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000690ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000692 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000693 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 unsigned size_reserve,
695 bool DelayInitialization)
696 : FunctionProtoTypes(this_()),
697 TemplateSpecializationTypes(this_()),
698 DependentTemplateSpecializationTypes(this_()),
699 SubstTemplateTemplateParmPacks(this_()),
700 GlobalNestedNameSpecifier(0),
701 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000702 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000703 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000704 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000705 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000706 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000707 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
708 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
709 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000710 NullTypeSourceInfo(QualType()),
711 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000713 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 Idents(idents), Selectors(sels),
715 BuiltinInfo(builtins),
716 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000717 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000718 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000719 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000720 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721{
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000723 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724
725 if (!DelayInitialization) {
726 assert(t && "No target supplied for ASTContext initialization");
727 InitBuiltinTypes(*t);
728 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000732 // Release the DenseMaps associated with DeclContext objects.
733 // FIXME: Is this the ideal solution?
734 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000735
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000736 // Call all of the deallocation functions on all of their targets.
737 for (DeallocationMap::const_iterator I = Deallocations.begin(),
738 E = Deallocations.end(); I != E; ++I)
739 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
740 (I->first)((I->second)[J]);
741
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000742 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000743 // because they can contain DenseMaps.
744 for (llvm::DenseMap<const ObjCContainerDecl*,
745 const ASTRecordLayout*>::iterator
746 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
747 // Increment in loop to prevent using deallocated memory.
748 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
749 R->Destroy(*this);
750
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000751 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
752 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
753 // Increment in loop to prevent using deallocated memory.
754 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
755 R->Destroy(*this);
756 }
Douglas Gregor63200642010-08-30 16:49:28 +0000757
758 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
759 AEnd = DeclAttrs.end();
760 A != AEnd; ++A)
761 A->second->~AttrVec();
762}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000763
Douglas Gregor00545312010-05-23 18:26:36 +0000764void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000765 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000766}
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000769ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000770 ExternalSource.reset(Source.take());
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000774 llvm::errs() << "\n*** AST Context Stats:\n";
775 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000776
Douglas Gregordbe833d2009-05-26 14:40:08 +0000777 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000778#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000779#define ABSTRACT_TYPE(Name, Parent)
780#include "clang/AST/TypeNodes.def"
781 0 // Extra
782 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
785 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
788
Douglas Gregordbe833d2009-05-26 14:40:08 +0000789 unsigned Idx = 0;
790 unsigned TotalBytes = 0;
791#define TYPE(Name, Parent) \
792 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000793 llvm::errs() << " " << counts[Idx] << " " << #Name \
794 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000795 TotalBytes += counts[Idx] * sizeof(Name##Type); \
796 ++Idx;
797#define ABSTRACT_TYPE(Name, Parent)
798#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
801
Douglas Gregor4923aa22010-07-02 20:37:36 +0000802 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
804 << NumImplicitDefaultConstructors
805 << " implicit default constructors created\n";
806 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
807 << NumImplicitCopyConstructors
808 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
811 << NumImplicitMoveConstructors
812 << " implicit move constructors created\n";
813 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
814 << NumImplicitCopyAssignmentOperators
815 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
818 << NumImplicitMoveAssignmentOperators
819 << " implicit move assignment operators created\n";
820 llvm::errs() << NumImplicitDestructorsDeclared << "/"
821 << NumImplicitDestructors
822 << " implicit destructors created\n";
823
Douglas Gregor2cf26342009-04-09 22:27:44 +0000824 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000825 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000826 ExternalSource->PrintStats();
827 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000828
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000829 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Douglas Gregor772eeae2011-08-12 06:49:56 +0000832TypedefDecl *ASTContext::getInt128Decl() const {
833 if (!Int128Decl) {
834 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
835 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
836 getTranslationUnitDecl(),
837 SourceLocation(),
838 SourceLocation(),
839 &Idents.get("__int128_t"),
840 TInfo);
841 }
842
843 return Int128Decl;
844}
845
846TypedefDecl *ASTContext::getUInt128Decl() const {
847 if (!UInt128Decl) {
848 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
849 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
850 getTranslationUnitDecl(),
851 SourceLocation(),
852 SourceLocation(),
853 &Idents.get("__uint128_t"),
854 TInfo);
855 }
856
857 return UInt128Decl;
858}
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
John McCalle27ec8a2009-10-23 23:03:21 +0000860void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000861 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000862 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000863 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000864}
865
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000866void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
867 assert((!this->Target || this->Target == &Target) &&
868 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000871 this->Target = &Target;
872
873 ABI.reset(createCXXABI(Target));
874 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // C99 6.2.5p19.
877 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 // C99 6.2.5p2.
880 InitBuiltinType(BoolTy, BuiltinType::Bool);
881 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000882 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 InitBuiltinType(CharTy, BuiltinType::Char_S);
884 else
885 InitBuiltinType(CharTy, BuiltinType::Char_U);
886 // C99 6.2.5p4.
887 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
888 InitBuiltinType(ShortTy, BuiltinType::Short);
889 InitBuiltinType(IntTy, BuiltinType::Int);
890 InitBuiltinType(LongTy, BuiltinType::Long);
891 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p6.
894 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
895 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
896 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
897 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
898 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // C99 6.2.5p10.
901 InitBuiltinType(FloatTy, BuiltinType::Float);
902 InitBuiltinType(DoubleTy, BuiltinType::Double);
903 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000904
Chris Lattner2df9ced2009-04-30 02:43:43 +0000905 // GNU extension, 128-bit integers.
906 InitBuiltinType(Int128Ty, BuiltinType::Int128);
907 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
908
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000909 // C++ 3.9.1p5
910 if (TargetInfo::isTypeSigned(Target.getWCharType()))
911 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
912 else // -fshort-wchar makes wchar_t be unsigned.
913 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
914 if (LangOpts.CPlusPlus && LangOpts.WChar)
915 WideCharTy = WCharTy;
916 else {
917 // C99 (or C++ using -fno-wchar).
918 WideCharTy = getFromTargetType(Target.getWCharType());
919 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000920
James Molloy392da482012-05-04 10:55:22 +0000921 WIntTy = getFromTargetType(Target.getWIntType());
922
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000923 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
924 InitBuiltinType(Char16Ty, BuiltinType::Char16);
925 else // C99
926 Char16Ty = getFromTargetType(Target.getChar16Type());
927
928 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
929 InitBuiltinType(Char32Ty, BuiltinType::Char32);
930 else // C99
931 Char32Ty = getFromTargetType(Target.getChar32Type());
932
Douglas Gregor898574e2008-12-05 23:32:09 +0000933 // Placeholder type for type-dependent expressions whose type is
934 // completely unknown. No code should ever check a type against
935 // DependentTy and users should never see it; however, it is here to
936 // help diagnose failures to properly check for type-dependent
937 // expressions.
938 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939
John McCall2a984ca2010-10-12 00:20:44 +0000940 // Placeholder type for functions.
941 InitBuiltinType(OverloadTy, BuiltinType::Overload);
942
John McCall864c0412011-04-26 20:42:42 +0000943 // Placeholder type for bound members.
944 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
945
John McCall3c3b7f92011-10-25 17:37:35 +0000946 // Placeholder type for pseudo-objects.
947 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
948
John McCall1de4d4e2011-04-07 08:22:57 +0000949 // "any" type; useful for debugger-like clients.
950 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
951
John McCall0ddaeb92011-10-17 18:09:15 +0000952 // Placeholder type for unbridged ARC casts.
953 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
954
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000955 // Placeholder type for builtin functions.
956 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
957
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 // C99 6.2.5p11.
959 FloatComplexTy = getComplexType(FloatTy);
960 DoubleComplexTy = getComplexType(DoubleTy);
961 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000962
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000963 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000964 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
965 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000966 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000967
968 if (LangOpts.OpenCL) {
969 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
970 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
971 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
972 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
973 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
974 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000975
Guy Benyei21f18c42013-02-07 10:55:47 +0000976 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000977 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000978 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000979
980 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000981 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
982 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000983
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000985
986 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000988 // void * type
989 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000990
991 // nullptr type (C++0x 2.14.7)
992 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000993
994 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
995 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000996
997 // Builtin type used to help define __builtin_va_list.
998 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000999}
1000
David Blaikied6471f72011-09-25 23:23:43 +00001001DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001002 return SourceMgr.getDiagnostics();
1003}
1004
Douglas Gregor63200642010-08-30 16:49:28 +00001005AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1006 AttrVec *&Result = DeclAttrs[D];
1007 if (!Result) {
1008 void *Mem = Allocate(sizeof(AttrVec));
1009 Result = new (Mem) AttrVec;
1010 }
1011
1012 return *Result;
1013}
1014
1015/// \brief Erase the attributes corresponding to the given declaration.
1016void ASTContext::eraseDeclAttrs(const Decl *D) {
1017 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1018 if (Pos != DeclAttrs.end()) {
1019 Pos->second->~AttrVec();
1020 DeclAttrs.erase(Pos);
1021 }
1022}
1023
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001024MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001025ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001026 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001027 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001028 = InstantiatedFromStaticDataMember.find(Var);
1029 if (Pos == InstantiatedFromStaticDataMember.end())
1030 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Douglas Gregor7caa6822009-07-24 20:34:43 +00001032 return Pos->second;
1033}
1034
Mike Stump1eb44332009-09-09 15:08:12 +00001035void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001036ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001037 TemplateSpecializationKind TSK,
1038 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001039 assert(Inst->isStaticDataMember() && "Not a static data member");
1040 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1041 assert(!InstantiatedFromStaticDataMember[Inst] &&
1042 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001043 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001044 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001045}
1046
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001047FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1048 const FunctionDecl *FD){
1049 assert(FD && "Specialization is 0");
1050 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001051 = ClassScopeSpecializationPattern.find(FD);
1052 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001053 return 0;
1054
1055 return Pos->second;
1056}
1057
1058void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1059 FunctionDecl *Pattern) {
1060 assert(FD && "Specialization is 0");
1061 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001062 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001063}
1064
John McCall7ba107a2009-11-18 02:36:19 +00001065NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001066ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001067 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001068 = InstantiatedFromUsingDecl.find(UUD);
1069 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001070 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Anders Carlsson0d8df782009-08-29 19:37:28 +00001072 return Pos->second;
1073}
1074
1075void
John McCalled976492009-12-04 22:46:56 +00001076ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1077 assert((isa<UsingDecl>(Pattern) ||
1078 isa<UnresolvedUsingValueDecl>(Pattern) ||
1079 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1080 "pattern decl is not a using decl");
1081 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1082 InstantiatedFromUsingDecl[Inst] = Pattern;
1083}
1084
1085UsingShadowDecl *
1086ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1087 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1088 = InstantiatedFromUsingShadowDecl.find(Inst);
1089 if (Pos == InstantiatedFromUsingShadowDecl.end())
1090 return 0;
1091
1092 return Pos->second;
1093}
1094
1095void
1096ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1097 UsingShadowDecl *Pattern) {
1098 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1099 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001100}
1101
Anders Carlssond8b285f2009-09-01 04:26:58 +00001102FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1103 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1104 = InstantiatedFromUnnamedFieldDecl.find(Field);
1105 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1106 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Anders Carlssond8b285f2009-09-01 04:26:58 +00001108 return Pos->second;
1109}
1110
1111void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1112 FieldDecl *Tmpl) {
1113 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1114 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1115 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1116 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Anders Carlssond8b285f2009-09-01 04:26:58 +00001118 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1119}
1120
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001121bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1122 const FieldDecl *LastFD) const {
1123 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001124 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001125}
1126
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001127bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1128 const FieldDecl *LastFD) const {
1129 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001130 FD->getBitWidthValue(*this) == 0 &&
1131 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001132}
1133
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001134bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1135 const FieldDecl *LastFD) const {
1136 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001137 FD->getBitWidthValue(*this) &&
1138 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001139}
1140
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001141bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001142 const FieldDecl *LastFD) const {
1143 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001144 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001145}
1146
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001147bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001148 const FieldDecl *LastFD) const {
1149 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001150 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001151}
1152
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001153ASTContext::overridden_cxx_method_iterator
1154ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1155 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001156 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001157 if (Pos == OverriddenMethods.end())
1158 return 0;
1159
1160 return Pos->second.begin();
1161}
1162
1163ASTContext::overridden_cxx_method_iterator
1164ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1165 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001166 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001167 if (Pos == OverriddenMethods.end())
1168 return 0;
1169
1170 return Pos->second.end();
1171}
1172
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001173unsigned
1174ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1175 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001176 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001177 if (Pos == OverriddenMethods.end())
1178 return 0;
1179
1180 return Pos->second.size();
1181}
1182
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001183void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1184 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001185 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001186 OverriddenMethods[Method].push_back(Overridden);
1187}
1188
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001189void ASTContext::getOverriddenMethods(
1190 const NamedDecl *D,
1191 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001192 assert(D);
1193
1194 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001195 Overridden.append(overridden_methods_begin(CXXMethod),
1196 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001197 return;
1198 }
1199
1200 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1201 if (!Method)
1202 return;
1203
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001204 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1205 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001206 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001207}
1208
Douglas Gregore6649772011-12-03 00:30:27 +00001209void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1210 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1211 assert(!Import->isFromASTFile() && "Non-local import declaration");
1212 if (!FirstLocalImport) {
1213 FirstLocalImport = Import;
1214 LastLocalImport = Import;
1215 return;
1216 }
1217
1218 LastLocalImport->NextLocalImport = Import;
1219 LastLocalImport = Import;
1220}
1221
Chris Lattner464175b2007-07-18 17:52:12 +00001222//===----------------------------------------------------------------------===//
1223// Type Sizing and Analysis
1224//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001225
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001226/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1227/// scalar floating point type.
1228const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001229 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001230 assert(BT && "Not a floating point type!");
1231 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001232 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001233 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001234 case BuiltinType::Float: return Target->getFloatFormat();
1235 case BuiltinType::Double: return Target->getDoubleFormat();
1236 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001237 }
1238}
1239
Ken Dyck8b752f12010-01-27 17:10:57 +00001240/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001241/// specified decl. Note that bitfields do not have a valid alignment, so
1242/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001243/// If @p RefAsPointee, references are treated like their underlying type
1244/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001245CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001246 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001247
John McCall4081a5c2010-10-08 18:24:19 +00001248 bool UseAlignAttrOnly = false;
1249 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1250 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001251
John McCall4081a5c2010-10-08 18:24:19 +00001252 // __attribute__((aligned)) can increase or decrease alignment
1253 // *except* on a struct or struct member, where it only increases
1254 // alignment unless 'packed' is also specified.
1255 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001256 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001257 // ignore that possibility; Sema should diagnose it.
1258 if (isa<FieldDecl>(D)) {
1259 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1260 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1261 } else {
1262 UseAlignAttrOnly = true;
1263 }
1264 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001265 else if (isa<FieldDecl>(D))
1266 UseAlignAttrOnly =
1267 D->hasAttr<PackedAttr>() ||
1268 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001269
John McCallba4f5d52011-01-20 07:57:12 +00001270 // If we're using the align attribute only, just ignore everything
1271 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001272 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001273 // do nothing
1274
John McCall4081a5c2010-10-08 18:24:19 +00001275 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001276 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001277 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001278 if (RefAsPointee)
1279 T = RT->getPointeeType();
1280 else
1281 T = getPointerType(RT->getPointeeType());
1282 }
1283 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001284 // Adjust alignments of declarations with array type by the
1285 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001286 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001287 const ArrayType *arrayType;
1288 if (MinWidth && (arrayType = getAsArrayType(T))) {
1289 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001290 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001291 else if (isa<ConstantArrayType>(arrayType) &&
1292 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001293 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001294
John McCall3b657512011-01-19 10:06:00 +00001295 // Walk through any array types while we're at it.
1296 T = getBaseElementType(arrayType);
1297 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001298 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001299 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1300 if (VD->hasGlobalStorage())
1301 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1302 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001303 }
John McCallba4f5d52011-01-20 07:57:12 +00001304
1305 // Fields can be subject to extra alignment constraints, like if
1306 // the field is packed, the struct is packed, or the struct has a
1307 // a max-field-alignment constraint (#pragma pack). So calculate
1308 // the actual alignment of the field within the struct, and then
1309 // (as we're expected to) constrain that by the alignment of the type.
1310 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1311 // So calculate the alignment of the field.
1312 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1313
1314 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001315 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001316
1317 // Use the GCD of that and the offset within the record.
1318 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1319 if (offset > 0) {
1320 // Alignment is always a power of 2, so the GCD will be a power of 2,
1321 // which means we get to do this crazy thing instead of Euclid's.
1322 uint64_t lowBitOfOffset = offset & (~offset + 1);
1323 if (lowBitOfOffset < fieldAlign)
1324 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1325 }
1326
1327 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001328 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001329 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001330
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001331 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001332}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001333
John McCall929bbfb2012-08-21 04:10:00 +00001334// getTypeInfoDataSizeInChars - Return the size of a type, in
1335// chars. If the type is a record, its data size is returned. This is
1336// the size of the memcpy that's performed when assigning this type
1337// using a trivial copy/move assignment operator.
1338std::pair<CharUnits, CharUnits>
1339ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1340 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1341
1342 // In C++, objects can sometimes be allocated into the tail padding
1343 // of a base-class subobject. We decide whether that's possible
1344 // during class layout, so here we can just trust the layout results.
1345 if (getLangOpts().CPlusPlus) {
1346 if (const RecordType *RT = T->getAs<RecordType>()) {
1347 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1348 sizeAndAlign.first = layout.getDataSize();
1349 }
1350 }
1351
1352 return sizeAndAlign;
1353}
1354
Richard Trieu910f17e2013-05-14 21:59:17 +00001355/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1356/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1357std::pair<CharUnits, CharUnits>
1358static getConstantArrayInfoInChars(const ASTContext &Context,
1359 const ConstantArrayType *CAT) {
1360 std::pair<CharUnits, CharUnits> EltInfo =
1361 Context.getTypeInfoInChars(CAT->getElementType());
1362 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001363 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1364 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001365 "Overflow in array type char size evaluation");
1366 uint64_t Width = EltInfo.first.getQuantity() * Size;
1367 unsigned Align = EltInfo.second.getQuantity();
1368 Width = llvm::RoundUpToAlignment(Width, Align);
1369 return std::make_pair(CharUnits::fromQuantity(Width),
1370 CharUnits::fromQuantity(Align));
1371}
1372
John McCallea1471e2010-05-20 01:18:31 +00001373std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001374ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001375 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1376 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001377 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001378 return std::make_pair(toCharUnitsFromBits(Info.first),
1379 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001380}
1381
1382std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001383ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001384 return getTypeInfoInChars(T.getTypePtr());
1385}
1386
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001387std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1388 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1389 if (it != MemoizedTypeInfo.end())
1390 return it->second;
1391
1392 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1393 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1394 return Info;
1395}
1396
1397/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1398/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001399///
1400/// FIXME: Pointers into different addr spaces could have different sizes and
1401/// alignment requirements: getPointerInfo should take an AddrSpace, this
1402/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001403std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001404ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001405 uint64_t Width=0;
1406 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001407 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001408#define TYPE(Class, Base)
1409#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001410#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001411#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1412#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001413 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001414
Chris Lattner692233e2007-07-13 22:27:08 +00001415 case Type::FunctionNoProto:
1416 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001417 // GCC extension: alignof(function) = 32 bits
1418 Width = 0;
1419 Align = 32;
1420 break;
1421
Douglas Gregor72564e72009-02-26 23:50:07 +00001422 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001423 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001424 Width = 0;
1425 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1426 break;
1427
Steve Narofffb22d962007-08-30 01:06:46 +00001428 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001429 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattner98be4942008-03-05 18:54:05 +00001431 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001432 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001433 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1434 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001435 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001436 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001437 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001438 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001439 }
Nate Begeman213541a2008-04-18 23:10:10 +00001440 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001441 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001442 const VectorType *VT = cast<VectorType>(T);
1443 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1444 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001445 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001446 // If the alignment is not a power of 2, round up to the next power of 2.
1447 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001448 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001449 Align = llvm::NextPowerOf2(Align);
1450 Width = llvm::RoundUpToAlignment(Width, Align);
1451 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001452 // Adjust the alignment based on the target max.
1453 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1454 if (TargetVectorAlign && TargetVectorAlign < Align)
1455 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001456 break;
1457 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001458
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001459 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001460 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001461 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001462 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001463 // GCC extension: alignof(void) = 8 bits.
1464 Width = 0;
1465 Align = 8;
1466 break;
1467
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001468 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001469 Width = Target->getBoolWidth();
1470 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001471 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001472 case BuiltinType::Char_S:
1473 case BuiltinType::Char_U:
1474 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001475 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001476 Width = Target->getCharWidth();
1477 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001478 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001479 case BuiltinType::WChar_S:
1480 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001481 Width = Target->getWCharWidth();
1482 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001483 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001484 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001485 Width = Target->getChar16Width();
1486 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001487 break;
1488 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001489 Width = Target->getChar32Width();
1490 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001491 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001492 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001493 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001494 Width = Target->getShortWidth();
1495 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001496 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001497 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001498 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getIntWidth();
1500 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001502 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001503 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001504 Width = Target->getLongWidth();
1505 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001507 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001508 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001509 Width = Target->getLongLongWidth();
1510 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001511 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001512 case BuiltinType::Int128:
1513 case BuiltinType::UInt128:
1514 Width = 128;
1515 Align = 128; // int128_t is 128-bit aligned on all targets.
1516 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001517 case BuiltinType::Half:
1518 Width = Target->getHalfWidth();
1519 Align = Target->getHalfAlign();
1520 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001521 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001522 Width = Target->getFloatWidth();
1523 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001524 break;
1525 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001526 Width = Target->getDoubleWidth();
1527 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001528 break;
1529 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001530 Width = Target->getLongDoubleWidth();
1531 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001532 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001533 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001534 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1535 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001536 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001537 case BuiltinType::ObjCId:
1538 case BuiltinType::ObjCClass:
1539 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001540 Width = Target->getPointerWidth(0);
1541 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001542 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001543 case BuiltinType::OCLSampler:
1544 // Samplers are modeled as integers.
1545 Width = Target->getIntWidth();
1546 Align = Target->getIntAlign();
1547 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001548 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001549 case BuiltinType::OCLImage1d:
1550 case BuiltinType::OCLImage1dArray:
1551 case BuiltinType::OCLImage1dBuffer:
1552 case BuiltinType::OCLImage2d:
1553 case BuiltinType::OCLImage2dArray:
1554 case BuiltinType::OCLImage3d:
1555 // Currently these types are pointers to opaque types.
1556 Width = Target->getPointerWidth(0);
1557 Align = Target->getPointerAlign(0);
1558 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001559 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001560 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001561 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001562 Width = Target->getPointerWidth(0);
1563 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001564 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001565 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001566 unsigned AS = getTargetAddressSpace(
1567 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001568 Width = Target->getPointerWidth(AS);
1569 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001570 break;
1571 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001572 case Type::LValueReference:
1573 case Type::RValueReference: {
1574 // alignof and sizeof should never enter this code path here, so we go
1575 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001576 unsigned AS = getTargetAddressSpace(
1577 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001578 Width = Target->getPointerWidth(AS);
1579 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001580 break;
1581 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001582 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001583 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001584 Width = Target->getPointerWidth(AS);
1585 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001586 break;
1587 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001588 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001589 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001590 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001591 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001592 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001593 case Type::Complex: {
1594 // Complex types have the same alignment as their elements, but twice the
1595 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001596 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001597 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001598 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001599 Align = EltInfo.second;
1600 break;
1601 }
John McCallc12c5bb2010-05-15 11:32:37 +00001602 case Type::ObjCObject:
1603 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001604 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001605 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001606 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001607 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001608 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001609 break;
1610 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001611 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001612 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001613 const TagType *TT = cast<TagType>(T);
1614
1615 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001616 Width = 8;
1617 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001618 break;
1619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Daniel Dunbar1d751182008-11-08 05:48:37 +00001621 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001622 return getTypeInfo(ET->getDecl()->getIntegerType());
1623
Daniel Dunbar1d751182008-11-08 05:48:37 +00001624 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001625 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001626 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001627 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001628 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001629 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001630
Chris Lattner9fcfe922009-10-22 05:17:15 +00001631 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001632 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1633 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001634
Richard Smith34b41d92011-02-20 03:19:35 +00001635 case Type::Auto: {
1636 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001637 assert(!A->getDeducedType().isNull() &&
1638 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001639 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001640 }
1641
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001642 case Type::Paren:
1643 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1644
Douglas Gregor18857642009-04-30 17:32:17 +00001645 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001646 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001647 std::pair<uint64_t, unsigned> Info
1648 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001649 // If the typedef has an aligned attribute on it, it overrides any computed
1650 // alignment we have. This violates the GCC documentation (which says that
1651 // attribute(aligned) can only round up) but matches its implementation.
1652 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1653 Align = AttrAlign;
1654 else
1655 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001656 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001657 break;
Chris Lattner71763312008-04-06 22:05:18 +00001658 }
Douglas Gregor18857642009-04-30 17:32:17 +00001659
1660 case Type::TypeOfExpr:
1661 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1662 .getTypePtr());
1663
1664 case Type::TypeOf:
1665 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1666
Anders Carlsson395b4752009-06-24 19:06:50 +00001667 case Type::Decltype:
1668 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1669 .getTypePtr());
1670
Sean Huntca63c202011-05-24 22:41:36 +00001671 case Type::UnaryTransform:
1672 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1673
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001674 case Type::Elaborated:
1675 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001676
John McCall9d156a72011-01-06 01:58:22 +00001677 case Type::Attributed:
1678 return getTypeInfo(
1679 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1680
Richard Smith3e4c6c42011-05-05 21:57:07 +00001681 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001682 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001683 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001684 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1685 // A type alias template specialization may refer to a typedef with the
1686 // aligned attribute on it.
1687 if (TST->isTypeAlias())
1688 return getTypeInfo(TST->getAliasedType().getTypePtr());
1689 else
1690 return getTypeInfo(getCanonicalType(T));
1691 }
1692
Eli Friedmanb001de72011-10-06 23:00:33 +00001693 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001694 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001695 std::pair<uint64_t, unsigned> Info
1696 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1697 Width = Info.first;
1698 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001699
1700 // If the size of the type doesn't exceed the platform's max
1701 // atomic promotion width, make the size and alignment more
1702 // favorable to atomic operations:
1703 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1704 // Round the size up to a power of 2.
1705 if (!llvm::isPowerOf2_64(Width))
1706 Width = llvm::NextPowerOf2(Width);
1707
1708 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001709 Align = static_cast<unsigned>(Width);
1710 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001711 }
1712
Douglas Gregor18857642009-04-30 17:32:17 +00001713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Eli Friedman2be46072011-10-14 20:59:01 +00001715 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001716 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001717}
1718
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001719/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1720CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1721 return CharUnits::fromQuantity(BitSize / getCharWidth());
1722}
1723
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001724/// toBits - Convert a size in characters to a size in characters.
1725int64_t ASTContext::toBits(CharUnits CharSize) const {
1726 return CharSize.getQuantity() * getCharWidth();
1727}
1728
Ken Dyckbdc601b2009-12-22 14:23:30 +00001729/// getTypeSizeInChars - Return the size of the specified type, in characters.
1730/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001731CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001732 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001733}
Jay Foad4ba2a172011-01-12 09:06:06 +00001734CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001735 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001736}
1737
Ken Dyck16e20cc2010-01-26 17:25:18 +00001738/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001739/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001740CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001741 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001742}
Jay Foad4ba2a172011-01-12 09:06:06 +00001743CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001744 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001745}
1746
Chris Lattner34ebde42009-01-27 18:08:34 +00001747/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1748/// type for the current target in bits. This can be different than the ABI
1749/// alignment in cases where it is beneficial for performance to overalign
1750/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001751unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001752 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001753
1754 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001755 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001756 T = CT->getElementType().getTypePtr();
1757 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001758 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1759 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001760 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1761
Chris Lattner34ebde42009-01-27 18:08:34 +00001762 return ABIAlign;
1763}
1764
Ulrich Weigand6b203512013-05-06 16:23:57 +00001765/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1766/// to a global variable of the specified type.
1767unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1768 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1769}
1770
1771/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1772/// should be given to a global variable of the specified type.
1773CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1774 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1775}
1776
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001777/// DeepCollectObjCIvars -
1778/// This routine first collects all declared, but not synthesized, ivars in
1779/// super class and then collects all ivars, including those synthesized for
1780/// current class. This routine is used for implementation of current class
1781/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001782///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001783void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1784 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001785 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001786 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1787 DeepCollectObjCIvars(SuperClass, false, Ivars);
1788 if (!leafClass) {
1789 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1790 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001791 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001792 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001793 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001794 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001795 Iv= Iv->getNextIvar())
1796 Ivars.push_back(Iv);
1797 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001798}
1799
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001800/// CollectInheritedProtocols - Collect all protocols in current class and
1801/// those inherited by it.
1802void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001803 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001804 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001805 // We can use protocol_iterator here instead of
1806 // all_referenced_protocol_iterator since we are walking all categories.
1807 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1808 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001809 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001810 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001811 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001812 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001813 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 CollectInheritedProtocols(*P, Protocols);
1815 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001816 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001817
1818 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001819 for (ObjCInterfaceDecl::visible_categories_iterator
1820 Cat = OI->visible_categories_begin(),
1821 CatEnd = OI->visible_categories_end();
1822 Cat != CatEnd; ++Cat) {
1823 CollectInheritedProtocols(*Cat, Protocols);
1824 }
1825
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001826 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1827 while (SD) {
1828 CollectInheritedProtocols(SD, Protocols);
1829 SD = SD->getSuperClass();
1830 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001831 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001832 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001833 PE = OC->protocol_end(); P != PE; ++P) {
1834 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001835 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001836 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1837 PE = Proto->protocol_end(); P != PE; ++P)
1838 CollectInheritedProtocols(*P, Protocols);
1839 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001840 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001841 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1842 PE = OP->protocol_end(); P != PE; ++P) {
1843 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001844 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001845 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1846 PE = Proto->protocol_end(); P != PE; ++P)
1847 CollectInheritedProtocols(*P, Protocols);
1848 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001849 }
1850}
1851
Jay Foad4ba2a172011-01-12 09:06:06 +00001852unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001853 unsigned count = 0;
1854 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001855 for (ObjCInterfaceDecl::known_extensions_iterator
1856 Ext = OI->known_extensions_begin(),
1857 ExtEnd = OI->known_extensions_end();
1858 Ext != ExtEnd; ++Ext) {
1859 count += Ext->ivar_size();
1860 }
1861
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001862 // Count ivar defined in this class's implementation. This
1863 // includes synthesized ivars.
1864 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001865 count += ImplDecl->ivar_size();
1866
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001867 return count;
1868}
1869
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001870bool ASTContext::isSentinelNullExpr(const Expr *E) {
1871 if (!E)
1872 return false;
1873
1874 // nullptr_t is always treated as null.
1875 if (E->getType()->isNullPtrType()) return true;
1876
1877 if (E->getType()->isAnyPointerType() &&
1878 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1879 Expr::NPC_ValueDependentIsNull))
1880 return true;
1881
1882 // Unfortunately, __null has type 'int'.
1883 if (isa<GNUNullExpr>(E)) return true;
1884
1885 return false;
1886}
1887
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001888/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1889ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1890 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1891 I = ObjCImpls.find(D);
1892 if (I != ObjCImpls.end())
1893 return cast<ObjCImplementationDecl>(I->second);
1894 return 0;
1895}
1896/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1897ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1898 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1899 I = ObjCImpls.find(D);
1900 if (I != ObjCImpls.end())
1901 return cast<ObjCCategoryImplDecl>(I->second);
1902 return 0;
1903}
1904
1905/// \brief Set the implementation of ObjCInterfaceDecl.
1906void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1907 ObjCImplementationDecl *ImplD) {
1908 assert(IFaceD && ImplD && "Passed null params");
1909 ObjCImpls[IFaceD] = ImplD;
1910}
1911/// \brief Set the implementation of ObjCCategoryDecl.
1912void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1913 ObjCCategoryImplDecl *ImplD) {
1914 assert(CatD && ImplD && "Passed null params");
1915 ObjCImpls[CatD] = ImplD;
1916}
1917
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001918const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1919 const NamedDecl *ND) const {
1920 if (const ObjCInterfaceDecl *ID =
1921 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001922 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001923 if (const ObjCCategoryDecl *CD =
1924 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001925 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001926 if (const ObjCImplDecl *IMD =
1927 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001928 return IMD->getClassInterface();
1929
1930 return 0;
1931}
1932
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001933/// \brief Get the copy initialization expression of VarDecl,or NULL if
1934/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001935Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001936 assert(VD && "Passed null params");
1937 assert(VD->hasAttr<BlocksAttr>() &&
1938 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001939 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001940 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001941 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1942}
1943
1944/// \brief Set the copy inialization expression of a block var decl.
1945void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1946 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001947 assert(VD->hasAttr<BlocksAttr>() &&
1948 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001949 BlockVarCopyInits[VD] = Init;
1950}
1951
John McCalla93c9342009-12-07 02:54:59 +00001952TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001953 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001954 if (!DataSize)
1955 DataSize = TypeLoc::getFullDataSizeForType(T);
1956 else
1957 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001958 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001959
John McCalla93c9342009-12-07 02:54:59 +00001960 TypeSourceInfo *TInfo =
1961 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1962 new (TInfo) TypeSourceInfo(T);
1963 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001964}
1965
John McCalla93c9342009-12-07 02:54:59 +00001966TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001967 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001968 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001969 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001970 return DI;
1971}
1972
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001973const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001974ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001975 return getObjCLayout(D, 0);
1976}
1977
1978const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001979ASTContext::getASTObjCImplementationLayout(
1980 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001981 return getObjCLayout(D->getClassInterface(), D);
1982}
1983
Chris Lattnera7674d82007-07-13 22:13:22 +00001984//===----------------------------------------------------------------------===//
1985// Type creation/memoization methods
1986//===----------------------------------------------------------------------===//
1987
Jay Foad4ba2a172011-01-12 09:06:06 +00001988QualType
John McCall3b657512011-01-19 10:06:00 +00001989ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1990 unsigned fastQuals = quals.getFastQualifiers();
1991 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001992
1993 // Check if we've already instantiated this type.
1994 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001995 ExtQuals::Profile(ID, baseType, quals);
1996 void *insertPos = 0;
1997 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1998 assert(eq->getQualifiers() == quals);
1999 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002000 }
2001
John McCall3b657512011-01-19 10:06:00 +00002002 // If the base type is not canonical, make the appropriate canonical type.
2003 QualType canon;
2004 if (!baseType->isCanonicalUnqualified()) {
2005 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002006 canonSplit.Quals.addConsistentQualifiers(quals);
2007 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002008
2009 // Re-find the insert position.
2010 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2011 }
2012
2013 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2014 ExtQualNodes.InsertNode(eq, insertPos);
2015 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002016}
2017
Jay Foad4ba2a172011-01-12 09:06:06 +00002018QualType
2019ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002020 QualType CanT = getCanonicalType(T);
2021 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002022 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002023
John McCall0953e762009-09-24 19:53:00 +00002024 // If we are composing extended qualifiers together, merge together
2025 // into one ExtQuals node.
2026 QualifierCollector Quals;
2027 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
John McCall0953e762009-09-24 19:53:00 +00002029 // If this type already has an address space specified, it cannot get
2030 // another one.
2031 assert(!Quals.hasAddressSpace() &&
2032 "Type cannot be in multiple addr spaces!");
2033 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002034
John McCall0953e762009-09-24 19:53:00 +00002035 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002036}
2037
Chris Lattnerb7d25532009-02-18 22:53:11 +00002038QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002039 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002040 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002041 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002042 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCall7f040a92010-12-24 02:08:15 +00002044 if (const PointerType *ptr = T->getAs<PointerType>()) {
2045 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002046 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002047 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2048 return getPointerType(ResultType);
2049 }
2050 }
Mike Stump1eb44332009-09-09 15:08:12 +00002051
John McCall0953e762009-09-24 19:53:00 +00002052 // If we are composing extended qualifiers together, merge together
2053 // into one ExtQuals node.
2054 QualifierCollector Quals;
2055 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
John McCall0953e762009-09-24 19:53:00 +00002057 // If this type already has an ObjCGC specified, it cannot get
2058 // another one.
2059 assert(!Quals.hasObjCGCAttr() &&
2060 "Type cannot have multiple ObjCGCs!");
2061 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
John McCall0953e762009-09-24 19:53:00 +00002063 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002064}
Chris Lattnera7674d82007-07-13 22:13:22 +00002065
John McCalle6a365d2010-12-19 02:44:49 +00002066const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2067 FunctionType::ExtInfo Info) {
2068 if (T->getExtInfo() == Info)
2069 return T;
2070
2071 QualType Result;
2072 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2073 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2074 } else {
2075 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2076 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2077 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002078 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002079 }
2080
2081 return cast<FunctionType>(Result.getTypePtr());
2082}
2083
Richard Smith60e141e2013-05-04 07:00:32 +00002084void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2085 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002086 FD = FD->getMostRecentDecl();
2087 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002088 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2090 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002091 if (FunctionDecl *Next = FD->getPreviousDecl())
2092 FD = Next;
2093 else
2094 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002095 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002096 if (ASTMutationListener *L = getASTMutationListener())
2097 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002098}
2099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100/// getComplexType - Return the uniqued reference to the type for a complex
2101/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002102QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // Unique pointers, to guarantee there is only one pointer of a particular
2104 // structure.
2105 llvm::FoldingSetNodeID ID;
2106 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 void *InsertPos = 0;
2109 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2110 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // If the pointee type isn't canonical, this won't be a canonical type either,
2113 // so fill in the canonical type field.
2114 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002115 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002116 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 // Get the new insert position for the node we care about.
2119 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002120 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 }
John McCall6b304a02009-09-24 23:30:46 +00002122 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 Types.push_back(New);
2124 ComplexTypes.InsertNode(New, InsertPos);
2125 return QualType(New, 0);
2126}
2127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128/// getPointerType - Return the uniqued reference to the type for a pointer to
2129/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002130QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 // Unique pointers, to guarantee there is only one pointer of a particular
2132 // structure.
2133 llvm::FoldingSetNodeID ID;
2134 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 void *InsertPos = 0;
2137 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2138 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 // If the pointee type isn't canonical, this won't be a canonical type either,
2141 // so fill in the canonical type field.
2142 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002143 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002144 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Bob Wilsonc90cc932013-03-15 17:12:43 +00002146 // Get the new insert position for the node we care about.
2147 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2148 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2149 }
John McCall6b304a02009-09-24 23:30:46 +00002150 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 Types.push_back(New);
2152 PointerTypes.InsertNode(New, InsertPos);
2153 return QualType(New, 0);
2154}
2155
Mike Stump1eb44332009-09-09 15:08:12 +00002156/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002157/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002158QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002159 assert(T->isFunctionType() && "block of function types only");
2160 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002161 // structure.
2162 llvm::FoldingSetNodeID ID;
2163 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Steve Naroff5618bd42008-08-27 16:04:49 +00002165 void *InsertPos = 0;
2166 if (BlockPointerType *PT =
2167 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2168 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002169
2170 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002171 // type either so fill in the canonical type field.
2172 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002173 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002174 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Steve Naroff5618bd42008-08-27 16:04:49 +00002176 // Get the new insert position for the node we care about.
2177 BlockPointerType *NewIP =
2178 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002179 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002180 }
John McCall6b304a02009-09-24 23:30:46 +00002181 BlockPointerType *New
2182 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002183 Types.push_back(New);
2184 BlockPointerTypes.InsertNode(New, InsertPos);
2185 return QualType(New, 0);
2186}
2187
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002188/// getLValueReferenceType - Return the uniqued reference to the type for an
2189/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002190QualType
2191ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002192 assert(getCanonicalType(T) != OverloadTy &&
2193 "Unresolved overloaded function type");
2194
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 // Unique pointers, to guarantee there is only one pointer of a particular
2196 // structure.
2197 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002198 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002199
2200 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002201 if (LValueReferenceType *RT =
2202 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002204
John McCall54e14c42009-10-22 22:37:11 +00002205 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2206
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // If the referencee type isn't canonical, this won't be a canonical type
2208 // either, so fill in the canonical type field.
2209 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002210 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2211 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2212 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002213
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002215 LValueReferenceType *NewIP =
2216 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002217 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 }
2219
John McCall6b304a02009-09-24 23:30:46 +00002220 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002221 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2222 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002224 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002225
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002226 return QualType(New, 0);
2227}
2228
2229/// getRValueReferenceType - Return the uniqued reference to the type for an
2230/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002231QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002232 // Unique pointers, to guarantee there is only one pointer of a particular
2233 // structure.
2234 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002235 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002236
2237 void *InsertPos = 0;
2238 if (RValueReferenceType *RT =
2239 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2240 return QualType(RT, 0);
2241
John McCall54e14c42009-10-22 22:37:11 +00002242 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2243
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002244 // If the referencee type isn't canonical, this won't be a canonical type
2245 // either, so fill in the canonical type field.
2246 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002247 if (InnerRef || !T.isCanonical()) {
2248 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2249 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002250
2251 // Get the new insert position for the node we care about.
2252 RValueReferenceType *NewIP =
2253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002254 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002255 }
2256
John McCall6b304a02009-09-24 23:30:46 +00002257 RValueReferenceType *New
2258 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259 Types.push_back(New);
2260 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 return QualType(New, 0);
2262}
2263
Sebastian Redlf30208a2009-01-24 21:16:55 +00002264/// getMemberPointerType - Return the uniqued reference to the type for a
2265/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002266QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002267 // Unique pointers, to guarantee there is only one pointer of a particular
2268 // structure.
2269 llvm::FoldingSetNodeID ID;
2270 MemberPointerType::Profile(ID, T, Cls);
2271
2272 void *InsertPos = 0;
2273 if (MemberPointerType *PT =
2274 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2275 return QualType(PT, 0);
2276
2277 // If the pointee or class type isn't canonical, this won't be a canonical
2278 // type either, so fill in the canonical type field.
2279 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002280 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002281 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2282
2283 // Get the new insert position for the node we care about.
2284 MemberPointerType *NewIP =
2285 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002286 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002287 }
John McCall6b304a02009-09-24 23:30:46 +00002288 MemberPointerType *New
2289 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002290 Types.push_back(New);
2291 MemberPointerTypes.InsertNode(New, InsertPos);
2292 return QualType(New, 0);
2293}
2294
Mike Stump1eb44332009-09-09 15:08:12 +00002295/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002296/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002297QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002298 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002299 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002300 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002301 assert((EltTy->isDependentType() ||
2302 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002303 "Constant array of VLAs is illegal!");
2304
Chris Lattner38aeec72009-05-13 04:12:56 +00002305 // Convert the array size into a canonical width matching the pointer size for
2306 // the target.
2307 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002308 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002309 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002312 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Reid Spencer5f016e22007-07-11 17:01:13 +00002314 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002315 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002316 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002318
John McCall3b657512011-01-19 10:06:00 +00002319 // If the element type isn't canonical or has qualifiers, this won't
2320 // be a canonical type either, so fill in the canonical type field.
2321 QualType Canon;
2322 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2323 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002324 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002325 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002326 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002327
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002329 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002330 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002331 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
John McCall6b304a02009-09-24 23:30:46 +00002334 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002335 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002336 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 Types.push_back(New);
2338 return QualType(New, 0);
2339}
2340
John McCallce889032011-01-18 08:40:38 +00002341/// getVariableArrayDecayedType - Turns the given type, which may be
2342/// variably-modified, into the corresponding type with all the known
2343/// sizes replaced with [*].
2344QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2345 // Vastly most common case.
2346 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002347
John McCallce889032011-01-18 08:40:38 +00002348 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002349
John McCallce889032011-01-18 08:40:38 +00002350 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002351 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002352 switch (ty->getTypeClass()) {
2353#define TYPE(Class, Base)
2354#define ABSTRACT_TYPE(Class, Base)
2355#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2356#include "clang/AST/TypeNodes.def"
2357 llvm_unreachable("didn't desugar past all non-canonical types?");
2358
2359 // These types should never be variably-modified.
2360 case Type::Builtin:
2361 case Type::Complex:
2362 case Type::Vector:
2363 case Type::ExtVector:
2364 case Type::DependentSizedExtVector:
2365 case Type::ObjCObject:
2366 case Type::ObjCInterface:
2367 case Type::ObjCObjectPointer:
2368 case Type::Record:
2369 case Type::Enum:
2370 case Type::UnresolvedUsing:
2371 case Type::TypeOfExpr:
2372 case Type::TypeOf:
2373 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002374 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002375 case Type::DependentName:
2376 case Type::InjectedClassName:
2377 case Type::TemplateSpecialization:
2378 case Type::DependentTemplateSpecialization:
2379 case Type::TemplateTypeParm:
2380 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002381 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002382 case Type::PackExpansion:
2383 llvm_unreachable("type should never be variably-modified");
2384
2385 // These types can be variably-modified but should never need to
2386 // further decay.
2387 case Type::FunctionNoProto:
2388 case Type::FunctionProto:
2389 case Type::BlockPointer:
2390 case Type::MemberPointer:
2391 return type;
2392
2393 // These types can be variably-modified. All these modifications
2394 // preserve structure except as noted by comments.
2395 // TODO: if we ever care about optimizing VLAs, there are no-op
2396 // optimizations available here.
2397 case Type::Pointer:
2398 result = getPointerType(getVariableArrayDecayedType(
2399 cast<PointerType>(ty)->getPointeeType()));
2400 break;
2401
2402 case Type::LValueReference: {
2403 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2404 result = getLValueReferenceType(
2405 getVariableArrayDecayedType(lv->getPointeeType()),
2406 lv->isSpelledAsLValue());
2407 break;
2408 }
2409
2410 case Type::RValueReference: {
2411 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2412 result = getRValueReferenceType(
2413 getVariableArrayDecayedType(lv->getPointeeType()));
2414 break;
2415 }
2416
Eli Friedmanb001de72011-10-06 23:00:33 +00002417 case Type::Atomic: {
2418 const AtomicType *at = cast<AtomicType>(ty);
2419 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2420 break;
2421 }
2422
John McCallce889032011-01-18 08:40:38 +00002423 case Type::ConstantArray: {
2424 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2425 result = getConstantArrayType(
2426 getVariableArrayDecayedType(cat->getElementType()),
2427 cat->getSize(),
2428 cat->getSizeModifier(),
2429 cat->getIndexTypeCVRQualifiers());
2430 break;
2431 }
2432
2433 case Type::DependentSizedArray: {
2434 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2435 result = getDependentSizedArrayType(
2436 getVariableArrayDecayedType(dat->getElementType()),
2437 dat->getSizeExpr(),
2438 dat->getSizeModifier(),
2439 dat->getIndexTypeCVRQualifiers(),
2440 dat->getBracketsRange());
2441 break;
2442 }
2443
2444 // Turn incomplete types into [*] types.
2445 case Type::IncompleteArray: {
2446 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2447 result = getVariableArrayType(
2448 getVariableArrayDecayedType(iat->getElementType()),
2449 /*size*/ 0,
2450 ArrayType::Normal,
2451 iat->getIndexTypeCVRQualifiers(),
2452 SourceRange());
2453 break;
2454 }
2455
2456 // Turn VLA types into [*] types.
2457 case Type::VariableArray: {
2458 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2459 result = getVariableArrayType(
2460 getVariableArrayDecayedType(vat->getElementType()),
2461 /*size*/ 0,
2462 ArrayType::Star,
2463 vat->getIndexTypeCVRQualifiers(),
2464 vat->getBracketsRange());
2465 break;
2466 }
2467 }
2468
2469 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002470 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002471}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002472
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002473/// getVariableArrayType - Returns a non-unique reference to the type for a
2474/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002475QualType ASTContext::getVariableArrayType(QualType EltTy,
2476 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002477 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002478 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002479 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002480 // Since we don't unique expressions, it isn't possible to unique VLA's
2481 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002482 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002483
John McCall3b657512011-01-19 10:06:00 +00002484 // Be sure to pull qualifiers off the element type.
2485 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2486 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002487 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002488 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002489 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002490 }
2491
John McCall6b304a02009-09-24 23:30:46 +00002492 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002493 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002494
2495 VariableArrayTypes.push_back(New);
2496 Types.push_back(New);
2497 return QualType(New, 0);
2498}
2499
Douglas Gregor898574e2008-12-05 23:32:09 +00002500/// getDependentSizedArrayType - Returns a non-unique reference to
2501/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002502/// type.
John McCall3b657512011-01-19 10:06:00 +00002503QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2504 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002505 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002506 unsigned elementTypeQuals,
2507 SourceRange brackets) const {
2508 assert((!numElements || numElements->isTypeDependent() ||
2509 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002510 "Size must be type- or value-dependent!");
2511
John McCall3b657512011-01-19 10:06:00 +00002512 // Dependently-sized array types that do not have a specified number
2513 // of elements will have their sizes deduced from a dependent
2514 // initializer. We do no canonicalization here at all, which is okay
2515 // because they can't be used in most locations.
2516 if (!numElements) {
2517 DependentSizedArrayType *newType
2518 = new (*this, TypeAlignment)
2519 DependentSizedArrayType(*this, elementType, QualType(),
2520 numElements, ASM, elementTypeQuals,
2521 brackets);
2522 Types.push_back(newType);
2523 return QualType(newType, 0);
2524 }
2525
2526 // Otherwise, we actually build a new type every time, but we
2527 // also build a canonical type.
2528
2529 SplitQualType canonElementType = getCanonicalType(elementType).split();
2530
2531 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002532 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002533 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002534 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002535 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002536
John McCall3b657512011-01-19 10:06:00 +00002537 // Look for an existing type with these properties.
2538 DependentSizedArrayType *canonTy =
2539 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002540
John McCall3b657512011-01-19 10:06:00 +00002541 // If we don't have one, build one.
2542 if (!canonTy) {
2543 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002544 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002545 QualType(), numElements, ASM, elementTypeQuals,
2546 brackets);
2547 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2548 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002549 }
2550
John McCall3b657512011-01-19 10:06:00 +00002551 // Apply qualifiers from the element type to the array.
2552 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002553 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002554
John McCall3b657512011-01-19 10:06:00 +00002555 // If we didn't need extra canonicalization for the element type,
2556 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002557 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002558 return canon;
2559
2560 // Otherwise, we need to build a type which follows the spelling
2561 // of the element type.
2562 DependentSizedArrayType *sugaredType
2563 = new (*this, TypeAlignment)
2564 DependentSizedArrayType(*this, elementType, canon, numElements,
2565 ASM, elementTypeQuals, brackets);
2566 Types.push_back(sugaredType);
2567 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002568}
2569
John McCall3b657512011-01-19 10:06:00 +00002570QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002571 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002572 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002573 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002574 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002575
John McCall3b657512011-01-19 10:06:00 +00002576 void *insertPos = 0;
2577 if (IncompleteArrayType *iat =
2578 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2579 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002580
2581 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002582 // either, so fill in the canonical type field. We also have to pull
2583 // qualifiers off the element type.
2584 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002585
John McCall3b657512011-01-19 10:06:00 +00002586 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2587 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002588 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002589 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002590 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002591
2592 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002593 IncompleteArrayType *existing =
2594 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2595 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002596 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002597
John McCall3b657512011-01-19 10:06:00 +00002598 IncompleteArrayType *newType = new (*this, TypeAlignment)
2599 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002600
John McCall3b657512011-01-19 10:06:00 +00002601 IncompleteArrayTypes.InsertNode(newType, insertPos);
2602 Types.push_back(newType);
2603 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002604}
2605
Steve Naroff73322922007-07-18 18:00:27 +00002606/// getVectorType - Return the unique reference to a vector type of
2607/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002608QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002609 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002610 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // Check if we've already instantiated a vector of this type.
2613 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002614 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002615
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 void *InsertPos = 0;
2617 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2618 return QualType(VTP, 0);
2619
2620 // If the element type isn't canonical, this won't be a canonical type either,
2621 // so fill in the canonical type field.
2622 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002623 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002624 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // Get the new insert position for the node we care about.
2627 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002628 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 }
John McCall6b304a02009-09-24 23:30:46 +00002630 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002631 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 VectorTypes.InsertNode(New, InsertPos);
2633 Types.push_back(New);
2634 return QualType(New, 0);
2635}
2636
Nate Begeman213541a2008-04-18 23:10:10 +00002637/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002638/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002639QualType
2640ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002641 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Steve Naroff73322922007-07-18 18:00:27 +00002643 // Check if we've already instantiated a vector of this type.
2644 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002645 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002646 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002647 void *InsertPos = 0;
2648 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2649 return QualType(VTP, 0);
2650
2651 // If the element type isn't canonical, this won't be a canonical type either,
2652 // so fill in the canonical type field.
2653 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002654 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002655 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Steve Naroff73322922007-07-18 18:00:27 +00002657 // Get the new insert position for the node we care about.
2658 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002659 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002660 }
John McCall6b304a02009-09-24 23:30:46 +00002661 ExtVectorType *New = new (*this, TypeAlignment)
2662 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002663 VectorTypes.InsertNode(New, InsertPos);
2664 Types.push_back(New);
2665 return QualType(New, 0);
2666}
2667
Jay Foad4ba2a172011-01-12 09:06:06 +00002668QualType
2669ASTContext::getDependentSizedExtVectorType(QualType vecType,
2670 Expr *SizeExpr,
2671 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002672 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002673 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002674 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002676 void *InsertPos = 0;
2677 DependentSizedExtVectorType *Canon
2678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2679 DependentSizedExtVectorType *New;
2680 if (Canon) {
2681 // We already have a canonical version of this array type; use it as
2682 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002683 New = new (*this, TypeAlignment)
2684 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2685 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002686 } else {
2687 QualType CanonVecTy = getCanonicalType(vecType);
2688 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002689 New = new (*this, TypeAlignment)
2690 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2691 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002692
2693 DependentSizedExtVectorType *CanonCheck
2694 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2695 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2696 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002697 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2698 } else {
2699 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2700 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002701 New = new (*this, TypeAlignment)
2702 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002703 }
2704 }
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002706 Types.push_back(New);
2707 return QualType(New, 0);
2708}
2709
Douglas Gregor72564e72009-02-26 23:50:07 +00002710/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002711///
Jay Foad4ba2a172011-01-12 09:06:06 +00002712QualType
2713ASTContext::getFunctionNoProtoType(QualType ResultTy,
2714 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002715 const CallingConv DefaultCC = Info.getCC();
2716 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2717 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 // Unique functions, to guarantee there is only one function of a particular
2719 // structure.
2720 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002721 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002724 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002725 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002729 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002730 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002731 Canonical =
2732 getFunctionNoProtoType(getCanonicalType(ResultTy),
2733 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002736 FunctionNoProtoType *NewIP =
2737 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002738 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 }
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Roman Divackycfe9af22011-03-01 17:40:53 +00002741 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002742 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002743 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002745 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 return QualType(New, 0);
2747}
2748
Douglas Gregor02dd7982013-01-17 23:36:45 +00002749/// \brief Determine whether \p T is canonical as the result type of a function.
2750static bool isCanonicalResultType(QualType T) {
2751 return T.isCanonical() &&
2752 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2753 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2754}
2755
Reid Spencer5f016e22007-07-11 17:01:13 +00002756/// getFunctionType - Return a normal function type with a typed argument
2757/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002758QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002759ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002760 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002761 size_t NumArgs = ArgArray.size();
2762
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 // Unique functions, to guarantee there is only one function of a particular
2764 // structure.
2765 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002766 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2767 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002768
2769 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002771 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002773
2774 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002775 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002776 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002777 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002779 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 isCanonical = false;
2781
Roman Divackycfe9af22011-03-01 17:40:53 +00002782 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2783 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2784 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002787 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002789 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002790 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 CanonicalArgs.reserve(NumArgs);
2792 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002793 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002794
John McCalle23cf432010-12-14 08:05:40 +00002795 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002796 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002797 CanonicalEPI.ExceptionSpecType = EST_None;
2798 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002799 CanonicalEPI.ExtInfo
2800 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2801
Douglas Gregor02dd7982013-01-17 23:36:45 +00002802 // Result types do not have ARC lifetime qualifiers.
2803 QualType CanResultTy = getCanonicalType(ResultTy);
2804 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2805 Qualifiers Qs = CanResultTy.getQualifiers();
2806 Qs.removeObjCLifetime();
2807 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2808 }
2809
Jordan Rosebea522f2013-03-08 21:51:21 +00002810 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002811
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002813 FunctionProtoType *NewIP =
2814 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002815 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002817
John McCallf85e1932011-06-15 23:02:42 +00002818 // FunctionProtoType objects are allocated with extra bytes after
2819 // them for three variable size arrays at the end:
2820 // - parameter types
2821 // - exception types
2822 // - consumed-arguments flags
2823 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002824 // expression, or information used to resolve the exception
2825 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002826 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002827 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002828 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002829 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002830 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002831 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002832 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002833 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002834 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2835 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002836 }
John McCallf85e1932011-06-15 23:02:42 +00002837 if (EPI.ConsumedArguments)
2838 Size += NumArgs * sizeof(bool);
2839
John McCalle23cf432010-12-14 08:05:40 +00002840 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002841 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2842 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002843 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002845 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 return QualType(FTP, 0);
2847}
2848
John McCall3cb0ebd2010-03-10 03:28:59 +00002849#ifndef NDEBUG
2850static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2851 if (!isa<CXXRecordDecl>(D)) return false;
2852 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2853 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2854 return true;
2855 if (RD->getDescribedClassTemplate() &&
2856 !isa<ClassTemplateSpecializationDecl>(RD))
2857 return true;
2858 return false;
2859}
2860#endif
2861
2862/// getInjectedClassNameType - Return the unique reference to the
2863/// injected class name type for the specified templated declaration.
2864QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002865 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002866 assert(NeedsInjectedClassNameType(Decl));
2867 if (Decl->TypeForDecl) {
2868 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002869 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002870 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2871 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2872 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2873 } else {
John McCallf4c73712011-01-19 06:33:43 +00002874 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002875 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002876 Decl->TypeForDecl = newType;
2877 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002878 }
2879 return QualType(Decl->TypeForDecl, 0);
2880}
2881
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002882/// getTypeDeclType - Return the unique reference to the type for the
2883/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002884QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002885 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002886 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Richard Smith162e1c12011-04-15 14:24:37 +00002888 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002889 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002890
John McCallbecb8d52010-03-10 06:48:02 +00002891 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2892 "Template type parameter types are always available.");
2893
John McCall19c85762010-02-16 03:57:14 +00002894 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002895 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002896 "struct/union has previous declaration");
2897 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002898 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002899 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002900 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002901 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002902 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002903 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002904 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002905 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2906 Decl->TypeForDecl = newType;
2907 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002908 } else
John McCallbecb8d52010-03-10 06:48:02 +00002909 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002910
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002911 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002912}
2913
Reid Spencer5f016e22007-07-11 17:01:13 +00002914/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002915/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002916QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002917ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2918 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002921 if (Canonical.isNull())
2922 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002923 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002924 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002925 Decl->TypeForDecl = newType;
2926 Types.push_back(newType);
2927 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002928}
2929
Jay Foad4ba2a172011-01-12 09:06:06 +00002930QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002931 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2932
Douglas Gregoref96ee02012-01-14 16:38:05 +00002933 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002934 if (PrevDecl->TypeForDecl)
2935 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2936
John McCallf4c73712011-01-19 06:33:43 +00002937 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2938 Decl->TypeForDecl = newType;
2939 Types.push_back(newType);
2940 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002941}
2942
Jay Foad4ba2a172011-01-12 09:06:06 +00002943QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002944 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2945
Douglas Gregoref96ee02012-01-14 16:38:05 +00002946 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002947 if (PrevDecl->TypeForDecl)
2948 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2949
John McCallf4c73712011-01-19 06:33:43 +00002950 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2951 Decl->TypeForDecl = newType;
2952 Types.push_back(newType);
2953 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002954}
2955
John McCall9d156a72011-01-06 01:58:22 +00002956QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2957 QualType modifiedType,
2958 QualType equivalentType) {
2959 llvm::FoldingSetNodeID id;
2960 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2961
2962 void *insertPos = 0;
2963 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2964 if (type) return QualType(type, 0);
2965
2966 QualType canon = getCanonicalType(equivalentType);
2967 type = new (*this, TypeAlignment)
2968 AttributedType(canon, attrKind, modifiedType, equivalentType);
2969
2970 Types.push_back(type);
2971 AttributedTypes.InsertNode(type, insertPos);
2972
2973 return QualType(type, 0);
2974}
2975
2976
John McCall49a832b2009-10-18 09:09:24 +00002977/// \brief Retrieve a substitution-result type.
2978QualType
2979ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002980 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002981 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002982 && "replacement types must always be canonical");
2983
2984 llvm::FoldingSetNodeID ID;
2985 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2986 void *InsertPos = 0;
2987 SubstTemplateTypeParmType *SubstParm
2988 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2989
2990 if (!SubstParm) {
2991 SubstParm = new (*this, TypeAlignment)
2992 SubstTemplateTypeParmType(Parm, Replacement);
2993 Types.push_back(SubstParm);
2994 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2995 }
2996
2997 return QualType(SubstParm, 0);
2998}
2999
Douglas Gregorc3069d62011-01-14 02:55:32 +00003000/// \brief Retrieve a
3001QualType ASTContext::getSubstTemplateTypeParmPackType(
3002 const TemplateTypeParmType *Parm,
3003 const TemplateArgument &ArgPack) {
3004#ifndef NDEBUG
3005 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3006 PEnd = ArgPack.pack_end();
3007 P != PEnd; ++P) {
3008 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3009 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3010 }
3011#endif
3012
3013 llvm::FoldingSetNodeID ID;
3014 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3015 void *InsertPos = 0;
3016 if (SubstTemplateTypeParmPackType *SubstParm
3017 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3018 return QualType(SubstParm, 0);
3019
3020 QualType Canon;
3021 if (!Parm->isCanonicalUnqualified()) {
3022 Canon = getCanonicalType(QualType(Parm, 0));
3023 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3024 ArgPack);
3025 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3026 }
3027
3028 SubstTemplateTypeParmPackType *SubstParm
3029 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3030 ArgPack);
3031 Types.push_back(SubstParm);
3032 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3033 return QualType(SubstParm, 0);
3034}
3035
Douglas Gregorfab9d672009-02-05 23:33:38 +00003036/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003037/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003038/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003039QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003040 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003041 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003042 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003043 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003044 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003045 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003046 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3047
3048 if (TypeParm)
3049 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003051 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003052 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003053 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003054
3055 TemplateTypeParmType *TypeCheck
3056 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3057 assert(!TypeCheck && "Template type parameter canonical type broken");
3058 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003059 } else
John McCall6b304a02009-09-24 23:30:46 +00003060 TypeParm = new (*this, TypeAlignment)
3061 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003062
3063 Types.push_back(TypeParm);
3064 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3065
3066 return QualType(TypeParm, 0);
3067}
3068
John McCall3cb0ebd2010-03-10 03:28:59 +00003069TypeSourceInfo *
3070ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3071 SourceLocation NameLoc,
3072 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003073 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003074 assert(!Name.getAsDependentTemplateName() &&
3075 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003076 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003077
3078 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003079 TemplateSpecializationTypeLoc TL =
3080 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003081 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003082 TL.setTemplateNameLoc(NameLoc);
3083 TL.setLAngleLoc(Args.getLAngleLoc());
3084 TL.setRAngleLoc(Args.getRAngleLoc());
3085 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3086 TL.setArgLocInfo(i, Args[i].getLocInfo());
3087 return DI;
3088}
3089
Mike Stump1eb44332009-09-09 15:08:12 +00003090QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003091ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003092 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003093 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003094 assert(!Template.getAsDependentTemplateName() &&
3095 "No dependent template names here!");
3096
John McCalld5532b62009-11-23 01:53:49 +00003097 unsigned NumArgs = Args.size();
3098
Chris Lattner5f9e2722011-07-23 10:55:15 +00003099 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003100 ArgVec.reserve(NumArgs);
3101 for (unsigned i = 0; i != NumArgs; ++i)
3102 ArgVec.push_back(Args[i].getArgument());
3103
John McCall31f17ec2010-04-27 00:57:59 +00003104 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003105 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003106}
3107
Douglas Gregorb70126a2012-02-03 17:16:23 +00003108#ifndef NDEBUG
3109static bool hasAnyPackExpansions(const TemplateArgument *Args,
3110 unsigned NumArgs) {
3111 for (unsigned I = 0; I != NumArgs; ++I)
3112 if (Args[I].isPackExpansion())
3113 return true;
3114
3115 return true;
3116}
3117#endif
3118
John McCall833ca992009-10-29 08:12:44 +00003119QualType
3120ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003121 const TemplateArgument *Args,
3122 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003123 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003124 assert(!Template.getAsDependentTemplateName() &&
3125 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003126 // Look through qualified template names.
3127 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3128 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003129
Douglas Gregorb70126a2012-02-03 17:16:23 +00003130 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003131 Template.getAsTemplateDecl() &&
3132 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003133 QualType CanonType;
3134 if (!Underlying.isNull())
3135 CanonType = getCanonicalType(Underlying);
3136 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003137 // We can get here with an alias template when the specialization contains
3138 // a pack expansion that does not match up with a parameter pack.
3139 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3140 "Caller must compute aliased type");
3141 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003142 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3143 NumArgs);
3144 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003145
Douglas Gregor1275ae02009-07-28 23:00:59 +00003146 // Allocate the (non-canonical) template specialization type, but don't
3147 // try to unique it: these types typically have location information that
3148 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003149 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3150 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003151 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003152 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003153 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003154 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3155 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Douglas Gregor55f6b142009-02-09 18:46:07 +00003157 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003158 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003159}
3160
Mike Stump1eb44332009-09-09 15:08:12 +00003161QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003162ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3163 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003164 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003165 assert(!Template.getAsDependentTemplateName() &&
3166 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003167
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003168 // Look through qualified template names.
3169 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3170 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003171
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003172 // Build the canonical template specialization type.
3173 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003174 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003175 CanonArgs.reserve(NumArgs);
3176 for (unsigned I = 0; I != NumArgs; ++I)
3177 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3178
3179 // Determine whether this canonical template specialization type already
3180 // exists.
3181 llvm::FoldingSetNodeID ID;
3182 TemplateSpecializationType::Profile(ID, CanonTemplate,
3183 CanonArgs.data(), NumArgs, *this);
3184
3185 void *InsertPos = 0;
3186 TemplateSpecializationType *Spec
3187 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3188
3189 if (!Spec) {
3190 // Allocate a new canonical template specialization type.
3191 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3192 sizeof(TemplateArgument) * NumArgs),
3193 TypeAlignment);
3194 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3195 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003196 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003197 Types.push_back(Spec);
3198 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3199 }
3200
3201 assert(Spec->isDependentType() &&
3202 "Non-dependent template-id type must have a canonical type");
3203 return QualType(Spec, 0);
3204}
3205
3206QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003207ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3208 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003209 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003210 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003211 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003212
3213 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003214 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003215 if (T)
3216 return QualType(T, 0);
3217
Douglas Gregor789b1f62010-02-04 18:10:26 +00003218 QualType Canon = NamedType;
3219 if (!Canon.isCanonical()) {
3220 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003221 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3222 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003223 (void)CheckT;
3224 }
3225
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003226 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003227 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003228 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003229 return QualType(T, 0);
3230}
3231
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003232QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003233ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003234 llvm::FoldingSetNodeID ID;
3235 ParenType::Profile(ID, InnerType);
3236
3237 void *InsertPos = 0;
3238 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3239 if (T)
3240 return QualType(T, 0);
3241
3242 QualType Canon = InnerType;
3243 if (!Canon.isCanonical()) {
3244 Canon = getCanonicalType(InnerType);
3245 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 assert(!CheckT && "Paren canonical type broken");
3247 (void)CheckT;
3248 }
3249
3250 T = new (*this) ParenType(InnerType, Canon);
3251 Types.push_back(T);
3252 ParenTypes.InsertNode(T, InsertPos);
3253 return QualType(T, 0);
3254}
3255
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003256QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3257 NestedNameSpecifier *NNS,
3258 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003259 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003260 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3261
3262 if (Canon.isNull()) {
3263 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003264 ElaboratedTypeKeyword CanonKeyword = Keyword;
3265 if (Keyword == ETK_None)
3266 CanonKeyword = ETK_Typename;
3267
3268 if (CanonNNS != NNS || CanonKeyword != Keyword)
3269 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003270 }
3271
3272 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003273 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003274
3275 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003276 DependentNameType *T
3277 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003278 if (T)
3279 return QualType(T, 0);
3280
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003281 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003282 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003283 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003284 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003285}
3286
Mike Stump1eb44332009-09-09 15:08:12 +00003287QualType
John McCall33500952010-06-11 00:33:02 +00003288ASTContext::getDependentTemplateSpecializationType(
3289 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003290 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003291 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003292 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003293 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003294 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003295 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3296 ArgCopy.push_back(Args[I].getArgument());
3297 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3298 ArgCopy.size(),
3299 ArgCopy.data());
3300}
3301
3302QualType
3303ASTContext::getDependentTemplateSpecializationType(
3304 ElaboratedTypeKeyword Keyword,
3305 NestedNameSpecifier *NNS,
3306 const IdentifierInfo *Name,
3307 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003308 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003309 assert((!NNS || NNS->isDependent()) &&
3310 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003311
Douglas Gregor789b1f62010-02-04 18:10:26 +00003312 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003313 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3314 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003315
3316 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003317 DependentTemplateSpecializationType *T
3318 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003319 if (T)
3320 return QualType(T, 0);
3321
John McCall33500952010-06-11 00:33:02 +00003322 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003323
John McCall33500952010-06-11 00:33:02 +00003324 ElaboratedTypeKeyword CanonKeyword = Keyword;
3325 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3326
3327 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003328 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003329 for (unsigned I = 0; I != NumArgs; ++I) {
3330 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3331 if (!CanonArgs[I].structurallyEquals(Args[I]))
3332 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003333 }
3334
John McCall33500952010-06-11 00:33:02 +00003335 QualType Canon;
3336 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3337 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3338 Name, NumArgs,
3339 CanonArgs.data());
3340
3341 // Find the insert position again.
3342 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3343 }
3344
3345 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3346 sizeof(TemplateArgument) * NumArgs),
3347 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003348 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003349 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003350 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003351 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003352 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003353}
3354
Douglas Gregorcded4f62011-01-14 17:04:44 +00003355QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003356 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003357 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003358 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003359
3360 assert(Pattern->containsUnexpandedParameterPack() &&
3361 "Pack expansions must expand one or more parameter packs");
3362 void *InsertPos = 0;
3363 PackExpansionType *T
3364 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3365 if (T)
3366 return QualType(T, 0);
3367
3368 QualType Canon;
3369 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003370 Canon = getCanonicalType(Pattern);
3371 // The canonical type might not contain an unexpanded parameter pack, if it
3372 // contains an alias template specialization which ignores one of its
3373 // parameters.
3374 if (Canon->containsUnexpandedParameterPack()) {
3375 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003376
Richard Smithd8672ef2012-07-16 00:20:35 +00003377 // Find the insert position again, in case we inserted an element into
3378 // PackExpansionTypes and invalidated our insert position.
3379 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3380 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003381 }
3382
Douglas Gregorcded4f62011-01-14 17:04:44 +00003383 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003384 Types.push_back(T);
3385 PackExpansionTypes.InsertNode(T, InsertPos);
3386 return QualType(T, 0);
3387}
3388
Chris Lattner88cb27a2008-04-07 04:56:42 +00003389/// CmpProtocolNames - Comparison predicate for sorting protocols
3390/// alphabetically.
3391static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3392 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003393 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003394}
3395
John McCallc12c5bb2010-05-15 11:32:37 +00003396static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003397 unsigned NumProtocols) {
3398 if (NumProtocols == 0) return true;
3399
Douglas Gregor61cc2962012-01-02 02:00:30 +00003400 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3401 return false;
3402
John McCall54e14c42009-10-22 22:37:11 +00003403 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003404 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3405 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003406 return false;
3407 return true;
3408}
3409
3410static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003411 unsigned &NumProtocols) {
3412 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Chris Lattner88cb27a2008-04-07 04:56:42 +00003414 // Sort protocols, keyed by name.
3415 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3416
Douglas Gregor61cc2962012-01-02 02:00:30 +00003417 // Canonicalize.
3418 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3419 Protocols[I] = Protocols[I]->getCanonicalDecl();
3420
Chris Lattner88cb27a2008-04-07 04:56:42 +00003421 // Remove duplicates.
3422 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3423 NumProtocols = ProtocolsEnd-Protocols;
3424}
3425
John McCallc12c5bb2010-05-15 11:32:37 +00003426QualType ASTContext::getObjCObjectType(QualType BaseType,
3427 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003428 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003429 // If the base type is an interface and there aren't any protocols
3430 // to add, then the interface type will do just fine.
3431 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3432 return BaseType;
3433
3434 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003435 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003436 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003437 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003438 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3439 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003440
John McCallc12c5bb2010-05-15 11:32:37 +00003441 // Build the canonical type, which has the canonical base type and
3442 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003443 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003444 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3445 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3446 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003447 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003448 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003449 unsigned UniqueCount = NumProtocols;
3450
John McCall54e14c42009-10-22 22:37:11 +00003451 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003452 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3453 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003454 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003455 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3456 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003457 }
3458
3459 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003460 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3461 }
3462
3463 unsigned Size = sizeof(ObjCObjectTypeImpl);
3464 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3465 void *Mem = Allocate(Size, TypeAlignment);
3466 ObjCObjectTypeImpl *T =
3467 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3468
3469 Types.push_back(T);
3470 ObjCObjectTypes.InsertNode(T, InsertPos);
3471 return QualType(T, 0);
3472}
3473
3474/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3475/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003476QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003477 llvm::FoldingSetNodeID ID;
3478 ObjCObjectPointerType::Profile(ID, ObjectT);
3479
3480 void *InsertPos = 0;
3481 if (ObjCObjectPointerType *QT =
3482 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3483 return QualType(QT, 0);
3484
3485 // Find the canonical object type.
3486 QualType Canonical;
3487 if (!ObjectT.isCanonical()) {
3488 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3489
3490 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003491 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3492 }
3493
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003494 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003495 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3496 ObjCObjectPointerType *QType =
3497 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003499 Types.push_back(QType);
3500 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003501 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003502}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003503
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003504/// getObjCInterfaceType - Return the unique reference to the type for the
3505/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003506QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3507 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003508 if (Decl->TypeForDecl)
3509 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Douglas Gregor0af55012011-12-16 03:12:41 +00003511 if (PrevDecl) {
3512 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3513 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3514 return QualType(PrevDecl->TypeForDecl, 0);
3515 }
3516
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003517 // Prefer the definition, if there is one.
3518 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3519 Decl = Def;
3520
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003521 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3522 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3523 Decl->TypeForDecl = T;
3524 Types.push_back(T);
3525 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003526}
3527
Douglas Gregor72564e72009-02-26 23:50:07 +00003528/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3529/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003530/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003531/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003532/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003533QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003534 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003535 if (tofExpr->isTypeDependent()) {
3536 llvm::FoldingSetNodeID ID;
3537 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Douglas Gregorb1975722009-07-30 23:18:24 +00003539 void *InsertPos = 0;
3540 DependentTypeOfExprType *Canon
3541 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3542 if (Canon) {
3543 // We already have a "canonical" version of an identical, dependent
3544 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003545 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003546 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003547 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003548 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003549 Canon
3550 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003551 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3552 toe = Canon;
3553 }
3554 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003555 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003556 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003557 }
Steve Naroff9752f252007-08-01 18:02:17 +00003558 Types.push_back(toe);
3559 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003560}
3561
Steve Naroff9752f252007-08-01 18:02:17 +00003562/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3563/// TypeOfType AST's. The only motivation to unique these nodes would be
3564/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003565/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003566/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003567QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003568 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003569 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003570 Types.push_back(tot);
3571 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003572}
3573
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003574
Anders Carlsson395b4752009-06-24 19:06:50 +00003575/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3576/// DecltypeType AST's. The only motivation to unique these nodes would be
3577/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003578/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003579/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003580QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003581 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003582
3583 // C++0x [temp.type]p2:
3584 // If an expression e involves a template parameter, decltype(e) denotes a
3585 // unique dependent type. Two such decltype-specifiers refer to the same
3586 // type only if their expressions are equivalent (14.5.6.1).
3587 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003588 llvm::FoldingSetNodeID ID;
3589 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003591 void *InsertPos = 0;
3592 DependentDecltypeType *Canon
3593 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3594 if (Canon) {
3595 // We already have a "canonical" version of an equivalent, dependent
3596 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003597 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003598 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003599 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003600 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003601 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003602 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3603 dt = Canon;
3604 }
3605 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003606 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3607 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003608 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003609 Types.push_back(dt);
3610 return QualType(dt, 0);
3611}
3612
Sean Huntca63c202011-05-24 22:41:36 +00003613/// getUnaryTransformationType - We don't unique these, since the memory
3614/// savings are minimal and these are rare.
3615QualType ASTContext::getUnaryTransformType(QualType BaseType,
3616 QualType UnderlyingType,
3617 UnaryTransformType::UTTKind Kind)
3618 const {
3619 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003620 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3621 Kind,
3622 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003623 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003624 Types.push_back(Ty);
3625 return QualType(Ty, 0);
3626}
3627
Richard Smith60e141e2013-05-04 07:00:32 +00003628/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3629/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3630/// canonical deduced-but-dependent 'auto' type.
3631QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003632 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003633 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3634 return getAutoDeductType();
3635
3636 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003637 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003638 llvm::FoldingSetNodeID ID;
3639 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3640 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3641 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003642
Richard Smitha2c36462013-04-26 16:15:35 +00003643 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003644 IsDecltypeAuto,
3645 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003646 Types.push_back(AT);
3647 if (InsertPos)
3648 AutoTypes.InsertNode(AT, InsertPos);
3649 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003650}
3651
Eli Friedmanb001de72011-10-06 23:00:33 +00003652/// getAtomicType - Return the uniqued reference to the atomic type for
3653/// the given value type.
3654QualType ASTContext::getAtomicType(QualType T) const {
3655 // Unique pointers, to guarantee there is only one pointer of a particular
3656 // structure.
3657 llvm::FoldingSetNodeID ID;
3658 AtomicType::Profile(ID, T);
3659
3660 void *InsertPos = 0;
3661 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3662 return QualType(AT, 0);
3663
3664 // If the atomic value type isn't canonical, this won't be a canonical type
3665 // either, so fill in the canonical type field.
3666 QualType Canonical;
3667 if (!T.isCanonical()) {
3668 Canonical = getAtomicType(getCanonicalType(T));
3669
3670 // Get the new insert position for the node we care about.
3671 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3672 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3673 }
3674 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3675 Types.push_back(New);
3676 AtomicTypes.InsertNode(New, InsertPos);
3677 return QualType(New, 0);
3678}
3679
Richard Smithad762fc2011-04-14 22:09:26 +00003680/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3681QualType ASTContext::getAutoDeductType() const {
3682 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003683 AutoDeductTy = QualType(
3684 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3685 /*dependent*/false),
3686 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003687 return AutoDeductTy;
3688}
3689
3690/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3691QualType ASTContext::getAutoRRefDeductType() const {
3692 if (AutoRRefDeductTy.isNull())
3693 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3694 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3695 return AutoRRefDeductTy;
3696}
3697
Reid Spencer5f016e22007-07-11 17:01:13 +00003698/// getTagDeclType - Return the unique reference to the type for the
3699/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003700QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003701 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003702 // FIXME: What is the design on getTagDeclType when it requires casting
3703 // away const? mutable?
3704 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003705}
3706
Mike Stump1eb44332009-09-09 15:08:12 +00003707/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3708/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3709/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003710CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003711 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003712}
3713
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003714/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3715CanQualType ASTContext::getIntMaxType() const {
3716 return getFromTargetType(Target->getIntMaxType());
3717}
3718
3719/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3720CanQualType ASTContext::getUIntMaxType() const {
3721 return getFromTargetType(Target->getUIntMaxType());
3722}
3723
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003724/// getSignedWCharType - Return the type of "signed wchar_t".
3725/// Used when in C++, as a GCC extension.
3726QualType ASTContext::getSignedWCharType() const {
3727 // FIXME: derive from "Target" ?
3728 return WCharTy;
3729}
3730
3731/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3732/// Used when in C++, as a GCC extension.
3733QualType ASTContext::getUnsignedWCharType() const {
3734 // FIXME: derive from "Target" ?
3735 return UnsignedIntTy;
3736}
3737
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003738QualType ASTContext::getIntPtrType() const {
3739 return getFromTargetType(Target->getIntPtrType());
3740}
3741
3742QualType ASTContext::getUIntPtrType() const {
3743 return getCorrespondingUnsignedType(getIntPtrType());
3744}
3745
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003746/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003747/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3748QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003749 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003750}
3751
Eli Friedman6902e412012-11-27 02:58:24 +00003752/// \brief Return the unique type for "pid_t" defined in
3753/// <sys/types.h>. We need this to compute the correct type for vfork().
3754QualType ASTContext::getProcessIDType() const {
3755 return getFromTargetType(Target->getProcessIDType());
3756}
3757
Chris Lattnere6327742008-04-02 05:18:44 +00003758//===----------------------------------------------------------------------===//
3759// Type Operators
3760//===----------------------------------------------------------------------===//
3761
Jay Foad4ba2a172011-01-12 09:06:06 +00003762CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003763 // Push qualifiers into arrays, and then discard any remaining
3764 // qualifiers.
3765 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003766 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003767 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003768 QualType Result;
3769 if (isa<ArrayType>(Ty)) {
3770 Result = getArrayDecayedType(QualType(Ty,0));
3771 } else if (isa<FunctionType>(Ty)) {
3772 Result = getPointerType(QualType(Ty, 0));
3773 } else {
3774 Result = QualType(Ty, 0);
3775 }
3776
3777 return CanQualType::CreateUnsafe(Result);
3778}
3779
John McCall62c28c82011-01-18 07:41:22 +00003780QualType ASTContext::getUnqualifiedArrayType(QualType type,
3781 Qualifiers &quals) {
3782 SplitQualType splitType = type.getSplitUnqualifiedType();
3783
3784 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3785 // the unqualified desugared type and then drops it on the floor.
3786 // We then have to strip that sugar back off with
3787 // getUnqualifiedDesugaredType(), which is silly.
3788 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003789 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003790
3791 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003792 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003793 quals = splitType.Quals;
3794 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003795 }
3796
John McCall62c28c82011-01-18 07:41:22 +00003797 // Otherwise, recurse on the array's element type.
3798 QualType elementType = AT->getElementType();
3799 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3800
3801 // If that didn't change the element type, AT has no qualifiers, so we
3802 // can just use the results in splitType.
3803 if (elementType == unqualElementType) {
3804 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003805 quals = splitType.Quals;
3806 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003807 }
3808
3809 // Otherwise, add in the qualifiers from the outermost type, then
3810 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003811 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003812
Douglas Gregor9dadd942010-05-17 18:45:21 +00003813 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003814 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003815 CAT->getSizeModifier(), 0);
3816 }
3817
Douglas Gregor9dadd942010-05-17 18:45:21 +00003818 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003819 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003820 }
3821
Douglas Gregor9dadd942010-05-17 18:45:21 +00003822 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003823 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003824 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003825 VAT->getSizeModifier(),
3826 VAT->getIndexTypeCVRQualifiers(),
3827 VAT->getBracketsRange());
3828 }
3829
3830 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003831 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003832 DSAT->getSizeModifier(), 0,
3833 SourceRange());
3834}
3835
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003836/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3837/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3838/// they point to and return true. If T1 and T2 aren't pointer types
3839/// or pointer-to-member types, or if they are not similar at this
3840/// level, returns false and leaves T1 and T2 unchanged. Top-level
3841/// qualifiers on T1 and T2 are ignored. This function will typically
3842/// be called in a loop that successively "unwraps" pointer and
3843/// pointer-to-member types to compare them at each level.
3844bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3845 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3846 *T2PtrType = T2->getAs<PointerType>();
3847 if (T1PtrType && T2PtrType) {
3848 T1 = T1PtrType->getPointeeType();
3849 T2 = T2PtrType->getPointeeType();
3850 return true;
3851 }
3852
3853 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3854 *T2MPType = T2->getAs<MemberPointerType>();
3855 if (T1MPType && T2MPType &&
3856 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3857 QualType(T2MPType->getClass(), 0))) {
3858 T1 = T1MPType->getPointeeType();
3859 T2 = T2MPType->getPointeeType();
3860 return true;
3861 }
3862
David Blaikie4e4d0842012-03-11 07:00:24 +00003863 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003864 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3865 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3866 if (T1OPType && T2OPType) {
3867 T1 = T1OPType->getPointeeType();
3868 T2 = T2OPType->getPointeeType();
3869 return true;
3870 }
3871 }
3872
3873 // FIXME: Block pointers, too?
3874
3875 return false;
3876}
3877
Jay Foad4ba2a172011-01-12 09:06:06 +00003878DeclarationNameInfo
3879ASTContext::getNameForTemplate(TemplateName Name,
3880 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003881 switch (Name.getKind()) {
3882 case TemplateName::QualifiedTemplate:
3883 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003884 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003885 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3886 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003887
John McCall14606042011-06-30 08:33:18 +00003888 case TemplateName::OverloadedTemplate: {
3889 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3890 // DNInfo work in progress: CHECKME: what about DNLoc?
3891 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3892 }
3893
3894 case TemplateName::DependentTemplate: {
3895 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003896 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003897 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003898 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3899 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003900 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003901 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3902 // DNInfo work in progress: FIXME: source locations?
3903 DeclarationNameLoc DNLoc;
3904 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3905 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3906 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003907 }
3908 }
3909
John McCall14606042011-06-30 08:33:18 +00003910 case TemplateName::SubstTemplateTemplateParm: {
3911 SubstTemplateTemplateParmStorage *subst
3912 = Name.getAsSubstTemplateTemplateParm();
3913 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3914 NameLoc);
3915 }
3916
3917 case TemplateName::SubstTemplateTemplateParmPack: {
3918 SubstTemplateTemplateParmPackStorage *subst
3919 = Name.getAsSubstTemplateTemplateParmPack();
3920 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3921 NameLoc);
3922 }
3923 }
3924
3925 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003926}
3927
Jay Foad4ba2a172011-01-12 09:06:06 +00003928TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003929 switch (Name.getKind()) {
3930 case TemplateName::QualifiedTemplate:
3931 case TemplateName::Template: {
3932 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003933 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003934 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003935 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3936
3937 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003938 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003939 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003940
John McCall14606042011-06-30 08:33:18 +00003941 case TemplateName::OverloadedTemplate:
3942 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003943
John McCall14606042011-06-30 08:33:18 +00003944 case TemplateName::DependentTemplate: {
3945 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3946 assert(DTN && "Non-dependent template names must refer to template decls.");
3947 return DTN->CanonicalTemplateName;
3948 }
3949
3950 case TemplateName::SubstTemplateTemplateParm: {
3951 SubstTemplateTemplateParmStorage *subst
3952 = Name.getAsSubstTemplateTemplateParm();
3953 return getCanonicalTemplateName(subst->getReplacement());
3954 }
3955
3956 case TemplateName::SubstTemplateTemplateParmPack: {
3957 SubstTemplateTemplateParmPackStorage *subst
3958 = Name.getAsSubstTemplateTemplateParmPack();
3959 TemplateTemplateParmDecl *canonParameter
3960 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3961 TemplateArgument canonArgPack
3962 = getCanonicalTemplateArgument(subst->getArgumentPack());
3963 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3964 }
3965 }
3966
3967 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003968}
3969
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003970bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3971 X = getCanonicalTemplateName(X);
3972 Y = getCanonicalTemplateName(Y);
3973 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3974}
3975
Mike Stump1eb44332009-09-09 15:08:12 +00003976TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003977ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003978 switch (Arg.getKind()) {
3979 case TemplateArgument::Null:
3980 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Douglas Gregor1275ae02009-07-28 23:00:59 +00003982 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003983 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Douglas Gregord2008e22012-04-06 22:40:38 +00003985 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003986 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3987 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
Eli Friedmand7a6b162012-09-26 02:36:12 +00003990 case TemplateArgument::NullPtr:
3991 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3992 /*isNullPtr*/true);
3993
Douglas Gregor788cd062009-11-11 01:00:40 +00003994 case TemplateArgument::Template:
3995 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003996
3997 case TemplateArgument::TemplateExpansion:
3998 return TemplateArgument(getCanonicalTemplateName(
3999 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004000 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004001
Douglas Gregor1275ae02009-07-28 23:00:59 +00004002 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004003 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Douglas Gregor1275ae02009-07-28 23:00:59 +00004005 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004006 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Douglas Gregor1275ae02009-07-28 23:00:59 +00004008 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004009 if (Arg.pack_size() == 0)
4010 return Arg;
4011
Douglas Gregor910f8002010-11-07 23:05:16 +00004012 TemplateArgument *CanonArgs
4013 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004014 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004015 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004016 AEnd = Arg.pack_end();
4017 A != AEnd; (void)++A, ++Idx)
4018 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Douglas Gregor910f8002010-11-07 23:05:16 +00004020 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004021 }
4022 }
4023
4024 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004025 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004026}
4027
Douglas Gregord57959a2009-03-27 23:10:48 +00004028NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004029ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004030 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004031 return 0;
4032
4033 switch (NNS->getKind()) {
4034 case NestedNameSpecifier::Identifier:
4035 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004036 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004037 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4038 NNS->getAsIdentifier());
4039
4040 case NestedNameSpecifier::Namespace:
4041 // A namespace is canonical; build a nested-name-specifier with
4042 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004043 return NestedNameSpecifier::Create(*this, 0,
4044 NNS->getAsNamespace()->getOriginalNamespace());
4045
4046 case NestedNameSpecifier::NamespaceAlias:
4047 // A namespace is canonical; build a nested-name-specifier with
4048 // this namespace and no prefix.
4049 return NestedNameSpecifier::Create(*this, 0,
4050 NNS->getAsNamespaceAlias()->getNamespace()
4051 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004052
4053 case NestedNameSpecifier::TypeSpec:
4054 case NestedNameSpecifier::TypeSpecWithTemplate: {
4055 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004056
4057 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4058 // break it apart into its prefix and identifier, then reconsititute those
4059 // as the canonical nested-name-specifier. This is required to canonicalize
4060 // a dependent nested-name-specifier involving typedefs of dependent-name
4061 // types, e.g.,
4062 // typedef typename T::type T1;
4063 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004064 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4065 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004066 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004067
Eli Friedman16412ef2012-03-03 04:09:56 +00004068 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4069 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4070 // first place?
John McCall3b657512011-01-19 10:06:00 +00004071 return NestedNameSpecifier::Create(*this, 0, false,
4072 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004073 }
4074
4075 case NestedNameSpecifier::Global:
4076 // The global specifier is canonical and unique.
4077 return NNS;
4078 }
4079
David Blaikie7530c032012-01-17 06:56:22 +00004080 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004081}
4082
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004083
Jay Foad4ba2a172011-01-12 09:06:06 +00004084const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004085 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004086 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004087 // Handle the common positive case fast.
4088 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4089 return AT;
4090 }
Mike Stump1eb44332009-09-09 15:08:12 +00004091
John McCall0953e762009-09-24 19:53:00 +00004092 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004093 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004094 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004095
John McCall0953e762009-09-24 19:53:00 +00004096 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004097 // implements C99 6.7.3p8: "If the specification of an array type includes
4098 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004100 // If we get here, we either have type qualifiers on the type, or we have
4101 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004102 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004103
John McCall3b657512011-01-19 10:06:00 +00004104 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004105 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004107 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004108 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004109 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004112 // Otherwise, we have an array and we have qualifiers on it. Push the
4113 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004114 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4117 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4118 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004119 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4121 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4122 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004123 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004124
Mike Stump1eb44332009-09-09 15:08:12 +00004125 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004126 = dyn_cast<DependentSizedArrayType>(ATy))
4127 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004128 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004129 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004130 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004131 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004132 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004134 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004135 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004136 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004137 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004138 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004139 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004140}
4141
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004142QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004143 // C99 6.7.5.3p7:
4144 // A declaration of a parameter as "array of type" shall be
4145 // adjusted to "qualified pointer to type", where the type
4146 // qualifiers (if any) are those specified within the [ and ] of
4147 // the array type derivation.
4148 if (T->isArrayType())
4149 return getArrayDecayedType(T);
4150
4151 // C99 6.7.5.3p8:
4152 // A declaration of a parameter as "function returning type"
4153 // shall be adjusted to "pointer to function returning type", as
4154 // in 6.3.2.1.
4155 if (T->isFunctionType())
4156 return getPointerType(T);
4157
4158 return T;
4159}
4160
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004161QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004162 T = getVariableArrayDecayedType(T);
4163 T = getAdjustedParameterType(T);
4164 return T.getUnqualifiedType();
4165}
4166
Chris Lattnere6327742008-04-02 05:18:44 +00004167/// getArrayDecayedType - Return the properly qualified result of decaying the
4168/// specified array type to a pointer. This operation is non-trivial when
4169/// handling typedefs etc. The canonical type of "T" must be an array type,
4170/// this returns a pointer to a properly qualified element of the array.
4171///
4172/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004173QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004174 // Get the element type with 'getAsArrayType' so that we don't lose any
4175 // typedefs in the element type of the array. This also handles propagation
4176 // of type qualifiers from the array type into the element type if present
4177 // (C99 6.7.3p8).
4178 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4179 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004181 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004182
4183 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004184 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004185}
4186
John McCall3b657512011-01-19 10:06:00 +00004187QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4188 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004189}
4190
John McCall3b657512011-01-19 10:06:00 +00004191QualType ASTContext::getBaseElementType(QualType type) const {
4192 Qualifiers qs;
4193 while (true) {
4194 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004195 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004196 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004197
John McCall3b657512011-01-19 10:06:00 +00004198 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004199 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201
John McCall3b657512011-01-19 10:06:00 +00004202 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004203}
4204
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004205/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004206uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004207ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4208 uint64_t ElementCount = 1;
4209 do {
4210 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004211 CA = dyn_cast_or_null<ConstantArrayType>(
4212 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004213 } while (CA);
4214 return ElementCount;
4215}
4216
Reid Spencer5f016e22007-07-11 17:01:13 +00004217/// getFloatingRank - Return a relative rank for floating point types.
4218/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004219static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004220 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004221 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004222
John McCall183700f2009-09-21 23:43:11 +00004223 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4224 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004225 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004226 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004227 case BuiltinType::Float: return FloatRank;
4228 case BuiltinType::Double: return DoubleRank;
4229 case BuiltinType::LongDouble: return LongDoubleRank;
4230 }
4231}
4232
Mike Stump1eb44332009-09-09 15:08:12 +00004233/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4234/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004235/// 'typeDomain' is a real floating point or complex type.
4236/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004237QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4238 QualType Domain) const {
4239 FloatingRank EltRank = getFloatingRank(Size);
4240 if (Domain->isComplexType()) {
4241 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004242 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004243 case FloatRank: return FloatComplexTy;
4244 case DoubleRank: return DoubleComplexTy;
4245 case LongDoubleRank: return LongDoubleComplexTy;
4246 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004247 }
Chris Lattner1361b112008-04-06 23:58:54 +00004248
4249 assert(Domain->isRealFloatingType() && "Unknown domain!");
4250 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004251 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004252 case FloatRank: return FloatTy;
4253 case DoubleRank: return DoubleTy;
4254 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004255 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004256 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004257}
4258
Chris Lattner7cfeb082008-04-06 23:55:33 +00004259/// getFloatingTypeOrder - Compare the rank of the two specified floating
4260/// point types, ignoring the domain of the type (i.e. 'double' ==
4261/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004262/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004263int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004264 FloatingRank LHSR = getFloatingRank(LHS);
4265 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Chris Lattnera75cea32008-04-06 23:38:49 +00004267 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004268 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004269 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004270 return 1;
4271 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004272}
4273
Chris Lattnerf52ab252008-04-06 22:59:24 +00004274/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4275/// routine will assert if passed a built-in type that isn't an integer or enum,
4276/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004277unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004278 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004279
Chris Lattnerf52ab252008-04-06 22:59:24 +00004280 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004281 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004282 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004283 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004284 case BuiltinType::Char_S:
4285 case BuiltinType::Char_U:
4286 case BuiltinType::SChar:
4287 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004288 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004289 case BuiltinType::Short:
4290 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004291 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004292 case BuiltinType::Int:
4293 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004294 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::Long:
4296 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004297 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004298 case BuiltinType::LongLong:
4299 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004300 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004301 case BuiltinType::Int128:
4302 case BuiltinType::UInt128:
4303 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004304 }
4305}
4306
Eli Friedman04e83572009-08-20 04:21:42 +00004307/// \brief Whether this is a promotable bitfield reference according
4308/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4309///
4310/// \returns the type this bit-field will promote to, or NULL if no
4311/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004312QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004313 if (E->isTypeDependent() || E->isValueDependent())
4314 return QualType();
4315
John McCall993f43f2013-05-06 21:39:12 +00004316 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004317 if (!Field)
4318 return QualType();
4319
4320 QualType FT = Field->getType();
4321
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004322 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004323 uint64_t IntSize = getTypeSize(IntTy);
4324 // GCC extension compatibility: if the bit-field size is less than or equal
4325 // to the size of int, it gets promoted no matter what its type is.
4326 // For instance, unsigned long bf : 4 gets promoted to signed int.
4327 if (BitWidth < IntSize)
4328 return IntTy;
4329
4330 if (BitWidth == IntSize)
4331 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4332
4333 // Types bigger than int are not subject to promotions, and therefore act
4334 // like the base type.
4335 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4336 // is ridiculous.
4337 return QualType();
4338}
4339
Eli Friedmana95d7572009-08-19 07:44:53 +00004340/// getPromotedIntegerType - Returns the type that Promotable will
4341/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4342/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004343QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004344 assert(!Promotable.isNull());
4345 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004346 if (const EnumType *ET = Promotable->getAs<EnumType>())
4347 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004348
4349 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4350 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4351 // (3.9.1) can be converted to a prvalue of the first of the following
4352 // types that can represent all the values of its underlying type:
4353 // int, unsigned int, long int, unsigned long int, long long int, or
4354 // unsigned long long int [...]
4355 // FIXME: Is there some better way to compute this?
4356 if (BT->getKind() == BuiltinType::WChar_S ||
4357 BT->getKind() == BuiltinType::WChar_U ||
4358 BT->getKind() == BuiltinType::Char16 ||
4359 BT->getKind() == BuiltinType::Char32) {
4360 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4361 uint64_t FromSize = getTypeSize(BT);
4362 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4363 LongLongTy, UnsignedLongLongTy };
4364 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4365 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4366 if (FromSize < ToSize ||
4367 (FromSize == ToSize &&
4368 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4369 return PromoteTypes[Idx];
4370 }
4371 llvm_unreachable("char type should fit into long long");
4372 }
4373 }
4374
4375 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004376 if (Promotable->isSignedIntegerType())
4377 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004378 uint64_t PromotableSize = getIntWidth(Promotable);
4379 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004380 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4381 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4382}
4383
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004384/// \brief Recurses in pointer/array types until it finds an objc retainable
4385/// type and returns its ownership.
4386Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4387 while (!T.isNull()) {
4388 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4389 return T.getObjCLifetime();
4390 if (T->isArrayType())
4391 T = getBaseElementType(T);
4392 else if (const PointerType *PT = T->getAs<PointerType>())
4393 T = PT->getPointeeType();
4394 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004395 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004396 else
4397 break;
4398 }
4399
4400 return Qualifiers::OCL_None;
4401}
4402
Mike Stump1eb44332009-09-09 15:08:12 +00004403/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004404/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004405/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004406int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004407 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4408 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004409 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Chris Lattnerf52ab252008-04-06 22:59:24 +00004411 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4412 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattner7cfeb082008-04-06 23:55:33 +00004414 unsigned LHSRank = getIntegerRank(LHSC);
4415 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004416
Chris Lattner7cfeb082008-04-06 23:55:33 +00004417 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4418 if (LHSRank == RHSRank) return 0;
4419 return LHSRank > RHSRank ? 1 : -1;
4420 }
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Chris Lattner7cfeb082008-04-06 23:55:33 +00004422 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4423 if (LHSUnsigned) {
4424 // If the unsigned [LHS] type is larger, return it.
4425 if (LHSRank >= RHSRank)
4426 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Chris Lattner7cfeb082008-04-06 23:55:33 +00004428 // If the signed type can represent all values of the unsigned type, it
4429 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004430 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 return -1;
4432 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004433
Chris Lattner7cfeb082008-04-06 23:55:33 +00004434 // If the unsigned [RHS] type is larger, return it.
4435 if (RHSRank >= LHSRank)
4436 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Chris Lattner7cfeb082008-04-06 23:55:33 +00004438 // If the signed type can represent all values of the unsigned type, it
4439 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004440 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004441 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004442}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004443
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004444static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004445CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4446 DeclContext *DC, IdentifierInfo *Id) {
4447 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004448 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004449 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004450 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004451 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004452}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004453
Mike Stump1eb44332009-09-09 15:08:12 +00004454// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004455QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004456 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004457 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004458 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004459 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004460 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004461
Anders Carlssonf06273f2007-11-19 00:25:30 +00004462 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Anders Carlsson71993dd2007-08-17 05:31:46 +00004464 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004465 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004466 // int flags;
4467 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004468 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004469 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004470 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004471 FieldTypes[3] = LongTy;
4472
Anders Carlsson71993dd2007-08-17 05:31:46 +00004473 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004474 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004475 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004476 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004477 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004478 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004479 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004480 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004481 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004482 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004483 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004484 }
4485
Douglas Gregor838db382010-02-11 01:19:42 +00004486 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004487 }
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Anders Carlsson71993dd2007-08-17 05:31:46 +00004489 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004490}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004491
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004492QualType ASTContext::getObjCSuperType() const {
4493 if (ObjCSuperType.isNull()) {
4494 RecordDecl *ObjCSuperTypeDecl =
4495 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4496 TUDecl->addDecl(ObjCSuperTypeDecl);
4497 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4498 }
4499 return ObjCSuperType;
4500}
4501
Douglas Gregor319ac892009-04-23 22:29:11 +00004502void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004503 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004504 assert(Rec && "Invalid CFConstantStringType");
4505 CFConstantStringTypeDecl = Rec->getDecl();
4506}
4507
Jay Foad4ba2a172011-01-12 09:06:06 +00004508QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004509 if (BlockDescriptorType)
4510 return getTagDeclType(BlockDescriptorType);
4511
4512 RecordDecl *T;
4513 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004514 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004515 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004516 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004517
4518 QualType FieldTypes[] = {
4519 UnsignedLongTy,
4520 UnsignedLongTy,
4521 };
4522
4523 const char *FieldNames[] = {
4524 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004525 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004526 };
4527
4528 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004529 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004530 SourceLocation(),
4531 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004532 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004533 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004534 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004535 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004536 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004537 T->addDecl(Field);
4538 }
4539
Douglas Gregor838db382010-02-11 01:19:42 +00004540 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004541
4542 BlockDescriptorType = T;
4543
4544 return getTagDeclType(BlockDescriptorType);
4545}
4546
Jay Foad4ba2a172011-01-12 09:06:06 +00004547QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004548 if (BlockDescriptorExtendedType)
4549 return getTagDeclType(BlockDescriptorExtendedType);
4550
4551 RecordDecl *T;
4552 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004553 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004554 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004555 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004556
4557 QualType FieldTypes[] = {
4558 UnsignedLongTy,
4559 UnsignedLongTy,
4560 getPointerType(VoidPtrTy),
4561 getPointerType(VoidPtrTy)
4562 };
4563
4564 const char *FieldNames[] = {
4565 "reserved",
4566 "Size",
4567 "CopyFuncPtr",
4568 "DestroyFuncPtr"
4569 };
4570
4571 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004572 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004573 SourceLocation(),
4574 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004575 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004576 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004577 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004578 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004579 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004580 T->addDecl(Field);
4581 }
4582
Douglas Gregor838db382010-02-11 01:19:42 +00004583 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004584
4585 BlockDescriptorExtendedType = T;
4586
4587 return getTagDeclType(BlockDescriptorExtendedType);
4588}
4589
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004590/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4591/// requires copy/dispose. Note that this must match the logic
4592/// in buildByrefHelpers.
4593bool ASTContext::BlockRequiresCopying(QualType Ty,
4594 const VarDecl *D) {
4595 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4596 const Expr *copyExpr = getBlockVarCopyInits(D);
4597 if (!copyExpr && record->hasTrivialDestructor()) return false;
4598
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004599 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004600 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004601
4602 if (!Ty->isObjCRetainableType()) return false;
4603
4604 Qualifiers qs = Ty.getQualifiers();
4605
4606 // If we have lifetime, that dominates.
4607 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4608 assert(getLangOpts().ObjCAutoRefCount);
4609
4610 switch (lifetime) {
4611 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4612
4613 // These are just bits as far as the runtime is concerned.
4614 case Qualifiers::OCL_ExplicitNone:
4615 case Qualifiers::OCL_Autoreleasing:
4616 return false;
4617
4618 // Tell the runtime that this is ARC __weak, called by the
4619 // byref routines.
4620 case Qualifiers::OCL_Weak:
4621 // ARC __strong __block variables need to be retained.
4622 case Qualifiers::OCL_Strong:
4623 return true;
4624 }
4625 llvm_unreachable("fell out of lifetime switch!");
4626 }
4627 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4628 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004629}
4630
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004631bool ASTContext::getByrefLifetime(QualType Ty,
4632 Qualifiers::ObjCLifetime &LifeTime,
4633 bool &HasByrefExtendedLayout) const {
4634
4635 if (!getLangOpts().ObjC1 ||
4636 getLangOpts().getGC() != LangOptions::NonGC)
4637 return false;
4638
4639 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004640 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004641 HasByrefExtendedLayout = true;
4642 LifeTime = Qualifiers::OCL_None;
4643 }
4644 else if (getLangOpts().ObjCAutoRefCount)
4645 LifeTime = Ty.getObjCLifetime();
4646 // MRR.
4647 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4648 LifeTime = Qualifiers::OCL_ExplicitNone;
4649 else
4650 LifeTime = Qualifiers::OCL_None;
4651 return true;
4652}
4653
Douglas Gregore97179c2011-09-08 01:46:34 +00004654TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4655 if (!ObjCInstanceTypeDecl)
4656 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4657 getTranslationUnitDecl(),
4658 SourceLocation(),
4659 SourceLocation(),
4660 &Idents.get("instancetype"),
4661 getTrivialTypeSourceInfo(getObjCIdType()));
4662 return ObjCInstanceTypeDecl;
4663}
4664
Anders Carlssone8c49532007-10-29 06:33:42 +00004665// This returns true if a type has been typedefed to BOOL:
4666// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004667static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004668 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004669 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4670 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004672 return false;
4673}
4674
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004675/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004676/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004677CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004678 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4679 return CharUnits::Zero();
4680
Ken Dyck199c3d62010-01-11 17:06:35 +00004681 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004683 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004684 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004685 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686 // Treat arrays as pointers, since that's how they're passed in.
4687 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004688 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004689 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004690}
4691
4692static inline
4693std::string charUnitsToString(const CharUnits &CU) {
4694 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004695}
4696
John McCall6b5a61b2011-02-07 10:33:21 +00004697/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004698/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004699std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4700 std::string S;
4701
David Chisnall5e530af2009-11-17 19:33:30 +00004702 const BlockDecl *Decl = Expr->getBlockDecl();
4703 QualType BlockTy =
4704 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4705 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004706 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004707 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4708 BlockTy->getAs<FunctionType>()->getResultType(),
4709 S, true /*Extended*/);
4710 else
4711 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4712 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004713 // Compute size of all parameters.
4714 // Start with computing size of a pointer in number of bytes.
4715 // FIXME: There might(should) be a better way of doing this computation!
4716 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004717 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4718 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004719 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004720 E = Decl->param_end(); PI != E; ++PI) {
4721 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004722 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004723 if (sz.isZero())
4724 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004725 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004726 ParmOffset += sz;
4727 }
4728 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004729 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004730 // Block pointer and offset.
4731 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004732
4733 // Argument types.
4734 ParmOffset = PtrSize;
4735 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4736 Decl->param_end(); PI != E; ++PI) {
4737 ParmVarDecl *PVDecl = *PI;
4738 QualType PType = PVDecl->getOriginalType();
4739 if (const ArrayType *AT =
4740 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4741 // Use array's original type only if it has known number of
4742 // elements.
4743 if (!isa<ConstantArrayType>(AT))
4744 PType = PVDecl->getType();
4745 } else if (PType->isFunctionType())
4746 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004747 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004748 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4749 S, true /*Extended*/);
4750 else
4751 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004752 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004753 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004754 }
John McCall6b5a61b2011-02-07 10:33:21 +00004755
4756 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004757}
4758
Douglas Gregorf968d832011-05-27 01:19:52 +00004759bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004760 std::string& S) {
4761 // Encode result type.
4762 getObjCEncodingForType(Decl->getResultType(), S);
4763 CharUnits ParmOffset;
4764 // Compute size of all parameters.
4765 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4766 E = Decl->param_end(); PI != E; ++PI) {
4767 QualType PType = (*PI)->getType();
4768 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004769 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004770 continue;
4771
David Chisnall5389f482010-12-30 14:05:53 +00004772 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004773 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004774 ParmOffset += sz;
4775 }
4776 S += charUnitsToString(ParmOffset);
4777 ParmOffset = CharUnits::Zero();
4778
4779 // Argument types.
4780 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4781 E = Decl->param_end(); PI != E; ++PI) {
4782 ParmVarDecl *PVDecl = *PI;
4783 QualType PType = PVDecl->getOriginalType();
4784 if (const ArrayType *AT =
4785 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4786 // Use array's original type only if it has known number of
4787 // elements.
4788 if (!isa<ConstantArrayType>(AT))
4789 PType = PVDecl->getType();
4790 } else if (PType->isFunctionType())
4791 PType = PVDecl->getType();
4792 getObjCEncodingForType(PType, S);
4793 S += charUnitsToString(ParmOffset);
4794 ParmOffset += getObjCEncodingTypeSize(PType);
4795 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004796
4797 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004798}
4799
Bob Wilsondc8dab62011-11-30 01:57:58 +00004800/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4801/// method parameter or return type. If Extended, include class names and
4802/// block object types.
4803void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4804 QualType T, std::string& S,
4805 bool Extended) const {
4806 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4807 getObjCEncodingForTypeQualifier(QT, S);
4808 // Encode parameter type.
4809 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4810 true /*OutermostType*/,
4811 false /*EncodingProperty*/,
4812 false /*StructField*/,
4813 Extended /*EncodeBlockParameters*/,
4814 Extended /*EncodeClassNames*/);
4815}
4816
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004817/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004818/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004819bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004820 std::string& S,
4821 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004822 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004823 // Encode return type.
4824 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4825 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004826 // Compute size of all parameters.
4827 // Start with computing size of a pointer in number of bytes.
4828 // FIXME: There might(should) be a better way of doing this computation!
4829 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004830 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004831 // The first two arguments (self and _cmd) are pointers; account for
4832 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004833 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004834 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004835 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004836 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004837 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004838 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004839 continue;
4840
Ken Dyck199c3d62010-01-11 17:06:35 +00004841 assert (sz.isPositive() &&
4842 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004843 ParmOffset += sz;
4844 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004845 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004846 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004847 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004849 // Argument types.
4850 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004851 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004852 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004853 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004854 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004855 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004856 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4857 // Use array's original type only if it has known number of
4858 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004859 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004860 PType = PVDecl->getType();
4861 } else if (PType->isFunctionType())
4862 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004863 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4864 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004865 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004866 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004867 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004868
4869 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004870}
4871
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004872/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004873/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004874/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4875/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004876/// Property attributes are stored as a comma-delimited C string. The simple
4877/// attributes readonly and bycopy are encoded as single characters. The
4878/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4879/// encoded as single characters, followed by an identifier. Property types
4880/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004881/// these attributes are defined by the following enumeration:
4882/// @code
4883/// enum PropertyAttributes {
4884/// kPropertyReadOnly = 'R', // property is read-only.
4885/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4886/// kPropertyByref = '&', // property is a reference to the value last assigned
4887/// kPropertyDynamic = 'D', // property is dynamic
4888/// kPropertyGetter = 'G', // followed by getter selector name
4889/// kPropertySetter = 'S', // followed by setter selector name
4890/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004891/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004892/// kPropertyWeak = 'W' // 'weak' property
4893/// kPropertyStrong = 'P' // property GC'able
4894/// kPropertyNonAtomic = 'N' // property non-atomic
4895/// };
4896/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004897void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004898 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004899 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004900 // Collect information from the property implementation decl(s).
4901 bool Dynamic = false;
4902 ObjCPropertyImplDecl *SynthesizePID = 0;
4903
4904 // FIXME: Duplicated code due to poor abstraction.
4905 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004906 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004907 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4908 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004909 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004910 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004911 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004912 if (PID->getPropertyDecl() == PD) {
4913 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4914 Dynamic = true;
4915 } else {
4916 SynthesizePID = PID;
4917 }
4918 }
4919 }
4920 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004921 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004922 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004923 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004924 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004925 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004926 if (PID->getPropertyDecl() == PD) {
4927 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4928 Dynamic = true;
4929 } else {
4930 SynthesizePID = PID;
4931 }
4932 }
Mike Stump1eb44332009-09-09 15:08:12 +00004933 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004934 }
4935 }
4936
4937 // FIXME: This is not very efficient.
4938 S = "T";
4939
4940 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004941 // GCC has some special rules regarding encoding of properties which
4942 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004943 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004944 true /* outermost type */,
4945 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004946
4947 if (PD->isReadOnly()) {
4948 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004949 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4950 S += ",C";
4951 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4952 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004953 } else {
4954 switch (PD->getSetterKind()) {
4955 case ObjCPropertyDecl::Assign: break;
4956 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004957 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004958 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004959 }
4960 }
4961
4962 // It really isn't clear at all what this means, since properties
4963 // are "dynamic by default".
4964 if (Dynamic)
4965 S += ",D";
4966
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004967 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4968 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004969
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004970 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4971 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004972 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004973 }
4974
4975 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4976 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004977 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004978 }
4979
4980 if (SynthesizePID) {
4981 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4982 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004983 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004984 }
4985
4986 // FIXME: OBJCGC: weak & strong
4987}
4988
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004989/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004990/// Another legacy compatibility encoding: 32-bit longs are encoded as
4991/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004992/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4993///
4994void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004995 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004996 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004997 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004998 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004999 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005000 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005001 PointeeTy = IntTy;
5002 }
5003 }
5004}
5005
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005006void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005007 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005008 // We follow the behavior of gcc, expanding structures which are
5009 // directly pointed to, and expanding embedded structures. Note that
5010 // these rules are sufficient to prevent recursive encoding of the
5011 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005012 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005013 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005014}
5015
John McCall3624e9e2012-12-20 02:45:14 +00005016static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5017 BuiltinType::Kind kind) {
5018 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005019 case BuiltinType::Void: return 'v';
5020 case BuiltinType::Bool: return 'B';
5021 case BuiltinType::Char_U:
5022 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005023 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005024 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005025 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005026 case BuiltinType::UInt: return 'I';
5027 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005028 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005029 case BuiltinType::UInt128: return 'T';
5030 case BuiltinType::ULongLong: return 'Q';
5031 case BuiltinType::Char_S:
5032 case BuiltinType::SChar: return 'c';
5033 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005034 case BuiltinType::WChar_S:
5035 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005036 case BuiltinType::Int: return 'i';
5037 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005038 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005039 case BuiltinType::LongLong: return 'q';
5040 case BuiltinType::Int128: return 't';
5041 case BuiltinType::Float: return 'f';
5042 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005043 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005044 case BuiltinType::NullPtr: return '*'; // like char*
5045
5046 case BuiltinType::Half:
5047 // FIXME: potentially need @encodes for these!
5048 return ' ';
5049
5050 case BuiltinType::ObjCId:
5051 case BuiltinType::ObjCClass:
5052 case BuiltinType::ObjCSel:
5053 llvm_unreachable("@encoding ObjC primitive type");
5054
5055 // OpenCL and placeholder types don't need @encodings.
5056 case BuiltinType::OCLImage1d:
5057 case BuiltinType::OCLImage1dArray:
5058 case BuiltinType::OCLImage1dBuffer:
5059 case BuiltinType::OCLImage2d:
5060 case BuiltinType::OCLImage2dArray:
5061 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005062 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005063 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005064 case BuiltinType::Dependent:
5065#define BUILTIN_TYPE(KIND, ID)
5066#define PLACEHOLDER_TYPE(KIND, ID) \
5067 case BuiltinType::KIND:
5068#include "clang/AST/BuiltinTypes.def"
5069 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005070 }
David Blaikie719e53f2013-01-09 17:48:41 +00005071 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005072}
5073
Douglas Gregor5471bc82011-09-08 17:18:35 +00005074static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5075 EnumDecl *Enum = ET->getDecl();
5076
5077 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5078 if (!Enum->isFixed())
5079 return 'i';
5080
5081 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005082 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5083 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005084}
5085
Jay Foad4ba2a172011-01-12 09:06:06 +00005086static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005087 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005088 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005089 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005090 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5091 // The GNU runtime requires more information; bitfields are encoded as b,
5092 // then the offset (in bits) of the first element, then the type of the
5093 // bitfield, then the size in bits. For example, in this structure:
5094 //
5095 // struct
5096 // {
5097 // int integer;
5098 // int flags:2;
5099 // };
5100 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5101 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5102 // information is not especially sensible, but we're stuck with it for
5103 // compatibility with GCC, although providing it breaks anything that
5104 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005105 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005106 const RecordDecl *RD = FD->getParent();
5107 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005108 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005109 if (const EnumType *ET = T->getAs<EnumType>())
5110 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005111 else {
5112 const BuiltinType *BT = T->castAs<BuiltinType>();
5113 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5114 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005115 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005116 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005117}
5118
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005119// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005120void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5121 bool ExpandPointedToStructures,
5122 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005123 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005124 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005125 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005126 bool StructField,
5127 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005128 bool EncodeClassNames,
5129 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005130 CanQualType CT = getCanonicalType(T);
5131 switch (CT->getTypeClass()) {
5132 case Type::Builtin:
5133 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005134 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005135 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005136 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5137 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5138 else
5139 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005141
John McCall3624e9e2012-12-20 02:45:14 +00005142 case Type::Complex: {
5143 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005144 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005145 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005146 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005147 return;
5148 }
John McCall3624e9e2012-12-20 02:45:14 +00005149
5150 case Type::Atomic: {
5151 const AtomicType *AT = T->castAs<AtomicType>();
5152 S += 'A';
5153 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5154 false, false);
5155 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005156 }
John McCall3624e9e2012-12-20 02:45:14 +00005157
5158 // encoding for pointer or reference types.
5159 case Type::Pointer:
5160 case Type::LValueReference:
5161 case Type::RValueReference: {
5162 QualType PointeeTy;
5163 if (isa<PointerType>(CT)) {
5164 const PointerType *PT = T->castAs<PointerType>();
5165 if (PT->isObjCSelType()) {
5166 S += ':';
5167 return;
5168 }
5169 PointeeTy = PT->getPointeeType();
5170 } else {
5171 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5172 }
5173
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005174 bool isReadOnly = false;
5175 // For historical/compatibility reasons, the read-only qualifier of the
5176 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5177 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005178 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005179 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005180 if (OutermostType && T.isConstQualified()) {
5181 isReadOnly = true;
5182 S += 'r';
5183 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005184 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005185 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005186 while (P->getAs<PointerType>())
5187 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005188 if (P.isConstQualified()) {
5189 isReadOnly = true;
5190 S += 'r';
5191 }
5192 }
5193 if (isReadOnly) {
5194 // Another legacy compatibility encoding. Some ObjC qualifier and type
5195 // combinations need to be rearranged.
5196 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005197 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005198 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005199 }
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005201 if (PointeeTy->isCharType()) {
5202 // char pointer types should be encoded as '*' unless it is a
5203 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005204 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005205 S += '*';
5206 return;
5207 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005208 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005209 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5210 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5211 S += '#';
5212 return;
5213 }
5214 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5215 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5216 S += '@';
5217 return;
5218 }
5219 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005220 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005221 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005222 getLegacyIntegralTypeEncoding(PointeeTy);
5223
Mike Stump1eb44332009-09-09 15:08:12 +00005224 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005225 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005226 return;
5227 }
John McCall3624e9e2012-12-20 02:45:14 +00005228
5229 case Type::ConstantArray:
5230 case Type::IncompleteArray:
5231 case Type::VariableArray: {
5232 const ArrayType *AT = cast<ArrayType>(CT);
5233
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005234 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005235 // Incomplete arrays are encoded as a pointer to the array element.
5236 S += '^';
5237
Mike Stump1eb44332009-09-09 15:08:12 +00005238 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005239 false, ExpandStructures, FD);
5240 } else {
5241 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005243 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5244 S += llvm::utostr(CAT->getSize().getZExtValue());
5245 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005246 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005247 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5248 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 S += '0';
5250 }
Mike Stump1eb44332009-09-09 15:08:12 +00005251
5252 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005253 false, ExpandStructures, FD);
5254 S += ']';
5255 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005256 return;
5257 }
Mike Stump1eb44332009-09-09 15:08:12 +00005258
John McCall3624e9e2012-12-20 02:45:14 +00005259 case Type::FunctionNoProto:
5260 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005261 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005262 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005263
John McCall3624e9e2012-12-20 02:45:14 +00005264 case Type::Record: {
5265 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005266 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005267 // Anonymous structures print as '?'
5268 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5269 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005270 if (ClassTemplateSpecializationDecl *Spec
5271 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5272 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005273 llvm::raw_string_ostream OS(S);
5274 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005275 TemplateArgs.data(),
5276 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005277 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005278 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005279 } else {
5280 S += '?';
5281 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005282 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005283 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005284 if (!RDecl->isUnion()) {
5285 getObjCEncodingForStructureImpl(RDecl, S, FD);
5286 } else {
5287 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5288 FieldEnd = RDecl->field_end();
5289 Field != FieldEnd; ++Field) {
5290 if (FD) {
5291 S += '"';
5292 S += Field->getNameAsString();
5293 S += '"';
5294 }
Mike Stump1eb44332009-09-09 15:08:12 +00005295
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005296 // Special case bit-fields.
5297 if (Field->isBitField()) {
5298 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005299 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005300 } else {
5301 QualType qt = Field->getType();
5302 getLegacyIntegralTypeEncoding(qt);
5303 getObjCEncodingForTypeImpl(qt, S, false, true,
5304 FD, /*OutermostType*/false,
5305 /*EncodingProperty*/false,
5306 /*StructField*/true);
5307 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005308 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005309 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005310 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005311 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005312 return;
5313 }
Mike Stump1eb44332009-09-09 15:08:12 +00005314
John McCall3624e9e2012-12-20 02:45:14 +00005315 case Type::BlockPointer: {
5316 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005317 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005318 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005319 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005320
5321 S += '<';
5322 // Block return type
5323 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5324 ExpandPointedToStructures, ExpandStructures,
5325 FD,
5326 false /* OutermostType */,
5327 EncodingProperty,
5328 false /* StructField */,
5329 EncodeBlockParameters,
5330 EncodeClassNames);
5331 // Block self
5332 S += "@?";
5333 // Block parameters
5334 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5335 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5336 E = FPT->arg_type_end(); I && (I != E); ++I) {
5337 getObjCEncodingForTypeImpl(*I, S,
5338 ExpandPointedToStructures,
5339 ExpandStructures,
5340 FD,
5341 false /* OutermostType */,
5342 EncodingProperty,
5343 false /* StructField */,
5344 EncodeBlockParameters,
5345 EncodeClassNames);
5346 }
5347 }
5348 S += '>';
5349 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005350 return;
5351 }
Mike Stump1eb44332009-09-09 15:08:12 +00005352
John McCall3624e9e2012-12-20 02:45:14 +00005353 case Type::ObjCObject:
5354 case Type::ObjCInterface: {
5355 // Ignore protocol qualifiers when mangling at this level.
5356 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005357
John McCall3624e9e2012-12-20 02:45:14 +00005358 // The assumption seems to be that this assert will succeed
5359 // because nested levels will have filtered out 'id' and 'Class'.
5360 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005361 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005362 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005363 S += '{';
5364 const IdentifierInfo *II = OI->getIdentifier();
5365 S += II->getName();
5366 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005367 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005368 DeepCollectObjCIvars(OI, true, Ivars);
5369 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005370 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005371 if (Field->isBitField())
5372 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005373 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005374 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5375 false, false, false, false, false,
5376 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005377 }
5378 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005379 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005380 }
Mike Stump1eb44332009-09-09 15:08:12 +00005381
John McCall3624e9e2012-12-20 02:45:14 +00005382 case Type::ObjCObjectPointer: {
5383 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005384 if (OPT->isObjCIdType()) {
5385 S += '@';
5386 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005387 }
Mike Stump1eb44332009-09-09 15:08:12 +00005388
Steve Naroff27d20a22009-10-28 22:03:49 +00005389 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5390 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5391 // Since this is a binary compatibility issue, need to consult with runtime
5392 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005393 S += '#';
5394 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005395 }
Mike Stump1eb44332009-09-09 15:08:12 +00005396
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005397 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005398 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005399 ExpandPointedToStructures,
5400 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005401 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005402 // Note that we do extended encoding of protocol qualifer list
5403 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005404 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005405 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5406 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005407 S += '<';
5408 S += (*I)->getNameAsString();
5409 S += '>';
5410 }
5411 S += '"';
5412 }
5413 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005414 }
Mike Stump1eb44332009-09-09 15:08:12 +00005415
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005416 QualType PointeeTy = OPT->getPointeeType();
5417 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005418 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5419 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005420 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005421 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005422 // {...};
5423 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005424 getObjCEncodingForTypeImpl(PointeeTy, S,
5425 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005426 NULL,
5427 false, false, false, false, false,
5428 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005429 return;
5430 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005431
5432 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005433 if (OPT->getInterfaceDecl() &&
5434 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005435 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005436 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005437 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5438 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005439 S += '<';
5440 S += (*I)->getNameAsString();
5441 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005442 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005443 S += '"';
5444 }
5445 return;
5446 }
Mike Stump1eb44332009-09-09 15:08:12 +00005447
John McCall532ec7b2010-05-17 23:56:34 +00005448 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005449 // FIXME: we shoul do better than that. 'M' is available.
5450 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005451 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005452
John McCall3624e9e2012-12-20 02:45:14 +00005453 case Type::Vector:
5454 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005455 // This matches gcc's encoding, even though technically it is
5456 // insufficient.
5457 // FIXME. We should do a better job than gcc.
5458 return;
John McCall3624e9e2012-12-20 02:45:14 +00005459
Richard Smithdc7a4f52013-04-30 13:56:41 +00005460 case Type::Auto:
5461 // We could see an undeduced auto type here during error recovery.
5462 // Just ignore it.
5463 return;
5464
John McCall3624e9e2012-12-20 02:45:14 +00005465#define ABSTRACT_TYPE(KIND, BASE)
5466#define TYPE(KIND, BASE)
5467#define DEPENDENT_TYPE(KIND, BASE) \
5468 case Type::KIND:
5469#define NON_CANONICAL_TYPE(KIND, BASE) \
5470 case Type::KIND:
5471#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5472 case Type::KIND:
5473#include "clang/AST/TypeNodes.def"
5474 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005475 }
John McCall3624e9e2012-12-20 02:45:14 +00005476 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005477}
5478
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005479void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5480 std::string &S,
5481 const FieldDecl *FD,
5482 bool includeVBases) const {
5483 assert(RDecl && "Expected non-null RecordDecl");
5484 assert(!RDecl->isUnion() && "Should not be called for unions");
5485 if (!RDecl->getDefinition())
5486 return;
5487
5488 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5489 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5490 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5491
5492 if (CXXRec) {
5493 for (CXXRecordDecl::base_class_iterator
5494 BI = CXXRec->bases_begin(),
5495 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5496 if (!BI->isVirtual()) {
5497 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005498 if (base->isEmpty())
5499 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005500 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005501 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5502 std::make_pair(offs, base));
5503 }
5504 }
5505 }
5506
5507 unsigned i = 0;
5508 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5509 FieldEnd = RDecl->field_end();
5510 Field != FieldEnd; ++Field, ++i) {
5511 uint64_t offs = layout.getFieldOffset(i);
5512 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005513 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005514 }
5515
5516 if (CXXRec && includeVBases) {
5517 for (CXXRecordDecl::base_class_iterator
5518 BI = CXXRec->vbases_begin(),
5519 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5520 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005521 if (base->isEmpty())
5522 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005523 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005524 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5525 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5526 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005527 }
5528 }
5529
5530 CharUnits size;
5531 if (CXXRec) {
5532 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5533 } else {
5534 size = layout.getSize();
5535 }
5536
5537 uint64_t CurOffs = 0;
5538 std::multimap<uint64_t, NamedDecl *>::iterator
5539 CurLayObj = FieldOrBaseOffsets.begin();
5540
Douglas Gregor58db7a52012-04-27 22:30:01 +00005541 if (CXXRec && CXXRec->isDynamicClass() &&
5542 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005543 if (FD) {
5544 S += "\"_vptr$";
5545 std::string recname = CXXRec->getNameAsString();
5546 if (recname.empty()) recname = "?";
5547 S += recname;
5548 S += '"';
5549 }
5550 S += "^^?";
5551 CurOffs += getTypeSize(VoidPtrTy);
5552 }
5553
5554 if (!RDecl->hasFlexibleArrayMember()) {
5555 // Mark the end of the structure.
5556 uint64_t offs = toBits(size);
5557 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5558 std::make_pair(offs, (NamedDecl*)0));
5559 }
5560
5561 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5562 assert(CurOffs <= CurLayObj->first);
5563
5564 if (CurOffs < CurLayObj->first) {
5565 uint64_t padding = CurLayObj->first - CurOffs;
5566 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5567 // packing/alignment of members is different that normal, in which case
5568 // the encoding will be out-of-sync with the real layout.
5569 // If the runtime switches to just consider the size of types without
5570 // taking into account alignment, we could make padding explicit in the
5571 // encoding (e.g. using arrays of chars). The encoding strings would be
5572 // longer then though.
5573 CurOffs += padding;
5574 }
5575
5576 NamedDecl *dcl = CurLayObj->second;
5577 if (dcl == 0)
5578 break; // reached end of structure.
5579
5580 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5581 // We expand the bases without their virtual bases since those are going
5582 // in the initial structure. Note that this differs from gcc which
5583 // expands virtual bases each time one is encountered in the hierarchy,
5584 // making the encoding type bigger than it really is.
5585 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005586 assert(!base->isEmpty());
5587 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005588 } else {
5589 FieldDecl *field = cast<FieldDecl>(dcl);
5590 if (FD) {
5591 S += '"';
5592 S += field->getNameAsString();
5593 S += '"';
5594 }
5595
5596 if (field->isBitField()) {
5597 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005598 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005599 } else {
5600 QualType qt = field->getType();
5601 getLegacyIntegralTypeEncoding(qt);
5602 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5603 /*OutermostType*/false,
5604 /*EncodingProperty*/false,
5605 /*StructField*/true);
5606 CurOffs += getTypeSize(field->getType());
5607 }
5608 }
5609 }
5610}
5611
Mike Stump1eb44332009-09-09 15:08:12 +00005612void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005613 std::string& S) const {
5614 if (QT & Decl::OBJC_TQ_In)
5615 S += 'n';
5616 if (QT & Decl::OBJC_TQ_Inout)
5617 S += 'N';
5618 if (QT & Decl::OBJC_TQ_Out)
5619 S += 'o';
5620 if (QT & Decl::OBJC_TQ_Bycopy)
5621 S += 'O';
5622 if (QT & Decl::OBJC_TQ_Byref)
5623 S += 'R';
5624 if (QT & Decl::OBJC_TQ_Oneway)
5625 S += 'V';
5626}
5627
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005628TypedefDecl *ASTContext::getObjCIdDecl() const {
5629 if (!ObjCIdDecl) {
5630 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5631 T = getObjCObjectPointerType(T);
5632 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5633 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5634 getTranslationUnitDecl(),
5635 SourceLocation(), SourceLocation(),
5636 &Idents.get("id"), IdInfo);
5637 }
5638
5639 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005640}
5641
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005642TypedefDecl *ASTContext::getObjCSelDecl() const {
5643 if (!ObjCSelDecl) {
5644 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5645 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5646 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5647 getTranslationUnitDecl(),
5648 SourceLocation(), SourceLocation(),
5649 &Idents.get("SEL"), SelInfo);
5650 }
5651 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005652}
5653
Douglas Gregor79d67262011-08-12 05:59:41 +00005654TypedefDecl *ASTContext::getObjCClassDecl() const {
5655 if (!ObjCClassDecl) {
5656 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5657 T = getObjCObjectPointerType(T);
5658 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5659 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5660 getTranslationUnitDecl(),
5661 SourceLocation(), SourceLocation(),
5662 &Idents.get("Class"), ClassInfo);
5663 }
5664
5665 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005666}
5667
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005668ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5669 if (!ObjCProtocolClassDecl) {
5670 ObjCProtocolClassDecl
5671 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5672 SourceLocation(),
5673 &Idents.get("Protocol"),
5674 /*PrevDecl=*/0,
5675 SourceLocation(), true);
5676 }
5677
5678 return ObjCProtocolClassDecl;
5679}
5680
Meador Ingec5613b22012-06-16 03:34:49 +00005681//===----------------------------------------------------------------------===//
5682// __builtin_va_list Construction Functions
5683//===----------------------------------------------------------------------===//
5684
5685static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5686 // typedef char* __builtin_va_list;
5687 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5688 TypeSourceInfo *TInfo
5689 = Context->getTrivialTypeSourceInfo(CharPtrType);
5690
5691 TypedefDecl *VaListTypeDecl
5692 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5693 Context->getTranslationUnitDecl(),
5694 SourceLocation(), SourceLocation(),
5695 &Context->Idents.get("__builtin_va_list"),
5696 TInfo);
5697 return VaListTypeDecl;
5698}
5699
5700static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5701 // typedef void* __builtin_va_list;
5702 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5703 TypeSourceInfo *TInfo
5704 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5705
5706 TypedefDecl *VaListTypeDecl
5707 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5708 Context->getTranslationUnitDecl(),
5709 SourceLocation(), SourceLocation(),
5710 &Context->Idents.get("__builtin_va_list"),
5711 TInfo);
5712 return VaListTypeDecl;
5713}
5714
Tim Northoverc264e162013-01-31 12:13:10 +00005715static TypedefDecl *
5716CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5717 RecordDecl *VaListTagDecl;
5718 if (Context->getLangOpts().CPlusPlus) {
5719 // namespace std { struct __va_list {
5720 NamespaceDecl *NS;
5721 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5722 Context->getTranslationUnitDecl(),
5723 /*Inline*/false, SourceLocation(),
5724 SourceLocation(), &Context->Idents.get("std"),
5725 /*PrevDecl*/0);
5726
5727 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5728 Context->getTranslationUnitDecl(),
5729 SourceLocation(), SourceLocation(),
5730 &Context->Idents.get("__va_list"));
5731 VaListTagDecl->setDeclContext(NS);
5732 } else {
5733 // struct __va_list
5734 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5735 Context->getTranslationUnitDecl(),
5736 &Context->Idents.get("__va_list"));
5737 }
5738
5739 VaListTagDecl->startDefinition();
5740
5741 const size_t NumFields = 5;
5742 QualType FieldTypes[NumFields];
5743 const char *FieldNames[NumFields];
5744
5745 // void *__stack;
5746 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5747 FieldNames[0] = "__stack";
5748
5749 // void *__gr_top;
5750 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5751 FieldNames[1] = "__gr_top";
5752
5753 // void *__vr_top;
5754 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5755 FieldNames[2] = "__vr_top";
5756
5757 // int __gr_offs;
5758 FieldTypes[3] = Context->IntTy;
5759 FieldNames[3] = "__gr_offs";
5760
5761 // int __vr_offs;
5762 FieldTypes[4] = Context->IntTy;
5763 FieldNames[4] = "__vr_offs";
5764
5765 // Create fields
5766 for (unsigned i = 0; i < NumFields; ++i) {
5767 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5768 VaListTagDecl,
5769 SourceLocation(),
5770 SourceLocation(),
5771 &Context->Idents.get(FieldNames[i]),
5772 FieldTypes[i], /*TInfo=*/0,
5773 /*BitWidth=*/0,
5774 /*Mutable=*/false,
5775 ICIS_NoInit);
5776 Field->setAccess(AS_public);
5777 VaListTagDecl->addDecl(Field);
5778 }
5779 VaListTagDecl->completeDefinition();
5780 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5781 Context->VaListTagTy = VaListTagType;
5782
5783 // } __builtin_va_list;
5784 TypedefDecl *VaListTypedefDecl
5785 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5786 Context->getTranslationUnitDecl(),
5787 SourceLocation(), SourceLocation(),
5788 &Context->Idents.get("__builtin_va_list"),
5789 Context->getTrivialTypeSourceInfo(VaListTagType));
5790
5791 return VaListTypedefDecl;
5792}
5793
Meador Ingec5613b22012-06-16 03:34:49 +00005794static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5795 // typedef struct __va_list_tag {
5796 RecordDecl *VaListTagDecl;
5797
5798 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5799 Context->getTranslationUnitDecl(),
5800 &Context->Idents.get("__va_list_tag"));
5801 VaListTagDecl->startDefinition();
5802
5803 const size_t NumFields = 5;
5804 QualType FieldTypes[NumFields];
5805 const char *FieldNames[NumFields];
5806
5807 // unsigned char gpr;
5808 FieldTypes[0] = Context->UnsignedCharTy;
5809 FieldNames[0] = "gpr";
5810
5811 // unsigned char fpr;
5812 FieldTypes[1] = Context->UnsignedCharTy;
5813 FieldNames[1] = "fpr";
5814
5815 // unsigned short reserved;
5816 FieldTypes[2] = Context->UnsignedShortTy;
5817 FieldNames[2] = "reserved";
5818
5819 // void* overflow_arg_area;
5820 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5821 FieldNames[3] = "overflow_arg_area";
5822
5823 // void* reg_save_area;
5824 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5825 FieldNames[4] = "reg_save_area";
5826
5827 // Create fields
5828 for (unsigned i = 0; i < NumFields; ++i) {
5829 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5830 SourceLocation(),
5831 SourceLocation(),
5832 &Context->Idents.get(FieldNames[i]),
5833 FieldTypes[i], /*TInfo=*/0,
5834 /*BitWidth=*/0,
5835 /*Mutable=*/false,
5836 ICIS_NoInit);
5837 Field->setAccess(AS_public);
5838 VaListTagDecl->addDecl(Field);
5839 }
5840 VaListTagDecl->completeDefinition();
5841 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005842 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005843
5844 // } __va_list_tag;
5845 TypedefDecl *VaListTagTypedefDecl
5846 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5847 Context->getTranslationUnitDecl(),
5848 SourceLocation(), SourceLocation(),
5849 &Context->Idents.get("__va_list_tag"),
5850 Context->getTrivialTypeSourceInfo(VaListTagType));
5851 QualType VaListTagTypedefType =
5852 Context->getTypedefType(VaListTagTypedefDecl);
5853
5854 // typedef __va_list_tag __builtin_va_list[1];
5855 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5856 QualType VaListTagArrayType
5857 = Context->getConstantArrayType(VaListTagTypedefType,
5858 Size, ArrayType::Normal, 0);
5859 TypeSourceInfo *TInfo
5860 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5861 TypedefDecl *VaListTypedefDecl
5862 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5863 Context->getTranslationUnitDecl(),
5864 SourceLocation(), SourceLocation(),
5865 &Context->Idents.get("__builtin_va_list"),
5866 TInfo);
5867
5868 return VaListTypedefDecl;
5869}
5870
5871static TypedefDecl *
5872CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5873 // typedef struct __va_list_tag {
5874 RecordDecl *VaListTagDecl;
5875 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5876 Context->getTranslationUnitDecl(),
5877 &Context->Idents.get("__va_list_tag"));
5878 VaListTagDecl->startDefinition();
5879
5880 const size_t NumFields = 4;
5881 QualType FieldTypes[NumFields];
5882 const char *FieldNames[NumFields];
5883
5884 // unsigned gp_offset;
5885 FieldTypes[0] = Context->UnsignedIntTy;
5886 FieldNames[0] = "gp_offset";
5887
5888 // unsigned fp_offset;
5889 FieldTypes[1] = Context->UnsignedIntTy;
5890 FieldNames[1] = "fp_offset";
5891
5892 // void* overflow_arg_area;
5893 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5894 FieldNames[2] = "overflow_arg_area";
5895
5896 // void* reg_save_area;
5897 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5898 FieldNames[3] = "reg_save_area";
5899
5900 // Create fields
5901 for (unsigned i = 0; i < NumFields; ++i) {
5902 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5903 VaListTagDecl,
5904 SourceLocation(),
5905 SourceLocation(),
5906 &Context->Idents.get(FieldNames[i]),
5907 FieldTypes[i], /*TInfo=*/0,
5908 /*BitWidth=*/0,
5909 /*Mutable=*/false,
5910 ICIS_NoInit);
5911 Field->setAccess(AS_public);
5912 VaListTagDecl->addDecl(Field);
5913 }
5914 VaListTagDecl->completeDefinition();
5915 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005916 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005917
5918 // } __va_list_tag;
5919 TypedefDecl *VaListTagTypedefDecl
5920 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5921 Context->getTranslationUnitDecl(),
5922 SourceLocation(), SourceLocation(),
5923 &Context->Idents.get("__va_list_tag"),
5924 Context->getTrivialTypeSourceInfo(VaListTagType));
5925 QualType VaListTagTypedefType =
5926 Context->getTypedefType(VaListTagTypedefDecl);
5927
5928 // typedef __va_list_tag __builtin_va_list[1];
5929 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5930 QualType VaListTagArrayType
5931 = Context->getConstantArrayType(VaListTagTypedefType,
5932 Size, ArrayType::Normal,0);
5933 TypeSourceInfo *TInfo
5934 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5935 TypedefDecl *VaListTypedefDecl
5936 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5937 Context->getTranslationUnitDecl(),
5938 SourceLocation(), SourceLocation(),
5939 &Context->Idents.get("__builtin_va_list"),
5940 TInfo);
5941
5942 return VaListTypedefDecl;
5943}
5944
5945static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5946 // typedef int __builtin_va_list[4];
5947 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5948 QualType IntArrayType
5949 = Context->getConstantArrayType(Context->IntTy,
5950 Size, ArrayType::Normal, 0);
5951 TypedefDecl *VaListTypedefDecl
5952 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5953 Context->getTranslationUnitDecl(),
5954 SourceLocation(), SourceLocation(),
5955 &Context->Idents.get("__builtin_va_list"),
5956 Context->getTrivialTypeSourceInfo(IntArrayType));
5957
5958 return VaListTypedefDecl;
5959}
5960
Logan Chieneae5a8202012-10-10 06:56:20 +00005961static TypedefDecl *
5962CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5963 RecordDecl *VaListDecl;
5964 if (Context->getLangOpts().CPlusPlus) {
5965 // namespace std { struct __va_list {
5966 NamespaceDecl *NS;
5967 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5968 Context->getTranslationUnitDecl(),
5969 /*Inline*/false, SourceLocation(),
5970 SourceLocation(), &Context->Idents.get("std"),
5971 /*PrevDecl*/0);
5972
5973 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5974 Context->getTranslationUnitDecl(),
5975 SourceLocation(), SourceLocation(),
5976 &Context->Idents.get("__va_list"));
5977
5978 VaListDecl->setDeclContext(NS);
5979
5980 } else {
5981 // struct __va_list {
5982 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5983 Context->getTranslationUnitDecl(),
5984 &Context->Idents.get("__va_list"));
5985 }
5986
5987 VaListDecl->startDefinition();
5988
5989 // void * __ap;
5990 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5991 VaListDecl,
5992 SourceLocation(),
5993 SourceLocation(),
5994 &Context->Idents.get("__ap"),
5995 Context->getPointerType(Context->VoidTy),
5996 /*TInfo=*/0,
5997 /*BitWidth=*/0,
5998 /*Mutable=*/false,
5999 ICIS_NoInit);
6000 Field->setAccess(AS_public);
6001 VaListDecl->addDecl(Field);
6002
6003 // };
6004 VaListDecl->completeDefinition();
6005
6006 // typedef struct __va_list __builtin_va_list;
6007 TypeSourceInfo *TInfo
6008 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6009
6010 TypedefDecl *VaListTypeDecl
6011 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6012 Context->getTranslationUnitDecl(),
6013 SourceLocation(), SourceLocation(),
6014 &Context->Idents.get("__builtin_va_list"),
6015 TInfo);
6016
6017 return VaListTypeDecl;
6018}
6019
Ulrich Weigandb8409212013-05-06 16:26:41 +00006020static TypedefDecl *
6021CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6022 // typedef struct __va_list_tag {
6023 RecordDecl *VaListTagDecl;
6024 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6025 Context->getTranslationUnitDecl(),
6026 &Context->Idents.get("__va_list_tag"));
6027 VaListTagDecl->startDefinition();
6028
6029 const size_t NumFields = 4;
6030 QualType FieldTypes[NumFields];
6031 const char *FieldNames[NumFields];
6032
6033 // long __gpr;
6034 FieldTypes[0] = Context->LongTy;
6035 FieldNames[0] = "__gpr";
6036
6037 // long __fpr;
6038 FieldTypes[1] = Context->LongTy;
6039 FieldNames[1] = "__fpr";
6040
6041 // void *__overflow_arg_area;
6042 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6043 FieldNames[2] = "__overflow_arg_area";
6044
6045 // void *__reg_save_area;
6046 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6047 FieldNames[3] = "__reg_save_area";
6048
6049 // Create fields
6050 for (unsigned i = 0; i < NumFields; ++i) {
6051 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6052 VaListTagDecl,
6053 SourceLocation(),
6054 SourceLocation(),
6055 &Context->Idents.get(FieldNames[i]),
6056 FieldTypes[i], /*TInfo=*/0,
6057 /*BitWidth=*/0,
6058 /*Mutable=*/false,
6059 ICIS_NoInit);
6060 Field->setAccess(AS_public);
6061 VaListTagDecl->addDecl(Field);
6062 }
6063 VaListTagDecl->completeDefinition();
6064 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6065 Context->VaListTagTy = VaListTagType;
6066
6067 // } __va_list_tag;
6068 TypedefDecl *VaListTagTypedefDecl
6069 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6070 Context->getTranslationUnitDecl(),
6071 SourceLocation(), SourceLocation(),
6072 &Context->Idents.get("__va_list_tag"),
6073 Context->getTrivialTypeSourceInfo(VaListTagType));
6074 QualType VaListTagTypedefType =
6075 Context->getTypedefType(VaListTagTypedefDecl);
6076
6077 // typedef __va_list_tag __builtin_va_list[1];
6078 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6079 QualType VaListTagArrayType
6080 = Context->getConstantArrayType(VaListTagTypedefType,
6081 Size, ArrayType::Normal,0);
6082 TypeSourceInfo *TInfo
6083 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6084 TypedefDecl *VaListTypedefDecl
6085 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6086 Context->getTranslationUnitDecl(),
6087 SourceLocation(), SourceLocation(),
6088 &Context->Idents.get("__builtin_va_list"),
6089 TInfo);
6090
6091 return VaListTypedefDecl;
6092}
6093
Meador Ingec5613b22012-06-16 03:34:49 +00006094static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6095 TargetInfo::BuiltinVaListKind Kind) {
6096 switch (Kind) {
6097 case TargetInfo::CharPtrBuiltinVaList:
6098 return CreateCharPtrBuiltinVaListDecl(Context);
6099 case TargetInfo::VoidPtrBuiltinVaList:
6100 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006101 case TargetInfo::AArch64ABIBuiltinVaList:
6102 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006103 case TargetInfo::PowerABIBuiltinVaList:
6104 return CreatePowerABIBuiltinVaListDecl(Context);
6105 case TargetInfo::X86_64ABIBuiltinVaList:
6106 return CreateX86_64ABIBuiltinVaListDecl(Context);
6107 case TargetInfo::PNaClABIBuiltinVaList:
6108 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006109 case TargetInfo::AAPCSABIBuiltinVaList:
6110 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006111 case TargetInfo::SystemZBuiltinVaList:
6112 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006113 }
6114
6115 llvm_unreachable("Unhandled __builtin_va_list type kind");
6116}
6117
6118TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6119 if (!BuiltinVaListDecl)
6120 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6121
6122 return BuiltinVaListDecl;
6123}
6124
Meador Ingefb40e3f2012-07-01 15:57:25 +00006125QualType ASTContext::getVaListTagType() const {
6126 // Force the creation of VaListTagTy by building the __builtin_va_list
6127 // declaration.
6128 if (VaListTagTy.isNull())
6129 (void) getBuiltinVaListDecl();
6130
6131 return VaListTagTy;
6132}
6133
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006134void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006135 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006136 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006137
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006138 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006139}
6140
John McCall0bd6feb2009-12-02 08:04:21 +00006141/// \brief Retrieve the template name that corresponds to a non-empty
6142/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006143TemplateName
6144ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6145 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006146 unsigned size = End - Begin;
6147 assert(size > 1 && "set is not overloaded!");
6148
6149 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6150 size * sizeof(FunctionTemplateDecl*));
6151 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6152
6153 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006154 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006155 NamedDecl *D = *I;
6156 assert(isa<FunctionTemplateDecl>(D) ||
6157 (isa<UsingShadowDecl>(D) &&
6158 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6159 *Storage++ = D;
6160 }
6161
6162 return TemplateName(OT);
6163}
6164
Douglas Gregor7532dc62009-03-30 22:58:21 +00006165/// \brief Retrieve the template name that represents a qualified
6166/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006167TemplateName
6168ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6169 bool TemplateKeyword,
6170 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006171 assert(NNS && "Missing nested-name-specifier in qualified template name");
6172
Douglas Gregor789b1f62010-02-04 18:10:26 +00006173 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006174 llvm::FoldingSetNodeID ID;
6175 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6176
6177 void *InsertPos = 0;
6178 QualifiedTemplateName *QTN =
6179 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6180 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006181 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6182 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006183 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6184 }
6185
6186 return TemplateName(QTN);
6187}
6188
6189/// \brief Retrieve the template name that represents a dependent
6190/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006191TemplateName
6192ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6193 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006194 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006195 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006196
6197 llvm::FoldingSetNodeID ID;
6198 DependentTemplateName::Profile(ID, NNS, Name);
6199
6200 void *InsertPos = 0;
6201 DependentTemplateName *QTN =
6202 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6203
6204 if (QTN)
6205 return TemplateName(QTN);
6206
6207 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6208 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006209 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6210 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006211 } else {
6212 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006213 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6214 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006215 DependentTemplateName *CheckQTN =
6216 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6217 assert(!CheckQTN && "Dependent type name canonicalization broken");
6218 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006219 }
6220
6221 DependentTemplateNames.InsertNode(QTN, InsertPos);
6222 return TemplateName(QTN);
6223}
6224
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006225/// \brief Retrieve the template name that represents a dependent
6226/// template name such as \c MetaFun::template operator+.
6227TemplateName
6228ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006229 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006230 assert((!NNS || NNS->isDependent()) &&
6231 "Nested name specifier must be dependent");
6232
6233 llvm::FoldingSetNodeID ID;
6234 DependentTemplateName::Profile(ID, NNS, Operator);
6235
6236 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006237 DependentTemplateName *QTN
6238 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006239
6240 if (QTN)
6241 return TemplateName(QTN);
6242
6243 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6244 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006245 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6246 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006247 } else {
6248 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006249 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6250 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006251
6252 DependentTemplateName *CheckQTN
6253 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6254 assert(!CheckQTN && "Dependent template name canonicalization broken");
6255 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006256 }
6257
6258 DependentTemplateNames.InsertNode(QTN, InsertPos);
6259 return TemplateName(QTN);
6260}
6261
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006262TemplateName
John McCall14606042011-06-30 08:33:18 +00006263ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6264 TemplateName replacement) const {
6265 llvm::FoldingSetNodeID ID;
6266 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6267
6268 void *insertPos = 0;
6269 SubstTemplateTemplateParmStorage *subst
6270 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6271
6272 if (!subst) {
6273 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6274 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6275 }
6276
6277 return TemplateName(subst);
6278}
6279
6280TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006281ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6282 const TemplateArgument &ArgPack) const {
6283 ASTContext &Self = const_cast<ASTContext &>(*this);
6284 llvm::FoldingSetNodeID ID;
6285 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6286
6287 void *InsertPos = 0;
6288 SubstTemplateTemplateParmPackStorage *Subst
6289 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6290
6291 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006292 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006293 ArgPack.pack_size(),
6294 ArgPack.pack_begin());
6295 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6296 }
6297
6298 return TemplateName(Subst);
6299}
6300
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006301/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006302/// TargetInfo, produce the corresponding type. The unsigned @p Type
6303/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006304CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006305 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006306 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006307 case TargetInfo::SignedShort: return ShortTy;
6308 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6309 case TargetInfo::SignedInt: return IntTy;
6310 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6311 case TargetInfo::SignedLong: return LongTy;
6312 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6313 case TargetInfo::SignedLongLong: return LongLongTy;
6314 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6315 }
6316
David Blaikieb219cfc2011-09-23 05:06:16 +00006317 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006318}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006319
6320//===----------------------------------------------------------------------===//
6321// Type Predicates.
6322//===----------------------------------------------------------------------===//
6323
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006324/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6325/// garbage collection attribute.
6326///
John McCallae278a32011-01-12 00:34:59 +00006327Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006328 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006329 return Qualifiers::GCNone;
6330
David Blaikie4e4d0842012-03-11 07:00:24 +00006331 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006332 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6333
6334 // Default behaviour under objective-C's gc is for ObjC pointers
6335 // (or pointers to them) be treated as though they were declared
6336 // as __strong.
6337 if (GCAttrs == Qualifiers::GCNone) {
6338 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6339 return Qualifiers::Strong;
6340 else if (Ty->isPointerType())
6341 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6342 } else {
6343 // It's not valid to set GC attributes on anything that isn't a
6344 // pointer.
6345#ifndef NDEBUG
6346 QualType CT = Ty->getCanonicalTypeInternal();
6347 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6348 CT = AT->getElementType();
6349 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6350#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006351 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006352 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006353}
6354
Chris Lattner6ac46a42008-04-07 06:51:04 +00006355//===----------------------------------------------------------------------===//
6356// Type Compatibility Testing
6357//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006358
Mike Stump1eb44332009-09-09 15:08:12 +00006359/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006360/// compatible.
6361static bool areCompatVectorTypes(const VectorType *LHS,
6362 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006363 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006364 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006365 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006366}
6367
Douglas Gregor255210e2010-08-06 10:14:59 +00006368bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6369 QualType SecondVec) {
6370 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6371 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6372
6373 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6374 return true;
6375
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006376 // Treat Neon vector types and most AltiVec vector types as if they are the
6377 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006378 const VectorType *First = FirstVec->getAs<VectorType>();
6379 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006380 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006381 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006382 First->getVectorKind() != VectorType::AltiVecPixel &&
6383 First->getVectorKind() != VectorType::AltiVecBool &&
6384 Second->getVectorKind() != VectorType::AltiVecPixel &&
6385 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006386 return true;
6387
6388 return false;
6389}
6390
Steve Naroff4084c302009-07-23 01:01:38 +00006391//===----------------------------------------------------------------------===//
6392// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6393//===----------------------------------------------------------------------===//
6394
6395/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6396/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006397bool
6398ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6399 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006400 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006401 return true;
6402 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6403 E = rProto->protocol_end(); PI != E; ++PI)
6404 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6405 return true;
6406 return false;
6407}
6408
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006409/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006410/// return true if lhs's protocols conform to rhs's protocol; false
6411/// otherwise.
6412bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6413 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6414 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6415 return false;
6416}
6417
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006418/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6419/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006420bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6421 QualType rhs) {
6422 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6423 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6424 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6425
6426 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6427 E = lhsQID->qual_end(); I != E; ++I) {
6428 bool match = false;
6429 ObjCProtocolDecl *lhsProto = *I;
6430 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6431 E = rhsOPT->qual_end(); J != E; ++J) {
6432 ObjCProtocolDecl *rhsProto = *J;
6433 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6434 match = true;
6435 break;
6436 }
6437 }
6438 if (!match)
6439 return false;
6440 }
6441 return true;
6442}
6443
Steve Naroff4084c302009-07-23 01:01:38 +00006444/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6445/// ObjCQualifiedIDType.
6446bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6447 bool compare) {
6448 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006449 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006450 lhs->isObjCIdType() || lhs->isObjCClassType())
6451 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006452 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006453 rhs->isObjCIdType() || rhs->isObjCClassType())
6454 return true;
6455
6456 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006457 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006458
Steve Naroff4084c302009-07-23 01:01:38 +00006459 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006460
Steve Naroff4084c302009-07-23 01:01:38 +00006461 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006462 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006463 // make sure we check the class hierarchy.
6464 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6465 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6466 E = lhsQID->qual_end(); I != E; ++I) {
6467 // when comparing an id<P> on lhs with a static type on rhs,
6468 // see if static class implements all of id's protocols, directly or
6469 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006470 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006471 return false;
6472 }
6473 }
6474 // If there are no qualifiers and no interface, we have an 'id'.
6475 return true;
6476 }
Mike Stump1eb44332009-09-09 15:08:12 +00006477 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006478 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6479 E = lhsQID->qual_end(); I != E; ++I) {
6480 ObjCProtocolDecl *lhsProto = *I;
6481 bool match = false;
6482
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.
6486 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6487 E = rhsOPT->qual_end(); J != E; ++J) {
6488 ObjCProtocolDecl *rhsProto = *J;
6489 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6490 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6491 match = true;
6492 break;
6493 }
6494 }
Mike Stump1eb44332009-09-09 15:08:12 +00006495 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006496 // make sure we check the class hierarchy.
6497 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6498 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6499 E = lhsQID->qual_end(); I != E; ++I) {
6500 // when comparing an id<P> on lhs with a static type on rhs,
6501 // see if static class implements all of id's protocols, directly or
6502 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006503 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006504 match = true;
6505 break;
6506 }
6507 }
6508 }
6509 if (!match)
6510 return false;
6511 }
Mike Stump1eb44332009-09-09 15:08:12 +00006512
Steve Naroff4084c302009-07-23 01:01:38 +00006513 return true;
6514 }
Mike Stump1eb44332009-09-09 15:08:12 +00006515
Steve Naroff4084c302009-07-23 01:01:38 +00006516 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6517 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6518
Mike Stump1eb44332009-09-09 15:08:12 +00006519 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006520 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006521 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006522 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6523 E = lhsOPT->qual_end(); I != E; ++I) {
6524 ObjCProtocolDecl *lhsProto = *I;
6525 bool match = false;
6526
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006527 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006528 // see if static class implements all of id's protocols, directly or
6529 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006530 // First, lhs protocols in the qualifier list must be found, direct
6531 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006532 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6533 E = rhsQID->qual_end(); J != E; ++J) {
6534 ObjCProtocolDecl *rhsProto = *J;
6535 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6536 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6537 match = true;
6538 break;
6539 }
6540 }
6541 if (!match)
6542 return false;
6543 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006544
6545 // Static class's protocols, or its super class or category protocols
6546 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6547 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6548 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6549 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6550 // This is rather dubious but matches gcc's behavior. If lhs has
6551 // no type qualifier and its class has no static protocol(s)
6552 // assume that it is mismatch.
6553 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6554 return false;
6555 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6556 LHSInheritedProtocols.begin(),
6557 E = LHSInheritedProtocols.end(); I != E; ++I) {
6558 bool match = false;
6559 ObjCProtocolDecl *lhsProto = (*I);
6560 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6561 E = rhsQID->qual_end(); J != E; ++J) {
6562 ObjCProtocolDecl *rhsProto = *J;
6563 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6564 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6565 match = true;
6566 break;
6567 }
6568 }
6569 if (!match)
6570 return false;
6571 }
6572 }
Steve Naroff4084c302009-07-23 01:01:38 +00006573 return true;
6574 }
6575 return false;
6576}
6577
Eli Friedman3d815e72008-08-22 00:56:42 +00006578/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006579/// compatible for assignment from RHS to LHS. This handles validation of any
6580/// protocol qualifiers on the LHS or RHS.
6581///
Steve Naroff14108da2009-07-10 23:34:53 +00006582bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6583 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006584 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6585 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6586
Steve Naroffde2e22d2009-07-15 18:40:39 +00006587 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006588 if (LHS->isObjCUnqualifiedIdOrClass() ||
6589 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006590 return true;
6591
John McCallc12c5bb2010-05-15 11:32:37 +00006592 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006593 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6594 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006595 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006596
6597 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6598 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6599 QualType(RHSOPT,0));
6600
John McCallc12c5bb2010-05-15 11:32:37 +00006601 // If we have 2 user-defined types, fall into that path.
6602 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006603 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006604
Steve Naroff4084c302009-07-23 01:01:38 +00006605 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006606}
6607
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006608/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006609/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006610/// arguments in block literals. When passed as arguments, passing 'A*' where
6611/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6612/// not OK. For the return type, the opposite is not OK.
6613bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6614 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006615 const ObjCObjectPointerType *RHSOPT,
6616 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006617 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006618 return true;
6619
6620 if (LHSOPT->isObjCBuiltinType()) {
6621 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6622 }
6623
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006624 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006625 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6626 QualType(RHSOPT,0),
6627 false);
6628
6629 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6630 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6631 if (LHS && RHS) { // We have 2 user-defined types.
6632 if (LHS != RHS) {
6633 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006634 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006635 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006636 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006637 }
6638 else
6639 return true;
6640 }
6641 return false;
6642}
6643
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006644/// getIntersectionOfProtocols - This routine finds the intersection of set
6645/// of protocols inherited from two distinct objective-c pointer objects.
6646/// It is used to build composite qualifier list of the composite type of
6647/// the conditional expression involving two objective-c pointer objects.
6648static
6649void getIntersectionOfProtocols(ASTContext &Context,
6650 const ObjCObjectPointerType *LHSOPT,
6651 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006652 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006653
John McCallc12c5bb2010-05-15 11:32:37 +00006654 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6655 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6656 assert(LHS->getInterface() && "LHS must have an interface base");
6657 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006658
6659 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6660 unsigned LHSNumProtocols = LHS->getNumProtocols();
6661 if (LHSNumProtocols > 0)
6662 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6663 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006665 Context.CollectInheritedProtocols(LHS->getInterface(),
6666 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006667 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6668 LHSInheritedProtocols.end());
6669 }
6670
6671 unsigned RHSNumProtocols = RHS->getNumProtocols();
6672 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006673 ObjCProtocolDecl **RHSProtocols =
6674 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006675 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6676 if (InheritedProtocolSet.count(RHSProtocols[i]))
6677 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006678 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006679 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006680 Context.CollectInheritedProtocols(RHS->getInterface(),
6681 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006682 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6683 RHSInheritedProtocols.begin(),
6684 E = RHSInheritedProtocols.end(); I != E; ++I)
6685 if (InheritedProtocolSet.count((*I)))
6686 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006687 }
6688}
6689
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006690/// areCommonBaseCompatible - Returns common base class of the two classes if
6691/// one found. Note that this is O'2 algorithm. But it will be called as the
6692/// last type comparison in a ?-exp of ObjC pointer types before a
6693/// warning is issued. So, its invokation is extremely rare.
6694QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006695 const ObjCObjectPointerType *Lptr,
6696 const ObjCObjectPointerType *Rptr) {
6697 const ObjCObjectType *LHS = Lptr->getObjectType();
6698 const ObjCObjectType *RHS = Rptr->getObjectType();
6699 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6700 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006701 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006702 return QualType();
6703
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006704 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006705 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006706 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006707 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006708 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6709
6710 QualType Result = QualType(LHS, 0);
6711 if (!Protocols.empty())
6712 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6713 Result = getObjCObjectPointerType(Result);
6714 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006715 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006716 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006717
6718 return QualType();
6719}
6720
John McCallc12c5bb2010-05-15 11:32:37 +00006721bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6722 const ObjCObjectType *RHS) {
6723 assert(LHS->getInterface() && "LHS is not an interface type");
6724 assert(RHS->getInterface() && "RHS is not an interface type");
6725
Chris Lattner6ac46a42008-04-07 06:51:04 +00006726 // Verify that the base decls are compatible: the RHS must be a subclass of
6727 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006728 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006729 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006730
Chris Lattner6ac46a42008-04-07 06:51:04 +00006731 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6732 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006733 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006734 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006735
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006736 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6737 // more detailed analysis is required.
6738 if (RHS->getNumProtocols() == 0) {
6739 // OK, if LHS is a superclass of RHS *and*
6740 // this superclass is assignment compatible with LHS.
6741 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006742 bool IsSuperClass =
6743 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6744 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006745 // OK if conversion of LHS to SuperClass results in narrowing of types
6746 // ; i.e., SuperClass may implement at least one of the protocols
6747 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6748 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6749 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006750 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006751 // If super class has no protocols, it is not a match.
6752 if (SuperClassInheritedProtocols.empty())
6753 return false;
6754
6755 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6756 LHSPE = LHS->qual_end();
6757 LHSPI != LHSPE; LHSPI++) {
6758 bool SuperImplementsProtocol = false;
6759 ObjCProtocolDecl *LHSProto = (*LHSPI);
6760
6761 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6762 SuperClassInheritedProtocols.begin(),
6763 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6764 ObjCProtocolDecl *SuperClassProto = (*I);
6765 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6766 SuperImplementsProtocol = true;
6767 break;
6768 }
6769 }
6770 if (!SuperImplementsProtocol)
6771 return false;
6772 }
6773 return true;
6774 }
6775 return false;
6776 }
Mike Stump1eb44332009-09-09 15:08:12 +00006777
John McCallc12c5bb2010-05-15 11:32:37 +00006778 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6779 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006780 LHSPI != LHSPE; LHSPI++) {
6781 bool RHSImplementsProtocol = false;
6782
6783 // If the RHS doesn't implement the protocol on the left, the types
6784 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006785 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6786 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006787 RHSPI != RHSPE; RHSPI++) {
6788 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006789 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006790 break;
6791 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006792 }
6793 // FIXME: For better diagnostics, consider passing back the protocol name.
6794 if (!RHSImplementsProtocol)
6795 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006796 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006797 // The RHS implements all protocols listed on the LHS.
6798 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006799}
6800
Steve Naroff389bf462009-02-12 17:52:19 +00006801bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6802 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006803 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6804 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006805
Steve Naroff14108da2009-07-10 23:34:53 +00006806 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006807 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006808
6809 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6810 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006811}
6812
Douglas Gregor569c3162010-08-07 11:51:51 +00006813bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6814 return canAssignObjCInterfaces(
6815 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6816 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6817}
6818
Mike Stump1eb44332009-09-09 15:08:12 +00006819/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006820/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006821/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006822/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006823bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6824 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006825 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006826 return hasSameType(LHS, RHS);
6827
Douglas Gregor447234d2010-07-29 15:18:02 +00006828 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006829}
6830
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006831bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006832 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006833}
6834
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006835bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6836 return !mergeTypes(LHS, RHS, true).isNull();
6837}
6838
Peter Collingbourne48466752010-10-24 18:30:18 +00006839/// mergeTransparentUnionType - if T is a transparent union type and a member
6840/// of T is compatible with SubType, return the merged type, else return
6841/// QualType()
6842QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6843 bool OfBlockPointer,
6844 bool Unqualified) {
6845 if (const RecordType *UT = T->getAsUnionType()) {
6846 RecordDecl *UD = UT->getDecl();
6847 if (UD->hasAttr<TransparentUnionAttr>()) {
6848 for (RecordDecl::field_iterator it = UD->field_begin(),
6849 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006850 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006851 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6852 if (!MT.isNull())
6853 return MT;
6854 }
6855 }
6856 }
6857
6858 return QualType();
6859}
6860
6861/// mergeFunctionArgumentTypes - merge two types which appear as function
6862/// argument types
6863QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6864 bool OfBlockPointer,
6865 bool Unqualified) {
6866 // GNU extension: two types are compatible if they appear as a function
6867 // argument, one of the types is a transparent union type and the other
6868 // type is compatible with a union member
6869 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6870 Unqualified);
6871 if (!lmerge.isNull())
6872 return lmerge;
6873
6874 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6875 Unqualified);
6876 if (!rmerge.isNull())
6877 return rmerge;
6878
6879 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6880}
6881
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006882QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006883 bool OfBlockPointer,
6884 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006885 const FunctionType *lbase = lhs->getAs<FunctionType>();
6886 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006887 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6888 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006889 bool allLTypes = true;
6890 bool allRTypes = true;
6891
6892 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006893 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006894 if (OfBlockPointer) {
6895 QualType RHS = rbase->getResultType();
6896 QualType LHS = lbase->getResultType();
6897 bool UnqualifiedResult = Unqualified;
6898 if (!UnqualifiedResult)
6899 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006900 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006901 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006902 else
John McCall8cc246c2010-12-15 01:06:38 +00006903 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6904 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006905 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006906
6907 if (Unqualified)
6908 retType = retType.getUnqualifiedType();
6909
6910 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6911 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6912 if (Unqualified) {
6913 LRetType = LRetType.getUnqualifiedType();
6914 RRetType = RRetType.getUnqualifiedType();
6915 }
6916
6917 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006918 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006919 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006920 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006921
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006922 // FIXME: double check this
6923 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6924 // rbase->getRegParmAttr() != 0 &&
6925 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006926 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6927 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006928
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006929 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006930 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006931 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006932
John McCall8cc246c2010-12-15 01:06:38 +00006933 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006934 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6935 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006936 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6937 return QualType();
6938
John McCallf85e1932011-06-15 23:02:42 +00006939 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6940 return QualType();
6941
John McCall8cc246c2010-12-15 01:06:38 +00006942 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6943 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006944
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006945 if (lbaseInfo.getNoReturn() != NoReturn)
6946 allLTypes = false;
6947 if (rbaseInfo.getNoReturn() != NoReturn)
6948 allRTypes = false;
6949
John McCallf85e1932011-06-15 23:02:42 +00006950 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006951
Eli Friedman3d815e72008-08-22 00:56:42 +00006952 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006953 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6954 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006955 unsigned lproto_nargs = lproto->getNumArgs();
6956 unsigned rproto_nargs = rproto->getNumArgs();
6957
6958 // Compatible functions must have the same number of arguments
6959 if (lproto_nargs != rproto_nargs)
6960 return QualType();
6961
6962 // Variadic and non-variadic functions aren't compatible
6963 if (lproto->isVariadic() != rproto->isVariadic())
6964 return QualType();
6965
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006966 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6967 return QualType();
6968
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006969 if (LangOpts.ObjCAutoRefCount &&
6970 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6971 return QualType();
6972
Eli Friedman3d815e72008-08-22 00:56:42 +00006973 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006974 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006975 for (unsigned i = 0; i < lproto_nargs; i++) {
6976 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6977 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006978 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6979 OfBlockPointer,
6980 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006981 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006982
6983 if (Unqualified)
6984 argtype = argtype.getUnqualifiedType();
6985
Eli Friedman3d815e72008-08-22 00:56:42 +00006986 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006987 if (Unqualified) {
6988 largtype = largtype.getUnqualifiedType();
6989 rargtype = rargtype.getUnqualifiedType();
6990 }
6991
Chris Lattner61710852008-10-05 17:34:18 +00006992 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6993 allLTypes = false;
6994 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6995 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006996 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006997
Eli Friedman3d815e72008-08-22 00:56:42 +00006998 if (allLTypes) return lhs;
6999 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007000
7001 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7002 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007003 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007004 }
7005
7006 if (lproto) allRTypes = false;
7007 if (rproto) allLTypes = false;
7008
Douglas Gregor72564e72009-02-26 23:50:07 +00007009 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007010 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007011 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007012 if (proto->isVariadic()) return QualType();
7013 // Check that the types are compatible with the types that
7014 // would result from default argument promotions (C99 6.7.5.3p15).
7015 // The only types actually affected are promotable integer
7016 // types and floats, which would be passed as a different
7017 // type depending on whether the prototype is visible.
7018 unsigned proto_nargs = proto->getNumArgs();
7019 for (unsigned i = 0; i < proto_nargs; ++i) {
7020 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007021
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007022 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007023 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007024 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7025 argTy = Enum->getDecl()->getIntegerType();
7026 if (argTy.isNull())
7027 return QualType();
7028 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007029
Eli Friedman3d815e72008-08-22 00:56:42 +00007030 if (argTy->isPromotableIntegerType() ||
7031 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7032 return QualType();
7033 }
7034
7035 if (allLTypes) return lhs;
7036 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007037
7038 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7039 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007040 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007041 }
7042
7043 if (allLTypes) return lhs;
7044 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007045 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007046}
7047
John McCallb9da7132013-03-21 00:10:07 +00007048/// Given that we have an enum type and a non-enum type, try to merge them.
7049static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7050 QualType other, bool isBlockReturnType) {
7051 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7052 // a signed integer type, or an unsigned integer type.
7053 // Compatibility is based on the underlying type, not the promotion
7054 // type.
7055 QualType underlyingType = ET->getDecl()->getIntegerType();
7056 if (underlyingType.isNull()) return QualType();
7057 if (Context.hasSameType(underlyingType, other))
7058 return other;
7059
7060 // In block return types, we're more permissive and accept any
7061 // integral type of the same size.
7062 if (isBlockReturnType && other->isIntegerType() &&
7063 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7064 return other;
7065
7066 return QualType();
7067}
7068
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007069QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007070 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007071 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007072 // C++ [expr]: If an expression initially has the type "reference to T", the
7073 // type is adjusted to "T" prior to any further analysis, the expression
7074 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007075 // expression is an lvalue unless the reference is an rvalue reference and
7076 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007077 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7078 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007079
7080 if (Unqualified) {
7081 LHS = LHS.getUnqualifiedType();
7082 RHS = RHS.getUnqualifiedType();
7083 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007084
Eli Friedman3d815e72008-08-22 00:56:42 +00007085 QualType LHSCan = getCanonicalType(LHS),
7086 RHSCan = getCanonicalType(RHS);
7087
7088 // If two types are identical, they are compatible.
7089 if (LHSCan == RHSCan)
7090 return LHS;
7091
John McCall0953e762009-09-24 19:53:00 +00007092 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007093 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7094 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007095 if (LQuals != RQuals) {
7096 // If any of these qualifiers are different, we have a type
7097 // mismatch.
7098 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007099 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7100 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007101 return QualType();
7102
7103 // Exactly one GC qualifier difference is allowed: __strong is
7104 // okay if the other type has no GC qualifier but is an Objective
7105 // C object pointer (i.e. implicitly strong by default). We fix
7106 // this by pretending that the unqualified type was actually
7107 // qualified __strong.
7108 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7109 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7110 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7111
7112 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7113 return QualType();
7114
7115 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7116 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7117 }
7118 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7119 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7120 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007121 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007122 }
7123
7124 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007125
Eli Friedman852d63b2009-06-01 01:22:52 +00007126 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7127 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007128
Chris Lattner1adb8832008-01-14 05:45:46 +00007129 // We want to consider the two function types to be the same for these
7130 // comparisons, just force one to the other.
7131 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7132 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007133
7134 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007135 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7136 LHSClass = Type::ConstantArray;
7137 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7138 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007139
John McCallc12c5bb2010-05-15 11:32:37 +00007140 // ObjCInterfaces are just specialized ObjCObjects.
7141 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7142 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7143
Nate Begeman213541a2008-04-18 23:10:10 +00007144 // Canonicalize ExtVector -> Vector.
7145 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7146 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007147
Chris Lattnera36a61f2008-04-07 05:43:21 +00007148 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007149 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007150 // Note that we only have special rules for turning block enum
7151 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007152 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007153 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007154 }
John McCall183700f2009-09-21 23:43:11 +00007155 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007156 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007157 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007158 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007159 if (OfBlockPointer && !BlockReturnType) {
7160 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7161 return LHS;
7162 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7163 return RHS;
7164 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007165
Eli Friedman3d815e72008-08-22 00:56:42 +00007166 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007167 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007168
Steve Naroff4a746782008-01-09 22:43:08 +00007169 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007170 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007171#define TYPE(Class, Base)
7172#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007173#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007174#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7175#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7176#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007177 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007178
Richard Smithdc7a4f52013-04-30 13:56:41 +00007179 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007180 case Type::LValueReference:
7181 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007182 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007183 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007184
John McCallc12c5bb2010-05-15 11:32:37 +00007185 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007186 case Type::IncompleteArray:
7187 case Type::VariableArray:
7188 case Type::FunctionProto:
7189 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007190 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007191
Chris Lattner1adb8832008-01-14 05:45:46 +00007192 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007193 {
7194 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007195 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7196 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007197 if (Unqualified) {
7198 LHSPointee = LHSPointee.getUnqualifiedType();
7199 RHSPointee = RHSPointee.getUnqualifiedType();
7200 }
7201 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7202 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007203 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007204 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007205 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007206 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007207 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007208 return getPointerType(ResultType);
7209 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007210 case Type::BlockPointer:
7211 {
7212 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007213 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7214 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007215 if (Unqualified) {
7216 LHSPointee = LHSPointee.getUnqualifiedType();
7217 RHSPointee = RHSPointee.getUnqualifiedType();
7218 }
7219 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7220 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007221 if (ResultType.isNull()) return QualType();
7222 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7223 return LHS;
7224 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7225 return RHS;
7226 return getBlockPointerType(ResultType);
7227 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007228 case Type::Atomic:
7229 {
7230 // Merge two pointer types, while trying to preserve typedef info
7231 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7232 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7233 if (Unqualified) {
7234 LHSValue = LHSValue.getUnqualifiedType();
7235 RHSValue = RHSValue.getUnqualifiedType();
7236 }
7237 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7238 Unqualified);
7239 if (ResultType.isNull()) return QualType();
7240 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7241 return LHS;
7242 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7243 return RHS;
7244 return getAtomicType(ResultType);
7245 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007246 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007247 {
7248 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7249 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7250 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7251 return QualType();
7252
7253 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7254 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007255 if (Unqualified) {
7256 LHSElem = LHSElem.getUnqualifiedType();
7257 RHSElem = RHSElem.getUnqualifiedType();
7258 }
7259
7260 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007261 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007262 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7263 return LHS;
7264 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7265 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007266 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7267 ArrayType::ArraySizeModifier(), 0);
7268 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7269 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007270 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7271 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007272 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7273 return LHS;
7274 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7275 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007276 if (LVAT) {
7277 // FIXME: This isn't correct! But tricky to implement because
7278 // the array's size has to be the size of LHS, but the type
7279 // has to be different.
7280 return LHS;
7281 }
7282 if (RVAT) {
7283 // FIXME: This isn't correct! But tricky to implement because
7284 // the array's size has to be the size of RHS, but the type
7285 // has to be different.
7286 return RHS;
7287 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007288 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7289 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007290 return getIncompleteArrayType(ResultType,
7291 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007292 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007293 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007294 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007295 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007296 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007297 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007298 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007299 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007300 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007301 case Type::Complex:
7302 // Distinct complex types are incompatible.
7303 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007304 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007305 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007306 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7307 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007308 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007309 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007310 case Type::ObjCObject: {
7311 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007312 // FIXME: This should be type compatibility, e.g. whether
7313 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007314 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7315 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7316 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007317 return LHS;
7318
Eli Friedman3d815e72008-08-22 00:56:42 +00007319 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007320 }
Steve Naroff14108da2009-07-10 23:34:53 +00007321 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007322 if (OfBlockPointer) {
7323 if (canAssignObjCInterfacesInBlockPointer(
7324 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007325 RHS->getAs<ObjCObjectPointerType>(),
7326 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007327 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007328 return QualType();
7329 }
John McCall183700f2009-09-21 23:43:11 +00007330 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7331 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007332 return LHS;
7333
Steve Naroffbc76dd02008-12-10 22:14:21 +00007334 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007335 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007336 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007337
David Blaikie7530c032012-01-17 06:56:22 +00007338 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007339}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007340
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007341bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7342 const FunctionProtoType *FromFunctionType,
7343 const FunctionProtoType *ToFunctionType) {
7344 if (FromFunctionType->hasAnyConsumedArgs() !=
7345 ToFunctionType->hasAnyConsumedArgs())
7346 return false;
7347 FunctionProtoType::ExtProtoInfo FromEPI =
7348 FromFunctionType->getExtProtoInfo();
7349 FunctionProtoType::ExtProtoInfo ToEPI =
7350 ToFunctionType->getExtProtoInfo();
7351 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7352 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7353 ArgIdx != NumArgs; ++ArgIdx) {
7354 if (FromEPI.ConsumedArguments[ArgIdx] !=
7355 ToEPI.ConsumedArguments[ArgIdx])
7356 return false;
7357 }
7358 return true;
7359}
7360
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007361/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7362/// 'RHS' attributes and returns the merged version; including for function
7363/// return types.
7364QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7365 QualType LHSCan = getCanonicalType(LHS),
7366 RHSCan = getCanonicalType(RHS);
7367 // If two types are identical, they are compatible.
7368 if (LHSCan == RHSCan)
7369 return LHS;
7370 if (RHSCan->isFunctionType()) {
7371 if (!LHSCan->isFunctionType())
7372 return QualType();
7373 QualType OldReturnType =
7374 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7375 QualType NewReturnType =
7376 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7377 QualType ResReturnType =
7378 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7379 if (ResReturnType.isNull())
7380 return QualType();
7381 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7382 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7383 // In either case, use OldReturnType to build the new function type.
7384 const FunctionType *F = LHS->getAs<FunctionType>();
7385 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7387 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007388 QualType ResultType =
7389 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007390 return ResultType;
7391 }
7392 }
7393 return QualType();
7394 }
7395
7396 // If the qualifiers are different, the types can still be merged.
7397 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7398 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7399 if (LQuals != RQuals) {
7400 // If any of these qualifiers are different, we have a type mismatch.
7401 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7402 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7403 return QualType();
7404
7405 // Exactly one GC qualifier difference is allowed: __strong is
7406 // okay if the other type has no GC qualifier but is an Objective
7407 // C object pointer (i.e. implicitly strong by default). We fix
7408 // this by pretending that the unqualified type was actually
7409 // qualified __strong.
7410 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7411 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7412 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7413
7414 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7415 return QualType();
7416
7417 if (GC_L == Qualifiers::Strong)
7418 return LHS;
7419 if (GC_R == Qualifiers::Strong)
7420 return RHS;
7421 return QualType();
7422 }
7423
7424 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7425 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7426 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7427 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7428 if (ResQT == LHSBaseQT)
7429 return LHS;
7430 if (ResQT == RHSBaseQT)
7431 return RHS;
7432 }
7433 return QualType();
7434}
7435
Chris Lattner5426bf62008-04-07 07:01:58 +00007436//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007437// Integer Predicates
7438//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007439
Jay Foad4ba2a172011-01-12 09:06:06 +00007440unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007441 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007442 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007443 if (T->isBooleanType())
7444 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007445 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007446 return (unsigned)getTypeSize(T);
7447}
7448
Abramo Bagnara762f1592012-09-09 10:21:24 +00007449QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007450 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007451
7452 // Turn <4 x signed int> -> <4 x unsigned int>
7453 if (const VectorType *VTy = T->getAs<VectorType>())
7454 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007455 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007456
7457 // For enums, we return the unsigned version of the base type.
7458 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007459 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007460
7461 const BuiltinType *BTy = T->getAs<BuiltinType>();
7462 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007463 switch (BTy->getKind()) {
7464 case BuiltinType::Char_S:
7465 case BuiltinType::SChar:
7466 return UnsignedCharTy;
7467 case BuiltinType::Short:
7468 return UnsignedShortTy;
7469 case BuiltinType::Int:
7470 return UnsignedIntTy;
7471 case BuiltinType::Long:
7472 return UnsignedLongTy;
7473 case BuiltinType::LongLong:
7474 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007475 case BuiltinType::Int128:
7476 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007477 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007478 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007479 }
7480}
7481
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007482ASTMutationListener::~ASTMutationListener() { }
7483
Richard Smith9dadfab2013-05-11 05:45:24 +00007484void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7485 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007486
7487//===----------------------------------------------------------------------===//
7488// Builtin Type Computation
7489//===----------------------------------------------------------------------===//
7490
7491/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007492/// pointer over the consumed characters. This returns the resultant type. If
7493/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7494/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7495/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007496///
7497/// RequiresICE is filled in on return to indicate whether the value is required
7498/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007499static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007500 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007501 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007502 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007503 // Modifiers.
7504 int HowLong = 0;
7505 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007506 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007507
Chris Lattner33daae62010-10-01 22:42:38 +00007508 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007509 bool Done = false;
7510 while (!Done) {
7511 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007512 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007513 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007514 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007515 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007516 case 'S':
7517 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7518 assert(!Signed && "Can't use 'S' modifier multiple times!");
7519 Signed = true;
7520 break;
7521 case 'U':
7522 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7523 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7524 Unsigned = true;
7525 break;
7526 case 'L':
7527 assert(HowLong <= 2 && "Can't have LLLL modifier");
7528 ++HowLong;
7529 break;
7530 }
7531 }
7532
7533 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007534
Chris Lattner86df27b2009-06-14 00:45:47 +00007535 // Read the base type.
7536 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007537 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007538 case 'v':
7539 assert(HowLong == 0 && !Signed && !Unsigned &&
7540 "Bad modifiers used with 'v'!");
7541 Type = Context.VoidTy;
7542 break;
7543 case 'f':
7544 assert(HowLong == 0 && !Signed && !Unsigned &&
7545 "Bad modifiers used with 'f'!");
7546 Type = Context.FloatTy;
7547 break;
7548 case 'd':
7549 assert(HowLong < 2 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'd'!");
7551 if (HowLong)
7552 Type = Context.LongDoubleTy;
7553 else
7554 Type = Context.DoubleTy;
7555 break;
7556 case 's':
7557 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7558 if (Unsigned)
7559 Type = Context.UnsignedShortTy;
7560 else
7561 Type = Context.ShortTy;
7562 break;
7563 case 'i':
7564 if (HowLong == 3)
7565 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7566 else if (HowLong == 2)
7567 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7568 else if (HowLong == 1)
7569 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7570 else
7571 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7572 break;
7573 case 'c':
7574 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7575 if (Signed)
7576 Type = Context.SignedCharTy;
7577 else if (Unsigned)
7578 Type = Context.UnsignedCharTy;
7579 else
7580 Type = Context.CharTy;
7581 break;
7582 case 'b': // boolean
7583 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7584 Type = Context.BoolTy;
7585 break;
7586 case 'z': // size_t.
7587 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7588 Type = Context.getSizeType();
7589 break;
7590 case 'F':
7591 Type = Context.getCFConstantStringType();
7592 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007593 case 'G':
7594 Type = Context.getObjCIdType();
7595 break;
7596 case 'H':
7597 Type = Context.getObjCSelType();
7598 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007599 case 'M':
7600 Type = Context.getObjCSuperType();
7601 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007602 case 'a':
7603 Type = Context.getBuiltinVaListType();
7604 assert(!Type.isNull() && "builtin va list type not initialized!");
7605 break;
7606 case 'A':
7607 // This is a "reference" to a va_list; however, what exactly
7608 // this means depends on how va_list is defined. There are two
7609 // different kinds of va_list: ones passed by value, and ones
7610 // passed by reference. An example of a by-value va_list is
7611 // x86, where va_list is a char*. An example of by-ref va_list
7612 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7613 // we want this argument to be a char*&; for x86-64, we want
7614 // it to be a __va_list_tag*.
7615 Type = Context.getBuiltinVaListType();
7616 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007617 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007618 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007619 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007620 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007621 break;
7622 case 'V': {
7623 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007624 unsigned NumElements = strtoul(Str, &End, 10);
7625 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007626 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007627
Chris Lattner14e0e742010-10-01 22:53:11 +00007628 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7629 RequiresICE, false);
7630 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007631
7632 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007633 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007634 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007635 break;
7636 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007637 case 'E': {
7638 char *End;
7639
7640 unsigned NumElements = strtoul(Str, &End, 10);
7641 assert(End != Str && "Missing vector size");
7642
7643 Str = End;
7644
7645 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7646 false);
7647 Type = Context.getExtVectorType(ElementType, NumElements);
7648 break;
7649 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007650 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007651 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7652 false);
7653 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007654 Type = Context.getComplexType(ElementType);
7655 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007656 }
7657 case 'Y' : {
7658 Type = Context.getPointerDiffType();
7659 break;
7660 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007661 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007662 Type = Context.getFILEType();
7663 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007664 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007665 return QualType();
7666 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007667 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007668 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007669 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007670 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007671 else
7672 Type = Context.getjmp_bufType();
7673
Mike Stumpfd612db2009-07-28 23:47:15 +00007674 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007675 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007676 return QualType();
7677 }
7678 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007679 case 'K':
7680 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7681 Type = Context.getucontext_tType();
7682
7683 if (Type.isNull()) {
7684 Error = ASTContext::GE_Missing_ucontext;
7685 return QualType();
7686 }
7687 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007688 case 'p':
7689 Type = Context.getProcessIDType();
7690 break;
Mike Stump782fa302009-07-28 02:25:19 +00007691 }
Mike Stump1eb44332009-09-09 15:08:12 +00007692
Chris Lattner33daae62010-10-01 22:42:38 +00007693 // If there are modifiers and if we're allowed to parse them, go for it.
7694 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007695 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007696 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007697 default: Done = true; --Str; break;
7698 case '*':
7699 case '&': {
7700 // Both pointers and references can have their pointee types
7701 // qualified with an address space.
7702 char *End;
7703 unsigned AddrSpace = strtoul(Str, &End, 10);
7704 if (End != Str && AddrSpace != 0) {
7705 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7706 Str = End;
7707 }
7708 if (c == '*')
7709 Type = Context.getPointerType(Type);
7710 else
7711 Type = Context.getLValueReferenceType(Type);
7712 break;
7713 }
7714 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7715 case 'C':
7716 Type = Type.withConst();
7717 break;
7718 case 'D':
7719 Type = Context.getVolatileType(Type);
7720 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007721 case 'R':
7722 Type = Type.withRestrict();
7723 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007724 }
7725 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007726
Chris Lattner14e0e742010-10-01 22:53:11 +00007727 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007728 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007729
Chris Lattner86df27b2009-06-14 00:45:47 +00007730 return Type;
7731}
7732
7733/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007734QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007735 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007736 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007737 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007738
Chris Lattner5f9e2722011-07-23 10:55:15 +00007739 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007740
Chris Lattner14e0e742010-10-01 22:53:11 +00007741 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007742 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007743 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7744 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007745 if (Error != GE_None)
7746 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007747
7748 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7749
Chris Lattner86df27b2009-06-14 00:45:47 +00007750 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007751 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007752 if (Error != GE_None)
7753 return QualType();
7754
Chris Lattner14e0e742010-10-01 22:53:11 +00007755 // If this argument is required to be an IntegerConstantExpression and the
7756 // caller cares, fill in the bitmask we return.
7757 if (RequiresICE && IntegerConstantArgs)
7758 *IntegerConstantArgs |= 1 << ArgTypes.size();
7759
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 // Do array -> pointer decay. The builtin should use the decayed type.
7761 if (Ty->isArrayType())
7762 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007763
Chris Lattner86df27b2009-06-14 00:45:47 +00007764 ArgTypes.push_back(Ty);
7765 }
7766
7767 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7768 "'.' should only occur at end of builtin type list!");
7769
John McCall00ccbef2010-12-21 00:44:39 +00007770 FunctionType::ExtInfo EI;
7771 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7772
7773 bool Variadic = (TypeStr[0] == '.');
7774
7775 // We really shouldn't be making a no-proto type here, especially in C++.
7776 if (ArgTypes.empty() && Variadic)
7777 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007778
John McCalle23cf432010-12-14 08:05:40 +00007779 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007780 EPI.ExtInfo = EI;
7781 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007782
Jordan Rosebea522f2013-03-08 21:51:21 +00007783 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007784}
Eli Friedmana95d7572009-08-19 07:44:53 +00007785
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007786GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007787 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007788 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007789
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007790 GVALinkage External = GVA_StrongExternal;
7791 switch (FD->getTemplateSpecializationKind()) {
7792 case TSK_Undeclared:
7793 case TSK_ExplicitSpecialization:
7794 External = GVA_StrongExternal;
7795 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007796
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007797 case TSK_ExplicitInstantiationDefinition:
7798 return GVA_ExplicitTemplateInstantiation;
7799
7800 case TSK_ExplicitInstantiationDeclaration:
7801 case TSK_ImplicitInstantiation:
7802 External = GVA_TemplateInstantiation;
7803 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007804 }
7805
7806 if (!FD->isInlined())
7807 return External;
7808
David Blaikie4e4d0842012-03-11 07:00:24 +00007809 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007810 // GNU or C99 inline semantics. Determine whether this symbol should be
7811 // externally visible.
7812 if (FD->isInlineDefinitionExternallyVisible())
7813 return External;
7814
7815 // C99 inline semantics, where the symbol is not externally visible.
7816 return GVA_C99Inline;
7817 }
7818
7819 // C++0x [temp.explicit]p9:
7820 // [ Note: The intent is that an inline function that is the subject of
7821 // an explicit instantiation declaration will still be implicitly
7822 // instantiated when used so that the body can be considered for
7823 // inlining, but that no out-of-line copy of the inline function would be
7824 // generated in the translation unit. -- end note ]
7825 if (FD->getTemplateSpecializationKind()
7826 == TSK_ExplicitInstantiationDeclaration)
7827 return GVA_C99Inline;
7828
7829 return GVA_CXXInline;
7830}
7831
7832GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007833 if (!VD->isExternallyVisible())
7834 return GVA_Internal;
7835
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007836 // If this is a static data member, compute the kind of template
7837 // specialization. Otherwise, this variable is not part of a
7838 // template.
7839 TemplateSpecializationKind TSK = TSK_Undeclared;
7840 if (VD->isStaticDataMember())
7841 TSK = VD->getTemplateSpecializationKind();
7842
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007843 switch (TSK) {
7844 case TSK_Undeclared:
7845 case TSK_ExplicitSpecialization:
7846 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007847
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007848 case TSK_ExplicitInstantiationDeclaration:
7849 llvm_unreachable("Variable should not be instantiated");
7850 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007851
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007852 case TSK_ExplicitInstantiationDefinition:
7853 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007854
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007855 case TSK_ImplicitInstantiation:
7856 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007857 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007858
7859 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007860}
7861
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007862bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007863 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7864 if (!VD->isFileVarDecl())
7865 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007866 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7867 // We never need to emit an uninstantiated function template.
7868 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7869 return false;
7870 } else
7871 return false;
7872
7873 // If this is a member of a class template, we do not need to emit it.
7874 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007875 return false;
7876
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007877 // Weak references don't produce any output by themselves.
7878 if (D->hasAttr<WeakRefAttr>())
7879 return false;
7880
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007881 // Aliases and used decls are required.
7882 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7883 return true;
7884
7885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7886 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007887 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007888 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007889
7890 // Constructors and destructors are required.
7891 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7892 return true;
7893
John McCalld5617ee2013-01-25 22:31:03 +00007894 // The key function for a class is required. This rule only comes
7895 // into play when inline functions can be key functions, though.
7896 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7897 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7898 const CXXRecordDecl *RD = MD->getParent();
7899 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7900 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7901 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7902 return true;
7903 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007904 }
7905 }
7906
7907 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7908
7909 // static, static inline, always_inline, and extern inline functions can
7910 // always be deferred. Normal inline functions can be deferred in C99/C++.
7911 // Implicit template instantiations can also be deferred in C++.
7912 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007913 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007914 return false;
7915 return true;
7916 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007917
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007918 const VarDecl *VD = cast<VarDecl>(D);
7919 assert(VD->isFileVarDecl() && "Expected file scoped var");
7920
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007921 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7922 return false;
7923
Richard Smith5f9a7e32012-11-12 21:38:00 +00007924 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007925 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007926 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7927 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007928
Richard Smith5f9a7e32012-11-12 21:38:00 +00007929 // Variables that have destruction with side-effects are required.
7930 if (VD->getType().isDestructedType())
7931 return true;
7932
7933 // Variables that have initialization with side-effects are required.
7934 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7935 return true;
7936
7937 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007938}
Charles Davis071cc7d2010-08-16 03:33:14 +00007939
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007940CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007941 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007942 return ABI->getDefaultMethodCallConv(isVariadic);
7943}
7944
7945CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007946 if (CC == CC_C && !LangOpts.MRTD &&
7947 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007948 return CC_Default;
7949 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007950}
7951
Jay Foad4ba2a172011-01-12 09:06:06 +00007952bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007953 // Pass through to the C++ ABI object
7954 return ABI->isNearlyEmpty(RD);
7955}
7956
Peter Collingbourne14110472011-01-13 18:57:25 +00007957MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007958 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007959 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007960 case TargetCXXABI::GenericItanium:
7961 case TargetCXXABI::GenericARM:
7962 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007963 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007964 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007965 return createMicrosoftMangleContext(*this, getDiagnostics());
7966 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007967 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007968}
7969
Charles Davis071cc7d2010-08-16 03:33:14 +00007970CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007971
7972size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007973 return ASTRecordLayouts.getMemorySize()
7974 + llvm::capacity_in_bytes(ObjCLayouts)
7975 + llvm::capacity_in_bytes(KeyFunctions)
7976 + llvm::capacity_in_bytes(ObjCImpls)
7977 + llvm::capacity_in_bytes(BlockVarCopyInits)
7978 + llvm::capacity_in_bytes(DeclAttrs)
7979 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7980 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7981 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7982 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7983 + llvm::capacity_in_bytes(OverriddenMethods)
7984 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007985 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007986 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007987}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007988
David Blaikie66cff722012-11-14 01:52:05 +00007989void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7990 // FIXME: This mangling should be applied to function local classes too
7991 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00007992 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00007993 return;
7994
7995 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7996 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7997 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7998}
7999
8000int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8001 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8002 UnnamedMangleNumbers.find(Tag);
8003 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8004}
8005
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008006unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8007 CXXRecordDecl *Lambda = CallOperator->getParent();
8008 return LambdaMangleContexts[Lambda->getDeclContext()]
8009 .getManglingNumber(CallOperator);
8010}
8011
8012
Ted Kremenekd211cb72011-10-06 05:00:56 +00008013void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8014 ParamIndices[D] = index;
8015}
8016
8017unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8018 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8019 assert(I != ParamIndices.end() &&
8020 "ParmIndices lacks entry set by ParmVarDecl");
8021 return I->second;
8022}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008023
Richard Smith211c8dd2013-06-05 00:46:14 +00008024APValue *
8025ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8026 bool MayCreate) {
8027 assert(E && E->getStorageDuration() == SD_Static &&
8028 "don't need to cache the computed value for this temporary");
8029 if (MayCreate)
8030 return &MaterializedTemporaryValues[E];
8031
8032 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8033 MaterializedTemporaryValues.find(E);
8034 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8035}
8036
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008037bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8038 const llvm::Triple &T = getTargetInfo().getTriple();
8039 if (!T.isOSDarwin())
8040 return false;
8041
8042 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8043 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8044 uint64_t Size = sizeChars.getQuantity();
8045 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8046 unsigned Align = alignChars.getQuantity();
8047 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8048 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8049}
Reid Klecknercff15122013-06-17 12:56:08 +00008050
8051namespace {
8052
8053 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8054 /// parents as defined by the \c RecursiveASTVisitor.
8055 ///
8056 /// Note that the relationship described here is purely in terms of AST
8057 /// traversal - there are other relationships (for example declaration context)
8058 /// in the AST that are better modeled by special matchers.
8059 ///
8060 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8061 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8062
8063 public:
8064 /// \brief Builds and returns the translation unit's parent map.
8065 ///
8066 /// The caller takes ownership of the returned \c ParentMap.
8067 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8068 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8069 Visitor.TraverseDecl(&TU);
8070 return Visitor.Parents;
8071 }
8072
8073 private:
8074 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8075
8076 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8077 }
8078
8079 bool shouldVisitTemplateInstantiations() const {
8080 return true;
8081 }
8082 bool shouldVisitImplicitCode() const {
8083 return true;
8084 }
8085 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8086 // are not triggered during data recursion.
8087 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8088 return false;
8089 }
8090
8091 template <typename T>
8092 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8093 if (Node == NULL)
8094 return true;
8095 if (ParentStack.size() > 0)
8096 // FIXME: Currently we add the same parent multiple times, for example
8097 // when we visit all subexpressions of template instantiations; this is
8098 // suboptimal, bug benign: the only way to visit those is with
8099 // hasAncestor / hasParent, and those do not create new matches.
8100 // The plan is to enable DynTypedNode to be storable in a map or hash
8101 // map. The main problem there is to implement hash functions /
8102 // comparison operators for all types that DynTypedNode supports that
8103 // do not have pointer identity.
8104 (*Parents)[Node].push_back(ParentStack.back());
8105 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8106 bool Result = (this ->* traverse) (Node);
8107 ParentStack.pop_back();
8108 return Result;
8109 }
8110
8111 bool TraverseDecl(Decl *DeclNode) {
8112 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8113 }
8114
8115 bool TraverseStmt(Stmt *StmtNode) {
8116 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8117 }
8118
8119 ASTContext::ParentMap *Parents;
8120 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8121
8122 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8123 };
8124
8125} // end namespace
8126
8127ASTContext::ParentVector
8128ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8129 assert(Node.getMemoizationData() &&
8130 "Invariant broken: only nodes that support memoization may be "
8131 "used in the parent map.");
8132 if (!AllParents) {
8133 // We always need to run over the whole translation unit, as
8134 // hasAncestor can escape any subtree.
8135 AllParents.reset(
8136 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8137 }
8138 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8139 if (I == AllParents->end()) {
8140 return ParentVector();
8141 }
8142 return I->second;
8143}